_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
2e44133d7e44091290c0d38439aa796c3739f0f10e95af925d686ce98496c3f0
ninenines/cowboy
ws_timeout_cancel.erl
%% Feel free to use, reuse and abuse the code in this file. -module(ws_timeout_cancel). -export([init/2]). -export([websocket_handle/2]). -export([websocket_info/2]). init(Req, _) -> erlang:start_timer(500, self(), should_not_cancel_timer), {cowboy_websocket, Req, undefined, #{ idle_timeout => 1000 }}. websocket_handle({text, Data}, State) -> {[{text, Data}], State}; websocket_handle({binary, Data}, State) -> {[{binary, Data}], State}. websocket_info(_Info, State) -> erlang:start_timer(500, self(), should_not_cancel_timer), {[], State}.
null
https://raw.githubusercontent.com/ninenines/cowboy/8795233c57f1f472781a22ffbf186ce38cc5b049/test/ws_SUITE_data/ws_timeout_cancel.erl
erlang
Feel free to use, reuse and abuse the code in this file.
-module(ws_timeout_cancel). -export([init/2]). -export([websocket_handle/2]). -export([websocket_info/2]). init(Req, _) -> erlang:start_timer(500, self(), should_not_cancel_timer), {cowboy_websocket, Req, undefined, #{ idle_timeout => 1000 }}. websocket_handle({text, Data}, State) -> {[{text, Data}], State}; websocket_handle({binary, Data}, State) -> {[{binary, Data}], State}. websocket_info(_Info, State) -> erlang:start_timer(500, self(), should_not_cancel_timer), {[], State}.
761c422877695e0eec349d9799622e13df48353c55c75f9d851f5e2914d24a6f
onedata/op-worker
monitoring_utils.erl
%%%-------------------------------------------------------------------- @author ( C ) 2016 ACK CYFRONET AGH This software is released under the MIT license cited in ' LICENSE.txt ' . %%% @end %%%-------------------------------------------------------------------- %%% @doc This module contains utils functions used to start and %%% update monitoring. %%% @end %%%-------------------------------------------------------------------- -module(monitoring_utils). -author("Michal Wrona"). -include("global_definitions.hrl"). -include("modules/fslogic/fslogic_common.hrl"). -include_lib("ctool/include/logging.hrl"). -include_lib("modules/monitoring/rrd_definitions.hrl"). %% API -export([create_and_update/2, create_and_update/3, create/3, update/4]). -define(BYTES_TO_BITS, 8). %%-------------------------------------------------------------------- %% @doc Creates RRD if not exists and updates it . %% @end %%-------------------------------------------------------------------- -spec create_and_update(datastore:key(), #monitoring_id{}) -> ok. create_and_update(SpaceId, MonitoringId) -> create_and_update(SpaceId, MonitoringId, #{}). %%-------------------------------------------------------------------- %% @doc Creates RRD if not exists and updates RRD . Updates rrd at previous and current PDP time slots . Updates at previous slot only if update at %% this slot was not performed earlier. %% @end %%-------------------------------------------------------------------- -spec create_and_update(datastore:key(), #monitoring_id{}, map()) -> ok. create_and_update(SpaceId, MonitoringId, UpdateValue) -> try CurrentTime = global_clock:timestamp_seconds(), {PreviousPDPTime, CurrentPDPTime, WaitingTime} = case CurrentTime rem ?STEP_IN_SECONDS of 0 -> {CurrentTime - ?STEP_IN_SECONDS, CurrentTime, 0}; Value -> {CurrentTime - Value, CurrentTime - Value + ?STEP_IN_SECONDS, ?STEP_IN_SECONDS - Value} end, ok = monitoring_utils:create(SpaceId, MonitoringId, PreviousPDPTime - ?STEP_IN_SECONDS), {ok, #document{value = #monitoring_state{last_update_time = LastUpdateTime} = MonitoringState}} = monitoring_state:get(MonitoringId), case LastUpdateTime =/= PreviousPDPTime of true -> ok = update(MonitoringId, MonitoringState, PreviousPDPTime, #{}); false -> ok end, {ok, #document{value = UpdatedMonitoringState}} = monitoring_state:get(MonitoringId), timer:apply_after(timer:seconds(WaitingTime), monitoring_utils, update, [MonitoringId, UpdatedMonitoringState, CurrentPDPTime, UpdateValue]), ok catch exit:{noproc, _} -> ok; T:M:Stacktrace -> ?error_stacktrace("Cannot update monitoring state for ~w - ~p:~p", [MonitoringId, T, M], Stacktrace) end. %%-------------------------------------------------------------------- %% @doc Creates rrd with optional initial buffer state . %% @end %%-------------------------------------------------------------------- -spec create(datastore:key(), #monitoring_id{}, non_neg_integer()) -> ok. create(SpaceId, #monitoring_id{main_subject_type = space, metric_type = storage_used, secondary_subject_type = user} = MonitoringId, CreationTime) -> rrd_utils:create_rrd(SpaceId, MonitoringId, #{storage_used => 0}, CreationTime); create(SpaceId, MonitoringId, CreationTime) -> rrd_utils:create_rrd(SpaceId, MonitoringId, #{}, CreationTime). %%-------------------------------------------------------------------- %% @doc Updates rrd with value corresponding to metric type . %% @end %%-------------------------------------------------------------------- -spec update(#monitoring_id{}, #monitoring_state{}, non_neg_integer(), map()) -> ok. update(#monitoring_id{main_subject_type = space, metric_type = storage_used, secondary_subject_type = user} = MonitoringId, MonitoringState, UpdateTime, UpdateValue) -> #monitoring_state{state_buffer = StateBuffer} = MonitoringState, CurrentSize = maps:get(storage_used, StateBuffer), SizeDifference = maps:get(size_difference, UpdateValue, 0), NewSize = CurrentSize + SizeDifference, {ok, _} = monitoring_state:update(MonitoringId, fun (State = #monitoring_state{state_buffer = Buffer}) -> {ok, State#monitoring_state{state_buffer = Buffer#{storage_used => NewSize}}} end), ok = rrd_utils:update_rrd(MonitoringId, MonitoringState, UpdateTime, [NewSize]); update(#monitoring_id{main_subject_type = space, main_subject_id = SpaceId, metric_type = storage_used} = MonitoringId, MonitoringState, UpdateTime, _UpdateValue) -> {ok, #document{value = #space_quota{current_size = CurrentSize}}} = space_quota:get(SpaceId), maybe_update(MonitoringId, MonitoringState, UpdateTime, CurrentSize); update(#monitoring_id{main_subject_type = space, main_subject_id = SpaceId, metric_type = storage_quota} = MonitoringId, MonitoringState, UpdateTime, _UpdateValue) -> {ok, SupSize} = provider_logic:get_support_size(SpaceId), maybe_update(MonitoringId, MonitoringState, UpdateTime, SupSize); update(#monitoring_id{main_subject_type = space, main_subject_id = SpaceId, metric_type = connected_users} = MonitoringId, MonitoringState, UpdateTime, _UpdateValue) -> {ok, EffUsers} = space_logic:get_eff_users(?ROOT_SESS_ID, SpaceId), ConnectedUsers = maps:size(EffUsers), maybe_update(MonitoringId, MonitoringState, UpdateTime, ConnectedUsers); update(#monitoring_id{main_subject_type = space, metric_type = data_access} = MonitoringId, MonitoringState, UpdateTime, UpdateValue) -> ReadCount = maps:get(read_counter, UpdateValue, 0), WriteCount = maps:get(write_counter, UpdateValue, 0), ok = rrd_utils:update_rrd(MonitoringId, MonitoringState, UpdateTime, [ReadCount, WriteCount]); update(#monitoring_id{main_subject_type = space, metric_type = block_access} = MonitoringId, MonitoringState, UpdateTime, UpdateValue) -> ReadCount = maps:get(read_operations_counter, UpdateValue, 0), WriteCount = maps:get(write_operations_counter, UpdateValue, 0), ok = rrd_utils:update_rrd(MonitoringId, MonitoringState, UpdateTime, [ReadCount, WriteCount]); update(#monitoring_id{main_subject_type = space, metric_type = remote_transfer} = MonitoringId, MonitoringState, UpdateTime, UpdateValue) -> TransferIn = maps:get(transfer_in, UpdateValue, 0) * ?BYTES_TO_BITS, ok = rrd_utils:update_rrd(MonitoringId, MonitoringState, UpdateTime, [TransferIn]). %%%=================================================================== Internal functions %%%=================================================================== %%-------------------------------------------------------------------- @private %% @doc Updates rrd if current update value is different than previous %% update value. %% @end %%-------------------------------------------------------------------- -spec maybe_update(#monitoring_id{}, #monitoring_state{}, non_neg_integer(), term()) -> ok. maybe_update(MonitoringId, MonitoringState, UpdateTime, UpdateValue) -> {ok, _} = monitoring_state:update(MonitoringId, fun (State = #monitoring_state{state_buffer = Buffer}) -> {ok, State#monitoring_state{state_buffer = Buffer#{previous_value => UpdateValue}}} end), ok = rrd_utils:update_rrd(MonitoringId, MonitoringState, UpdateTime, [UpdateValue]).
null
https://raw.githubusercontent.com/onedata/op-worker/b0e4045090b180f28c79d40b9b334d7411ec3ca5/src/modules/monitoring/monitoring_utils.erl
erlang
-------------------------------------------------------------------- @end -------------------------------------------------------------------- @doc This module contains utils functions used to start and update monitoring. @end -------------------------------------------------------------------- API -------------------------------------------------------------------- @doc @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc this slot was not performed earlier. @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc @end -------------------------------------------------------------------- =================================================================== =================================================================== -------------------------------------------------------------------- @doc update value. @end --------------------------------------------------------------------
@author ( C ) 2016 ACK CYFRONET AGH This software is released under the MIT license cited in ' LICENSE.txt ' . -module(monitoring_utils). -author("Michal Wrona"). -include("global_definitions.hrl"). -include("modules/fslogic/fslogic_common.hrl"). -include_lib("ctool/include/logging.hrl"). -include_lib("modules/monitoring/rrd_definitions.hrl"). -export([create_and_update/2, create_and_update/3, create/3, update/4]). -define(BYTES_TO_BITS, 8). Creates RRD if not exists and updates it . -spec create_and_update(datastore:key(), #monitoring_id{}) -> ok. create_and_update(SpaceId, MonitoringId) -> create_and_update(SpaceId, MonitoringId, #{}). Creates RRD if not exists and updates RRD . Updates rrd at previous and current PDP time slots . Updates at previous slot only if update at -spec create_and_update(datastore:key(), #monitoring_id{}, map()) -> ok. create_and_update(SpaceId, MonitoringId, UpdateValue) -> try CurrentTime = global_clock:timestamp_seconds(), {PreviousPDPTime, CurrentPDPTime, WaitingTime} = case CurrentTime rem ?STEP_IN_SECONDS of 0 -> {CurrentTime - ?STEP_IN_SECONDS, CurrentTime, 0}; Value -> {CurrentTime - Value, CurrentTime - Value + ?STEP_IN_SECONDS, ?STEP_IN_SECONDS - Value} end, ok = monitoring_utils:create(SpaceId, MonitoringId, PreviousPDPTime - ?STEP_IN_SECONDS), {ok, #document{value = #monitoring_state{last_update_time = LastUpdateTime} = MonitoringState}} = monitoring_state:get(MonitoringId), case LastUpdateTime =/= PreviousPDPTime of true -> ok = update(MonitoringId, MonitoringState, PreviousPDPTime, #{}); false -> ok end, {ok, #document{value = UpdatedMonitoringState}} = monitoring_state:get(MonitoringId), timer:apply_after(timer:seconds(WaitingTime), monitoring_utils, update, [MonitoringId, UpdatedMonitoringState, CurrentPDPTime, UpdateValue]), ok catch exit:{noproc, _} -> ok; T:M:Stacktrace -> ?error_stacktrace("Cannot update monitoring state for ~w - ~p:~p", [MonitoringId, T, M], Stacktrace) end. Creates rrd with optional initial buffer state . -spec create(datastore:key(), #monitoring_id{}, non_neg_integer()) -> ok. create(SpaceId, #monitoring_id{main_subject_type = space, metric_type = storage_used, secondary_subject_type = user} = MonitoringId, CreationTime) -> rrd_utils:create_rrd(SpaceId, MonitoringId, #{storage_used => 0}, CreationTime); create(SpaceId, MonitoringId, CreationTime) -> rrd_utils:create_rrd(SpaceId, MonitoringId, #{}, CreationTime). Updates rrd with value corresponding to metric type . -spec update(#monitoring_id{}, #monitoring_state{}, non_neg_integer(), map()) -> ok. update(#monitoring_id{main_subject_type = space, metric_type = storage_used, secondary_subject_type = user} = MonitoringId, MonitoringState, UpdateTime, UpdateValue) -> #monitoring_state{state_buffer = StateBuffer} = MonitoringState, CurrentSize = maps:get(storage_used, StateBuffer), SizeDifference = maps:get(size_difference, UpdateValue, 0), NewSize = CurrentSize + SizeDifference, {ok, _} = monitoring_state:update(MonitoringId, fun (State = #monitoring_state{state_buffer = Buffer}) -> {ok, State#monitoring_state{state_buffer = Buffer#{storage_used => NewSize}}} end), ok = rrd_utils:update_rrd(MonitoringId, MonitoringState, UpdateTime, [NewSize]); update(#monitoring_id{main_subject_type = space, main_subject_id = SpaceId, metric_type = storage_used} = MonitoringId, MonitoringState, UpdateTime, _UpdateValue) -> {ok, #document{value = #space_quota{current_size = CurrentSize}}} = space_quota:get(SpaceId), maybe_update(MonitoringId, MonitoringState, UpdateTime, CurrentSize); update(#monitoring_id{main_subject_type = space, main_subject_id = SpaceId, metric_type = storage_quota} = MonitoringId, MonitoringState, UpdateTime, _UpdateValue) -> {ok, SupSize} = provider_logic:get_support_size(SpaceId), maybe_update(MonitoringId, MonitoringState, UpdateTime, SupSize); update(#monitoring_id{main_subject_type = space, main_subject_id = SpaceId, metric_type = connected_users} = MonitoringId, MonitoringState, UpdateTime, _UpdateValue) -> {ok, EffUsers} = space_logic:get_eff_users(?ROOT_SESS_ID, SpaceId), ConnectedUsers = maps:size(EffUsers), maybe_update(MonitoringId, MonitoringState, UpdateTime, ConnectedUsers); update(#monitoring_id{main_subject_type = space, metric_type = data_access} = MonitoringId, MonitoringState, UpdateTime, UpdateValue) -> ReadCount = maps:get(read_counter, UpdateValue, 0), WriteCount = maps:get(write_counter, UpdateValue, 0), ok = rrd_utils:update_rrd(MonitoringId, MonitoringState, UpdateTime, [ReadCount, WriteCount]); update(#monitoring_id{main_subject_type = space, metric_type = block_access} = MonitoringId, MonitoringState, UpdateTime, UpdateValue) -> ReadCount = maps:get(read_operations_counter, UpdateValue, 0), WriteCount = maps:get(write_operations_counter, UpdateValue, 0), ok = rrd_utils:update_rrd(MonitoringId, MonitoringState, UpdateTime, [ReadCount, WriteCount]); update(#monitoring_id{main_subject_type = space, metric_type = remote_transfer} = MonitoringId, MonitoringState, UpdateTime, UpdateValue) -> TransferIn = maps:get(transfer_in, UpdateValue, 0) * ?BYTES_TO_BITS, ok = rrd_utils:update_rrd(MonitoringId, MonitoringState, UpdateTime, [TransferIn]). Internal functions @private Updates rrd if current update value is different than previous -spec maybe_update(#monitoring_id{}, #monitoring_state{}, non_neg_integer(), term()) -> ok. maybe_update(MonitoringId, MonitoringState, UpdateTime, UpdateValue) -> {ok, _} = monitoring_state:update(MonitoringId, fun (State = #monitoring_state{state_buffer = Buffer}) -> {ok, State#monitoring_state{state_buffer = Buffer#{previous_value => UpdateValue}}} end), ok = rrd_utils:update_rrd(MonitoringId, MonitoringState, UpdateTime, [UpdateValue]).
5db61484a55e059133199e83467bd53f629703ee01473f06c75635f03ed93ca8
dom96/SimpleIRC
disconnecttest.hs
{-# LANGUAGE OverloadedStrings #-} import Network.SimpleIRC import Data.Maybe import Control.Concurrent.Chan import Control.Concurrent (threadDelay) import qualified Data.ByteString.Char8 as B onDisconnect :: MIrc -> IO () onDisconnect mIrc = do addr <- getAddress mIrc putStrLn $ "Disconnected from " ++ (B.unpack addr) m <- reconnect mIrc either (\err -> putStrLn $ "Unable to reconnect: " ++ show err) (\_ -> putStrLn "Successfully reconnected!") m events = [(Disconnect onDisconnect)] freenode = (mkDefaultConfig "irc.ninthbit.net" "SimpleIRCBot") { cChannels = ["#bots"], cEvents = events } main = do connect freenode True True waitForever where waitForever = do threadDelay 50000 waitForever
null
https://raw.githubusercontent.com/dom96/SimpleIRC/ee5ab54fcff9ae974458a9394a2484709724e9dc/tests/disconnecttest.hs
haskell
# LANGUAGE OverloadedStrings #
import Network.SimpleIRC import Data.Maybe import Control.Concurrent.Chan import Control.Concurrent (threadDelay) import qualified Data.ByteString.Char8 as B onDisconnect :: MIrc -> IO () onDisconnect mIrc = do addr <- getAddress mIrc putStrLn $ "Disconnected from " ++ (B.unpack addr) m <- reconnect mIrc either (\err -> putStrLn $ "Unable to reconnect: " ++ show err) (\_ -> putStrLn "Successfully reconnected!") m events = [(Disconnect onDisconnect)] freenode = (mkDefaultConfig "irc.ninthbit.net" "SimpleIRCBot") { cChannels = ["#bots"], cEvents = events } main = do connect freenode True True waitForever where waitForever = do threadDelay 50000 waitForever
1a76fdafa0313e807e2ca6f748e814eaaf0cdd252f76764bcbbd370b0079986c
aggieben/weblocks
suggest.lisp
(in-package :weblocks-test) ;;; test render-suggest (deftest-html render-suggest-1 (with-request :get nil (render-suggest 'some-name '("a" "b" "c") :input-id 'i1 :choices-id 'c1)) (htm (:select :id "I1" :name "some-name" (:option "a") (:option "b") (:option "c")) (:script :type "text/javascript" (fmt "~%// <![CDATA[~%") (fmt "replaceDropdownWithSuggest(false, 'I1', 'some-name', 'C1');") (fmt "~%// ]]>~%")))) (deftest-html render-suggest-2 (with-request :get nil (render-suggest 'some-name (lambda (a) '("a" "b" "c")) :input-id 'i1 :choices-id 'c1)) (htm (:input :type "text" :id "I1" :name "some-name" :class "suggest" :maxlength "40") (:div :id "C1" :class "suggest" :style "display: none" "") (:script :type "text/javascript" (fmt "~%// <![CDATA[~%") (fmt "declareSuggest('I1', 'C1', 'abc123', 'weblocks-session=1%3ATEST');") (fmt "~%// ]]>~%")))) (deftest render-suggest-3 (with-request :get nil (let ((*weblocks-output-stream* (make-string-output-stream))) (declare (special *weblocks-output-stream*)) (render-suggest 'some-name (lambda (a) '("a" "b" "c")) :input-id 'i1 :choices-id 'c1)) (do-request `(("pure" . "true") (,weblocks::*action-string* . "abc123")))) "<ul><li>a</li><li>b</li><li>c</li></ul>") (deftest-html render-suggest-4 (with-request :get nil (render-suggest 'some-name '("a" "b" "c") :input-id 'i1 :choices-id 'c1 :default-value "b")) (htm (:select :id "I1" :name "some-name" (:option "a") (:option :selected "selected" "b") (:option "c")) (:script :type "text/javascript" (fmt "~%// <![CDATA[~%") (fmt "replaceDropdownWithSuggest(false, 'I1', 'some-name', 'C1', 'b');") (fmt "~%// ]]>~%")))) (deftest-html render-suggest-5 (with-request :get nil (render-suggest 'some-name (lambda (a) '("a" "b" "c")) :input-id 'i1 :choices-id 'c1 :default-value "test")) (htm (:input :type "text" :id "I1" :name "some-name" :class "suggest" :value "test" :maxlength "40") (:div :id "C1" :class "suggest" :style "display: none" "") (:script :type "text/javascript" (fmt "~%// <![CDATA[~%") (fmt "declareSuggest('I1', 'C1', 'abc123', 'weblocks-session=1%3ATEST');") (fmt "~%// ]]>~%")))) (deftest-html render-suggest-6 (with-request :get nil (render-suggest 'some-name '("a" "b" "c") :input-id 'i1 :choices-id 'c1 :default-value '("test" "b"))) (htm (:select :id "I1" :name "some-name" (:option "a") (:option :selected "selected" "b") (:option "c")) (:script :type "text/javascript" (fmt "~%// <![CDATA[~%") (fmt "replaceDropdownWithSuggest(false, 'I1', 'some-name', 'C1', 'test');") (fmt "~%// ]]>~%")))) (deftest-html render-suggest-7 (with-request :get nil (render-suggest 'some-name '("a" "b" "c") :input-id 'i1 :choices-id 'c1 :welcome-name (cons "foo" "bar"))) (htm (:select :id "I1" :name "some-name" (:option :value "bar" "[Select foo]") (:option "a") (:option "b") (:option "c")) (:script :type "text/javascript" (fmt "~%// <![CDATA[~%") (fmt "replaceDropdownWithSuggest(true, 'I1', 'some-name', 'C1');") (fmt "~%// ]]>~%")))) (deftest-html render-suggest-8 (with-request :get nil (make-request-ajax) (render-suggest 'some-name '("a" "b" "c") :input-id 'i1 :choices-id 'c1)) (htm (:input :type "text" :id "I1" :name "some-name" :class "suggest" :maxlength "40") (:div :id "C1" :class "suggest" :style "display: none" "") (:script :type "text/javascript" (fmt "~%// <![CDATA[~%") (fmt "declareSuggest('I1', 'C1', [\"a\",\"b\",\"c\"], 'weblocks-session=1%3ATEST');") (fmt "~%// ]]>~%")))) ;;; test format-suggest-list (deftest format-suggest-list-1 (weblocks::format-suggest-list '("a" "b" "c")) "<ul><li>a</li><li>b</li><li>c</li></ul>")
null
https://raw.githubusercontent.com/aggieben/weblocks/8d86be6a4fff8dde0b94181ba60d0dca2cbd9e25/test/snippets/suggest.lisp
lisp
test render-suggest test format-suggest-list
(in-package :weblocks-test) (deftest-html render-suggest-1 (with-request :get nil (render-suggest 'some-name '("a" "b" "c") :input-id 'i1 :choices-id 'c1)) (htm (:select :id "I1" :name "some-name" (:option "a") (:option "b") (:option "c")) (:script :type "text/javascript" (fmt "~%// <![CDATA[~%") (fmt "replaceDropdownWithSuggest(false, 'I1', 'some-name', 'C1');") (fmt "~%// ]]>~%")))) (deftest-html render-suggest-2 (with-request :get nil (render-suggest 'some-name (lambda (a) '("a" "b" "c")) :input-id 'i1 :choices-id 'c1)) (htm (:input :type "text" :id "I1" :name "some-name" :class "suggest" :maxlength "40") (:div :id "C1" :class "suggest" :style "display: none" "") (:script :type "text/javascript" (fmt "~%// <![CDATA[~%") (fmt "declareSuggest('I1', 'C1', 'abc123', 'weblocks-session=1%3ATEST');") (fmt "~%// ]]>~%")))) (deftest render-suggest-3 (with-request :get nil (let ((*weblocks-output-stream* (make-string-output-stream))) (declare (special *weblocks-output-stream*)) (render-suggest 'some-name (lambda (a) '("a" "b" "c")) :input-id 'i1 :choices-id 'c1)) (do-request `(("pure" . "true") (,weblocks::*action-string* . "abc123")))) "<ul><li>a</li><li>b</li><li>c</li></ul>") (deftest-html render-suggest-4 (with-request :get nil (render-suggest 'some-name '("a" "b" "c") :input-id 'i1 :choices-id 'c1 :default-value "b")) (htm (:select :id "I1" :name "some-name" (:option "a") (:option :selected "selected" "b") (:option "c")) (:script :type "text/javascript" (fmt "~%// <![CDATA[~%") (fmt "replaceDropdownWithSuggest(false, 'I1', 'some-name', 'C1', 'b');") (fmt "~%// ]]>~%")))) (deftest-html render-suggest-5 (with-request :get nil (render-suggest 'some-name (lambda (a) '("a" "b" "c")) :input-id 'i1 :choices-id 'c1 :default-value "test")) (htm (:input :type "text" :id "I1" :name "some-name" :class "suggest" :value "test" :maxlength "40") (:div :id "C1" :class "suggest" :style "display: none" "") (:script :type "text/javascript" (fmt "~%// <![CDATA[~%") (fmt "declareSuggest('I1', 'C1', 'abc123', 'weblocks-session=1%3ATEST');") (fmt "~%// ]]>~%")))) (deftest-html render-suggest-6 (with-request :get nil (render-suggest 'some-name '("a" "b" "c") :input-id 'i1 :choices-id 'c1 :default-value '("test" "b"))) (htm (:select :id "I1" :name "some-name" (:option "a") (:option :selected "selected" "b") (:option "c")) (:script :type "text/javascript" (fmt "~%// <![CDATA[~%") (fmt "replaceDropdownWithSuggest(false, 'I1', 'some-name', 'C1', 'test');") (fmt "~%// ]]>~%")))) (deftest-html render-suggest-7 (with-request :get nil (render-suggest 'some-name '("a" "b" "c") :input-id 'i1 :choices-id 'c1 :welcome-name (cons "foo" "bar"))) (htm (:select :id "I1" :name "some-name" (:option :value "bar" "[Select foo]") (:option "a") (:option "b") (:option "c")) (:script :type "text/javascript" (fmt "~%// <![CDATA[~%") (fmt "replaceDropdownWithSuggest(true, 'I1', 'some-name', 'C1');") (fmt "~%// ]]>~%")))) (deftest-html render-suggest-8 (with-request :get nil (make-request-ajax) (render-suggest 'some-name '("a" "b" "c") :input-id 'i1 :choices-id 'c1)) (htm (:input :type "text" :id "I1" :name "some-name" :class "suggest" :maxlength "40") (:div :id "C1" :class "suggest" :style "display: none" "") (:script :type "text/javascript" (fmt "~%// <![CDATA[~%") (fmt "declareSuggest('I1', 'C1', [\"a\",\"b\",\"c\"], 'weblocks-session=1%3ATEST');") (fmt "~%// ]]>~%")))) (deftest format-suggest-list-1 (weblocks::format-suggest-list '("a" "b" "c")) "<ul><li>a</li><li>b</li><li>c</li></ul>")
495759fbe93c41eefd2695262d43ead424bc968c78089bf60215a117011c64d5
S8A/htdp-exercises
ex146.rkt
The first three lines of this file were inserted by . They record metadata ;; about the language level of this file in a form that our tools can easily process. #reader(lib "htdp-beginner-reader.ss" "lang")((modname ex146) (read-case-sensitive #t) (teachpacks ((lib "image.rkt" "teachpack" "2htdp") (lib "universe.rkt" "teachpack" "2htdp") (lib "batch-io.rkt" "teachpack" "2htdp"))) (htdp-settings #(#t constructor repeating-decimal #f #t none #f ((lib "image.rkt" "teachpack" "2htdp") (lib "universe.rkt" "teachpack" "2htdp") (lib "batch-io.rkt" "teachpack" "2htdp")) #f))) An NEList - of - temperatures is one of : – ( cons CTemperature ' ( ) ) – ( cons CTemperature NEList - of - temperatures ) ; interpretation non-empty lists of Celsius temperatures NEList - of - temperatures - > Number ; computes the average of a non-empty list of temperatures (define (average alot) (/ (sum alot) (how-many alot))) (check-expect (average (cons 1 (cons 2 (cons 3 '())))) 2) (check-expect (average (cons 2 '())) 2) (check-expect (average (cons 1 (cons 2 '()))) 1.5) (check-expect (average (cons 3 (cons 2 '()))) 2.5) (check-expect (average (cons 0 (cons 3 (cons 2 '())))) 5/3) ; List-of-temperatures -> Number ; adds up the temperatures on the given list (define (sum ne-l) (cond [(empty? (rest ne-l)) (first ne-l)] [else (+ (first ne-l) (sum (rest ne-l)))])) (check-expect (sum (cons 1 (cons 2 (cons 3 '())))) 6) ; List-of-temperatures -> Number ; counts the temperatures on the given list (define (how-many alot) (cond [(empty? (rest alot)) 1] [(cons? (rest alot)) (+ 1 (how-many (rest alot)))])) (check-expect (how-many (cons 1 (cons 2 (cons 3 '())))) 3)
null
https://raw.githubusercontent.com/S8A/htdp-exercises/578e49834a9513f29ef81b7589b28081c5e0b69f/ex146.rkt
racket
about the language level of this file in a form that our tools can easily process. interpretation non-empty lists of Celsius temperatures computes the average of a non-empty list of temperatures List-of-temperatures -> Number adds up the temperatures on the given list List-of-temperatures -> Number counts the temperatures on the given list
The first three lines of this file were inserted by . They record metadata #reader(lib "htdp-beginner-reader.ss" "lang")((modname ex146) (read-case-sensitive #t) (teachpacks ((lib "image.rkt" "teachpack" "2htdp") (lib "universe.rkt" "teachpack" "2htdp") (lib "batch-io.rkt" "teachpack" "2htdp"))) (htdp-settings #(#t constructor repeating-decimal #f #t none #f ((lib "image.rkt" "teachpack" "2htdp") (lib "universe.rkt" "teachpack" "2htdp") (lib "batch-io.rkt" "teachpack" "2htdp")) #f))) An NEList - of - temperatures is one of : – ( cons CTemperature ' ( ) ) – ( cons CTemperature NEList - of - temperatures ) NEList - of - temperatures - > Number (define (average alot) (/ (sum alot) (how-many alot))) (check-expect (average (cons 1 (cons 2 (cons 3 '())))) 2) (check-expect (average (cons 2 '())) 2) (check-expect (average (cons 1 (cons 2 '()))) 1.5) (check-expect (average (cons 3 (cons 2 '()))) 2.5) (check-expect (average (cons 0 (cons 3 (cons 2 '())))) 5/3) (define (sum ne-l) (cond [(empty? (rest ne-l)) (first ne-l)] [else (+ (first ne-l) (sum (rest ne-l)))])) (check-expect (sum (cons 1 (cons 2 (cons 3 '())))) 6) (define (how-many alot) (cond [(empty? (rest alot)) 1] [(cons? (rest alot)) (+ 1 (how-many (rest alot)))])) (check-expect (how-many (cons 1 (cons 2 (cons 3 '())))) 3)
e72fc0630abc3546752d4fb2fa0e4cde98db969293c36eaefa0dd337ee6ddea5
pyr/cyanite
index.clj
(ns io.cyanite.index (:require [com.stuartsierra.component :as component] [clojure.string :refer [join split]] [clojure.set :refer [union intersection]] [globber.glob :refer [glob]])) (defprotocol MetricIndex (register! [this path]) (prefixes [this pattern]) (truncate! [this]) (multiplex-aggregates [this prefixes]) (extract-aggregate [this prefix])) ;; Path explansion / artificial aggreate paths ;; (defn make-pattern [aggregates] (re-pattern (str "(.*)(\\_)(" (join "|" aggregates) ")"))) (defn multiplex-aggregates-paths [aggregates paths] (mapcat (fn [path] (if (not (:expandable path)) (map #(assoc path :path (str (:path path) %) :text (str (:text path) %)) (cons "" (map #(str "_" %) aggregates))) [path])) paths)) (defn extract-aggregate-path [pattern path] (if-let [[_ extracted :as all] (re-matches pattern path)] [extracted (keyword (last all))] [path :default])) ;; Implementation ;; ============== ;; ;; We build an inverted index of segment to path ;; To service query we resolve and expand multiple ;; options (delimited in curly brackets) or multiple ;; characters (in a [] character class) then we dispatch ;; resolve our inverted index and filter on the result list ;; (defn- segmentize [path] (let [elems (split path #"\.")] (map-indexed vector elems))) (defn prefix-info [length [path matches]] (let [lengths (set (map second matches))] {:path path :text (last (split path #"\.")) :id path :allowChildren (if (some (partial < length) lengths) 1 0) :expandable (if (some (partial < length) lengths) 1 0) :leaf (if (boolean (lengths length)) 1 0)})) (defn truncate-to [pattern-length [path length]] [(join "." (take pattern-length (split path #"\."))) length]) (defn- push-segment* [segments segment path length] (into (sorted-map) (update segments segment (fn [paths tuple] (into (sorted-set) (conj paths tuple))) [path length]))) (defn- by-pos [db pos] (-> @db (get pos) keys)) (defn- by-segment [db pos segment] (get (get @db pos) segment)) (defn- by-segments [db pos segments] (mapcat (partial by-segment db pos) segments)) (defn- matches [db pattern leaves?] (let [segments (segmentize pattern) length (count segments) pred (partial (if leaves? = <=) length) matches (for [[pos pattern] segments] (->> (by-pos db pos) (glob pattern) (by-segments db pos) (filter (comp pred second)) (set))) paths (reduce union #{} matches)] (->> (reduce intersection paths matches) (map (partial truncate-to length)) (group-by first) (map (partial prefix-info length)) (sort-by :path)))) ;; ;; Indexes ;; (defrecord AtomIndex [options db aggregates pattern] component/Lifecycle (start [this] (let [aggregates (or (:aggregates options) [])] (assoc this :db (atom {}) :aggregates aggregates :pattern (make-pattern aggregates)))) (stop [this] (assoc this :db nil :aggregates nil :pattern nil)) MetricIndex (register! [this path] (let [segments (segmentize path) length (count segments)] (doseq [[pos segment] segments] (swap! db update pos push-segment* segment path length)))) (prefixes [index pattern] (matches db pattern false)) (truncate! [this] (reset! db {})) (multiplex-aggregates [this prefixes] (multiplex-aggregates-paths aggregates prefixes)) (extract-aggregate [this prefix] (extract-aggregate-path pattern prefix))) (defrecord EmptyIndex [] component/Lifecycle (start [this] this) (stop [this] this) MetricIndex (register! [this path]) (prefixes [index pattern])) (defmulti build-index (comp (fnil keyword "agent") :type)) (defmethod build-index :empty [options] (EmptyIndex.)) (defmethod build-index :atom [options] (map->AtomIndex options))
null
https://raw.githubusercontent.com/pyr/cyanite/2b9a1f26df808abdad3465dd1946036749b93000/src/io/cyanite/index.clj
clojure
Path explansion / artificial aggreate paths Implementation ============== We build an inverted index of segment to path To service query we resolve and expand multiple options (delimited in curly brackets) or multiple characters (in a [] character class) then we dispatch resolve our inverted index and filter on the result list Indexes
(ns io.cyanite.index (:require [com.stuartsierra.component :as component] [clojure.string :refer [join split]] [clojure.set :refer [union intersection]] [globber.glob :refer [glob]])) (defprotocol MetricIndex (register! [this path]) (prefixes [this pattern]) (truncate! [this]) (multiplex-aggregates [this prefixes]) (extract-aggregate [this prefix])) (defn make-pattern [aggregates] (re-pattern (str "(.*)(\\_)(" (join "|" aggregates) ")"))) (defn multiplex-aggregates-paths [aggregates paths] (mapcat (fn [path] (if (not (:expandable path)) (map #(assoc path :path (str (:path path) %) :text (str (:text path) %)) (cons "" (map #(str "_" %) aggregates))) [path])) paths)) (defn extract-aggregate-path [pattern path] (if-let [[_ extracted :as all] (re-matches pattern path)] [extracted (keyword (last all))] [path :default])) (defn- segmentize [path] (let [elems (split path #"\.")] (map-indexed vector elems))) (defn prefix-info [length [path matches]] (let [lengths (set (map second matches))] {:path path :text (last (split path #"\.")) :id path :allowChildren (if (some (partial < length) lengths) 1 0) :expandable (if (some (partial < length) lengths) 1 0) :leaf (if (boolean (lengths length)) 1 0)})) (defn truncate-to [pattern-length [path length]] [(join "." (take pattern-length (split path #"\."))) length]) (defn- push-segment* [segments segment path length] (into (sorted-map) (update segments segment (fn [paths tuple] (into (sorted-set) (conj paths tuple))) [path length]))) (defn- by-pos [db pos] (-> @db (get pos) keys)) (defn- by-segment [db pos segment] (get (get @db pos) segment)) (defn- by-segments [db pos segments] (mapcat (partial by-segment db pos) segments)) (defn- matches [db pattern leaves?] (let [segments (segmentize pattern) length (count segments) pred (partial (if leaves? = <=) length) matches (for [[pos pattern] segments] (->> (by-pos db pos) (glob pattern) (by-segments db pos) (filter (comp pred second)) (set))) paths (reduce union #{} matches)] (->> (reduce intersection paths matches) (map (partial truncate-to length)) (group-by first) (map (partial prefix-info length)) (sort-by :path)))) (defrecord AtomIndex [options db aggregates pattern] component/Lifecycle (start [this] (let [aggregates (or (:aggregates options) [])] (assoc this :db (atom {}) :aggregates aggregates :pattern (make-pattern aggregates)))) (stop [this] (assoc this :db nil :aggregates nil :pattern nil)) MetricIndex (register! [this path] (let [segments (segmentize path) length (count segments)] (doseq [[pos segment] segments] (swap! db update pos push-segment* segment path length)))) (prefixes [index pattern] (matches db pattern false)) (truncate! [this] (reset! db {})) (multiplex-aggregates [this prefixes] (multiplex-aggregates-paths aggregates prefixes)) (extract-aggregate [this prefix] (extract-aggregate-path pattern prefix))) (defrecord EmptyIndex [] component/Lifecycle (start [this] this) (stop [this] this) MetricIndex (register! [this path]) (prefixes [index pattern])) (defmulti build-index (comp (fnil keyword "agent") :type)) (defmethod build-index :empty [options] (EmptyIndex.)) (defmethod build-index :atom [options] (map->AtomIndex options))
757a8dffb192e1ba4776d835051eb79563aeb48fd54ba92ef73b2b56704c4b85
evilmartians/foundry
fy_ratio.ml
(***********************************************************************) (* *) (* Objective Caml *) (* *) , projet Cristal , INRIA Rocquencourt (* *) Copyright 1996 Institut National de Recherche en Informatique et en Automatique . All rights reserved . This file is distributed under the terms of the GNU Library General Public License , with (* the special exception on linking described in file ../../LICENSE. *) (* *) (***********************************************************************) open Fy_int_misc open Fy_nat open Fy_big_int open Fy_arith_flags (* Definition of the type ratio : Conventions : - the denominator is always a positive number - the sign of n/0 is the sign of n These convention is automatically respected when a ratio is created with the create_ratio primitive *) type ratio = { mutable numerator : big_int; mutable denominator : big_int; mutable normalized : bool} let failwith_zero name = let s = "infinite or undefined rational number" in failwith (if String.length name = 0 then s else name ^ " " ^ s) let numerator_ratio r = r.numerator and denominator_ratio r = r.denominator let null_denominator r = sign_big_int r.denominator = 0 let verify_null_denominator r = if sign_big_int r.denominator = 0 then (if !error_when_null_denominator_flag then (failwith_zero "") else true) else false let sign_ratio r = sign_big_int r.numerator (* Physical normalization of rational numbers *) 1/0 , 0/0 and -1/0 are the normalized forms for n/0 numbers let normalize_ratio r = if r.normalized then r else if verify_null_denominator r then begin r.numerator <- big_int_of_int (sign_big_int r.numerator); r.normalized <- true; r end else begin let p = gcd_big_int r.numerator r.denominator in if eq_big_int p unit_big_int then begin r.normalized <- true; r end else begin r.numerator <- div_big_int (r.numerator) p; r.denominator <- div_big_int (r.denominator) p; r.normalized <- true; r end end let cautious_normalize_ratio r = if (!normalize_ratio_flag) then (normalize_ratio r) else r let cautious_normalize_ratio_when_printing r = if (!normalize_ratio_when_printing_flag) then (normalize_ratio r) else r let create_ratio bi1 bi2 = match sign_big_int bi2 with -1 -> cautious_normalize_ratio { numerator = minus_big_int bi1; denominator = minus_big_int bi2; normalized = false } | 0 -> if !error_when_null_denominator_flag then (failwith_zero "create_ratio") else cautious_normalize_ratio { numerator = bi1; denominator = bi2; normalized = false } | _ -> cautious_normalize_ratio { numerator = bi1; denominator = bi2; normalized = false } let create_normalized_ratio bi1 bi2 = match sign_big_int bi2 with -1 -> { numerator = minus_big_int bi1; denominator = minus_big_int bi2; normalized = true } | 0 -> if !error_when_null_denominator_flag then failwith_zero "create_normalized_ratio" else { numerator = bi1; denominator = bi2; normalized = true } | _ -> { numerator = bi1; denominator = bi2; normalized = true } let is_normalized_ratio r = r.normalized let report_sign_ratio r bi = if sign_ratio r = -1 then minus_big_int bi else bi let abs_ratio r = { numerator = abs_big_int r.numerator; denominator = r.denominator; normalized = r.normalized } let is_integer_ratio r = eq_big_int ((normalize_ratio r).denominator) unit_big_int (* Operations on rational numbers *) let add_ratio r1 r2 = if !normalize_ratio_flag then begin let p = gcd_big_int ((normalize_ratio r1).denominator) ((normalize_ratio r2).denominator) in if eq_big_int p unit_big_int then {numerator = add_big_int (mult_big_int (r1.numerator) r2.denominator) (mult_big_int (r2.numerator) r1.denominator); denominator = mult_big_int (r1.denominator) r2.denominator; normalized = true} else begin let d1 = div_big_int (r1.denominator) p and d2 = div_big_int (r2.denominator) p in let n = add_big_int (mult_big_int (r1.numerator) d2) (mult_big_int d1 r2.numerator) in let p' = gcd_big_int n p in { numerator = div_big_int n p'; denominator = mult_big_int d1 (div_big_int (r2.denominator) p'); normalized = true } end end else { numerator = add_big_int (mult_big_int (r1.numerator) r2.denominator) (mult_big_int (r1.denominator) r2.numerator); denominator = mult_big_int (r1.denominator) r2.denominator; normalized = false } let minus_ratio r = { numerator = minus_big_int (r.numerator); denominator = r.denominator; normalized = r.normalized } let add_int_ratio i r = ignore (cautious_normalize_ratio r); { numerator = add_big_int (mult_int_big_int i r.denominator) r.numerator; denominator = r.denominator; normalized = r.normalized } let add_big_int_ratio bi r = ignore (cautious_normalize_ratio r); { numerator = add_big_int (mult_big_int bi r.denominator) r.numerator ; denominator = r.denominator; normalized = r.normalized } let sub_ratio r1 r2 = add_ratio r1 (minus_ratio r2) let mult_ratio r1 r2 = if !normalize_ratio_flag then begin let p1 = gcd_big_int ((normalize_ratio r1).numerator) ((normalize_ratio r2).denominator) and p2 = gcd_big_int (r2.numerator) r1.denominator in let (n1, d2) = if eq_big_int p1 unit_big_int then (r1.numerator, r2.denominator) else (div_big_int (r1.numerator) p1, div_big_int (r2.denominator) p1) and (n2, d1) = if eq_big_int p2 unit_big_int then (r2.numerator, r1.denominator) else (div_big_int r2.numerator p2, div_big_int r1.denominator p2) in { numerator = mult_big_int n1 n2; denominator = mult_big_int d1 d2; normalized = true } end else { numerator = mult_big_int (r1.numerator) r2.numerator; denominator = mult_big_int (r1.denominator) r2.denominator; normalized = false } let mult_int_ratio i r = if !normalize_ratio_flag then begin let p = gcd_big_int ((normalize_ratio r).denominator) (big_int_of_int i) in if eq_big_int p unit_big_int then { numerator = mult_big_int (big_int_of_int i) r.numerator; denominator = r.denominator; normalized = true } else { numerator = mult_big_int (div_big_int (big_int_of_int i) p) r.numerator; denominator = div_big_int (r.denominator) p; normalized = true } end else { numerator = mult_int_big_int i r.numerator; denominator = r.denominator; normalized = false } let mult_big_int_ratio bi r = if !normalize_ratio_flag then begin let p = gcd_big_int ((normalize_ratio r).denominator) bi in if eq_big_int p unit_big_int then { numerator = mult_big_int bi r.numerator; denominator = r.denominator; normalized = true } else { numerator = mult_big_int (div_big_int bi p) r.numerator; denominator = div_big_int (r.denominator) p; normalized = true } end else { numerator = mult_big_int bi r.numerator; denominator = r.denominator; normalized = false } let square_ratio r = ignore (cautious_normalize_ratio r); { numerator = square_big_int r.numerator; denominator = square_big_int r.denominator; normalized = r.normalized } let inverse_ratio r = if !error_when_null_denominator_flag && (sign_big_int r.numerator) = 0 then failwith_zero "inverse_ratio" else {numerator = report_sign_ratio r r.denominator; denominator = abs_big_int r.numerator; normalized = r.normalized} let div_ratio r1 r2 = mult_ratio r1 (inverse_ratio r2) Integer part of a rational number (* Odd function *) let integer_ratio r = if null_denominator r then failwith_zero "integer_ratio" else if sign_ratio r = 0 then zero_big_int else report_sign_ratio r (div_big_int (abs_big_int r.numerator) (abs_big_int r.denominator)) (* Floor of a rational number *) (* Always less or equal to r *) let floor_ratio r = ignore (verify_null_denominator r); div_big_int (r.numerator) r.denominator (* Round of a rational number *) Odd function , 1/2 - > 1 let round_ratio r = ignore (verify_null_denominator r); let abs_num = abs_big_int r.numerator in let bi = div_big_int abs_num r.denominator in report_sign_ratio r (if sign_big_int (sub_big_int (mult_int_big_int 2 (sub_big_int abs_num (mult_big_int (r.denominator) bi))) r.denominator) = -1 then bi else succ_big_int bi) let ceiling_ratio r = if (is_integer_ratio r) then r.numerator else succ_big_int (floor_ratio r) Comparison operators on rational numbers let eq_ratio r1 r2 = ignore (normalize_ratio r1); ignore (normalize_ratio r2); eq_big_int (r1.numerator) r2.numerator && eq_big_int (r1.denominator) r2.denominator let compare_ratio r1 r2 = if verify_null_denominator r1 then let sign_num_r1 = sign_big_int r1.numerator in if (verify_null_denominator r2) then let sign_num_r2 = sign_big_int r2.numerator in if sign_num_r1 = 1 && sign_num_r2 = -1 then 1 else if sign_num_r1 = -1 && sign_num_r2 = 1 then -1 else 0 else sign_num_r1 else if verify_null_denominator r2 then -(sign_big_int r2.numerator) else match compare_int (sign_big_int r1.numerator) (sign_big_int r2.numerator) with 1 -> 1 | -1 -> -1 | _ -> if eq_big_int (r1.denominator) r2.denominator then compare_big_int (r1.numerator) r2.numerator else compare_big_int (mult_big_int (r1.numerator) r2.denominator) (mult_big_int (r1.denominator) r2.numerator) let lt_ratio r1 r2 = compare_ratio r1 r2 < 0 and le_ratio r1 r2 = compare_ratio r1 r2 <= 0 and gt_ratio r1 r2 = compare_ratio r1 r2 > 0 and ge_ratio r1 r2 = compare_ratio r1 r2 >= 0 let max_ratio r1 r2 = if lt_ratio r1 r2 then r2 else r1 and min_ratio r1 r2 = if gt_ratio r1 r2 then r2 else r1 let eq_big_int_ratio bi r = (is_integer_ratio r) && eq_big_int bi r.numerator let compare_big_int_ratio bi r = ignore (normalize_ratio r); if (verify_null_denominator r) then -(sign_big_int r.numerator) else compare_big_int (mult_big_int bi r.denominator) r.numerator let lt_big_int_ratio bi r = compare_big_int_ratio bi r < 0 and le_big_int_ratio bi r = compare_big_int_ratio bi r <= 0 and gt_big_int_ratio bi r = compare_big_int_ratio bi r > 0 and ge_big_int_ratio bi r = compare_big_int_ratio bi r >= 0 Coercions (* Coercions with type int *) let int_of_ratio r = if ((is_integer_ratio r) && (is_int_big_int r.numerator)) then (int_of_big_int r.numerator) else failwith "integer argument required" and ratio_of_int i = { numerator = big_int_of_int i; denominator = unit_big_int; normalized = true } Coercions with type let ratio_of_nat nat = { numerator = big_int_of_nat nat; denominator = unit_big_int; normalized = true } and nat_of_ratio r = ignore (normalize_ratio r); if not (is_integer_ratio r) then failwith "nat_of_ratio" else if sign_big_int r.numerator > -1 then nat_of_big_int (r.numerator) else failwith "nat_of_ratio" (* Coercions with type big_int *) let ratio_of_big_int bi = { numerator = bi; denominator = unit_big_int; normalized = true } and big_int_of_ratio r = ignore (normalize_ratio r); if is_integer_ratio r then r.numerator else failwith "big_int_of_ratio" let div_int_ratio i r = ignore (verify_null_denominator r); mult_int_ratio i (inverse_ratio r) let div_ratio_int r i = div_ratio r (ratio_of_int i) let div_big_int_ratio bi r = ignore (verify_null_denominator r); mult_big_int_ratio bi (inverse_ratio r) let div_ratio_big_int r bi = div_ratio r (ratio_of_big_int bi) (* Functions on type string *) (* giving floating point approximations of rational numbers *) (* Compares strings that contains only digits, have the same length, from index i to index i + l *) let rec compare_num_string s1 s2 i len = if i >= len then 0 else let c1 = int_of_char s1.[i] and c2 = int_of_char s2.[i] in match compare_int c1 c2 with | 0 -> compare_num_string s1 s2 (succ i) len | c -> c;; (* Position of the leading digit of the decimal expansion *) (* of a strictly positive rational number *) (* if the decimal expansion of a non null rational r is equal to *) sigma for to N of then msd_ratio r = N (* Nota : for a big_int we have msd_ratio = nums_digits_big_int -1 *) Tests if s has only zeros characters from index i to index let rec only_zeros s i lim = i >= lim || s.[i] == '0' && only_zeros s (succ i) lim;; (* Nota : for a big_int we have msd_ratio = nums_digits_big_int -1 *) let msd_ratio r = ignore (cautious_normalize_ratio r); if null_denominator r then failwith_zero "msd_ratio" else if sign_big_int r.numerator == 0 then 0 else begin let str_num = string_of_big_int r.numerator and str_den = string_of_big_int r.denominator in let size_num = String.length str_num and size_den = String.length str_den in let size_min = min size_num size_den in let m = size_num - size_den in let cmp = compare_num_string str_num str_den 0 size_min in match cmp with | 1 -> m | -1 -> pred m | _ -> if m >= 0 then m else if only_zeros str_den size_min size_den then m else pred m end ;; (* Decimal approximations of rational numbers *) (* Approximation with fix decimal point *) (* This is an odd function and the last digit is round off *) Format integer_part . decimal_part_with_n_digits let approx_ratio_fix n r = (* Don't need to normalize *) if (null_denominator r) then failwith_zero "approx_ratio_fix" else let sign_r = sign_ratio r in if sign_r = 0 r = 0 else r.numerator and r.denominator are not null numbers s1 contains one more digit than desired for the round off operation s1 contains one more digit than desired for the round off operation *) if n >= 0 then begin let s1 = string_of_nat (nat_of_big_int (div_big_int (base_power_big_int 10 (succ n) (abs_big_int r.numerator)) r.denominator)) in Round up and add 1 in front if needed let s2 = if round_futur_last_digit s1 0 (String.length s1) then "1" ^ s1 else s1 in let l2 = String.length s2 - 1 in if s2 without last digit is xxxxyyy with n ' yyy ' digits : < sign > xxxx . yyy if s2 without last digit is yy with < = n digits : < sign > 0 . 0yy <sign> xxxx . yyy if s2 without last digit is yy with <= n digits: <sign> 0 . 0yy *) if l2 > n then begin let s = String.make (l2 + 2) '0' in String.set s 0 (if sign_r = -1 then '-' else '+'); String.blit s2 0 s 1 (l2 - n); String.set s (l2 - n + 1) '.'; String.blit s2 (l2 - n) s (l2 - n + 2) n; s end else begin let s = String.make (n + 3) '0' in String.set s 0 (if sign_r = -1 then '-' else '+'); String.set s 2 '.'; String.blit s2 0 s (n + 3 - l2) l2; s end end else begin (* Dubious; what is this code supposed to do? *) let s = string_of_big_int (div_big_int (abs_big_int r.numerator) (base_power_big_int 10 (-n) r.denominator)) in let len = succ (String.length s) in let s' = String.make len '0' in String.set s' 0 (if sign_r = -1 then '-' else '+'); String.blit s 0 s' 1 (pred len); s' end (* Number of digits of the decimal representation of an int *) let num_decimal_digits_int n = String.length (string_of_int n) (* Approximation with floating decimal point *) (* This is an odd function and the last digit is round off *) (* Format (+/-)(0. n_first_digits e msd)/(1. n_zeros e (msd+1) *) let approx_ratio_exp n r = (* Don't need to normalize *) if (null_denominator r) then failwith_zero "approx_ratio_exp" else if n <= 0 then invalid_arg "approx_ratio_exp" else let sign_r = sign_ratio r and i = ref (n + 3) in if sign_r = 0 then let s = String.make (n + 5) '0' in (String.blit "+0." 0 s 0 3); (String.blit "e0" 0 s !i 2); s else let msd = msd_ratio (abs_ratio r) in let k = n - msd in let s = (let nat = nat_of_big_int (if k < 0 then div_big_int (abs_big_int r.numerator) (base_power_big_int 10 (- k) r.denominator) else div_big_int (base_power_big_int 10 k (abs_big_int r.numerator)) r.denominator) in string_of_nat nat) in if (round_futur_last_digit s 0 (String.length s)) then let m = num_decimal_digits_int (succ msd) in let str = String.make (n + m + 4) '0' in (String.blit (if sign_r = -1 then "-1." else "+1.") 0 str 0 3); String.set str !i ('e'); incr i; (if m = 0 then String.set str !i '0' else String.blit (string_of_int (succ msd)) 0 str !i m); str else let m = num_decimal_digits_int (succ msd) and p = n + 3 in let str = String.make (succ (m + p)) '0' in (String.blit (if sign_r = -1 then "-0." else "+0.") 0 str 0 3); (String.blit s 0 str 3 n); String.set str p 'e'; (if m = 0 then String.set str (succ p) '0' else (String.blit (string_of_int (succ msd)) 0 str (succ p) m)); str (* String approximation of a rational with a fixed number of significant *) (* digits printed *) let float_of_rational_string r = let s = approx_ratio_exp !floating_precision r in if String.get s 0 = '+' then (String.sub s 1 (pred (String.length s))) else s (* Coercions with type string *) let string_of_ratio r = ignore (cautious_normalize_ratio_when_printing r); if !approx_printing_flag then float_of_rational_string r else string_of_big_int r.numerator ^ "/" ^ string_of_big_int r.denominator XL : j'ai puissamment simplifie " ratio_of_string " en virant la notation scientifique . scientifique. *) let ratio_of_string s = try let n = String.index s '/' in create_ratio (sys_big_int_of_string s 0 n) (sys_big_int_of_string s (n+1) (String.length s - n - 1)) with Not_found -> { numerator = big_int_of_string s; denominator = unit_big_int; normalized = true } (* Coercion with type float *) let float_of_ratio r = float_of_string (float_of_rational_string r) XL : suppression de ratio_of_float let power_ratio_positive_int r n = create_ratio (power_big_int_positive_int (r.numerator) n) (power_big_int_positive_int (r.denominator) n) let power_ratio_positive_big_int r bi = create_ratio (power_big_int_positive_big_int (r.numerator) bi) (power_big_int_positive_big_int (r.denominator) bi)
null
https://raw.githubusercontent.com/evilmartians/foundry/ce947c7dcca79ab7a7ce25870e9fc0eb15e9c2bd/vendor/ocaml-num/fy_ratio.ml
ocaml
********************************************************************* Objective Caml the special exception on linking described in file ../../LICENSE. ********************************************************************* Definition of the type ratio : Conventions : - the denominator is always a positive number - the sign of n/0 is the sign of n These convention is automatically respected when a ratio is created with the create_ratio primitive Physical normalization of rational numbers Operations on rational numbers Odd function Floor of a rational number Always less or equal to r Round of a rational number Coercions with type int Coercions with type big_int Functions on type string giving floating point approximations of rational numbers Compares strings that contains only digits, have the same length, from index i to index i + l Position of the leading digit of the decimal expansion of a strictly positive rational number if the decimal expansion of a non null rational r is equal to Nota : for a big_int we have msd_ratio = nums_digits_big_int -1 Nota : for a big_int we have msd_ratio = nums_digits_big_int -1 Decimal approximations of rational numbers Approximation with fix decimal point This is an odd function and the last digit is round off Don't need to normalize Dubious; what is this code supposed to do? Number of digits of the decimal representation of an int Approximation with floating decimal point This is an odd function and the last digit is round off Format (+/-)(0. n_first_digits e msd)/(1. n_zeros e (msd+1) Don't need to normalize String approximation of a rational with a fixed number of significant digits printed Coercions with type string Coercion with type float
, projet Cristal , INRIA Rocquencourt Copyright 1996 Institut National de Recherche en Informatique et en Automatique . All rights reserved . This file is distributed under the terms of the GNU Library General Public License , with open Fy_int_misc open Fy_nat open Fy_big_int open Fy_arith_flags type ratio = { mutable numerator : big_int; mutable denominator : big_int; mutable normalized : bool} let failwith_zero name = let s = "infinite or undefined rational number" in failwith (if String.length name = 0 then s else name ^ " " ^ s) let numerator_ratio r = r.numerator and denominator_ratio r = r.denominator let null_denominator r = sign_big_int r.denominator = 0 let verify_null_denominator r = if sign_big_int r.denominator = 0 then (if !error_when_null_denominator_flag then (failwith_zero "") else true) else false let sign_ratio r = sign_big_int r.numerator 1/0 , 0/0 and -1/0 are the normalized forms for n/0 numbers let normalize_ratio r = if r.normalized then r else if verify_null_denominator r then begin r.numerator <- big_int_of_int (sign_big_int r.numerator); r.normalized <- true; r end else begin let p = gcd_big_int r.numerator r.denominator in if eq_big_int p unit_big_int then begin r.normalized <- true; r end else begin r.numerator <- div_big_int (r.numerator) p; r.denominator <- div_big_int (r.denominator) p; r.normalized <- true; r end end let cautious_normalize_ratio r = if (!normalize_ratio_flag) then (normalize_ratio r) else r let cautious_normalize_ratio_when_printing r = if (!normalize_ratio_when_printing_flag) then (normalize_ratio r) else r let create_ratio bi1 bi2 = match sign_big_int bi2 with -1 -> cautious_normalize_ratio { numerator = minus_big_int bi1; denominator = minus_big_int bi2; normalized = false } | 0 -> if !error_when_null_denominator_flag then (failwith_zero "create_ratio") else cautious_normalize_ratio { numerator = bi1; denominator = bi2; normalized = false } | _ -> cautious_normalize_ratio { numerator = bi1; denominator = bi2; normalized = false } let create_normalized_ratio bi1 bi2 = match sign_big_int bi2 with -1 -> { numerator = minus_big_int bi1; denominator = minus_big_int bi2; normalized = true } | 0 -> if !error_when_null_denominator_flag then failwith_zero "create_normalized_ratio" else { numerator = bi1; denominator = bi2; normalized = true } | _ -> { numerator = bi1; denominator = bi2; normalized = true } let is_normalized_ratio r = r.normalized let report_sign_ratio r bi = if sign_ratio r = -1 then minus_big_int bi else bi let abs_ratio r = { numerator = abs_big_int r.numerator; denominator = r.denominator; normalized = r.normalized } let is_integer_ratio r = eq_big_int ((normalize_ratio r).denominator) unit_big_int let add_ratio r1 r2 = if !normalize_ratio_flag then begin let p = gcd_big_int ((normalize_ratio r1).denominator) ((normalize_ratio r2).denominator) in if eq_big_int p unit_big_int then {numerator = add_big_int (mult_big_int (r1.numerator) r2.denominator) (mult_big_int (r2.numerator) r1.denominator); denominator = mult_big_int (r1.denominator) r2.denominator; normalized = true} else begin let d1 = div_big_int (r1.denominator) p and d2 = div_big_int (r2.denominator) p in let n = add_big_int (mult_big_int (r1.numerator) d2) (mult_big_int d1 r2.numerator) in let p' = gcd_big_int n p in { numerator = div_big_int n p'; denominator = mult_big_int d1 (div_big_int (r2.denominator) p'); normalized = true } end end else { numerator = add_big_int (mult_big_int (r1.numerator) r2.denominator) (mult_big_int (r1.denominator) r2.numerator); denominator = mult_big_int (r1.denominator) r2.denominator; normalized = false } let minus_ratio r = { numerator = minus_big_int (r.numerator); denominator = r.denominator; normalized = r.normalized } let add_int_ratio i r = ignore (cautious_normalize_ratio r); { numerator = add_big_int (mult_int_big_int i r.denominator) r.numerator; denominator = r.denominator; normalized = r.normalized } let add_big_int_ratio bi r = ignore (cautious_normalize_ratio r); { numerator = add_big_int (mult_big_int bi r.denominator) r.numerator ; denominator = r.denominator; normalized = r.normalized } let sub_ratio r1 r2 = add_ratio r1 (minus_ratio r2) let mult_ratio r1 r2 = if !normalize_ratio_flag then begin let p1 = gcd_big_int ((normalize_ratio r1).numerator) ((normalize_ratio r2).denominator) and p2 = gcd_big_int (r2.numerator) r1.denominator in let (n1, d2) = if eq_big_int p1 unit_big_int then (r1.numerator, r2.denominator) else (div_big_int (r1.numerator) p1, div_big_int (r2.denominator) p1) and (n2, d1) = if eq_big_int p2 unit_big_int then (r2.numerator, r1.denominator) else (div_big_int r2.numerator p2, div_big_int r1.denominator p2) in { numerator = mult_big_int n1 n2; denominator = mult_big_int d1 d2; normalized = true } end else { numerator = mult_big_int (r1.numerator) r2.numerator; denominator = mult_big_int (r1.denominator) r2.denominator; normalized = false } let mult_int_ratio i r = if !normalize_ratio_flag then begin let p = gcd_big_int ((normalize_ratio r).denominator) (big_int_of_int i) in if eq_big_int p unit_big_int then { numerator = mult_big_int (big_int_of_int i) r.numerator; denominator = r.denominator; normalized = true } else { numerator = mult_big_int (div_big_int (big_int_of_int i) p) r.numerator; denominator = div_big_int (r.denominator) p; normalized = true } end else { numerator = mult_int_big_int i r.numerator; denominator = r.denominator; normalized = false } let mult_big_int_ratio bi r = if !normalize_ratio_flag then begin let p = gcd_big_int ((normalize_ratio r).denominator) bi in if eq_big_int p unit_big_int then { numerator = mult_big_int bi r.numerator; denominator = r.denominator; normalized = true } else { numerator = mult_big_int (div_big_int bi p) r.numerator; denominator = div_big_int (r.denominator) p; normalized = true } end else { numerator = mult_big_int bi r.numerator; denominator = r.denominator; normalized = false } let square_ratio r = ignore (cautious_normalize_ratio r); { numerator = square_big_int r.numerator; denominator = square_big_int r.denominator; normalized = r.normalized } let inverse_ratio r = if !error_when_null_denominator_flag && (sign_big_int r.numerator) = 0 then failwith_zero "inverse_ratio" else {numerator = report_sign_ratio r r.denominator; denominator = abs_big_int r.numerator; normalized = r.normalized} let div_ratio r1 r2 = mult_ratio r1 (inverse_ratio r2) Integer part of a rational number let integer_ratio r = if null_denominator r then failwith_zero "integer_ratio" else if sign_ratio r = 0 then zero_big_int else report_sign_ratio r (div_big_int (abs_big_int r.numerator) (abs_big_int r.denominator)) let floor_ratio r = ignore (verify_null_denominator r); div_big_int (r.numerator) r.denominator Odd function , 1/2 - > 1 let round_ratio r = ignore (verify_null_denominator r); let abs_num = abs_big_int r.numerator in let bi = div_big_int abs_num r.denominator in report_sign_ratio r (if sign_big_int (sub_big_int (mult_int_big_int 2 (sub_big_int abs_num (mult_big_int (r.denominator) bi))) r.denominator) = -1 then bi else succ_big_int bi) let ceiling_ratio r = if (is_integer_ratio r) then r.numerator else succ_big_int (floor_ratio r) Comparison operators on rational numbers let eq_ratio r1 r2 = ignore (normalize_ratio r1); ignore (normalize_ratio r2); eq_big_int (r1.numerator) r2.numerator && eq_big_int (r1.denominator) r2.denominator let compare_ratio r1 r2 = if verify_null_denominator r1 then let sign_num_r1 = sign_big_int r1.numerator in if (verify_null_denominator r2) then let sign_num_r2 = sign_big_int r2.numerator in if sign_num_r1 = 1 && sign_num_r2 = -1 then 1 else if sign_num_r1 = -1 && sign_num_r2 = 1 then -1 else 0 else sign_num_r1 else if verify_null_denominator r2 then -(sign_big_int r2.numerator) else match compare_int (sign_big_int r1.numerator) (sign_big_int r2.numerator) with 1 -> 1 | -1 -> -1 | _ -> if eq_big_int (r1.denominator) r2.denominator then compare_big_int (r1.numerator) r2.numerator else compare_big_int (mult_big_int (r1.numerator) r2.denominator) (mult_big_int (r1.denominator) r2.numerator) let lt_ratio r1 r2 = compare_ratio r1 r2 < 0 and le_ratio r1 r2 = compare_ratio r1 r2 <= 0 and gt_ratio r1 r2 = compare_ratio r1 r2 > 0 and ge_ratio r1 r2 = compare_ratio r1 r2 >= 0 let max_ratio r1 r2 = if lt_ratio r1 r2 then r2 else r1 and min_ratio r1 r2 = if gt_ratio r1 r2 then r2 else r1 let eq_big_int_ratio bi r = (is_integer_ratio r) && eq_big_int bi r.numerator let compare_big_int_ratio bi r = ignore (normalize_ratio r); if (verify_null_denominator r) then -(sign_big_int r.numerator) else compare_big_int (mult_big_int bi r.denominator) r.numerator let lt_big_int_ratio bi r = compare_big_int_ratio bi r < 0 and le_big_int_ratio bi r = compare_big_int_ratio bi r <= 0 and gt_big_int_ratio bi r = compare_big_int_ratio bi r > 0 and ge_big_int_ratio bi r = compare_big_int_ratio bi r >= 0 Coercions let int_of_ratio r = if ((is_integer_ratio r) && (is_int_big_int r.numerator)) then (int_of_big_int r.numerator) else failwith "integer argument required" and ratio_of_int i = { numerator = big_int_of_int i; denominator = unit_big_int; normalized = true } Coercions with type let ratio_of_nat nat = { numerator = big_int_of_nat nat; denominator = unit_big_int; normalized = true } and nat_of_ratio r = ignore (normalize_ratio r); if not (is_integer_ratio r) then failwith "nat_of_ratio" else if sign_big_int r.numerator > -1 then nat_of_big_int (r.numerator) else failwith "nat_of_ratio" let ratio_of_big_int bi = { numerator = bi; denominator = unit_big_int; normalized = true } and big_int_of_ratio r = ignore (normalize_ratio r); if is_integer_ratio r then r.numerator else failwith "big_int_of_ratio" let div_int_ratio i r = ignore (verify_null_denominator r); mult_int_ratio i (inverse_ratio r) let div_ratio_int r i = div_ratio r (ratio_of_int i) let div_big_int_ratio bi r = ignore (verify_null_denominator r); mult_big_int_ratio bi (inverse_ratio r) let div_ratio_big_int r bi = div_ratio r (ratio_of_big_int bi) let rec compare_num_string s1 s2 i len = if i >= len then 0 else let c1 = int_of_char s1.[i] and c2 = int_of_char s2.[i] in match compare_int c1 c2 with | 0 -> compare_num_string s1 s2 (succ i) len | c -> c;; sigma for to N of then msd_ratio r = N Tests if s has only zeros characters from index i to index let rec only_zeros s i lim = i >= lim || s.[i] == '0' && only_zeros s (succ i) lim;; let msd_ratio r = ignore (cautious_normalize_ratio r); if null_denominator r then failwith_zero "msd_ratio" else if sign_big_int r.numerator == 0 then 0 else begin let str_num = string_of_big_int r.numerator and str_den = string_of_big_int r.denominator in let size_num = String.length str_num and size_den = String.length str_den in let size_min = min size_num size_den in let m = size_num - size_den in let cmp = compare_num_string str_num str_den 0 size_min in match cmp with | 1 -> m | -1 -> pred m | _ -> if m >= 0 then m else if only_zeros str_den size_min size_den then m else pred m end ;; Format integer_part . decimal_part_with_n_digits let approx_ratio_fix n r = if (null_denominator r) then failwith_zero "approx_ratio_fix" else let sign_r = sign_ratio r in if sign_r = 0 r = 0 else r.numerator and r.denominator are not null numbers s1 contains one more digit than desired for the round off operation s1 contains one more digit than desired for the round off operation *) if n >= 0 then begin let s1 = string_of_nat (nat_of_big_int (div_big_int (base_power_big_int 10 (succ n) (abs_big_int r.numerator)) r.denominator)) in Round up and add 1 in front if needed let s2 = if round_futur_last_digit s1 0 (String.length s1) then "1" ^ s1 else s1 in let l2 = String.length s2 - 1 in if s2 without last digit is xxxxyyy with n ' yyy ' digits : < sign > xxxx . yyy if s2 without last digit is yy with < = n digits : < sign > 0 . 0yy <sign> xxxx . yyy if s2 without last digit is yy with <= n digits: <sign> 0 . 0yy *) if l2 > n then begin let s = String.make (l2 + 2) '0' in String.set s 0 (if sign_r = -1 then '-' else '+'); String.blit s2 0 s 1 (l2 - n); String.set s (l2 - n + 1) '.'; String.blit s2 (l2 - n) s (l2 - n + 2) n; s end else begin let s = String.make (n + 3) '0' in String.set s 0 (if sign_r = -1 then '-' else '+'); String.set s 2 '.'; String.blit s2 0 s (n + 3 - l2) l2; s end end else begin let s = string_of_big_int (div_big_int (abs_big_int r.numerator) (base_power_big_int 10 (-n) r.denominator)) in let len = succ (String.length s) in let s' = String.make len '0' in String.set s' 0 (if sign_r = -1 then '-' else '+'); String.blit s 0 s' 1 (pred len); s' end let num_decimal_digits_int n = String.length (string_of_int n) let approx_ratio_exp n r = if (null_denominator r) then failwith_zero "approx_ratio_exp" else if n <= 0 then invalid_arg "approx_ratio_exp" else let sign_r = sign_ratio r and i = ref (n + 3) in if sign_r = 0 then let s = String.make (n + 5) '0' in (String.blit "+0." 0 s 0 3); (String.blit "e0" 0 s !i 2); s else let msd = msd_ratio (abs_ratio r) in let k = n - msd in let s = (let nat = nat_of_big_int (if k < 0 then div_big_int (abs_big_int r.numerator) (base_power_big_int 10 (- k) r.denominator) else div_big_int (base_power_big_int 10 k (abs_big_int r.numerator)) r.denominator) in string_of_nat nat) in if (round_futur_last_digit s 0 (String.length s)) then let m = num_decimal_digits_int (succ msd) in let str = String.make (n + m + 4) '0' in (String.blit (if sign_r = -1 then "-1." else "+1.") 0 str 0 3); String.set str !i ('e'); incr i; (if m = 0 then String.set str !i '0' else String.blit (string_of_int (succ msd)) 0 str !i m); str else let m = num_decimal_digits_int (succ msd) and p = n + 3 in let str = String.make (succ (m + p)) '0' in (String.blit (if sign_r = -1 then "-0." else "+0.") 0 str 0 3); (String.blit s 0 str 3 n); String.set str p 'e'; (if m = 0 then String.set str (succ p) '0' else (String.blit (string_of_int (succ msd)) 0 str (succ p) m)); str let float_of_rational_string r = let s = approx_ratio_exp !floating_precision r in if String.get s 0 = '+' then (String.sub s 1 (pred (String.length s))) else s let string_of_ratio r = ignore (cautious_normalize_ratio_when_printing r); if !approx_printing_flag then float_of_rational_string r else string_of_big_int r.numerator ^ "/" ^ string_of_big_int r.denominator XL : j'ai puissamment simplifie " ratio_of_string " en virant la notation scientifique . scientifique. *) let ratio_of_string s = try let n = String.index s '/' in create_ratio (sys_big_int_of_string s 0 n) (sys_big_int_of_string s (n+1) (String.length s - n - 1)) with Not_found -> { numerator = big_int_of_string s; denominator = unit_big_int; normalized = true } let float_of_ratio r = float_of_string (float_of_rational_string r) XL : suppression de ratio_of_float let power_ratio_positive_int r n = create_ratio (power_big_int_positive_int (r.numerator) n) (power_big_int_positive_int (r.denominator) n) let power_ratio_positive_big_int r bi = create_ratio (power_big_int_positive_big_int (r.numerator) bi) (power_big_int_positive_big_int (r.denominator) bi)
837d249a0408f9126d8a2db7212348b6fe3b303edce60a64e2df3fd9ef5df35f
ocaml/ood
append.ml
[@@@part "0"] let usage_msg = "append [-verbose] <file1> [<file2>] ... -o <output>" [@@@part "1"] let verbose = ref false let input_files = ref [] let output_file = ref "" [@@@part "2"] let anon_fun filename = input_files := filename :: !input_files [@@@part "3"] let speclist = [ ("-verbose", Arg.Set verbose, "Output debug information"); ("-o", Arg.Set_string output_file, "Set output file name"); ] [@@@part "4"] let () = Arg.parse speclist anon_fun usage_msg (* Main functionality here *)
null
https://raw.githubusercontent.com/ocaml/ood/19e9548bbe22717cf465167ba08e8a539665dc3f/data/tutorials/en/examples/append.ml
ocaml
Main functionality here
[@@@part "0"] let usage_msg = "append [-verbose] <file1> [<file2>] ... -o <output>" [@@@part "1"] let verbose = ref false let input_files = ref [] let output_file = ref "" [@@@part "2"] let anon_fun filename = input_files := filename :: !input_files [@@@part "3"] let speclist = [ ("-verbose", Arg.Set verbose, "Output debug information"); ("-o", Arg.Set_string output_file, "Set output file name"); ] [@@@part "4"] let () = Arg.parse speclist anon_fun usage_msg
9077a93679c411624af67ef002ca61bc2f9588fce4ffbe3adc72c748d58df0fa
ekmett/ekmett.github.com
Cont.hs
{-# OPTIONS_GHC -fglasgow-exts #-} ------------------------------------------------------------------------------------------- -- | -- Module : Control.Monad.Indexed.Cont Copyright : 2008 , -- License : BSD -- Maintainer : < > -- Stability : experimental -- Portability : rank-2 Types required for correctness of shift, but they can be removed ------------------------------------------------------------------------------------------- module Control.Monad.Indexed.Cont ( IxMonadCont(reset, shift) , IxContT(IxContT, runIxContT) , runIxContT_ , IxCont(IxCont) , runIxCont , runIxCont_ ) where import Control.Applicative import Control.Functor.Pointed import Control.Monad.Trans import Control.Monad.Identity import Control.Monad.Indexed import Control.Monad.State import Control.Monad.Reader import Control.Monad.Indexed.Trans class IxMonad m => IxMonadCont m where reset :: m a o o -> m r r a shift :: (forall i. (a -> m i i o) -> m r j j) -> m r o a -- shift :: ((a -> m i i o) -> m r j j) -> m r o a newtype IxContT m r o a = IxContT { runIxContT :: (a -> m o) -> m r } runIxContT_ :: Monad m => IxContT m r a a -> m r runIxContT_ m = runIxContT m return instance IxFunctor (IxContT m) where imap f m = IxContT $ \c -> runIxContT m (c . f) instance IxPointed (IxContT m) where ireturn a = IxContT ($a) instance Monad m => IxApplicative (IxContT m) where iap = iapIxMonad instance Monad m => IxMonad (IxContT m) where ibind f c = IxContT $ \k -> runIxContT c $ \a -> runIxContT (f a) k instance Monad m => IxMonadCont (IxContT m) where reset e = IxContT $ \k -> runIxContT e return >>= k shift e = IxContT $ \k -> e (\a -> IxContT (\k' -> k a >>= k')) `runIxContT` return instance Monad m => Functor (IxContT m i j) where fmap = imap instance Monad m => Pointed (IxContT m i i) where point = ireturn instance Monad m => Applicative (IxContT m i i) where pure = ireturn (<*>) = iap instance Monad m => Monad (IxContT m i i) where return = ireturn m >>= k = ibind k m instance = > MonadCont ( IxContT m i i ) where -- callCC f = shift (\k -> f k >>>= k) instance IxMonadTrans IxContT where ilift m = IxContT (m >>=) instance MonadReader e m => MonadReader e (IxContT m i i) where ask = ilift ask local f m = IxContT $ \c -> do r <- ask local f (runIxContT m (local (const r) . c)) instance MonadState e m => MonadState e (IxContT m i i) where get = ilift get put = ilift . put instance MonadIO m => MonadIO (IxContT m i i) where liftIO = ilift . liftIO newtype IxCont r o a = IxCont (IxContT Identity r o a) deriving (IxFunctor, IxPointed, IxApplicative, IxMonad, IxMonadCont) runIxCont :: IxCont r o a -> (a -> o) -> r runIxCont (IxCont k) f = runIdentity $ runIxContT k (return . f) runIxCont_ :: IxCont r a a -> r runIxCont_ m = runIxCont m id instance MonadCont ( IxCont i i ) where -- callCC f = shift (\k -> f k >>>= k) instance Functor (IxCont i j) where fmap = imap instance Pointed (IxCont i i) where point = ireturn instance Applicative (IxCont i i) where pure = ireturn (<*>) = iap instance Monad (IxCont i i) where return = ireturn m >>= k = ibind k m
null
https://raw.githubusercontent.com/ekmett/ekmett.github.com/8d3abab5b66db631e148e1d046d18909bece5893/haskell/category-extras-backup/_darcs/pristine/src/Control/Monad/Indexed/Cont.hs
haskell
# OPTIONS_GHC -fglasgow-exts # ----------------------------------------------------------------------------------------- | Module : Control.Monad.Indexed.Cont License : BSD Stability : experimental Portability : rank-2 Types required for correctness of shift, but they can be removed ----------------------------------------------------------------------------------------- shift :: ((a -> m i i o) -> m r j j) -> m r o a callCC f = shift (\k -> f k >>>= k) callCC f = shift (\k -> f k >>>= k)
Copyright : 2008 , Maintainer : < > module Control.Monad.Indexed.Cont ( IxMonadCont(reset, shift) , IxContT(IxContT, runIxContT) , runIxContT_ , IxCont(IxCont) , runIxCont , runIxCont_ ) where import Control.Applicative import Control.Functor.Pointed import Control.Monad.Trans import Control.Monad.Identity import Control.Monad.Indexed import Control.Monad.State import Control.Monad.Reader import Control.Monad.Indexed.Trans class IxMonad m => IxMonadCont m where reset :: m a o o -> m r r a shift :: (forall i. (a -> m i i o) -> m r j j) -> m r o a newtype IxContT m r o a = IxContT { runIxContT :: (a -> m o) -> m r } runIxContT_ :: Monad m => IxContT m r a a -> m r runIxContT_ m = runIxContT m return instance IxFunctor (IxContT m) where imap f m = IxContT $ \c -> runIxContT m (c . f) instance IxPointed (IxContT m) where ireturn a = IxContT ($a) instance Monad m => IxApplicative (IxContT m) where iap = iapIxMonad instance Monad m => IxMonad (IxContT m) where ibind f c = IxContT $ \k -> runIxContT c $ \a -> runIxContT (f a) k instance Monad m => IxMonadCont (IxContT m) where reset e = IxContT $ \k -> runIxContT e return >>= k shift e = IxContT $ \k -> e (\a -> IxContT (\k' -> k a >>= k')) `runIxContT` return instance Monad m => Functor (IxContT m i j) where fmap = imap instance Monad m => Pointed (IxContT m i i) where point = ireturn instance Monad m => Applicative (IxContT m i i) where pure = ireturn (<*>) = iap instance Monad m => Monad (IxContT m i i) where return = ireturn m >>= k = ibind k m instance = > MonadCont ( IxContT m i i ) where instance IxMonadTrans IxContT where ilift m = IxContT (m >>=) instance MonadReader e m => MonadReader e (IxContT m i i) where ask = ilift ask local f m = IxContT $ \c -> do r <- ask local f (runIxContT m (local (const r) . c)) instance MonadState e m => MonadState e (IxContT m i i) where get = ilift get put = ilift . put instance MonadIO m => MonadIO (IxContT m i i) where liftIO = ilift . liftIO newtype IxCont r o a = IxCont (IxContT Identity r o a) deriving (IxFunctor, IxPointed, IxApplicative, IxMonad, IxMonadCont) runIxCont :: IxCont r o a -> (a -> o) -> r runIxCont (IxCont k) f = runIdentity $ runIxContT k (return . f) runIxCont_ :: IxCont r a a -> r runIxCont_ m = runIxCont m id instance MonadCont ( IxCont i i ) where instance Functor (IxCont i j) where fmap = imap instance Pointed (IxCont i i) where point = ireturn instance Applicative (IxCont i i) where pure = ireturn (<*>) = iap instance Monad (IxCont i i) where return = ireturn m >>= k = ibind k m
15d4e33430c52ed23ae79448bfe0ffa05f51698426f8e971f7c0ffcea8d5b06b
heshrobe/joshua-dist
clique-struct.lisp
-*- Mode : LISP ; Syntax : Common - Lisp ; Package : Ideal ; Base : 10 -*- (in-package :ideal) ;;;;******************************************************** Copyright ( c ) 1989 , 1992 Rockwell International -- All rights reserved . Rockwell International Science Center Palo Alto Lab ;;;;******************************************************** Sampath ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; (eval-when (:compile-toplevel :load-toplevel :execute) (export '(CLIQUE-NODE CLIQUE-NODE-NAME CLIQUE-NODE-PRINT-NAME CLIQUE-NODE-UNUSED-SLOT CLIQUE-NODE-COMPONENT-NODES CLIQUE-NODE-SEPERATOR-NODES CLIQUE-NODE-RESIDUAL-NODES))) ;-------------------------------------------------------- Clique node structures ;******************************* CLIQUE NODES: ************************** ;********************Structure, Access, Creation and all (defstruct (clique-node (:print-function print-clique-node)(:include node)) component-nodes residual-nodes seperator-nodes number-of-residual-states lambda-activator-nodes pi-activated-p) (store-ideal-struct-info (clique-node (:print-function print-clique-node)(:include node)) component-nodes residual-nodes seperator-nodes number-of-residual-states lambda-activator-nodes pi-activated-p) (defidealprintfn clique-node (print-clique-node (c-node st) (format st "#<CLIQUE ~A>" (clique-node-name c-node))))
null
https://raw.githubusercontent.com/heshrobe/joshua-dist/f59f06303f9fabef3e945a920cf9a26d9c2fd55e/ideal/code/clique-struct.lisp
lisp
Syntax : Common - Lisp ; Package : Ideal ; Base : 10 -*- ******************************************************** ******************************************************** ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; -------------------------------------------------------- ******************************* CLIQUE NODES: ************************** ********************Structure, Access, Creation and all
(in-package :ideal) Copyright ( c ) 1989 , 1992 Rockwell International -- All rights reserved . Rockwell International Science Center Palo Alto Lab (eval-when (:compile-toplevel :load-toplevel :execute) (export '(CLIQUE-NODE CLIQUE-NODE-NAME CLIQUE-NODE-PRINT-NAME CLIQUE-NODE-UNUSED-SLOT CLIQUE-NODE-COMPONENT-NODES CLIQUE-NODE-SEPERATOR-NODES CLIQUE-NODE-RESIDUAL-NODES))) Clique node structures (defstruct (clique-node (:print-function print-clique-node)(:include node)) component-nodes residual-nodes seperator-nodes number-of-residual-states lambda-activator-nodes pi-activated-p) (store-ideal-struct-info (clique-node (:print-function print-clique-node)(:include node)) component-nodes residual-nodes seperator-nodes number-of-residual-states lambda-activator-nodes pi-activated-p) (defidealprintfn clique-node (print-clique-node (c-node st) (format st "#<CLIQUE ~A>" (clique-node-name c-node))))
d3145a0f6edf131ec1b1ac043dbc4dc4ec9972d3042ea1558c7e65d3e70cdbb3
paurkedal/ocaml-cothrift
ppx_thrift_processor.ml
Copyright ( C ) 2016 < > * * This library is free software ; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation , either version 3 of the License , or ( at your * option ) any later version , with the 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 GNU Lesser General Public * License for more details . * * You should have received a copy of the GNU Lesser General Public License * along with this library . If not , see < / > . * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at your * option) any later version, with the 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 GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see </>. *) open Ast_helper open Ast_convenience open Asttypes open Location open Longident open Parsetree open Ppx_thrift_helper open Ppx_thrift_read open Ppx_thrift_write let processor_sig_of_module_type ~env pmtd = let loc = pmtd.pmtd_loc in let name = pmtd.pmtd_name in let funct_name = mkloc (name.txt ^ "_processor") name.loc in let arg_mty = Mty.ident (mkloc (Lident name.txt) name.loc) in let result_mty = Mty.with_ (Mty.ident (mkloc (Ldot (Lident "Thrift_sig", "Processor")) loc)) [Pwith_typesubst (Type.mk ~params:[[%type: 'a], Invariant] ~manifest:[%type: 'a io] (mknoloc "io"))] in let funct_mty = Mty.functor_ ~loc (mknoloc "X") (Some arg_mty) result_mty in Sig.module_ ~loc (Md.mk ~loc funct_name funct_mty) let extract_arguments t = let rec loop arg_fields = function | [%type: unit -> [%t? rt] io] -> (arg_fields, rt) | {ptyp_desc = Ptyp_arrow (label, at, rt)} -> let attrs = at.ptyp_attributes in let arg_field = Type.field ~attrs (mknoloc label) at in loop (arg_field :: arg_fields) rt | _ -> raise_errorf "RPC functions must be reducible to unit -> 'a io." in loop [] t let handler_of_signature_item ~env psig = match psig.psig_desc with | Psig_value pval -> let name = pval.pval_name in let common_handler arg_fields cont = let mk_arg pld = let arg_lid = mkloc (Lident pld.pld_name.txt) pld.pld_name.loc in (pld.pld_name.txt, Exp.ident arg_lid) in let func_name = mkloc (Ldot (Lident "X", name.txt)) name.loc in let struct_name = name.txt ^ "_args" in let call = Exp.apply (Exp.ident func_name) (List.map mk_arg arg_fields) in checked_reader_expr_of_record ~env ~struct_name arg_fields (cont call) in let arg_fields, result_type = extract_arguments pval.pval_type in let name_expr = ExpC.string ~loc:name.loc name.txt in begin match result_type with | [%type: unit] -> let is_oneway = false in (* TODO: Use it to complain. *) let handler = common_handler arg_fields (fun call -> call) in [%expr ([%e name_expr], Handler_unit ([%e ExpC.bool is_oneway], [%e handler]))] | _ -> let union_name = name.txt ^ "_result" in let result_writer = writer_expr_of_core_type ~env ~union_name result_type in let handler = if is_exception_variant result_type then let cont call = [%expr [%e call] () >>= fun r -> let is_exn = match r with `Ok _ -> false | _ -> true in return (is_exn, (fun () -> [%e result_writer] r)) ] in common_handler arg_fields cont else let cont call = [%expr [%e call] () >>= fun r -> let write_result () = write_struct_begin [%e ExpC.string union_name] >>= fun () -> [%e result_writer] r >>= fun () -> write_struct_end () in return (false, write_result) ] in common_handler arg_fields cont in [%expr ([%e name_expr], Handler [%e handler])] end | _ -> raise_errorf "Thrift interfaces may only contain values." let partial_arg_type_of_signature_item ~env psig = match psig.psig_desc with | Psig_value pval -> let arg_fields, result_type = extract_arguments pval.pval_type in let name = mkloc ("partial_" ^ pval.pval_name.txt ^ "_args") pval.pval_name.loc in Str.type_ [partial_type_of_record name arg_fields] | _ -> raise_errorf "Thrift interfaces may only contain values." let processor_str_of_module_type ~env pmtd = let loc = pmtd.pmtd_loc in match pmtd.pmtd_type with | Some {pmty_desc = Pmty_signature psigs} -> let name = pmtd.pmtd_name in let funct_name = mkloc (name.txt ^ "_processor") name.loc in let arg_mty = Mty.ident (mkloc (Lident name.txt) name.loc) in let result_mod = List.map (partial_arg_type_of_signature_item ~env) psigs @ [%str type handler = | Handler of (unit -> (bool * (unit -> unit Io.io)) Io.io) | Handler_unit of bool * (unit -> unit Io.io) let handlers = Hashtbl.create 11 let () = Array.iter (fun (k, v) -> Hashtbl.add handlers k v) [%e Exp.array (List.map (handler_of_signature_item ~env) psigs)] ] in let funct_mod = Mod.functor_ (mknoloc "X") (Some arg_mty) (Mod.structure result_mod) in Str.module_ ~loc (Mb.mk ~loc funct_name funct_mod) | Some _ -> raise_errorf "Can only derive thrift client from simple signatures." | None -> raise_errorf "Cannot derive thrift client without a signature."
null
https://raw.githubusercontent.com/paurkedal/ocaml-cothrift/4410e5123ec6b3769c0d046f1abf4a73e9b56a0f/ppx/ppx_thrift_processor.ml
ocaml
TODO: Use it to complain.
Copyright ( C ) 2016 < > * * This library is free software ; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation , either version 3 of the License , or ( at your * option ) any later version , with the 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 GNU Lesser General Public * License for more details . * * You should have received a copy of the GNU Lesser General Public License * along with this library . If not , see < / > . * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at your * option) any later version, with the 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 GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see </>. *) open Ast_helper open Ast_convenience open Asttypes open Location open Longident open Parsetree open Ppx_thrift_helper open Ppx_thrift_read open Ppx_thrift_write let processor_sig_of_module_type ~env pmtd = let loc = pmtd.pmtd_loc in let name = pmtd.pmtd_name in let funct_name = mkloc (name.txt ^ "_processor") name.loc in let arg_mty = Mty.ident (mkloc (Lident name.txt) name.loc) in let result_mty = Mty.with_ (Mty.ident (mkloc (Ldot (Lident "Thrift_sig", "Processor")) loc)) [Pwith_typesubst (Type.mk ~params:[[%type: 'a], Invariant] ~manifest:[%type: 'a io] (mknoloc "io"))] in let funct_mty = Mty.functor_ ~loc (mknoloc "X") (Some arg_mty) result_mty in Sig.module_ ~loc (Md.mk ~loc funct_name funct_mty) let extract_arguments t = let rec loop arg_fields = function | [%type: unit -> [%t? rt] io] -> (arg_fields, rt) | {ptyp_desc = Ptyp_arrow (label, at, rt)} -> let attrs = at.ptyp_attributes in let arg_field = Type.field ~attrs (mknoloc label) at in loop (arg_field :: arg_fields) rt | _ -> raise_errorf "RPC functions must be reducible to unit -> 'a io." in loop [] t let handler_of_signature_item ~env psig = match psig.psig_desc with | Psig_value pval -> let name = pval.pval_name in let common_handler arg_fields cont = let mk_arg pld = let arg_lid = mkloc (Lident pld.pld_name.txt) pld.pld_name.loc in (pld.pld_name.txt, Exp.ident arg_lid) in let func_name = mkloc (Ldot (Lident "X", name.txt)) name.loc in let struct_name = name.txt ^ "_args" in let call = Exp.apply (Exp.ident func_name) (List.map mk_arg arg_fields) in checked_reader_expr_of_record ~env ~struct_name arg_fields (cont call) in let arg_fields, result_type = extract_arguments pval.pval_type in let name_expr = ExpC.string ~loc:name.loc name.txt in begin match result_type with | [%type: unit] -> let handler = common_handler arg_fields (fun call -> call) in [%expr ([%e name_expr], Handler_unit ([%e ExpC.bool is_oneway], [%e handler]))] | _ -> let union_name = name.txt ^ "_result" in let result_writer = writer_expr_of_core_type ~env ~union_name result_type in let handler = if is_exception_variant result_type then let cont call = [%expr [%e call] () >>= fun r -> let is_exn = match r with `Ok _ -> false | _ -> true in return (is_exn, (fun () -> [%e result_writer] r)) ] in common_handler arg_fields cont else let cont call = [%expr [%e call] () >>= fun r -> let write_result () = write_struct_begin [%e ExpC.string union_name] >>= fun () -> [%e result_writer] r >>= fun () -> write_struct_end () in return (false, write_result) ] in common_handler arg_fields cont in [%expr ([%e name_expr], Handler [%e handler])] end | _ -> raise_errorf "Thrift interfaces may only contain values." let partial_arg_type_of_signature_item ~env psig = match psig.psig_desc with | Psig_value pval -> let arg_fields, result_type = extract_arguments pval.pval_type in let name = mkloc ("partial_" ^ pval.pval_name.txt ^ "_args") pval.pval_name.loc in Str.type_ [partial_type_of_record name arg_fields] | _ -> raise_errorf "Thrift interfaces may only contain values." let processor_str_of_module_type ~env pmtd = let loc = pmtd.pmtd_loc in match pmtd.pmtd_type with | Some {pmty_desc = Pmty_signature psigs} -> let name = pmtd.pmtd_name in let funct_name = mkloc (name.txt ^ "_processor") name.loc in let arg_mty = Mty.ident (mkloc (Lident name.txt) name.loc) in let result_mod = List.map (partial_arg_type_of_signature_item ~env) psigs @ [%str type handler = | Handler of (unit -> (bool * (unit -> unit Io.io)) Io.io) | Handler_unit of bool * (unit -> unit Io.io) let handlers = Hashtbl.create 11 let () = Array.iter (fun (k, v) -> Hashtbl.add handlers k v) [%e Exp.array (List.map (handler_of_signature_item ~env) psigs)] ] in let funct_mod = Mod.functor_ (mknoloc "X") (Some arg_mty) (Mod.structure result_mod) in Str.module_ ~loc (Mb.mk ~loc funct_name funct_mod) | Some _ -> raise_errorf "Can only derive thrift client from simple signatures." | None -> raise_errorf "Cannot derive thrift client without a signature."
05943f378c4b7df7e8958f86217ced3c738ffbf5fe60b2afbfb4e3ce14b023bd
camlunity/ocaml-react
test.ml
---------------------------------------------------------------------------- Copyright ( c ) % % COPYRIGHTYEAR%% , . All rights reserved . Distributed under a BSD license , see license at the end of the file . ---------------------------------------------------------------------------- Copyright (c) %%COPYRIGHTYEAR%%, Daniel C. Bünzli. All rights reserved. Distributed under a BSD license, see license at the end of the file. ----------------------------------------------------------------------------*) Tests for react 's combinators . Compile with -g to get a precise backtrace to the error . Note that the testing mechanism itself ( cf . and vals ) needs a correct implementation ; particulary w.r.t . updates with side effects . Compile with -g to get a precise backtrace to the error. Note that the testing mechanism itself (cf. occs and vals) needs a correct implementation; particulary w.r.t. updates with side effects. *) open React;; let pp_list ppv pp l = Format.fprintf pp "@[["; List.iter (fun v -> Format.fprintf pp "%a;@ " ppv v) l; Format.fprintf pp "]@]" let pr_value pp name v = Format.printf "@[<hov 2>%s =@ %a@]@." name pp v let e_pr ?iff pp name e = E.trace ?iff (pr_value pp name) e let s_pr ?iff pp name s = S.trace ?iff (pr_value pp name) s (* Tests the event e has occurences occs. *) let occs ?(eq = ( = )) e occs = let occs = ref occs in let assert_occ o = match !occs with | o' :: occs' when eq o' o -> occs := occs' | _ -> assert false in E.map assert_occ e, occs (* Tests the signal s goes through vals. *) let vals ?(eq = ( = )) s vals = let vals = ref vals in let assert_val v = match !vals with | v' :: vals' when eq v' v -> vals := vals' | _ -> assert false in S.map assert_val s, vals (* Tests that we went through all vals or occs *) let empty (_, r) = assert (!r = []) (* To initialize asserts of dynamic creations. *) let assert_e_stub () = ref (occs E.never []) let assert_s_stub v = ref (vals (S.const v) [v]) (* To keep references for the g.c. (warning also stops the given nodes) *) let keep_eref e = E.stop e let keep_sref s = S.stop s (* To artificially raise the rank of events and signals *) let high_e e = let id e = E.map (fun v -> v) e in (id (id (id (id (id (id (id (id e)))))))) let high_s s = let id s = S.map (fun v -> v) s in (id (id (id (id (id (id (id (id s)))))))) (* Event tests *) let test_no_leak () = let x, send_x = E.create () in let count = ref 0 in let w = let w = Weak.create 1 in let e = E.map (fun x -> incr count) x in Weak.set w 0 (Some e); w in List.iter send_x [0; 1; 2]; Gc.full_major (); List.iter send_x [3; 4; 5]; (match Weak.get w 0 with None -> () | Some _ -> assert false); if !count > 3 then assert false else () let test_once_drop_once () = let w, send_w = E.create () in let x = E.once w in let y = E.drop_once w in let assert_x = occs x [0] in let assert_y = occs y [1; 2; 3] in let assert_dx = assert_e_stub () in let assert_dy = assert_e_stub () in let dyn () = let dx = E.once w in let dy = E.drop_once w in assert_dx := occs dx [1]; assert_dy := occs dy [2; 3] in let create_dyn = E.map (fun v -> if v = 1 then dyn ()) w in Gc.full_major (); List.iter send_w [0; 1; 2; 3]; List.iter empty [assert_x; assert_y; !assert_dx; !assert_dy]; keep_eref create_dyn let test_app () = let f x y = x + y in let w, send_w = E.create () in let x = E.map (fun w -> f w) w in let y = E.drop_once w in let z = E.app x y in let assert_z = occs z [ 2; 4; 6 ] in let assert_dz = assert_e_stub () in let dyn () = let dx = E.drop_once (E.map (fun w -> f w) w) in let dz = E.app dx y in assert_dz := occs dz [ 4; 6 ]; in let create_dyn = E.map (fun v -> if v = 1 then dyn ()) w in Gc.full_major (); List.iter send_w [0; 1; 2; 3]; List.iter empty [assert_z; !assert_dz]; keep_eref create_dyn let test_map_stamp_filter_fmap () = let v, send_v = E.create () in let w = E.map (fun s -> "z:" ^ s) v in let x = E.stamp v "bla" in let y = E.filter (fun s -> String.length s = 5) v in let z = E.fmap (fun s -> if s = "blu" then Some "hip" else None) v in let assert_w = occs w ["z:didap"; "z:dip"; "z:didop"; "z:blu"] in let assert_x = occs x ["bla"; "bla"; "bla"; "bla"] in let assert_y = occs y ["didap"; "didop"] in let assert_z = occs z ["hip"] in let assert_dw = assert_e_stub () in let assert_dx = assert_e_stub () in let assert_dy = assert_e_stub () in let assert_dz = assert_e_stub () in let dyn () = let dw = E.map (fun s -> String.length s) v in let dx = E.stamp v 4 in let dy = E.filter (fun s -> String.length s = 5) v in let dz = E.fmap (fun s -> if s = "didap" then Some "ha" else None) v in let _ = E.map (fun _ -> assert false) (E.fmap (fun _ -> None) x) in assert_dw := occs dw [5; 3; 5; 3]; assert_dx := occs dx [4; 4; 4; 4]; assert_dy := occs dy ["didap"; "didop"]; assert_dz := occs dz ["ha"]; in let create_dyn = E.map (fun v -> if v = "didap" then dyn ()) v in Gc.full_major (); List.iter send_v ["didap"; "dip"; "didop"; "blu"]; List.iter empty [assert_w; assert_x; assert_y; assert_z]; List.iter empty [!assert_dw; !assert_dx]; List.iter empty [!assert_dy; !assert_dz]; keep_eref create_dyn let test_diff_changes () = let x, send_x = E.create () in let y = E.diff ( - ) x in let z = E.changes x in let assert_y = occs y [ 0; 1; 1; 0] in let assert_z = occs z [ 1; 2; 3] in let assert_dy = assert_e_stub () in let assert_dz = assert_e_stub () in let dyn () = let dy = E.diff ( - ) x in let dz = E.changes z in assert_dy := occs dy [1; 0]; assert_dz := occs dz [2; 3]; in let create_dyn = E.map (fun v -> if v = 2 then dyn ()) x in Gc.full_major (); List.iter send_x [1; 1; 2; 3; 3]; List.iter empty [assert_y; assert_z; !assert_dy; !assert_dz]; keep_eref create_dyn let test_dismiss () = let x, send_x = E.create () in let y = E.fmap (fun x -> if x mod 2 = 0 then Some x else None) x in let z = E.dismiss y x in let assert_z = occs z [1; 3; 5] in let assert_dz = assert_e_stub () in let dyn () = let dz = E.dismiss y x in assert_dz := occs dz [3; 5]; in let create_dyn = E.map (fun v -> if v = 2 then dyn()) x in Gc.full_major (); List.iter send_x [0; 1; 2; 3; 4; 5]; List.iter empty [assert_z; !assert_dz]; keep_eref create_dyn let test_when () = let e, send_e = E.create () in let s = S.hold 0 e in let c = S.map (fun x -> x mod 2 = 0) s in let w = E.when_ c e in let ovals = [2; 4; 4; 6; 4] in let assert_w = occs w ovals in let assert_dw = assert_e_stub () in let assert_dhw = assert_e_stub () in let dyn () = let dw = E.when_ c e in let dhw = E.when_ (high_s c) (high_e e) in assert_dw := occs dw ovals; assert_dhw := occs dhw ovals in let create_dyn = E.map (fun v -> if v = 2 then dyn ()) e in Gc.full_major (); List.iter send_e [ 1; 3; 1; 2; 4; 4; 6; 1; 3; 4 ]; List.iter empty [assert_w; !assert_dw; !assert_dhw ]; keep_eref create_dyn let test_until () = let x, send_x = E.create () in let stop = E.filter (fun v -> v = 3) x in let e = E.until stop x in let assert_e = occs e [1; 2] in let assert_de = assert_e_stub () in let assert_de' = assert_e_stub () in let dyn () = let de = E.until stop x in let de' = E.until (E.filter (fun v -> v = 5) x) x in assert_de := occs de []; assert_de' := occs de' [3; 4] in let create_dyn = E.map (fun v -> if v = 3 then dyn ()) x in Gc.full_major (); List.iter send_x [1; 2; 3; 4; 5]; List.iter empty [assert_e; !assert_de; !assert_de']; keep_eref create_dyn let test_accum () = let f, send_f = E.create () in let a = E.accum f 0 in let assert_a = occs a [2; -1; -2] in let assert_da = assert_e_stub () in let dyn () = let da = E.accum f 0 in assert_da := occs da [1; 2]; in let create_dyn = let count = ref 0 in E.map (fun _ -> incr count; if !count = 2 then dyn ()) f in Gc.full_major (); List.iter send_f [( + ) 2; ( - ) 1; ( * ) 2]; List.iter empty [assert_a; !assert_da]; keep_eref create_dyn let test_fold () = let x, send_x = E.create () in let c = E.fold ( + ) 0 x in let assert_c = occs c [1; 3; 6; 10] in let assert_dc = assert_e_stub () in let dyn () = let dc = E.fold ( + ) 0 x in assert_dc := occs dc [2; 5; 9]; in let create_dyn = E.map (fun v -> if v = 2 then dyn ()) x in Gc.full_major (); List.iter send_x [1; 2; 3; 4]; List.iter empty [assert_c; !assert_dc]; keep_eref create_dyn let test_select () = let w, send_w = E.create () in let x, send_x = E.create () in let y = E.map succ w in let z = E.map succ y in let tw = E.map (fun v -> `Int v) w in let tx = E.map (fun v -> `Bool v) x in let t = E.select [tw; tx] in let sy = E.select [y; z] in (* always y. *) always let assert_t = occs t [ `Int 0; `Bool false; `Int 1; `Int 2; `Int 3 ] in let assert_sy = occs sy [1; 2; 3; 4] in let assert_sz = occs sz [2; 3; 4; 5] in let assert_d = assert_e_stub () in let dyn () = let d = E.select [y; w; z] in assert_d := occs d [3; 4] in let create_dyn = E.map (fun v -> if v = 2 then dyn ()) w in Gc.full_major (); send_w 0; send_x false; List.iter send_w [1; 2; 3;]; empty assert_t; List.iter empty [assert_sy; assert_sz; !assert_d]; keep_eref create_dyn let test_merge () = let w, send_w = E.create () in let x, send_x = E.create () in let y = E.map succ w in let z = E.merge (fun acc v -> v :: acc) [] [w; x; y] in let assert_z = occs z [[2; 1]; [4]; [3; 2]] in let assert_dz = assert_e_stub () in let dyn () = let dz = E.merge (fun acc v -> v :: acc) [] [y; x; w] in assert_dz := occs dz [[4]; [2; 3]] in let create_dyn = E.map (fun v -> if v = 4 then dyn ()) x in Gc.full_major (); send_w 1; send_x 4; send_w 2; List.iter empty [assert_z; !assert_dz]; keep_eref create_dyn let test_switch () = let x, send_x = E.create () in let switch e = E.fmap (fun v -> if v mod 3 = 0 then Some (E.map (( * ) v) e) else None) x in let s = E.switch x (switch x) in let hs = E.switch x (switch (high_e x)) in let assert_s = occs s [1; 2; 9; 12; 15; 36; 42; 48; 81] in let assert_hs = occs hs [1; 2; 9; 12; 15; 36; 42; 48; 81] in let assert_ds = assert_e_stub () in let assert_dhs = assert_e_stub () in let dyn () = let ds = E.switch x (switch x) in let dhs = E.switch x (switch (high_e x)) in assert_ds := occs ds [9; 12; 15; 36; 42; 48; 81]; assert_ds := occs dhs [9; 12; 15; 36; 42; 48; 81] in let create_dyn = E.map (fun v -> if v = 3 then dyn ()) x in Gc.full_major (); List.iter send_x [1; 2; 3; 4; 5; 6; 7; 8; 9]; List.iter empty [assert_s; assert_hs; !assert_ds; !assert_dhs]; keep_eref create_dyn let test_fix () = let x, send_x = E.create () in let c1 () = E.stamp x `C2 in let c2 () = E.stamp x `C1 in let loop result = let switch = function `C1 -> c1 () | `C2 -> c2 () in let switcher = E.switch (c1 ()) (E.map switch result) in switcher, switcher in let l = E.fix loop in let assert_l = occs l [`C2; `C1; `C2] in let assert_dl = assert_e_stub () in let dyn () = let dl = E.fix loop in assert_dl := occs dl [`C2; `C1]; in let create_dyn = E.map (fun v -> if v = 2 then dyn ()) x in Gc.full_major (); List.iter send_x [1; 2; 3]; List.iter empty [assert_l; !assert_dl]; keep_eref create_dyn let test_events () = test_no_leak (); test_once_drop_once (); test_app (); test_map_stamp_filter_fmap (); test_diff_changes (); test_when (); test_dismiss (); test_until (); test_accum (); test_fold (); test_select (); test_merge (); test_switch (); test_fix () Signal tests let test_no_leak () = let x, set_x = S.create 0 in let count = ref 0 in let w = let w = Weak.create 1 in let e = S.map (fun x -> incr count) x in Weak.set w 0 (Some e); w in List.iter set_x [ 0; 1; 2]; Gc.full_major (); List.iter set_x [ 3; 4; 5]; (match Weak.get w 0 with None -> () | Some _ -> assert false); if !count > 3 then assert false else () let test_hold () = let e, send_e = E.create () in let e', send_e' = E.create () in let he = high_e e in let s = S.hold 1 e in let assert_s = vals s [1; 2; 3; 4] in let assert_ds = assert_s_stub 0 in let assert_dhs = assert_s_stub 0 in let assert_ds' = assert_s_stub 0 in let dyn () = let ds = S.hold 42 e in (* init value unused. *) let dhs = S.hold 44 he in (* init value unused. *) let ds' = S.hold 128 e' in (* init value used. *) assert_ds := vals ds [3; 4]; assert_dhs := vals dhs [3; 4]; assert_ds' := vals ds' [128; 2; 4] in let create_dyn = S.map (fun v -> if v = 3 then dyn ()) s in Gc.full_major (); List.iter send_e [ 1; 1; 1; 1; 2; 2; 2; 3; 3; 3]; List.iter send_e' [2; 4]; List.iter send_e [4; 4; 4]; List.iter empty [assert_s; !assert_ds; !assert_dhs; !assert_ds']; keep_sref create_dyn let test_app () = let f x y = x + y in let fl x y = S.app (S.app ~eq:(==) (S.const f) x) y in let x, set_x = S.create 0 in let y, set_y = S.create 0 in let z = fl x y in let assert_z = vals z [ 0; 1; 3; 4 ] in let assert_dz = assert_s_stub 0 in let assert_dhz = assert_s_stub 0 in let dyn () = let dz = fl x y in let dhz = fl (high_s x) (high_s y) in assert_dz := vals dz [3; 4]; assert_dhz := vals dhz [3; 4]; in let create_dyn = S.map (fun v -> if v = 2 then dyn ()) y in Gc.full_major (); set_x 1; set_y 2; set_x 1; set_y 3; List.iter empty [assert_z; !assert_dz; !assert_dhz]; keep_sref create_dyn let test_map_filter_fmap () = let even x = x mod 2 = 0 in let odd x = x mod 2 <> 0 in let meven x = if even x then Some (x * 2) else None in let modd x = if odd x then Some (x * 2) else None in let double x = 2 * x in let x, set_x = S.create 1 in let x2 = S.map double x in let fe = S.filter even 56 x in let fo = S.filter odd 56 x in let fme = S.fmap meven 7 x in let fmo = S.fmap modd 7 x in let assert_x2 = vals x2 [ 2; 4; 6; 8; 10] in let assert_fe = vals fe [ 56; 2; 4;] in let assert_fo = vals fo [ 1; 3; 5] in let assert_fme = vals fme [ 7; 4; 8;] in let assert_fmo = vals fmo [ 2; 6; 10;] in let assert_dx2 = assert_s_stub 0 in let assert_dhx2 = assert_s_stub 0 in let assert_dfe = assert_s_stub 0 in let assert_dhfe = assert_s_stub 0 in let assert_dfo = assert_s_stub 0 in let assert_dhfo = assert_s_stub 0 in let assert_dfme = assert_s_stub 0 in let assert_dhfme = assert_s_stub 0 in let assert_dfmo = assert_s_stub 0 in let assert_dhfmo = assert_s_stub 0 in let dyn () = let dx2 = S.map double x in let dhx2 = S.map double (high_s x) in let dfe = S.filter even 56 x in let dhfe = S.filter even 56 (high_s x) in let dfo = S.filter odd 56 x in let dhfo = S.filter odd 56 (high_s x) in let dfme = S.fmap meven 7 x in let dhfme = S.fmap meven 7 (high_s x) in let dfmo = S.fmap modd 7 x in let dhfmo = S.fmap modd 7 (high_s x) in assert_dx2 := vals dx2 [6; 8; 10]; assert_dhx2 := vals dhx2 [6; 8; 10]; assert_dfe := vals dfe [56; 4]; assert_dhfe := vals dhfe [56; 4]; assert_dfo := vals dfo [3; 5]; assert_dhfo := vals dhfo [3; 5]; assert_dfme := vals dfme [7; 8;]; assert_dhfme := vals dhfme [7; 8;]; assert_dfmo := vals dfmo [6; 10]; assert_dhfmo := vals dhfmo [6; 10]; () in let create_dyn = S.map (fun v -> if v = 3 then dyn ()) x in Gc.full_major (); List.iter set_x [ 1; 2; 3; 4; 4; 5; 5]; List.iter empty [assert_x2; assert_fe; assert_fo; assert_fme; assert_fmo; !assert_dx2; !assert_dhx2; !assert_dfe; !assert_dhfe; !assert_dfo ; !assert_dhfo; !assert_dfme ; !assert_dhfme ; !assert_dfmo ; !assert_dhfmo ]; keep_sref create_dyn let test_diff_changes () = let e, send_e = E.create () in let s = S.hold 1 e in let d = S.diff (fun x y -> x - y) s in let c = S.changes s in let assert_dd = assert_e_stub () in let assert_dhd = assert_e_stub () in let assert_dc = assert_e_stub () in let assert_dhc = assert_e_stub () in let dyn () = let dd = S.diff (fun x y -> x - y) s in let dhd = S.diff (fun x y -> x - y) (high_s s) in let dc = S.changes s in let dhc = S.changes (high_s s) in assert_dd := occs dd [1]; assert_dhd := occs dhd [1]; assert_dc := occs dc [4]; assert_dhc := occs dhc [4] in let create_dyn = S.map (fun v -> if v = 3 then dyn ()) s in let assert_d = occs d [2; 1] in let assert_c = occs c [3; 4] in Gc.full_major (); List.iter send_e [1; 1; 3; 3; 4; 4]; List.iter empty [assert_d; assert_c; !assert_dd; !assert_dhd; !assert_dc; !assert_dhc]; keep_sref create_dyn let test_sample () = let pair v v' = v, v' in let e, send_e = E.create () in let sampler () = E.filter (fun x -> x mod 2 = 0) e in let s = S.hold 0 e in let sam = S.sample pair (sampler ()) s in let ovals = [ (2, 2); (2, 2); (4, 4); (4, 4)] in let assert_sam = occs sam ovals in let assert_dsam = assert_e_stub () in let assert_dhsam = assert_e_stub () in let dyn () = let dsam = S.sample pair (sampler ()) s in let dhsam = S.sample pair (high_e (sampler ())) (high_s s) in assert_dsam := occs dsam ovals; assert_dhsam := occs dhsam ovals in let create_dyn = S.map (fun v -> if v = 2 then dyn ()) s in Gc.full_major (); List.iter send_e [1; 1; 2; 2; 3; 3; 4; 4]; List.iter empty [assert_sam; !assert_dsam; !assert_dhsam]; keep_sref create_dyn let test_when () = let s, set_s = S.create 0 in let ce = S.map (fun x -> x mod 2 = 0) s in let co = S.map (fun x -> x mod 2 <> 0) s in let se = S.when_ ce 42 s in let so = S.when_ co 56 s in let assert_se = vals se [ 0; 2; 4; 6; 4 ] in let assert_so = vals so [ 56; 1; 3; 1; 3 ] in let assert_dse = assert_s_stub 0 in let assert_dhse = assert_s_stub 0 in let assert_dso = assert_s_stub 0 in let assert_dhso = assert_s_stub 0 in let dyn () = let dse = S.when_ ce 42 s in let dhse = S.when_ ce 42 (high_s s) in let dso = S.when_ co 56 s in let dhso = S.when_ co 56 (high_s s) in assert_dse := vals dse [6; 4]; assert_dhse := vals dhse [6; 4]; assert_dso := vals dso [56; 1; 3]; assert_dhso := vals dhso [56; 1; 3 ] in let create_dyn = S.map (fun v -> if v = 6 then dyn ()) s in Gc.full_major (); List.iter set_s [ 1; 3; 1; 2; 4; 4; 6; 1; 3; 4 ]; List.iter empty [assert_se; assert_so; !assert_dse; !assert_dhse; !assert_dso; !assert_dhso]; keep_sref create_dyn let test_dismiss () = let x, send_x = E.create () in let y = E.fmap (fun x -> if x mod 2 = 0 then Some x else None) x in let z = S.dismiss y 4 (S.hold 44 x) in let assert_z = vals z [44; 1; 3; 5] in let assert_dz = assert_s_stub 0 in let dyn () = let dz = S.dismiss y 4 (S.hold 44 x) in assert_dz := vals dz [4; 3; 5]; in let create_dyn = E.map (fun v -> if v = 2 then dyn()) x in Gc.full_major (); List.iter send_x [0; 1; 2; 3; 4; 5]; List.iter empty [assert_z; !assert_dz]; keep_eref create_dyn let test_accum () = let f, send_f = E.create () in let a = S.accum f 0 in let assert_a = vals a [ 0; 2; -1; -2] in let assert_da = assert_s_stub 0 in let assert_dha = assert_s_stub 0 in let dyn () = let da = S.accum f 3 in let dha = S.accum (high_e f) 3 in assert_da := vals da [-2; -4]; assert_dha := vals dha [-2; -4] in let create_dyn = let count = ref 0 in E.map (fun _ -> incr count; if !count = 2 then dyn()) f in Gc.full_major (); List.iter send_f [( + ) 2; ( - ) 1; ( * ) 2]; List.iter empty [assert_a; !assert_da; !assert_dha]; keep_eref create_dyn let test_fold () = let x, send_x = E.create () in let c = S.fold ( + ) 0 x in let assert_c = vals c [ 0; 1; 3; 6; 10] in let assert_dc = assert_s_stub 0 in let assert_dhc = assert_s_stub 0 in let dyn () = let dc = S.fold ( + ) 2 x in let dhc = S.fold ( + ) 2 (high_e x) in assert_dc := vals dc [4; 7; 11]; assert_dhc := vals dhc [4; 7; 11] in let create_dyn = E.map (fun v -> if v = 2 then dyn ()) x in Gc.full_major (); List.iter send_x [1; 2; 3; 4]; List.iter empty [assert_c; !assert_dc; !assert_dhc ]; keep_eref create_dyn let test_merge () = let cons acc v = v :: acc in let w, set_w = S.create 0 in let x, set_x = S.create 1 in let y = S.map succ w in let z = S.map List.rev (S.merge cons [] [w; x; y]) in let assert_z = vals z [[0; 1; 1]; [1; 1; 2]; [1; 4; 2]; [2; 4; 3]] in let assert_dz = assert_s_stub [] in let assert_dhz = assert_s_stub [] in let dyn () = let dz = S.map List.rev (S.merge cons [] [w; x; y]) in let dhz = S.map List.rev (S.merge cons [] [(high_s w); x; y; S.const 2]) in assert_dz := vals dz [[1; 4; 2]; [2; 4; 3]]; assert_dhz := vals dhz [[1; 4; 2; 2]; [2; 4; 3; 2]] in let create_dyn = S.map (fun v -> if v = 4 then dyn ()) x in Gc.full_major (); set_w 1; set_x 4; set_w 2; set_w 2; List.iter empty [assert_z; !assert_dz; !assert_dhz]; keep_sref create_dyn let test_switch () = let x, send_x = E.create () in let s = S.hold 0 x in let switch s = E.fmap (fun v -> if v mod 3 = 0 then Some (S.map (( * ) v) s) else None) x in let sw = S.switch s (switch s) in let hsw = S.switch s (switch (high_s s)) in let assert_sw = vals sw [0; 1; 2; 9; 12; 15; 36; 42; 48; 81] in let assert_hsw = vals hsw [0; 1; 2; 9; 12; 15; 36; 42; 48; 81] in let assert_dsw = assert_s_stub 0 in let assert_dhsw = assert_s_stub 0 in let dyn () = let dsw = S.switch s (switch s) in let dhsw = S.switch s (switch (high_s s)) in assert_dsw := vals dsw [9; 12; 15; 36; 42; 48; 81]; assert_dhsw := vals dhsw [9; 12; 15; 36; 42; 48; 81]; in let create_dyn = E.map (fun v -> if v = 3 then dyn ()) x in Gc.full_major (); List.iter send_x [1; 1; 2; 2; 3; 4; 4; 5; 5; 6; 6; 7; 7; 8; 8; 9; 9]; List.iter empty [assert_sw; assert_hsw; !assert_dsw; !assert_dhsw]; keep_eref create_dyn let test_switch_const () = let x, send_x = E.create () in let switch = E.map (fun x -> S.const x) x in let sw = S.switch (S.const 0) switch in let assert_sw = vals sw [0; 1; 2; 3] in let assert_dsw = assert_s_stub 0 in let dyn () = let dsw = S.switch (S.const 0) switch in assert_dsw := vals dsw [2; 3]; in let create_dyn = E.map (fun v -> if v = 2 then dyn ()) x in Gc.full_major (); List.iter send_x [0; 1; 2; 3]; List.iter empty [assert_sw; !assert_dsw ]; keep_eref create_dyn let test_switch1 () = (* dynamic creation depends on triggering prim. *) let ex, send_x = E.create () in let x = S.hold 0 ex in let dcount = ref 0 in let assert_d1 = assert_s_stub 0 in let assert_d2 = assert_s_stub 0 in let assert_d3 = assert_s_stub 0 in let dyn v = let d = S.map (fun x -> v * x) x in begin match !dcount with | 0 -> assert_d1 := vals d [9; 12; 15; 18; 21; 24; 27] | 1 -> assert_d2 := vals d [36; 42; 48; 54] | 2 -> assert_d3 := vals d [81] | _ -> assert false end; incr dcount; d in let change x = if x mod 3 = 0 then Some (dyn x) else None in let s = S.switch x (E.fmap change (S.changes x)) in let assert_s = vals s [0; 1; 2; 9; 12; 15; 36; 42; 48; 81 ] in Gc.full_major (); List.iter send_x [1; 1; 2; 3; 3; 4; 5; 6; 6; 7; 8; 9; 9 ]; List.iter empty [assert_s; !assert_d1; !assert_d2; !assert_d3] let test_switch2 () = (* test_switch1 + high rank. *) let ex, send_x = E.create () in let x = S.hold 0 ex in let high_x = high_s x in let dcount = ref 0 in let assert_d1 = assert_s_stub 0 in let assert_d2 = assert_s_stub 0 in let assert_d3 = assert_s_stub 0 in let dyn v = let d = S.map (fun x -> v * x) high_x in begin match !dcount with | 0 -> assert_d1 := vals d [9; 12; 15; 18; 21; 24; 27] | 1 -> assert_d2 := vals d [36; 42; 48; 54] | 2 -> assert_d3 := vals d [81] | _ -> assert false end; incr dcount; d in let change x = if x mod 3 = 0 then Some (dyn x) else None in let s = S.switch x (E.fmap change (S.changes x)) in let assert_s = vals s [0; 1; 2; 9; 12; 15; 36; 42; 48; 81 ] in Gc.full_major (); List.iter send_x [1; 1; 2; 2; 3; 3; 4; 4; 5; 5; 6; 6; 7; 7; 8; 8; 9; 9]; List.iter empty [assert_s; !assert_d1; !assert_d2; !assert_d3] let test_switch3 () = (* dynamic creation does not depend on triggering prim. *) let ex, send_x = E.create () in let ey, send_y = E.create () in let x = S.hold 0 ex in let y = S.hold 0 ey in let dcount = ref 0 in let assert_d1 = assert_s_stub 0 in let assert_d2 = assert_s_stub 0 in let assert_d3 = assert_s_stub 0 in let dyn v = let d = S.map (fun y -> v * y) y in begin match !dcount with | 0 -> assert_d1 := vals d [6; 3; 6; 3; 6] | 1 -> assert_d2 := vals d [12; 6; 12] | 2 -> assert_d3 := vals d [18] | _ -> assert false end; incr dcount; d in let change x = if x mod 3 = 0 then Some (dyn x) else None in let s = S.switch y (E.fmap change (S.changes x)) in let assert_s = vals s [0; 1; 2; 6; 3; 6; 12; 6; 12; 18] in Gc.full_major (); List.iter send_y [1; 1; 2; 2]; List.iter send_x [1; 1; 2; 2; 3; 3]; List.iter send_y [1; 1; 2; 2]; List.iter send_x [4; 4; 5; 5; 6; 6]; List.iter send_y [1; 1; 2; 2]; List.iter send_x [7; 7; 8; 8; 9; 9]; List.iter empty [assert_s; !assert_d1; !assert_d2; !assert_d3] let test_switch4 () = (* test_switch3 + high rank. *) let ex, set_x = E.create () in let ey, set_y = E.create () in let x = S.hold 0 ex in let y = S.hold 0 ey in let dcount = ref 0 in let assert_d1 = assert_s_stub 0 in let assert_d2 = assert_s_stub 0 in let assert_d3 = assert_s_stub 0 in let dyn v = let d = S.map (fun y -> v * y) (high_s y) in begin match !dcount with | 0 -> assert_d1 := vals d [6; 3; 6; 3; 6] | 1 -> assert_d2 := vals d [12; 6; 12] | 2 -> assert_d3 := vals d [18] | _ -> assert false end; incr dcount; d in let change x = if x mod 3 = 0 then Some (dyn x) else None in let s = S.switch y (E.fmap change (S.changes x)) in let assert_s = vals s [0; 1; 2; 6; 3; 6; 12; 6; 12; 18] in Gc.full_major (); List.iter set_y [1; 1; 2; 2]; List.iter set_x [1; 1; 2; 2; 3; 3]; List.iter set_y [1; 1; 2; 2]; List.iter set_x [4; 4; 5; 5; 6; 6]; List.iter set_y [1; 1; 2; 2]; List.iter set_x [7; 7; 8; 8; 9; 9]; List.iter empty [assert_s; !assert_d1; !assert_d2; !assert_d3] let test_fix () = let s, set_s = S.create 0 in let history s = let push v = function | v' :: _ as l -> if v = v' then l else v :: l | [] -> [ v ] in let define h = let h' = S.l2 push s h in h', (h', S.map (fun x -> x) h) in S.fix [] define in let h, hm = history s in let assert_h = vals h [[0]; [1; 0;]; [2; 1; 0;]; [3; 2; 1; 0;]] in let assert_hm = vals hm [[0]; [1; 0;]; [2; 1; 0]; [3; 2; 1; 0;]] in let assert_dh = assert_s_stub [] in let assert_dhm = assert_s_stub [] in let assert_dhh = assert_s_stub [] in let assert_dhhm = assert_s_stub [] in let dyn () = let dh, dhm = history s in let dhh, dhhm = history (high_s s) in assert_dh := vals dh [[1]; [2; 1]; [3; 2; 1]]; assert_dhm := vals dhm [[]; [1]; [2; 1]; [3; 2; 1]]; assert_dhh := vals dhh [[1]; [2; 1]; [3; 2; 1]]; assert_dhhm := vals dhhm [[]; [1]; [2; 1]; [3; 2; 1]]; in let create_dyn = S.map (fun v -> if v = 1 then dyn ()) s in Gc.full_major (); List.iter set_s [0; 1; 1; 2; 3]; List.iter empty [assert_h; assert_hm; !assert_dh; !assert_dhm; !assert_dhh; !assert_dhhm]; keep_sref create_dyn let test_fix' () = let s, set_s = S.create 0 in let f, set_f = S.create 3 in let hs = high_s s in let assert_cs = assert_s_stub 0 in let assert_chs = assert_s_stub 0 in let assert_cdhs = assert_s_stub 0 in let assert_ss = assert_s_stub 0 in let assert_shs = assert_s_stub 0 in let assert_sdhs = assert_s_stub 0 in let assert_fs = assert_s_stub 0 in let assert_fhs = assert_s_stub 0 in let assert_fdhs = assert_s_stub 0 in let dyn () = let cs = S.fix 0 (fun h -> S.const 2, S.Int.( + ) h s) in let chs = S.fix 0 (fun h -> S.const 2, S.Int.( + ) h hs) in let cdhs = S.fix 0 (fun h -> S.const 2, S.Int.( + ) h (high_s s)) in let ss = S.fix 0 (fun h -> s, S.Int.( + ) h s) in let shs = S.fix 0 (fun h -> s, S.Int.( + ) h hs) in let sdhs = S.fix 0 (fun h -> s, S.Int.( + ) h (high_s s)) in let fs = S.fix 0 (fun h -> f, S.Int.( + ) h s) in let fhs = S.fix 0 (fun h -> f, S.Int.( + ) h hs) in let fdhs = S.fix 0 (fun h -> f, S.Int.( + ) h (high_s s)) in let cs_vals = [1; 3; 4; 5; ] in assert_cs := vals cs cs_vals; assert_chs := vals chs cs_vals; assert_cdhs := vals cdhs cs_vals; let ss_vals = [1; 2; 3; 4; 5; 6] in assert_ss := vals ss ss_vals; assert_shs := vals shs ss_vals; assert_sdhs := vals sdhs ss_vals; let fs_vals = [1; 4; 5; 6; 4 ] in assert_fs := vals fs fs_vals; assert_fhs := vals fhs fs_vals; assert_fdhs := vals fdhs fs_vals; in let create_dyn = S.map (fun v -> if v = 1 then dyn ()) s in Gc.full_major (); List.iter set_s [0; 1; 1; 2; 3]; List.iter set_f [1]; List.iter empty [!assert_cs; !assert_chs; !assert_cdhs; !assert_ss; !assert_shs; !assert_sdhs; !assert_fs; !assert_fhs; !assert_fdhs]; keep_sref create_dyn let test_lifters () = let f1 a = 1 + a in let f2 a0 a1 = a0 + a1 in let f3 a0 a1 a2 = a0 + a1 + a2 in let f4 a0 a1 a2 a3 = a0 + a1 + a2 + a3 in let f5 a0 a1 a2 a3 a4 = a0 + a1 + a2 + a3 + a4 in let f6 a0 a1 a2 a3 a4 a5 = a0 + a1 + a2 + a3 + a4 + a5 in let x, set_x = S.create 0 in let x1 = S.l1 f1 x in let x2 = S.l2 f2 x x1 in let x3 = S.l3 f3 x x1 x2 in let x4 = S.l4 f4 x x1 x2 x3 in let x5 = S.l5 f5 x x1 x2 x3 x4 in let x6 = S.l6 f6 x x1 x2 x3 x4 x5 in let a_x1 = vals x1 [1; 2] in let a_x2 = vals x2 [1; 3] in let a_x3 = vals x3 [2; 6] in let a_x4 = vals x4 [4; 12] in let a_x5 = vals x5 [8; 24] in let a_x6 = vals x6 [16; 48] in let a_dx1 = assert_s_stub 0 in let a_dx2 = assert_s_stub 0 in let a_dx3 = assert_s_stub 0 in let a_dx4 = assert_s_stub 0 in let a_dx5 = assert_s_stub 0 in let a_dx6 = assert_s_stub 0 in let dyn () = let dx1 = S.l1 f1 x in let dx2 = S.l2 f2 x x1 in let dx3 = S.l3 f3 x x1 x2 in let dx4 = S.l4 f4 x x1 x2 x3 in let dx5 = S.l5 f5 x x1 x2 x3 x4 in let dx6 = S.l6 f6 x x1 x2 x3 x4 x5 in a_dx1 := vals dx1 [2]; a_dx2 := vals dx2 [3]; a_dx3 := vals dx3 [6]; a_dx4 := vals dx4 [12]; a_dx5 := vals dx5 [24]; a_dx6 := vals dx6 [48] in let create_dyn = S.map (fun v -> if v = 1 then dyn ()) x in Gc.full_major (); List.iter set_x [0; 1]; List.iter empty [ a_x1; a_x2; a_x3; a_x4; a_x5; a_x6; !a_dx1; !a_dx2; !a_dx3; !a_dx4; !a_dx5; !a_dx6 ]; keep_sref create_dyn let test_signals () = test_no_leak (); test_hold (); test_app (); test_map_filter_fmap (); test_diff_changes (); test_sample (); test_when (); test_dismiss (); test_accum (); test_fold (); test_merge (); test_switch (); test_switch_const (); test_switch1 (); test_switch2 (); test_switch3 (); test_switch4 (); test_fix (); test_fix' (); test_lifters (); () (* bug fixes *) let test_jake_heap_bug () = Gc.full_major (); let id x = x in rank 0 let _ = S.map (fun x -> if x = 2 then Gc.full_major ()) a in let _ = let a1 = S.map id a in rank 2 rank 2 rank 2 in let _ = rank 1 rank 1 in rank 3 rank 4 let a_h = vals h [ 1; 5 ] in set_a 2; empty a_h let test_misc () = test_jake_heap_bug () let main () = test_events (); test_signals (); test_misc (); print_endline "All tests succeeded." let () = main () ---------------------------------------------------------------------------- Copyright ( c ) % % COPYRIGHTYEAR%% , 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 . Neither the name of the Daniel C. Bünzli nor the names of contributors may be used to endorse or promote products derived from this software without specific prior written permission . THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS " AND ANY EXPRESS OR 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 . ---------------------------------------------------------------------------- Copyright (c) %%COPYRIGHTYEAR%%, Daniel C. Bünzli 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. Neither the name of the Daniel C. Bünzli nor the names of contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR 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. ----------------------------------------------------------------------------*)
null
https://raw.githubusercontent.com/camlunity/ocaml-react/e492c3a508ec25c2c07622f155c3a2d5bb364dd1/test/test.ml
ocaml
Tests the event e has occurences occs. Tests the signal s goes through vals. Tests that we went through all vals or occs To initialize asserts of dynamic creations. To keep references for the g.c. (warning also stops the given nodes) To artificially raise the rank of events and signals Event tests always y. init value unused. init value unused. init value used. dynamic creation depends on triggering prim. test_switch1 + high rank. dynamic creation does not depend on triggering prim. test_switch3 + high rank. bug fixes
---------------------------------------------------------------------------- Copyright ( c ) % % COPYRIGHTYEAR%% , . All rights reserved . Distributed under a BSD license , see license at the end of the file . ---------------------------------------------------------------------------- Copyright (c) %%COPYRIGHTYEAR%%, Daniel C. Bünzli. All rights reserved. Distributed under a BSD license, see license at the end of the file. ----------------------------------------------------------------------------*) Tests for react 's combinators . Compile with -g to get a precise backtrace to the error . Note that the testing mechanism itself ( cf . and vals ) needs a correct implementation ; particulary w.r.t . updates with side effects . Compile with -g to get a precise backtrace to the error. Note that the testing mechanism itself (cf. occs and vals) needs a correct implementation; particulary w.r.t. updates with side effects. *) open React;; let pp_list ppv pp l = Format.fprintf pp "@[["; List.iter (fun v -> Format.fprintf pp "%a;@ " ppv v) l; Format.fprintf pp "]@]" let pr_value pp name v = Format.printf "@[<hov 2>%s =@ %a@]@." name pp v let e_pr ?iff pp name e = E.trace ?iff (pr_value pp name) e let s_pr ?iff pp name s = S.trace ?iff (pr_value pp name) s let occs ?(eq = ( = )) e occs = let occs = ref occs in let assert_occ o = match !occs with | o' :: occs' when eq o' o -> occs := occs' | _ -> assert false in E.map assert_occ e, occs let vals ?(eq = ( = )) s vals = let vals = ref vals in let assert_val v = match !vals with | v' :: vals' when eq v' v -> vals := vals' | _ -> assert false in S.map assert_val s, vals let empty (_, r) = assert (!r = []) let assert_e_stub () = ref (occs E.never []) let assert_s_stub v = ref (vals (S.const v) [v]) let keep_eref e = E.stop e let keep_sref s = S.stop s let high_e e = let id e = E.map (fun v -> v) e in (id (id (id (id (id (id (id (id e)))))))) let high_s s = let id s = S.map (fun v -> v) s in (id (id (id (id (id (id (id (id s)))))))) let test_no_leak () = let x, send_x = E.create () in let count = ref 0 in let w = let w = Weak.create 1 in let e = E.map (fun x -> incr count) x in Weak.set w 0 (Some e); w in List.iter send_x [0; 1; 2]; Gc.full_major (); List.iter send_x [3; 4; 5]; (match Weak.get w 0 with None -> () | Some _ -> assert false); if !count > 3 then assert false else () let test_once_drop_once () = let w, send_w = E.create () in let x = E.once w in let y = E.drop_once w in let assert_x = occs x [0] in let assert_y = occs y [1; 2; 3] in let assert_dx = assert_e_stub () in let assert_dy = assert_e_stub () in let dyn () = let dx = E.once w in let dy = E.drop_once w in assert_dx := occs dx [1]; assert_dy := occs dy [2; 3] in let create_dyn = E.map (fun v -> if v = 1 then dyn ()) w in Gc.full_major (); List.iter send_w [0; 1; 2; 3]; List.iter empty [assert_x; assert_y; !assert_dx; !assert_dy]; keep_eref create_dyn let test_app () = let f x y = x + y in let w, send_w = E.create () in let x = E.map (fun w -> f w) w in let y = E.drop_once w in let z = E.app x y in let assert_z = occs z [ 2; 4; 6 ] in let assert_dz = assert_e_stub () in let dyn () = let dx = E.drop_once (E.map (fun w -> f w) w) in let dz = E.app dx y in assert_dz := occs dz [ 4; 6 ]; in let create_dyn = E.map (fun v -> if v = 1 then dyn ()) w in Gc.full_major (); List.iter send_w [0; 1; 2; 3]; List.iter empty [assert_z; !assert_dz]; keep_eref create_dyn let test_map_stamp_filter_fmap () = let v, send_v = E.create () in let w = E.map (fun s -> "z:" ^ s) v in let x = E.stamp v "bla" in let y = E.filter (fun s -> String.length s = 5) v in let z = E.fmap (fun s -> if s = "blu" then Some "hip" else None) v in let assert_w = occs w ["z:didap"; "z:dip"; "z:didop"; "z:blu"] in let assert_x = occs x ["bla"; "bla"; "bla"; "bla"] in let assert_y = occs y ["didap"; "didop"] in let assert_z = occs z ["hip"] in let assert_dw = assert_e_stub () in let assert_dx = assert_e_stub () in let assert_dy = assert_e_stub () in let assert_dz = assert_e_stub () in let dyn () = let dw = E.map (fun s -> String.length s) v in let dx = E.stamp v 4 in let dy = E.filter (fun s -> String.length s = 5) v in let dz = E.fmap (fun s -> if s = "didap" then Some "ha" else None) v in let _ = E.map (fun _ -> assert false) (E.fmap (fun _ -> None) x) in assert_dw := occs dw [5; 3; 5; 3]; assert_dx := occs dx [4; 4; 4; 4]; assert_dy := occs dy ["didap"; "didop"]; assert_dz := occs dz ["ha"]; in let create_dyn = E.map (fun v -> if v = "didap" then dyn ()) v in Gc.full_major (); List.iter send_v ["didap"; "dip"; "didop"; "blu"]; List.iter empty [assert_w; assert_x; assert_y; assert_z]; List.iter empty [!assert_dw; !assert_dx]; List.iter empty [!assert_dy; !assert_dz]; keep_eref create_dyn let test_diff_changes () = let x, send_x = E.create () in let y = E.diff ( - ) x in let z = E.changes x in let assert_y = occs y [ 0; 1; 1; 0] in let assert_z = occs z [ 1; 2; 3] in let assert_dy = assert_e_stub () in let assert_dz = assert_e_stub () in let dyn () = let dy = E.diff ( - ) x in let dz = E.changes z in assert_dy := occs dy [1; 0]; assert_dz := occs dz [2; 3]; in let create_dyn = E.map (fun v -> if v = 2 then dyn ()) x in Gc.full_major (); List.iter send_x [1; 1; 2; 3; 3]; List.iter empty [assert_y; assert_z; !assert_dy; !assert_dz]; keep_eref create_dyn let test_dismiss () = let x, send_x = E.create () in let y = E.fmap (fun x -> if x mod 2 = 0 then Some x else None) x in let z = E.dismiss y x in let assert_z = occs z [1; 3; 5] in let assert_dz = assert_e_stub () in let dyn () = let dz = E.dismiss y x in assert_dz := occs dz [3; 5]; in let create_dyn = E.map (fun v -> if v = 2 then dyn()) x in Gc.full_major (); List.iter send_x [0; 1; 2; 3; 4; 5]; List.iter empty [assert_z; !assert_dz]; keep_eref create_dyn let test_when () = let e, send_e = E.create () in let s = S.hold 0 e in let c = S.map (fun x -> x mod 2 = 0) s in let w = E.when_ c e in let ovals = [2; 4; 4; 6; 4] in let assert_w = occs w ovals in let assert_dw = assert_e_stub () in let assert_dhw = assert_e_stub () in let dyn () = let dw = E.when_ c e in let dhw = E.when_ (high_s c) (high_e e) in assert_dw := occs dw ovals; assert_dhw := occs dhw ovals in let create_dyn = E.map (fun v -> if v = 2 then dyn ()) e in Gc.full_major (); List.iter send_e [ 1; 3; 1; 2; 4; 4; 6; 1; 3; 4 ]; List.iter empty [assert_w; !assert_dw; !assert_dhw ]; keep_eref create_dyn let test_until () = let x, send_x = E.create () in let stop = E.filter (fun v -> v = 3) x in let e = E.until stop x in let assert_e = occs e [1; 2] in let assert_de = assert_e_stub () in let assert_de' = assert_e_stub () in let dyn () = let de = E.until stop x in let de' = E.until (E.filter (fun v -> v = 5) x) x in assert_de := occs de []; assert_de' := occs de' [3; 4] in let create_dyn = E.map (fun v -> if v = 3 then dyn ()) x in Gc.full_major (); List.iter send_x [1; 2; 3; 4; 5]; List.iter empty [assert_e; !assert_de; !assert_de']; keep_eref create_dyn let test_accum () = let f, send_f = E.create () in let a = E.accum f 0 in let assert_a = occs a [2; -1; -2] in let assert_da = assert_e_stub () in let dyn () = let da = E.accum f 0 in assert_da := occs da [1; 2]; in let create_dyn = let count = ref 0 in E.map (fun _ -> incr count; if !count = 2 then dyn ()) f in Gc.full_major (); List.iter send_f [( + ) 2; ( - ) 1; ( * ) 2]; List.iter empty [assert_a; !assert_da]; keep_eref create_dyn let test_fold () = let x, send_x = E.create () in let c = E.fold ( + ) 0 x in let assert_c = occs c [1; 3; 6; 10] in let assert_dc = assert_e_stub () in let dyn () = let dc = E.fold ( + ) 0 x in assert_dc := occs dc [2; 5; 9]; in let create_dyn = E.map (fun v -> if v = 2 then dyn ()) x in Gc.full_major (); List.iter send_x [1; 2; 3; 4]; List.iter empty [assert_c; !assert_dc]; keep_eref create_dyn let test_select () = let w, send_w = E.create () in let x, send_x = E.create () in let y = E.map succ w in let z = E.map succ y in let tw = E.map (fun v -> `Int v) w in let tx = E.map (fun v -> `Bool v) x in let t = E.select [tw; tx] in always let assert_t = occs t [ `Int 0; `Bool false; `Int 1; `Int 2; `Int 3 ] in let assert_sy = occs sy [1; 2; 3; 4] in let assert_sz = occs sz [2; 3; 4; 5] in let assert_d = assert_e_stub () in let dyn () = let d = E.select [y; w; z] in assert_d := occs d [3; 4] in let create_dyn = E.map (fun v -> if v = 2 then dyn ()) w in Gc.full_major (); send_w 0; send_x false; List.iter send_w [1; 2; 3;]; empty assert_t; List.iter empty [assert_sy; assert_sz; !assert_d]; keep_eref create_dyn let test_merge () = let w, send_w = E.create () in let x, send_x = E.create () in let y = E.map succ w in let z = E.merge (fun acc v -> v :: acc) [] [w; x; y] in let assert_z = occs z [[2; 1]; [4]; [3; 2]] in let assert_dz = assert_e_stub () in let dyn () = let dz = E.merge (fun acc v -> v :: acc) [] [y; x; w] in assert_dz := occs dz [[4]; [2; 3]] in let create_dyn = E.map (fun v -> if v = 4 then dyn ()) x in Gc.full_major (); send_w 1; send_x 4; send_w 2; List.iter empty [assert_z; !assert_dz]; keep_eref create_dyn let test_switch () = let x, send_x = E.create () in let switch e = E.fmap (fun v -> if v mod 3 = 0 then Some (E.map (( * ) v) e) else None) x in let s = E.switch x (switch x) in let hs = E.switch x (switch (high_e x)) in let assert_s = occs s [1; 2; 9; 12; 15; 36; 42; 48; 81] in let assert_hs = occs hs [1; 2; 9; 12; 15; 36; 42; 48; 81] in let assert_ds = assert_e_stub () in let assert_dhs = assert_e_stub () in let dyn () = let ds = E.switch x (switch x) in let dhs = E.switch x (switch (high_e x)) in assert_ds := occs ds [9; 12; 15; 36; 42; 48; 81]; assert_ds := occs dhs [9; 12; 15; 36; 42; 48; 81] in let create_dyn = E.map (fun v -> if v = 3 then dyn ()) x in Gc.full_major (); List.iter send_x [1; 2; 3; 4; 5; 6; 7; 8; 9]; List.iter empty [assert_s; assert_hs; !assert_ds; !assert_dhs]; keep_eref create_dyn let test_fix () = let x, send_x = E.create () in let c1 () = E.stamp x `C2 in let c2 () = E.stamp x `C1 in let loop result = let switch = function `C1 -> c1 () | `C2 -> c2 () in let switcher = E.switch (c1 ()) (E.map switch result) in switcher, switcher in let l = E.fix loop in let assert_l = occs l [`C2; `C1; `C2] in let assert_dl = assert_e_stub () in let dyn () = let dl = E.fix loop in assert_dl := occs dl [`C2; `C1]; in let create_dyn = E.map (fun v -> if v = 2 then dyn ()) x in Gc.full_major (); List.iter send_x [1; 2; 3]; List.iter empty [assert_l; !assert_dl]; keep_eref create_dyn let test_events () = test_no_leak (); test_once_drop_once (); test_app (); test_map_stamp_filter_fmap (); test_diff_changes (); test_when (); test_dismiss (); test_until (); test_accum (); test_fold (); test_select (); test_merge (); test_switch (); test_fix () Signal tests let test_no_leak () = let x, set_x = S.create 0 in let count = ref 0 in let w = let w = Weak.create 1 in let e = S.map (fun x -> incr count) x in Weak.set w 0 (Some e); w in List.iter set_x [ 0; 1; 2]; Gc.full_major (); List.iter set_x [ 3; 4; 5]; (match Weak.get w 0 with None -> () | Some _ -> assert false); if !count > 3 then assert false else () let test_hold () = let e, send_e = E.create () in let e', send_e' = E.create () in let he = high_e e in let s = S.hold 1 e in let assert_s = vals s [1; 2; 3; 4] in let assert_ds = assert_s_stub 0 in let assert_dhs = assert_s_stub 0 in let assert_ds' = assert_s_stub 0 in let dyn () = assert_ds := vals ds [3; 4]; assert_dhs := vals dhs [3; 4]; assert_ds' := vals ds' [128; 2; 4] in let create_dyn = S.map (fun v -> if v = 3 then dyn ()) s in Gc.full_major (); List.iter send_e [ 1; 1; 1; 1; 2; 2; 2; 3; 3; 3]; List.iter send_e' [2; 4]; List.iter send_e [4; 4; 4]; List.iter empty [assert_s; !assert_ds; !assert_dhs; !assert_ds']; keep_sref create_dyn let test_app () = let f x y = x + y in let fl x y = S.app (S.app ~eq:(==) (S.const f) x) y in let x, set_x = S.create 0 in let y, set_y = S.create 0 in let z = fl x y in let assert_z = vals z [ 0; 1; 3; 4 ] in let assert_dz = assert_s_stub 0 in let assert_dhz = assert_s_stub 0 in let dyn () = let dz = fl x y in let dhz = fl (high_s x) (high_s y) in assert_dz := vals dz [3; 4]; assert_dhz := vals dhz [3; 4]; in let create_dyn = S.map (fun v -> if v = 2 then dyn ()) y in Gc.full_major (); set_x 1; set_y 2; set_x 1; set_y 3; List.iter empty [assert_z; !assert_dz; !assert_dhz]; keep_sref create_dyn let test_map_filter_fmap () = let even x = x mod 2 = 0 in let odd x = x mod 2 <> 0 in let meven x = if even x then Some (x * 2) else None in let modd x = if odd x then Some (x * 2) else None in let double x = 2 * x in let x, set_x = S.create 1 in let x2 = S.map double x in let fe = S.filter even 56 x in let fo = S.filter odd 56 x in let fme = S.fmap meven 7 x in let fmo = S.fmap modd 7 x in let assert_x2 = vals x2 [ 2; 4; 6; 8; 10] in let assert_fe = vals fe [ 56; 2; 4;] in let assert_fo = vals fo [ 1; 3; 5] in let assert_fme = vals fme [ 7; 4; 8;] in let assert_fmo = vals fmo [ 2; 6; 10;] in let assert_dx2 = assert_s_stub 0 in let assert_dhx2 = assert_s_stub 0 in let assert_dfe = assert_s_stub 0 in let assert_dhfe = assert_s_stub 0 in let assert_dfo = assert_s_stub 0 in let assert_dhfo = assert_s_stub 0 in let assert_dfme = assert_s_stub 0 in let assert_dhfme = assert_s_stub 0 in let assert_dfmo = assert_s_stub 0 in let assert_dhfmo = assert_s_stub 0 in let dyn () = let dx2 = S.map double x in let dhx2 = S.map double (high_s x) in let dfe = S.filter even 56 x in let dhfe = S.filter even 56 (high_s x) in let dfo = S.filter odd 56 x in let dhfo = S.filter odd 56 (high_s x) in let dfme = S.fmap meven 7 x in let dhfme = S.fmap meven 7 (high_s x) in let dfmo = S.fmap modd 7 x in let dhfmo = S.fmap modd 7 (high_s x) in assert_dx2 := vals dx2 [6; 8; 10]; assert_dhx2 := vals dhx2 [6; 8; 10]; assert_dfe := vals dfe [56; 4]; assert_dhfe := vals dhfe [56; 4]; assert_dfo := vals dfo [3; 5]; assert_dhfo := vals dhfo [3; 5]; assert_dfme := vals dfme [7; 8;]; assert_dhfme := vals dhfme [7; 8;]; assert_dfmo := vals dfmo [6; 10]; assert_dhfmo := vals dhfmo [6; 10]; () in let create_dyn = S.map (fun v -> if v = 3 then dyn ()) x in Gc.full_major (); List.iter set_x [ 1; 2; 3; 4; 4; 5; 5]; List.iter empty [assert_x2; assert_fe; assert_fo; assert_fme; assert_fmo; !assert_dx2; !assert_dhx2; !assert_dfe; !assert_dhfe; !assert_dfo ; !assert_dhfo; !assert_dfme ; !assert_dhfme ; !assert_dfmo ; !assert_dhfmo ]; keep_sref create_dyn let test_diff_changes () = let e, send_e = E.create () in let s = S.hold 1 e in let d = S.diff (fun x y -> x - y) s in let c = S.changes s in let assert_dd = assert_e_stub () in let assert_dhd = assert_e_stub () in let assert_dc = assert_e_stub () in let assert_dhc = assert_e_stub () in let dyn () = let dd = S.diff (fun x y -> x - y) s in let dhd = S.diff (fun x y -> x - y) (high_s s) in let dc = S.changes s in let dhc = S.changes (high_s s) in assert_dd := occs dd [1]; assert_dhd := occs dhd [1]; assert_dc := occs dc [4]; assert_dhc := occs dhc [4] in let create_dyn = S.map (fun v -> if v = 3 then dyn ()) s in let assert_d = occs d [2; 1] in let assert_c = occs c [3; 4] in Gc.full_major (); List.iter send_e [1; 1; 3; 3; 4; 4]; List.iter empty [assert_d; assert_c; !assert_dd; !assert_dhd; !assert_dc; !assert_dhc]; keep_sref create_dyn let test_sample () = let pair v v' = v, v' in let e, send_e = E.create () in let sampler () = E.filter (fun x -> x mod 2 = 0) e in let s = S.hold 0 e in let sam = S.sample pair (sampler ()) s in let ovals = [ (2, 2); (2, 2); (4, 4); (4, 4)] in let assert_sam = occs sam ovals in let assert_dsam = assert_e_stub () in let assert_dhsam = assert_e_stub () in let dyn () = let dsam = S.sample pair (sampler ()) s in let dhsam = S.sample pair (high_e (sampler ())) (high_s s) in assert_dsam := occs dsam ovals; assert_dhsam := occs dhsam ovals in let create_dyn = S.map (fun v -> if v = 2 then dyn ()) s in Gc.full_major (); List.iter send_e [1; 1; 2; 2; 3; 3; 4; 4]; List.iter empty [assert_sam; !assert_dsam; !assert_dhsam]; keep_sref create_dyn let test_when () = let s, set_s = S.create 0 in let ce = S.map (fun x -> x mod 2 = 0) s in let co = S.map (fun x -> x mod 2 <> 0) s in let se = S.when_ ce 42 s in let so = S.when_ co 56 s in let assert_se = vals se [ 0; 2; 4; 6; 4 ] in let assert_so = vals so [ 56; 1; 3; 1; 3 ] in let assert_dse = assert_s_stub 0 in let assert_dhse = assert_s_stub 0 in let assert_dso = assert_s_stub 0 in let assert_dhso = assert_s_stub 0 in let dyn () = let dse = S.when_ ce 42 s in let dhse = S.when_ ce 42 (high_s s) in let dso = S.when_ co 56 s in let dhso = S.when_ co 56 (high_s s) in assert_dse := vals dse [6; 4]; assert_dhse := vals dhse [6; 4]; assert_dso := vals dso [56; 1; 3]; assert_dhso := vals dhso [56; 1; 3 ] in let create_dyn = S.map (fun v -> if v = 6 then dyn ()) s in Gc.full_major (); List.iter set_s [ 1; 3; 1; 2; 4; 4; 6; 1; 3; 4 ]; List.iter empty [assert_se; assert_so; !assert_dse; !assert_dhse; !assert_dso; !assert_dhso]; keep_sref create_dyn let test_dismiss () = let x, send_x = E.create () in let y = E.fmap (fun x -> if x mod 2 = 0 then Some x else None) x in let z = S.dismiss y 4 (S.hold 44 x) in let assert_z = vals z [44; 1; 3; 5] in let assert_dz = assert_s_stub 0 in let dyn () = let dz = S.dismiss y 4 (S.hold 44 x) in assert_dz := vals dz [4; 3; 5]; in let create_dyn = E.map (fun v -> if v = 2 then dyn()) x in Gc.full_major (); List.iter send_x [0; 1; 2; 3; 4; 5]; List.iter empty [assert_z; !assert_dz]; keep_eref create_dyn let test_accum () = let f, send_f = E.create () in let a = S.accum f 0 in let assert_a = vals a [ 0; 2; -1; -2] in let assert_da = assert_s_stub 0 in let assert_dha = assert_s_stub 0 in let dyn () = let da = S.accum f 3 in let dha = S.accum (high_e f) 3 in assert_da := vals da [-2; -4]; assert_dha := vals dha [-2; -4] in let create_dyn = let count = ref 0 in E.map (fun _ -> incr count; if !count = 2 then dyn()) f in Gc.full_major (); List.iter send_f [( + ) 2; ( - ) 1; ( * ) 2]; List.iter empty [assert_a; !assert_da; !assert_dha]; keep_eref create_dyn let test_fold () = let x, send_x = E.create () in let c = S.fold ( + ) 0 x in let assert_c = vals c [ 0; 1; 3; 6; 10] in let assert_dc = assert_s_stub 0 in let assert_dhc = assert_s_stub 0 in let dyn () = let dc = S.fold ( + ) 2 x in let dhc = S.fold ( + ) 2 (high_e x) in assert_dc := vals dc [4; 7; 11]; assert_dhc := vals dhc [4; 7; 11] in let create_dyn = E.map (fun v -> if v = 2 then dyn ()) x in Gc.full_major (); List.iter send_x [1; 2; 3; 4]; List.iter empty [assert_c; !assert_dc; !assert_dhc ]; keep_eref create_dyn let test_merge () = let cons acc v = v :: acc in let w, set_w = S.create 0 in let x, set_x = S.create 1 in let y = S.map succ w in let z = S.map List.rev (S.merge cons [] [w; x; y]) in let assert_z = vals z [[0; 1; 1]; [1; 1; 2]; [1; 4; 2]; [2; 4; 3]] in let assert_dz = assert_s_stub [] in let assert_dhz = assert_s_stub [] in let dyn () = let dz = S.map List.rev (S.merge cons [] [w; x; y]) in let dhz = S.map List.rev (S.merge cons [] [(high_s w); x; y; S.const 2]) in assert_dz := vals dz [[1; 4; 2]; [2; 4; 3]]; assert_dhz := vals dhz [[1; 4; 2; 2]; [2; 4; 3; 2]] in let create_dyn = S.map (fun v -> if v = 4 then dyn ()) x in Gc.full_major (); set_w 1; set_x 4; set_w 2; set_w 2; List.iter empty [assert_z; !assert_dz; !assert_dhz]; keep_sref create_dyn let test_switch () = let x, send_x = E.create () in let s = S.hold 0 x in let switch s = E.fmap (fun v -> if v mod 3 = 0 then Some (S.map (( * ) v) s) else None) x in let sw = S.switch s (switch s) in let hsw = S.switch s (switch (high_s s)) in let assert_sw = vals sw [0; 1; 2; 9; 12; 15; 36; 42; 48; 81] in let assert_hsw = vals hsw [0; 1; 2; 9; 12; 15; 36; 42; 48; 81] in let assert_dsw = assert_s_stub 0 in let assert_dhsw = assert_s_stub 0 in let dyn () = let dsw = S.switch s (switch s) in let dhsw = S.switch s (switch (high_s s)) in assert_dsw := vals dsw [9; 12; 15; 36; 42; 48; 81]; assert_dhsw := vals dhsw [9; 12; 15; 36; 42; 48; 81]; in let create_dyn = E.map (fun v -> if v = 3 then dyn ()) x in Gc.full_major (); List.iter send_x [1; 1; 2; 2; 3; 4; 4; 5; 5; 6; 6; 7; 7; 8; 8; 9; 9]; List.iter empty [assert_sw; assert_hsw; !assert_dsw; !assert_dhsw]; keep_eref create_dyn let test_switch_const () = let x, send_x = E.create () in let switch = E.map (fun x -> S.const x) x in let sw = S.switch (S.const 0) switch in let assert_sw = vals sw [0; 1; 2; 3] in let assert_dsw = assert_s_stub 0 in let dyn () = let dsw = S.switch (S.const 0) switch in assert_dsw := vals dsw [2; 3]; in let create_dyn = E.map (fun v -> if v = 2 then dyn ()) x in Gc.full_major (); List.iter send_x [0; 1; 2; 3]; List.iter empty [assert_sw; !assert_dsw ]; keep_eref create_dyn let ex, send_x = E.create () in let x = S.hold 0 ex in let dcount = ref 0 in let assert_d1 = assert_s_stub 0 in let assert_d2 = assert_s_stub 0 in let assert_d3 = assert_s_stub 0 in let dyn v = let d = S.map (fun x -> v * x) x in begin match !dcount with | 0 -> assert_d1 := vals d [9; 12; 15; 18; 21; 24; 27] | 1 -> assert_d2 := vals d [36; 42; 48; 54] | 2 -> assert_d3 := vals d [81] | _ -> assert false end; incr dcount; d in let change x = if x mod 3 = 0 then Some (dyn x) else None in let s = S.switch x (E.fmap change (S.changes x)) in let assert_s = vals s [0; 1; 2; 9; 12; 15; 36; 42; 48; 81 ] in Gc.full_major (); List.iter send_x [1; 1; 2; 3; 3; 4; 5; 6; 6; 7; 8; 9; 9 ]; List.iter empty [assert_s; !assert_d1; !assert_d2; !assert_d3] let ex, send_x = E.create () in let x = S.hold 0 ex in let high_x = high_s x in let dcount = ref 0 in let assert_d1 = assert_s_stub 0 in let assert_d2 = assert_s_stub 0 in let assert_d3 = assert_s_stub 0 in let dyn v = let d = S.map (fun x -> v * x) high_x in begin match !dcount with | 0 -> assert_d1 := vals d [9; 12; 15; 18; 21; 24; 27] | 1 -> assert_d2 := vals d [36; 42; 48; 54] | 2 -> assert_d3 := vals d [81] | _ -> assert false end; incr dcount; d in let change x = if x mod 3 = 0 then Some (dyn x) else None in let s = S.switch x (E.fmap change (S.changes x)) in let assert_s = vals s [0; 1; 2; 9; 12; 15; 36; 42; 48; 81 ] in Gc.full_major (); List.iter send_x [1; 1; 2; 2; 3; 3; 4; 4; 5; 5; 6; 6; 7; 7; 8; 8; 9; 9]; List.iter empty [assert_s; !assert_d1; !assert_d2; !assert_d3] let ex, send_x = E.create () in let ey, send_y = E.create () in let x = S.hold 0 ex in let y = S.hold 0 ey in let dcount = ref 0 in let assert_d1 = assert_s_stub 0 in let assert_d2 = assert_s_stub 0 in let assert_d3 = assert_s_stub 0 in let dyn v = let d = S.map (fun y -> v * y) y in begin match !dcount with | 0 -> assert_d1 := vals d [6; 3; 6; 3; 6] | 1 -> assert_d2 := vals d [12; 6; 12] | 2 -> assert_d3 := vals d [18] | _ -> assert false end; incr dcount; d in let change x = if x mod 3 = 0 then Some (dyn x) else None in let s = S.switch y (E.fmap change (S.changes x)) in let assert_s = vals s [0; 1; 2; 6; 3; 6; 12; 6; 12; 18] in Gc.full_major (); List.iter send_y [1; 1; 2; 2]; List.iter send_x [1; 1; 2; 2; 3; 3]; List.iter send_y [1; 1; 2; 2]; List.iter send_x [4; 4; 5; 5; 6; 6]; List.iter send_y [1; 1; 2; 2]; List.iter send_x [7; 7; 8; 8; 9; 9]; List.iter empty [assert_s; !assert_d1; !assert_d2; !assert_d3] let ex, set_x = E.create () in let ey, set_y = E.create () in let x = S.hold 0 ex in let y = S.hold 0 ey in let dcount = ref 0 in let assert_d1 = assert_s_stub 0 in let assert_d2 = assert_s_stub 0 in let assert_d3 = assert_s_stub 0 in let dyn v = let d = S.map (fun y -> v * y) (high_s y) in begin match !dcount with | 0 -> assert_d1 := vals d [6; 3; 6; 3; 6] | 1 -> assert_d2 := vals d [12; 6; 12] | 2 -> assert_d3 := vals d [18] | _ -> assert false end; incr dcount; d in let change x = if x mod 3 = 0 then Some (dyn x) else None in let s = S.switch y (E.fmap change (S.changes x)) in let assert_s = vals s [0; 1; 2; 6; 3; 6; 12; 6; 12; 18] in Gc.full_major (); List.iter set_y [1; 1; 2; 2]; List.iter set_x [1; 1; 2; 2; 3; 3]; List.iter set_y [1; 1; 2; 2]; List.iter set_x [4; 4; 5; 5; 6; 6]; List.iter set_y [1; 1; 2; 2]; List.iter set_x [7; 7; 8; 8; 9; 9]; List.iter empty [assert_s; !assert_d1; !assert_d2; !assert_d3] let test_fix () = let s, set_s = S.create 0 in let history s = let push v = function | v' :: _ as l -> if v = v' then l else v :: l | [] -> [ v ] in let define h = let h' = S.l2 push s h in h', (h', S.map (fun x -> x) h) in S.fix [] define in let h, hm = history s in let assert_h = vals h [[0]; [1; 0;]; [2; 1; 0;]; [3; 2; 1; 0;]] in let assert_hm = vals hm [[0]; [1; 0;]; [2; 1; 0]; [3; 2; 1; 0;]] in let assert_dh = assert_s_stub [] in let assert_dhm = assert_s_stub [] in let assert_dhh = assert_s_stub [] in let assert_dhhm = assert_s_stub [] in let dyn () = let dh, dhm = history s in let dhh, dhhm = history (high_s s) in assert_dh := vals dh [[1]; [2; 1]; [3; 2; 1]]; assert_dhm := vals dhm [[]; [1]; [2; 1]; [3; 2; 1]]; assert_dhh := vals dhh [[1]; [2; 1]; [3; 2; 1]]; assert_dhhm := vals dhhm [[]; [1]; [2; 1]; [3; 2; 1]]; in let create_dyn = S.map (fun v -> if v = 1 then dyn ()) s in Gc.full_major (); List.iter set_s [0; 1; 1; 2; 3]; List.iter empty [assert_h; assert_hm; !assert_dh; !assert_dhm; !assert_dhh; !assert_dhhm]; keep_sref create_dyn let test_fix' () = let s, set_s = S.create 0 in let f, set_f = S.create 3 in let hs = high_s s in let assert_cs = assert_s_stub 0 in let assert_chs = assert_s_stub 0 in let assert_cdhs = assert_s_stub 0 in let assert_ss = assert_s_stub 0 in let assert_shs = assert_s_stub 0 in let assert_sdhs = assert_s_stub 0 in let assert_fs = assert_s_stub 0 in let assert_fhs = assert_s_stub 0 in let assert_fdhs = assert_s_stub 0 in let dyn () = let cs = S.fix 0 (fun h -> S.const 2, S.Int.( + ) h s) in let chs = S.fix 0 (fun h -> S.const 2, S.Int.( + ) h hs) in let cdhs = S.fix 0 (fun h -> S.const 2, S.Int.( + ) h (high_s s)) in let ss = S.fix 0 (fun h -> s, S.Int.( + ) h s) in let shs = S.fix 0 (fun h -> s, S.Int.( + ) h hs) in let sdhs = S.fix 0 (fun h -> s, S.Int.( + ) h (high_s s)) in let fs = S.fix 0 (fun h -> f, S.Int.( + ) h s) in let fhs = S.fix 0 (fun h -> f, S.Int.( + ) h hs) in let fdhs = S.fix 0 (fun h -> f, S.Int.( + ) h (high_s s)) in let cs_vals = [1; 3; 4; 5; ] in assert_cs := vals cs cs_vals; assert_chs := vals chs cs_vals; assert_cdhs := vals cdhs cs_vals; let ss_vals = [1; 2; 3; 4; 5; 6] in assert_ss := vals ss ss_vals; assert_shs := vals shs ss_vals; assert_sdhs := vals sdhs ss_vals; let fs_vals = [1; 4; 5; 6; 4 ] in assert_fs := vals fs fs_vals; assert_fhs := vals fhs fs_vals; assert_fdhs := vals fdhs fs_vals; in let create_dyn = S.map (fun v -> if v = 1 then dyn ()) s in Gc.full_major (); List.iter set_s [0; 1; 1; 2; 3]; List.iter set_f [1]; List.iter empty [!assert_cs; !assert_chs; !assert_cdhs; !assert_ss; !assert_shs; !assert_sdhs; !assert_fs; !assert_fhs; !assert_fdhs]; keep_sref create_dyn let test_lifters () = let f1 a = 1 + a in let f2 a0 a1 = a0 + a1 in let f3 a0 a1 a2 = a0 + a1 + a2 in let f4 a0 a1 a2 a3 = a0 + a1 + a2 + a3 in let f5 a0 a1 a2 a3 a4 = a0 + a1 + a2 + a3 + a4 in let f6 a0 a1 a2 a3 a4 a5 = a0 + a1 + a2 + a3 + a4 + a5 in let x, set_x = S.create 0 in let x1 = S.l1 f1 x in let x2 = S.l2 f2 x x1 in let x3 = S.l3 f3 x x1 x2 in let x4 = S.l4 f4 x x1 x2 x3 in let x5 = S.l5 f5 x x1 x2 x3 x4 in let x6 = S.l6 f6 x x1 x2 x3 x4 x5 in let a_x1 = vals x1 [1; 2] in let a_x2 = vals x2 [1; 3] in let a_x3 = vals x3 [2; 6] in let a_x4 = vals x4 [4; 12] in let a_x5 = vals x5 [8; 24] in let a_x6 = vals x6 [16; 48] in let a_dx1 = assert_s_stub 0 in let a_dx2 = assert_s_stub 0 in let a_dx3 = assert_s_stub 0 in let a_dx4 = assert_s_stub 0 in let a_dx5 = assert_s_stub 0 in let a_dx6 = assert_s_stub 0 in let dyn () = let dx1 = S.l1 f1 x in let dx2 = S.l2 f2 x x1 in let dx3 = S.l3 f3 x x1 x2 in let dx4 = S.l4 f4 x x1 x2 x3 in let dx5 = S.l5 f5 x x1 x2 x3 x4 in let dx6 = S.l6 f6 x x1 x2 x3 x4 x5 in a_dx1 := vals dx1 [2]; a_dx2 := vals dx2 [3]; a_dx3 := vals dx3 [6]; a_dx4 := vals dx4 [12]; a_dx5 := vals dx5 [24]; a_dx6 := vals dx6 [48] in let create_dyn = S.map (fun v -> if v = 1 then dyn ()) x in Gc.full_major (); List.iter set_x [0; 1]; List.iter empty [ a_x1; a_x2; a_x3; a_x4; a_x5; a_x6; !a_dx1; !a_dx2; !a_dx3; !a_dx4; !a_dx5; !a_dx6 ]; keep_sref create_dyn let test_signals () = test_no_leak (); test_hold (); test_app (); test_map_filter_fmap (); test_diff_changes (); test_sample (); test_when (); test_dismiss (); test_accum (); test_fold (); test_merge (); test_switch (); test_switch_const (); test_switch1 (); test_switch2 (); test_switch3 (); test_switch4 (); test_fix (); test_fix' (); test_lifters (); () let test_jake_heap_bug () = Gc.full_major (); let id x = x in rank 0 let _ = S.map (fun x -> if x = 2 then Gc.full_major ()) a in let _ = let a1 = S.map id a in rank 2 rank 2 rank 2 in let _ = rank 1 rank 1 in rank 3 rank 4 let a_h = vals h [ 1; 5 ] in set_a 2; empty a_h let test_misc () = test_jake_heap_bug () let main () = test_events (); test_signals (); test_misc (); print_endline "All tests succeeded." let () = main () ---------------------------------------------------------------------------- Copyright ( c ) % % COPYRIGHTYEAR%% , 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 . Neither the name of the Daniel C. Bünzli nor the names of contributors may be used to endorse or promote products derived from this software without specific prior written permission . THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS " AND ANY EXPRESS OR 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 . ---------------------------------------------------------------------------- Copyright (c) %%COPYRIGHTYEAR%%, Daniel C. Bünzli 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. Neither the name of the Daniel C. Bünzli nor the names of contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR 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. ----------------------------------------------------------------------------*)
9355e8f263ffb99e3ff3e4289e446dc941f10f49727362d7ccbd9c195080f02c
rmloveland/scheme48-0.53
c-primop.scm
Copyright ( c ) 1994 by . See file COPYING . Code generation for primops . (define-record-type c-primop :c-primop (make-c-primop simple? generate) c-primop? (simple? c-primop-simple?) (generate c-primop-generate)) (define (simple-c-primop? primop) (c-primop-simple? (primop-code-data primop))) (define (primop-generate-c primop call port indent) ((c-primop-generate (primop-code-data primop)) call port indent)) (define-syntax define-c-generator (lambda (exp r$ c$) (destructure (((ignore id simple? generate) exp)) `(set-primop-code-data! (,(r$ 'get-prescheme-primop) ',id) (,(r$ 'make-c-primop) ,simple? ,generate )))))
null
https://raw.githubusercontent.com/rmloveland/scheme48-0.53/1ae4531fac7150bd2af42d124da9b50dd1b89ec1/ps-compiler/prescheme/primop/c-primop.scm
scheme
Copyright ( c ) 1994 by . See file COPYING . Code generation for primops . (define-record-type c-primop :c-primop (make-c-primop simple? generate) c-primop? (simple? c-primop-simple?) (generate c-primop-generate)) (define (simple-c-primop? primop) (c-primop-simple? (primop-code-data primop))) (define (primop-generate-c primop call port indent) ((c-primop-generate (primop-code-data primop)) call port indent)) (define-syntax define-c-generator (lambda (exp r$ c$) (destructure (((ignore id simple? generate) exp)) `(set-primop-code-data! (,(r$ 'get-prescheme-primop) ',id) (,(r$ 'make-c-primop) ,simple? ,generate )))))
69554fc96a6e9066e1defc3a22d70452667c20c46ef6baaf6d1b3c23b91b1636
c-cube/jsonrpc2
jsonrpc2_core.ml
module J = Yojson.Safe type 'a printer = Format.formatter -> 'a -> unit type code = int let code_parse_error : code = (-32700) let code_invalid_request : code = (-32600) let code_method_not_found : code = (-32601) let code_invalid_param : code = (-32602) let code_internal_error : code = (-32603) let opt_map_ f = function None -> None | Some x -> Some (f x) * { 2 The protocol part , independent from IO and Transport } module Protocol : sig type json = J.t type t (** A jsonrpc2 connection. *) val create : unit -> t (** Create a state machine for Jsonrpc2 *) val clear : t -> unit (** Clear all internal state. *) module Id : sig type t val equal : t -> t -> bool val hash : t -> int val pp : t printer module Tbl : Hashtbl.S with type key = t end * { 3 Send requests and notifications to the other side } type message = json (** Message sent to the other side *) val error : t -> code -> string -> message val request : t -> meth:string -> params:json option -> message * Id.t (** Create a request message, for which an answer is expected. *) val notify : t -> meth:string -> params:json option -> message (** Create a notification message, ie. no response is expected. *) (** Actions to be done next. This includes sending messages out on the connection, calling a method, or finishing a local request. *) type action = | Send of message | Send_batch of message list | Start_call of (Id.t * string * json option) | Notify of string * json option | Fill_request of (Id.t * (json,int * string) result) | Error_without_id of int * string val process_msg : t -> message -> (action list, code*string) result (** Process incoming message *) val process_call_reply : t -> Id.t -> (json, string) result -> action list (** Send the response for the given call to the other side *) end = struct type json = J.t module Id = struct type t = | Int of int | String of string | Null let equal = (=) let hash = Hashtbl.hash let to_string = function | Int i -> string_of_int i | String s -> s | Null -> "null" let pp out id = Format.pp_print_string out (to_string id) let to_json = function | Int i -> `Int i | String s -> `String s | Null -> `Null module Tbl = Hashtbl.Make(struct type nonrec t = t let equal = equal let hash = hash end) end type message = json type to_reply = | TR_single | TR_batch of { mutable missing: int; mutable done_: message list; } type t = { mutable id_ : int; active: unit Id.Tbl.t; (* active requests *) to_reply: to_reply Id.Tbl.t; (* active calls to which we shall answer *) } let create () : t = { id_=0; active=Id.Tbl.create 24; to_reply=Id.Tbl.create 24; } let clear (self:t) : unit = self.id_ <- 0; Id.Tbl.clear self.active; Id.Tbl.clear self.to_reply (* Get a fresh ID for this connection *) let fresh_id_ (self:t) : Id.t = let i = self.id_ in self.id_ <- i + 1; Id.Int i (* Build the JSON message to send for the given {b request} *) let mk_request_ ~id ~meth ~params = let l = [ "method", `String meth; "jsonrpc", `String "2.0"; "id", Id.to_json id; ] in let l = match params with None -> l | Some x -> ("params",x) :: l in `Assoc l (* Build the JSON message to send for the given {b notification} *) let mk_notify_ ~meth ~params = let l = [ "method", `String meth; "jsonrpc", `String "2.0"; ] in let l = match params with None -> l | Some x -> ("params", x) :: l in `Assoc l (* Build a response message *) let mk_response (id:Id.t) msg : json = `Assoc [ "jsonrpc", `String "2.0"; "result", msg; "id", Id.to_json id; ] (* Build an error message *) let error_ _self ~id code msg : json = let l = [ "jsonrpc", `String "2.0"; "error", `Assoc [ "code", `Int code; "message", `String msg; ] ] in let l = match id with | None -> l | Some id -> ("id", Id.to_json id) :: l in `Assoc l let error self code msg = error_ ~id:None self code msg let request (self:t) ~meth ~params : message * Id.t = let id = fresh_id_ self in Id.Tbl.add self.active id (); let msg = mk_request_ ~id ~meth ~params in msg, id (* Notify the remote server *) let notify (_self:t) ~meth ~params : message = mk_notify_ ~meth ~params module P_ : sig type +'a t val return : 'a -> 'a t val fail : string -> _ t val is_list : bool t val (>>=) : 'a t -> ('a -> 'b t) -> 'b t val (>|=) : 'a t -> ('a -> 'b) -> 'b t val field : string -> 'a t -> 'a t val field_opt : string -> 'a t -> 'a option t val json : json t val one_of : string -> 'a t list -> 'a t val int : int t val string : string t val null : unit t val list : 'a t -> 'a list t val run : 'a t -> json -> ('a, string lazy_t) result end = struct type +'a t = json -> ('a, (string * json) list) result let return x _ = Ok x let error_ ?(ctx=[]) j e = Error ((e,j)::ctx) let errorf_ ?ctx j fmt = Printf.ksprintf (error_ ?ctx j) fmt let fail s j = Error [s,j] let (>>=) x f j = match x j with | Ok x -> f x j | Error e -> Error e let (>|=) x f j = match x j with | Ok x -> Ok (f x) | Error e -> Error e let json j = Ok j let is_list = function `List _ -> Ok true | _ -> Ok false let int = function | `Int i -> Ok i | `String s as j -> (try Ok (int_of_string s) with _ -> errorf_ j "expected int") | j -> error_ j "expected int" let string = function | `Int i -> Ok (string_of_int i) | `String s -> Ok s | j -> error_ j "expected string" let null = function `Null -> Ok () | j -> error_ j "expected null" let field name f : _ t = function | `Assoc l as j -> (match List.assoc name l with | x -> f x | exception Not_found -> errorf_ j "no field '%s' found in object" name) | j -> error_ j "expected object" let field_opt name f : _ t = function | `Assoc l -> (match List.assoc name l with | x -> (match f x with Ok x -> Ok (Some x) | Error e -> Error e) | exception Not_found -> Ok None) | j -> error_ j "expected object" let rec one_of what l j = match l with | [] -> errorf_ j "expected %s, none matched the given list" what | x :: tl -> match x j with | Ok x -> Ok x | Error _ -> one_of what tl j let list f : _ t = function | `List l -> let rec aux acc = function | [] -> Ok (List.rev acc) | x :: tl -> match f x with | Error ctx -> error_ ~ctx x "in list" | Ok x -> aux (x::acc) tl in aux [] l | j -> error_ j "expected list" let run (p:_ t) (j:json) : _ result = match p j with | Ok x -> Ok x | Error l -> let msg = lazy ( String.concat "\n" @@ List.rev_map (fun (e,j) -> e ^ " in " ^ J.to_string j) l ) in Error msg end type incoming = | I_error of Id.t * code * string | I_request of Id.t * string * json option | I_notify of string * json option | I_response of Id.t * json type incoming_full = | IF_one of incoming | IF_batch of incoming list let parse_id : Id.t P_.t = let open P_ in one_of "id" [ (int >|= fun x -> Id.Int x); (string >|= fun x -> Id.String x); (null >|= fun () -> Id.Null); ] let parse_error : (int*string) P_.t = let open P_ in field "code" int >>= fun code -> field "message" string >|= fun msg -> (code,msg) let parse_incoming : incoming P_.t = let open P_ in field "jsonrpc" string >>= function | "2.0" -> one_of "incoming message" [ (field "error" parse_error >>= fun (c,e) -> field "id" parse_id >|= fun id -> I_error (id,c,e)); (field "result" json >>= fun j -> field "id" parse_id >|= fun id -> I_response(id,j)); (field "method" string >>= fun name -> field_opt "params" json >>= fun params -> field_opt "id" parse_id >|= function | Some id -> I_request (id, name, params) | None -> I_notify (name, params)) ] | _ -> fail "expected field 'jsonrpc' to contain '2.0'" let parse_incoming_full : incoming_full P_.t = let open P_ in is_list >>= function | true -> list parse_incoming >>= fun l -> if l=[] then fail "batch must be non-empty" else return (IF_batch l) | false -> parse_incoming >|= fun x -> IF_one x (** Actions to be done next. This includes sending messages out on the connection, calling a method, or finishing a local request. *) type action = | Send of message | Send_batch of message list | Start_call of (Id.t * string * json option) | Notify of string * json option | Fill_request of (Id.t * (json,int * string) result) | Error_without_id of int * string let acts_of_inc self ~tr (i:incoming) : action = match i with | I_notify (s,m) -> Notify (s,m) | I_request (id,s,m) -> if Id.Tbl.mem self.to_reply id then ( Send (error_ self ~id:None code_internal_error "ID already used in a request") ) else ( Id.Tbl.add self.to_reply id tr; (* update count of messages in this batch to answer to *) (match tr with TR_single -> () | TR_batch r -> r.missing <- r.missing + 1); Start_call (id,s,m) ) | I_response (id,m) -> if Id.Tbl.mem self.active id then ( Id.Tbl.remove self.active id; Fill_request (id,Ok m) ) else ( Send (error_ self ~id:None code_internal_error "no request with given ID") ) | I_error (Id.Null,code,msg) -> Error_without_id (code,msg) | I_error (id,code,msg) -> if Id.Tbl.mem self.active id then ( Id.Tbl.remove self.active id; Fill_request (id, Error (code, msg)) ) else ( Send (error_ self ~id:None code_internal_error "no request with given ID") ) let process_msg (self:t) (m:message) : (action list, _) result = match P_.run parse_incoming_full m with | Error (lazy e) -> Error (code_invalid_request, e) | Ok (IF_one m) -> Ok [acts_of_inc ~tr:TR_single self m] | Ok (IF_batch l) -> let tr = TR_batch {missing=0; done_=[]} in Ok (List.map (acts_of_inc ~tr self) l) let process_call_reply self id res : _ list = let msg_of_res = function | Ok res -> mk_response id res | Error e -> error_ self ~id:(Some id) code_invalid_param e in match Id.Tbl.find self.to_reply id with | exception Not_found -> invalid_arg (Printf.sprintf "already replied to id %s" (Id.to_string id)) | TR_single -> Id.Tbl.remove self.to_reply id; [Send (msg_of_res res)] | TR_batch r -> Id.Tbl.remove self.to_reply id; r.done_ <- msg_of_res res :: r.done_; r.missing <- r.missing - 1; if r.missing = 0 then ( [Send_batch r.done_] ) else [] end module Make(IO : Jsonrpc2_intf.IO) : Jsonrpc2_intf.S with module IO = IO = struct module IO = IO module Id = Protocol.Id type json = J.t type t = { proto: Protocol.t; methods: (string, method_) Hashtbl.t; reponse_promises: (json, code*string) result IO.Future.promise Id.Tbl.t; (* promises to fullfill *) ic: IO.in_channel; oc: IO.out_channel; send_lock: IO.lock; (* avoid concurrent writes *) } and method_ = (t -> params:json option -> return:((json, string) result -> unit) -> unit) * A method available through JSON - RPC let create ~ic ~oc () : t = { ic; oc; reponse_promises=Id.Tbl.create 32; methods=Hashtbl.create 16; send_lock=IO.create_lock(); proto=Protocol.create(); } let declare_method (self:t) name meth : unit = Hashtbl.replace self.methods name meth let declare_method_with self ~decode_arg ~encode_res name f : unit = declare_method self name (fun self ~params ~return -> match params with | None -> (* pass [return] as a continuation to {!f} *) f self ~params:None ~return:(fun y -> return (Ok (encode_res y))) | Some p -> match decode_arg p with | Error e -> return (Error e) | Ok x -> (* pass [return] as a continuation to {!f} *) f self ~params:(Some x) ~return:(fun y -> return (Ok (encode_res y)))) let declare_blocking_method_with self ~decode_arg ~encode_res name f : unit = declare_method self name (fun _self ~params ~return -> match params with | None -> return (Ok (encode_res (f None))) | Some p -> match decode_arg p with | Error e -> return (Error e) | Ok x -> return (Ok (encode_res (f (Some x))))) * { 2 Client side } exception Jsonrpc2_error of int * string (** Code + message *) type message = json let request (self:t) ~meth ~params : message * _ IO.Future.t = let msg, id = Protocol.request self.proto ~meth ~params in (* future response, with sender associated to ID *) let future, promise = IO.Future.make ~on_cancel:(fun () -> Id.Tbl.remove self.reponse_promises id) () in Id.Tbl.add self.reponse_promises id promise; msg, future (* Notify the remote server *) let notify (self:t) ~meth ~params : message = Protocol.notify self.proto ~meth ~params let send_msg_ (self:t) (s:string) : _ IO.t = IO.with_lock self.send_lock (fun () -> IO.write_string self.oc s) (* send a single message *) let send (self:t) (m:message) : _ result IO.t = let json = J.to_string m in let full_s = Printf.sprintf "Content-Length: %d\r\n\r\n%s" (String.length json) json in send_msg_ self full_s let send_request self ~meth ~params : _ IO.t = let open IO.Infix in let msg, res = request self ~meth ~params in send self msg >>= function | Error e -> IO.return (Error e) | Ok () -> IO.Future.wait res >|= fun r -> match r with | Ok x -> Ok x | Error (code,e) -> Error (Jsonrpc2_error (code,e)) let send_notify self ~meth ~params : _ IO.t = let msg = notify self ~meth ~params in send self msg let send_request_with ~encode_params ~decode_res self ~meth ~params : _ IO.t = let open IO.Infix in send_request self ~meth ~params:(opt_map_ encode_params params) >>= function | Error _ as e -> IO.return e | Ok x -> let r = match decode_res x with | Ok x -> Ok x | Error s -> Error (Jsonrpc2_error (code_invalid_request, s)) in IO.return r let send_notify_with ~encode_params self ~meth ~params : _ IO.t = send_notify self ~meth ~params:(opt_map_ encode_params params) (* send a batch message *) let send_batch (self:t) (l:message list) : _ result IO.t = let json = J.to_string (`List l) in let full_s = Printf.sprintf "Content-Length: %d\r\n\r\n%s" (String.length json) json in send_msg_ self full_s bind on IO+result let (>>=?) x f = let open IO.Infix in x >>= function | Error _ as err -> IO.return err | Ok x -> f x (* read a full message *) let read_msg (self:t) : ((string * string) list * json, exn) result IO.t = let rec read_headers acc = IO.read_line self.ic >>=? function | "\r" -> IO.return (Ok acc) (* last separator *) | line -> begin match if String.get line (String.length line-1) <> '\r' then raise Not_found; let i = String.index line ':' in if i<0 || String.get line (i+1) <> ' ' then raise Not_found; String.sub line 0 i, String.trim (String.sub line (i+1) (String.length line-i-2)) with | pair -> read_headers (pair :: acc) | exception _ -> IO.return (Error (Jsonrpc2_error (code_parse_error, "invalid header: " ^ line))) end in read_headers [] >>=? fun headers -> let ok = match List.assoc "Content-Type" headers with | "utf8" | "utf-8" -> true | _ -> false | exception Not_found -> true in if ok then ( match int_of_string (List.assoc "Content-Length" headers) with | n -> let buf = Bytes.make n '\000' in IO.read_exact self.ic buf n >>=? fun () -> begin match J.from_string (Bytes.unsafe_to_string buf) with | j -> IO.return @@ Ok (headers, j) | exception _ -> IO.return (Error (Jsonrpc2_error (code_parse_error, "cannot decode json"))) end | exception _ -> IO.return @@ Error (Jsonrpc2_error(code_parse_error, "missing Content-Length' header")) ) else ( IO.return @@ Error (Jsonrpc2_error(code_invalid_request, "content-type must be 'utf-8'")) ) (* execute actions demanded by the protocole *) let rec exec_actions (self:t) l : _ result IO.t = let open IO.Infix in match l with | [] -> IO.return (Ok ()) | a :: tl -> begin match a with | Protocol.Send msg -> send self msg | Protocol.Send_batch l -> send_batch self l | Protocol.Start_call (id, name, params) -> begin match Hashtbl.find self.methods name with | m -> let fut, promise = IO.Future.make () in m self ~params ~return:(fun r -> IO.Future.fullfill promise r); (* now wait for the method's response, and reply to protocol *) IO.Future.wait fut >>= fun res -> let acts' = Protocol.process_call_reply self.proto id res in exec_actions self acts' | exception Not_found -> send self (Protocol.error self.proto code_method_not_found "method not found") end | Protocol.Notify (name,params) -> begin match Hashtbl.find self.methods name with | m -> (* execute notification, do not process response *) m self ~params ~return:(fun _ -> ()); IO.return (Ok ()) | exception Not_found -> send self (Protocol.error self.proto code_method_not_found "method not found") end | Protocol.Fill_request (id, res) -> begin match Id.Tbl.find self.reponse_promises id with | promise -> IO.Future.fullfill promise res; IO.return (Ok ()) | exception Not_found -> send self @@ Protocol.error self.proto code_internal_error "no such request" end | Protocol.Error_without_id (code,msg) -> IO.return (Error (Jsonrpc2_error (code,msg))) end >>=? fun () -> exec_actions self tl let run (self:t) : _ IO.t = let open IO.Infix in let rec loop() : _ IO.t = read_msg self >>= function | Error End_of_file -> IO.return (Ok ()) (* done! *) | Error (Jsonrpc2_error (code, msg)) -> send self (Protocol.error self.proto code msg) >>=? fun () -> loop () | Error _ as err -> IO.return err (* exit now *) | Ok (_hd, msg) -> begin match Protocol.process_msg self.proto msg with | Ok actions -> exec_actions self actions | Error (code,msg) -> send self (Protocol.error self.proto code msg) end >>=? fun () -> loop () in loop () end
null
https://raw.githubusercontent.com/c-cube/jsonrpc2/c230d056c8084435b0d681f1be5cc15a0fba834b/src/jsonrpc2_core.ml
ocaml
* A jsonrpc2 connection. * Create a state machine for Jsonrpc2 * Clear all internal state. * Message sent to the other side * Create a request message, for which an answer is expected. * Create a notification message, ie. no response is expected. * Actions to be done next. This includes sending messages out on the connection, calling a method, or finishing a local request. * Process incoming message * Send the response for the given call to the other side active requests active calls to which we shall answer Get a fresh ID for this connection Build the JSON message to send for the given {b request} Build the JSON message to send for the given {b notification} Build a response message Build an error message Notify the remote server * Actions to be done next. This includes sending messages out on the connection, calling a method, or finishing a local request. update count of messages in this batch to answer to promises to fullfill avoid concurrent writes pass [return] as a continuation to {!f} pass [return] as a continuation to {!f} * Code + message future response, with sender associated to ID Notify the remote server send a single message send a batch message read a full message last separator execute actions demanded by the protocole now wait for the method's response, and reply to protocol execute notification, do not process response done! exit now
module J = Yojson.Safe type 'a printer = Format.formatter -> 'a -> unit type code = int let code_parse_error : code = (-32700) let code_invalid_request : code = (-32600) let code_method_not_found : code = (-32601) let code_invalid_param : code = (-32602) let code_internal_error : code = (-32603) let opt_map_ f = function None -> None | Some x -> Some (f x) * { 2 The protocol part , independent from IO and Transport } module Protocol : sig type json = J.t type t val create : unit -> t val clear : t -> unit module Id : sig type t val equal : t -> t -> bool val hash : t -> int val pp : t printer module Tbl : Hashtbl.S with type key = t end * { 3 Send requests and notifications to the other side } type message = json val error : t -> code -> string -> message val request : t -> meth:string -> params:json option -> message * Id.t val notify : t -> meth:string -> params:json option -> message type action = | Send of message | Send_batch of message list | Start_call of (Id.t * string * json option) | Notify of string * json option | Fill_request of (Id.t * (json,int * string) result) | Error_without_id of int * string val process_msg : t -> message -> (action list, code*string) result val process_call_reply : t -> Id.t -> (json, string) result -> action list end = struct type json = J.t module Id = struct type t = | Int of int | String of string | Null let equal = (=) let hash = Hashtbl.hash let to_string = function | Int i -> string_of_int i | String s -> s | Null -> "null" let pp out id = Format.pp_print_string out (to_string id) let to_json = function | Int i -> `Int i | String s -> `String s | Null -> `Null module Tbl = Hashtbl.Make(struct type nonrec t = t let equal = equal let hash = hash end) end type message = json type to_reply = | TR_single | TR_batch of { mutable missing: int; mutable done_: message list; } type t = { mutable id_ : int; } let create () : t = { id_=0; active=Id.Tbl.create 24; to_reply=Id.Tbl.create 24; } let clear (self:t) : unit = self.id_ <- 0; Id.Tbl.clear self.active; Id.Tbl.clear self.to_reply let fresh_id_ (self:t) : Id.t = let i = self.id_ in self.id_ <- i + 1; Id.Int i let mk_request_ ~id ~meth ~params = let l = [ "method", `String meth; "jsonrpc", `String "2.0"; "id", Id.to_json id; ] in let l = match params with None -> l | Some x -> ("params",x) :: l in `Assoc l let mk_notify_ ~meth ~params = let l = [ "method", `String meth; "jsonrpc", `String "2.0"; ] in let l = match params with None -> l | Some x -> ("params", x) :: l in `Assoc l let mk_response (id:Id.t) msg : json = `Assoc [ "jsonrpc", `String "2.0"; "result", msg; "id", Id.to_json id; ] let error_ _self ~id code msg : json = let l = [ "jsonrpc", `String "2.0"; "error", `Assoc [ "code", `Int code; "message", `String msg; ] ] in let l = match id with | None -> l | Some id -> ("id", Id.to_json id) :: l in `Assoc l let error self code msg = error_ ~id:None self code msg let request (self:t) ~meth ~params : message * Id.t = let id = fresh_id_ self in Id.Tbl.add self.active id (); let msg = mk_request_ ~id ~meth ~params in msg, id let notify (_self:t) ~meth ~params : message = mk_notify_ ~meth ~params module P_ : sig type +'a t val return : 'a -> 'a t val fail : string -> _ t val is_list : bool t val (>>=) : 'a t -> ('a -> 'b t) -> 'b t val (>|=) : 'a t -> ('a -> 'b) -> 'b t val field : string -> 'a t -> 'a t val field_opt : string -> 'a t -> 'a option t val json : json t val one_of : string -> 'a t list -> 'a t val int : int t val string : string t val null : unit t val list : 'a t -> 'a list t val run : 'a t -> json -> ('a, string lazy_t) result end = struct type +'a t = json -> ('a, (string * json) list) result let return x _ = Ok x let error_ ?(ctx=[]) j e = Error ((e,j)::ctx) let errorf_ ?ctx j fmt = Printf.ksprintf (error_ ?ctx j) fmt let fail s j = Error [s,j] let (>>=) x f j = match x j with | Ok x -> f x j | Error e -> Error e let (>|=) x f j = match x j with | Ok x -> Ok (f x) | Error e -> Error e let json j = Ok j let is_list = function `List _ -> Ok true | _ -> Ok false let int = function | `Int i -> Ok i | `String s as j -> (try Ok (int_of_string s) with _ -> errorf_ j "expected int") | j -> error_ j "expected int" let string = function | `Int i -> Ok (string_of_int i) | `String s -> Ok s | j -> error_ j "expected string" let null = function `Null -> Ok () | j -> error_ j "expected null" let field name f : _ t = function | `Assoc l as j -> (match List.assoc name l with | x -> f x | exception Not_found -> errorf_ j "no field '%s' found in object" name) | j -> error_ j "expected object" let field_opt name f : _ t = function | `Assoc l -> (match List.assoc name l with | x -> (match f x with Ok x -> Ok (Some x) | Error e -> Error e) | exception Not_found -> Ok None) | j -> error_ j "expected object" let rec one_of what l j = match l with | [] -> errorf_ j "expected %s, none matched the given list" what | x :: tl -> match x j with | Ok x -> Ok x | Error _ -> one_of what tl j let list f : _ t = function | `List l -> let rec aux acc = function | [] -> Ok (List.rev acc) | x :: tl -> match f x with | Error ctx -> error_ ~ctx x "in list" | Ok x -> aux (x::acc) tl in aux [] l | j -> error_ j "expected list" let run (p:_ t) (j:json) : _ result = match p j with | Ok x -> Ok x | Error l -> let msg = lazy ( String.concat "\n" @@ List.rev_map (fun (e,j) -> e ^ " in " ^ J.to_string j) l ) in Error msg end type incoming = | I_error of Id.t * code * string | I_request of Id.t * string * json option | I_notify of string * json option | I_response of Id.t * json type incoming_full = | IF_one of incoming | IF_batch of incoming list let parse_id : Id.t P_.t = let open P_ in one_of "id" [ (int >|= fun x -> Id.Int x); (string >|= fun x -> Id.String x); (null >|= fun () -> Id.Null); ] let parse_error : (int*string) P_.t = let open P_ in field "code" int >>= fun code -> field "message" string >|= fun msg -> (code,msg) let parse_incoming : incoming P_.t = let open P_ in field "jsonrpc" string >>= function | "2.0" -> one_of "incoming message" [ (field "error" parse_error >>= fun (c,e) -> field "id" parse_id >|= fun id -> I_error (id,c,e)); (field "result" json >>= fun j -> field "id" parse_id >|= fun id -> I_response(id,j)); (field "method" string >>= fun name -> field_opt "params" json >>= fun params -> field_opt "id" parse_id >|= function | Some id -> I_request (id, name, params) | None -> I_notify (name, params)) ] | _ -> fail "expected field 'jsonrpc' to contain '2.0'" let parse_incoming_full : incoming_full P_.t = let open P_ in is_list >>= function | true -> list parse_incoming >>= fun l -> if l=[] then fail "batch must be non-empty" else return (IF_batch l) | false -> parse_incoming >|= fun x -> IF_one x type action = | Send of message | Send_batch of message list | Start_call of (Id.t * string * json option) | Notify of string * json option | Fill_request of (Id.t * (json,int * string) result) | Error_without_id of int * string let acts_of_inc self ~tr (i:incoming) : action = match i with | I_notify (s,m) -> Notify (s,m) | I_request (id,s,m) -> if Id.Tbl.mem self.to_reply id then ( Send (error_ self ~id:None code_internal_error "ID already used in a request") ) else ( Id.Tbl.add self.to_reply id tr; (match tr with TR_single -> () | TR_batch r -> r.missing <- r.missing + 1); Start_call (id,s,m) ) | I_response (id,m) -> if Id.Tbl.mem self.active id then ( Id.Tbl.remove self.active id; Fill_request (id,Ok m) ) else ( Send (error_ self ~id:None code_internal_error "no request with given ID") ) | I_error (Id.Null,code,msg) -> Error_without_id (code,msg) | I_error (id,code,msg) -> if Id.Tbl.mem self.active id then ( Id.Tbl.remove self.active id; Fill_request (id, Error (code, msg)) ) else ( Send (error_ self ~id:None code_internal_error "no request with given ID") ) let process_msg (self:t) (m:message) : (action list, _) result = match P_.run parse_incoming_full m with | Error (lazy e) -> Error (code_invalid_request, e) | Ok (IF_one m) -> Ok [acts_of_inc ~tr:TR_single self m] | Ok (IF_batch l) -> let tr = TR_batch {missing=0; done_=[]} in Ok (List.map (acts_of_inc ~tr self) l) let process_call_reply self id res : _ list = let msg_of_res = function | Ok res -> mk_response id res | Error e -> error_ self ~id:(Some id) code_invalid_param e in match Id.Tbl.find self.to_reply id with | exception Not_found -> invalid_arg (Printf.sprintf "already replied to id %s" (Id.to_string id)) | TR_single -> Id.Tbl.remove self.to_reply id; [Send (msg_of_res res)] | TR_batch r -> Id.Tbl.remove self.to_reply id; r.done_ <- msg_of_res res :: r.done_; r.missing <- r.missing - 1; if r.missing = 0 then ( [Send_batch r.done_] ) else [] end module Make(IO : Jsonrpc2_intf.IO) : Jsonrpc2_intf.S with module IO = IO = struct module IO = IO module Id = Protocol.Id type json = J.t type t = { proto: Protocol.t; methods: (string, method_) Hashtbl.t; reponse_promises: ic: IO.in_channel; oc: IO.out_channel; } and method_ = (t -> params:json option -> return:((json, string) result -> unit) -> unit) * A method available through JSON - RPC let create ~ic ~oc () : t = { ic; oc; reponse_promises=Id.Tbl.create 32; methods=Hashtbl.create 16; send_lock=IO.create_lock(); proto=Protocol.create(); } let declare_method (self:t) name meth : unit = Hashtbl.replace self.methods name meth let declare_method_with self ~decode_arg ~encode_res name f : unit = declare_method self name (fun self ~params ~return -> match params with | None -> f self ~params:None ~return:(fun y -> return (Ok (encode_res y))) | Some p -> match decode_arg p with | Error e -> return (Error e) | Ok x -> f self ~params:(Some x) ~return:(fun y -> return (Ok (encode_res y)))) let declare_blocking_method_with self ~decode_arg ~encode_res name f : unit = declare_method self name (fun _self ~params ~return -> match params with | None -> return (Ok (encode_res (f None))) | Some p -> match decode_arg p with | Error e -> return (Error e) | Ok x -> return (Ok (encode_res (f (Some x))))) * { 2 Client side } exception Jsonrpc2_error of int * string type message = json let request (self:t) ~meth ~params : message * _ IO.Future.t = let msg, id = Protocol.request self.proto ~meth ~params in let future, promise = IO.Future.make ~on_cancel:(fun () -> Id.Tbl.remove self.reponse_promises id) () in Id.Tbl.add self.reponse_promises id promise; msg, future let notify (self:t) ~meth ~params : message = Protocol.notify self.proto ~meth ~params let send_msg_ (self:t) (s:string) : _ IO.t = IO.with_lock self.send_lock (fun () -> IO.write_string self.oc s) let send (self:t) (m:message) : _ result IO.t = let json = J.to_string m in let full_s = Printf.sprintf "Content-Length: %d\r\n\r\n%s" (String.length json) json in send_msg_ self full_s let send_request self ~meth ~params : _ IO.t = let open IO.Infix in let msg, res = request self ~meth ~params in send self msg >>= function | Error e -> IO.return (Error e) | Ok () -> IO.Future.wait res >|= fun r -> match r with | Ok x -> Ok x | Error (code,e) -> Error (Jsonrpc2_error (code,e)) let send_notify self ~meth ~params : _ IO.t = let msg = notify self ~meth ~params in send self msg let send_request_with ~encode_params ~decode_res self ~meth ~params : _ IO.t = let open IO.Infix in send_request self ~meth ~params:(opt_map_ encode_params params) >>= function | Error _ as e -> IO.return e | Ok x -> let r = match decode_res x with | Ok x -> Ok x | Error s -> Error (Jsonrpc2_error (code_invalid_request, s)) in IO.return r let send_notify_with ~encode_params self ~meth ~params : _ IO.t = send_notify self ~meth ~params:(opt_map_ encode_params params) let send_batch (self:t) (l:message list) : _ result IO.t = let json = J.to_string (`List l) in let full_s = Printf.sprintf "Content-Length: %d\r\n\r\n%s" (String.length json) json in send_msg_ self full_s bind on IO+result let (>>=?) x f = let open IO.Infix in x >>= function | Error _ as err -> IO.return err | Ok x -> f x let read_msg (self:t) : ((string * string) list * json, exn) result IO.t = let rec read_headers acc = IO.read_line self.ic >>=? function | line -> begin match if String.get line (String.length line-1) <> '\r' then raise Not_found; let i = String.index line ':' in if i<0 || String.get line (i+1) <> ' ' then raise Not_found; String.sub line 0 i, String.trim (String.sub line (i+1) (String.length line-i-2)) with | pair -> read_headers (pair :: acc) | exception _ -> IO.return (Error (Jsonrpc2_error (code_parse_error, "invalid header: " ^ line))) end in read_headers [] >>=? fun headers -> let ok = match List.assoc "Content-Type" headers with | "utf8" | "utf-8" -> true | _ -> false | exception Not_found -> true in if ok then ( match int_of_string (List.assoc "Content-Length" headers) with | n -> let buf = Bytes.make n '\000' in IO.read_exact self.ic buf n >>=? fun () -> begin match J.from_string (Bytes.unsafe_to_string buf) with | j -> IO.return @@ Ok (headers, j) | exception _ -> IO.return (Error (Jsonrpc2_error (code_parse_error, "cannot decode json"))) end | exception _ -> IO.return @@ Error (Jsonrpc2_error(code_parse_error, "missing Content-Length' header")) ) else ( IO.return @@ Error (Jsonrpc2_error(code_invalid_request, "content-type must be 'utf-8'")) ) let rec exec_actions (self:t) l : _ result IO.t = let open IO.Infix in match l with | [] -> IO.return (Ok ()) | a :: tl -> begin match a with | Protocol.Send msg -> send self msg | Protocol.Send_batch l -> send_batch self l | Protocol.Start_call (id, name, params) -> begin match Hashtbl.find self.methods name with | m -> let fut, promise = IO.Future.make () in m self ~params ~return:(fun r -> IO.Future.fullfill promise r); IO.Future.wait fut >>= fun res -> let acts' = Protocol.process_call_reply self.proto id res in exec_actions self acts' | exception Not_found -> send self (Protocol.error self.proto code_method_not_found "method not found") end | Protocol.Notify (name,params) -> begin match Hashtbl.find self.methods name with | m -> m self ~params ~return:(fun _ -> ()); IO.return (Ok ()) | exception Not_found -> send self (Protocol.error self.proto code_method_not_found "method not found") end | Protocol.Fill_request (id, res) -> begin match Id.Tbl.find self.reponse_promises id with | promise -> IO.Future.fullfill promise res; IO.return (Ok ()) | exception Not_found -> send self @@ Protocol.error self.proto code_internal_error "no such request" end | Protocol.Error_without_id (code,msg) -> IO.return (Error (Jsonrpc2_error (code,msg))) end >>=? fun () -> exec_actions self tl let run (self:t) : _ IO.t = let open IO.Infix in let rec loop() : _ IO.t = read_msg self >>= function | Error End_of_file -> | Error (Jsonrpc2_error (code, msg)) -> send self (Protocol.error self.proto code msg) >>=? fun () -> loop () | Ok (_hd, msg) -> begin match Protocol.process_msg self.proto msg with | Ok actions -> exec_actions self actions | Error (code,msg) -> send self (Protocol.error self.proto code msg) end >>=? fun () -> loop () in loop () end
c119a2f939c6a1e4aa2b7eeb01278e688a7cdbdb6fbc76062d7c04273309018f
glutamate/bugpan
CompiledSrcsSinks.hs
module CompiledSrcsSinks where import EvalM import BuiltIn import PrettyPrint import TNUtils import HaskSyntaxUntyped data Src = Src { srcName :: String, srcArgT :: T, srcOutT :: T, srcImpModule :: [String], srcCode :: SrcCode } deriving Show data SrcCode = SrcOnce (String) --type tmax -> dt -> IO (a) | SrcRealTimeSig (String) --type t -> dt -> IO (a) where sourcetype = signal a instance Show SrcCode where show (SrcOnce _) = "SrcOnce" show (SrcRealTimeSig _) = "SrcRealTimeSig" data Sink = Sink { snkName :: String, snkArgT :: T, snkInT :: T, snkImpModule :: [String], snkCode :: V->String->String } lookupSrc nm = safeHead [s | s@(Src nm1 _ _ _ _) <- srcs, nm == nm1] srcs = [ Src "uniform1" (PairT realT realT) (realT) ["System.Random"] $ SrcOnce ("(\\_ _ (lo,hi) -> randomRIO (lo,hi))"), Src "uniform" (PairT realT realT) (SignalT realT) ["System.Random"] $ SrcRealTimeSig ("(\\_ _ (lo,hi)-> randomRIO (lo::Double,hi::Double))"), Src "poisson1" (realT) (realT) ["RandomSources"] $ SrcOnce ("poisson1"), Src "poisson" (realT) (ListT (PairT realT UnitT)) ["RandomSources"] $ SrcOnce ("poisson"), Src "regular" (realT) (ListT (PairT realT UnitT)) ["RandomSources"] $ SrcOnce ("regular")] snks = []
null
https://raw.githubusercontent.com/glutamate/bugpan/d0983152f5afce306049262cba296df00e52264b/CompiledSrcsSinks.hs
haskell
type tmax -> dt -> IO (a) type t -> dt -> IO (a) where sourcetype = signal a
module CompiledSrcsSinks where import EvalM import BuiltIn import PrettyPrint import TNUtils import HaskSyntaxUntyped data Src = Src { srcName :: String, srcArgT :: T, srcOutT :: T, srcImpModule :: [String], srcCode :: SrcCode } deriving Show instance Show SrcCode where show (SrcOnce _) = "SrcOnce" show (SrcRealTimeSig _) = "SrcRealTimeSig" data Sink = Sink { snkName :: String, snkArgT :: T, snkInT :: T, snkImpModule :: [String], snkCode :: V->String->String } lookupSrc nm = safeHead [s | s@(Src nm1 _ _ _ _) <- srcs, nm == nm1] srcs = [ Src "uniform1" (PairT realT realT) (realT) ["System.Random"] $ SrcOnce ("(\\_ _ (lo,hi) -> randomRIO (lo,hi))"), Src "uniform" (PairT realT realT) (SignalT realT) ["System.Random"] $ SrcRealTimeSig ("(\\_ _ (lo,hi)-> randomRIO (lo::Double,hi::Double))"), Src "poisson1" (realT) (realT) ["RandomSources"] $ SrcOnce ("poisson1"), Src "poisson" (realT) (ListT (PairT realT UnitT)) ["RandomSources"] $ SrcOnce ("poisson"), Src "regular" (realT) (ListT (PairT realT UnitT)) ["RandomSources"] $ SrcOnce ("regular")] snks = []
702ca6018ca1f5330294c3eb97da0eda5a565ac5ad7ab2cc5cb5d30d461bf433
Lovesan/virgil
references.lisp
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*- Copyright ( C ) 2010 - 2012 , < > ;;; 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. (in-package #:virgil) (define-immediate-type reference-type () ((referenced-type :initarg :type :initform nil :reader rtype-type) (mode :initarg :mode :initform :in :reader rtype-mode) (nullable-p :initarg :nullable :initform nil :reader rtype-nullable-p)) (:base-type pointer) (:lisp-type (type) (let ((rtype (lisp-type (rtype-type type)))) (if (rtype-nullable-p type) `(or void ,rtype) rtype))) (:prototype (type) (if (rtype-nullable-p type) void (prototype (rtype-type type)))) (:prototype-expansion (type) (if (rtype-nullable-p type) 'void (expand-prototype (rtype-type type)))) (:allocator-expansion (value type) `(raw-alloc ,(compute-fixed-size type))) (:deallocator-expansion (pointer type) `(raw-free ,pointer)) (:dynamic-extent-expansion (var value-var body type) (let ((nullable (rtype-nullable-p type)) (fbody (intern (symbol-name (gensym (string 'body))) :virgil))) `(flet ((,fbody (,var) ,@body)) ,(let ((expansion (expand-reference-dynamic-extent var (gensym) value-var `((,fbody ,var)) (rtype-mode type) (rtype-type type)))) (if nullable `(if (voidp ,value-var) (let ((,var &0)) (prog1 (,fbody ,var) ,(when (member (rtype-mode type) '(:out :inout)) `(setf ,value-var void)))) ,expansion) expansion))))) (:callback-dynamic-extent-expansion (var raw-value body type) (let ((mode (rtype-mode type)) (rtype (rtype-type type)) (nullable (rtype-nullable-p type))) (if (eq mode :in) (call-next-method) (with-gensyms (pointer) `(let ((,pointer ,raw-value)) (declare (type pointer ,pointer)) (let ((,var ,(if (eq mode :out) (expand-prototype type) (expand-translate-value pointer type)))) (declare (type ,(lisp-type type) ,var)) (prog1 (progn ,@body) ,(if nullable `(when (and (&? ,pointer) (not (voidp ,var))) ,(expand-write-value var pointer rtype)) (expand-write-value var pointer rtype)))))))))) (defmethod convert-value (value (type reference-type)) (let ((rtype (rtype-type type)) (nullable (rtype-nullable-p type))) (labels ((alloc-ref (value) (let ((pointer (allocate-value value rtype))) (write-value value pointer rtype) pointer)) (convert-ref (value) (if (and *handle-cycles* (not (immediate-type-p rtype))) (or (cdr (assoc value *written-values* :test #'eq)) (alloc-ref value)) (alloc-ref value)))) (if nullable (if (voidp value) &0 (convert-ref value)) (convert-ref value))))) (defmethod expand-convert-value (value (type reference-type)) (let ((rtype (rtype-type type)) (nullable (rtype-nullable-p type))) (once-only ((value `(the ,(lisp-type type) ,value))) `(flet ((alloc-ref (,value) ,(with-gensyms (pointer) `(let ((,pointer ,(expand-allocate-value value rtype))) (declare (type pointer ,pointer)) ,(expand-write-value value pointer rtype) ,pointer)))) (flet ((convert-ref (,value) ,(if (immediate-type-p rtype) `(alloc-ref ,value) `(if *handle-cycles* (or (cdr (assoc ,value *written-values* :test #'eq)) (alloc-ref ,value)) (alloc-ref ,value))))) ,(if nullable `(if (voidp ,value) &0 (convert-ref ,value)) `(convert-ref ,value))))))) (defmethod translate-value (pointer (type reference-type)) (let ((rtype (rtype-type type)) (nullable (rtype-nullable-p type))) (labels ((translate-ref (pointer) (read-value pointer nil rtype))) (if nullable (if (&? pointer) (translate-ref pointer) void) (translate-ref pointer))))) (defmethod expand-translate-value (pointer (type reference-type)) (let ((rtype (rtype-type type)) (nullable (rtype-nullable-p type))) (once-only ((pointer `(the pointer ,pointer))) `(flet ((read-ref (,pointer) ,(expand-read-value pointer nil rtype))) ,(if nullable `(if (&? ,pointer) (read-ref ,pointer) void) `(read-ref ,pointer)))))) (defmethod clean-value (pointer value (type reference-type)) (let ((rtype (rtype-type type)) (nullable (rtype-nullable-p type))) (labels ((clean-ref (reference value) (if (and *handle-cycles* (not (immediate-type-p rtype))) (unless (member reference *cleaned-values* :test #'&=) (clean-value reference value rtype) (free-value reference rtype)) (progn (clean-value reference value rtype) (free-value reference rtype))))) (let ((reference (deref pointer 'pointer))) (if nullable (when (&? reference) (clean-ref reference value)) (clean-ref reference value)))))) (defmethod expand-clean-value (pointer value (type reference-type)) (let ((rtype (rtype-type type)) (nullable (rtype-nullable-p type)) (reference (gensym (string 'reference)))) (once-only ((pointer `(the pointer ,pointer)) (value `(the ,(lisp-type type) ,value))) `(flet ((clean-ref (,reference ,value) ,(expand-clean-value reference value rtype) ,(expand-free-value reference rtype))) ,(let ((expansion (if (immediate-type-p rtype) `(clean-ref ,reference ,value) `(if *handle-cycles* (unless (member ,reference *cleaned-values* :test #'&=) (clean-ref ,reference ,value)) (clean-ref ,reference ,value))))) `(let ((,reference (deref ,pointer 'pointer))) (declare (type pointer ,reference)) ,(if nullable `(when (&? ,reference) ,expansion) expansion))))))) (defmethod expand-reference-dynamic-extent (var size-var value-var body mode (type reference-type)) (with-gensyms (pointer-var) `(with-raw-pointer (,var ,(compute-fixed-size type) ,size-var) ,(expand-reference-dynamic-extent pointer-var (gensym) value-var `((setf (deref ,var '*) ,pointer-var) nil ,@body) mode (rtype-type type))))) (define-type-parser & (referenced-type &optional (mode :in) nullable) (check-type mode (member :in :out :inout)) (make-instance 'reference-type :type (parse-typespec referenced-type) :mode mode :nullable nullable)) (defmethod unparse-type ((type reference-type)) (list* '& (unparse-type (rtype-type type)) (rtype-mode type) (ensure-list (rtype-nullable-p type)))) (defun ensure-var-spec (spec) (destructuring-bind (var &optional (size-var (gensym)) &rest rest) (ensure-list spec) (if (and (not (constantp var)) (not (constantp size-var)) (symbolp var) (symbolp size-var) (not (eq var size-var)) (null rest)) (values var size-var) (error "Ill-formed variable spec: ~s" spec)))) (defmacro with-reference ((var value-var type &optional (mode :in) nullable) &body body) (check-type mode (member :in :out :inout)) (check-type value-var symbol) (assert (not (constantp value-var)) (value-var)) (multiple-value-bind (type constantp) (eval-if-constantp type) (multiple-value-bind (var size-var) (ensure-var-spec var) (let ((expansion (if constantp (expand-reference-dynamic-extent var size-var value-var body mode (parse-typespec type)) (with-gensyms (type-var pointer-var) `(progv (when *handle-cycles* '(*readen-values* *written-values* *cleaned-values*)) (when *handle-cycles* '(() () ())) (let* ((,type-var (parse-typespec ,type)) (,size-var (compute-size ,value-var ,type-var)) (,pointer-var (allocate-value ,value-var ,type-var)) (,var ,pointer-var)) (declare (type pointer ,var ,pointer-var) (type non-negative-fixnum ,size-var) (ignorable ,size-var)) (unwind-protect ,(case mode (:in `(progn (write-value ,value-var ,pointer-var ,type-var) ,@body)) (:out `(prog1 (progn ,@body) (setf ,value-var (read-value ,pointer-var ,value-var ,type-var)))) (:inout `(progn (write-value ,value-var ,pointer-var ,type-var) (prog1 (progn ,@body) (setf ,value-var (read-value ,pointer-var ,value-var ,type-var)))))) (progn (clean-value ,pointer-var ,value-var ,type-var) (free-value ,pointer-var ,type-var))))))))) (if nullable `(if (voidp ,value-var) (let ((,var &0) (,size-var 0)) (declare (ignorable ,size-var)) (prog1 (progn ,@body) ,(when (member mode '(:out :inout)) `(setf ,value-var void)))) ,expansion) expansion))))) (defmacro with-references ((&rest specs) &body body) (if (endp specs) `(progn ,@body) `(with-reference ,(first specs) (with-references ,(rest specs) ,@body)))) (defmacro with-pointer ((var value type &optional (mode :in) nullable) &body body) (with-gensyms (value-var) `(let ((,value-var ,value)) (declare (ignorable ,value-var)) (with-reference (,var ,value-var ,type ,mode ,nullable) ,@body)))) (defmacro with-pointers ((&rest specs) &body body) (if (endp specs) `(progn ,@body) `(with-pointer ,(first specs) (with-pointers ,(rest specs) ,@body)))) (defmacro with-value ((var pointer-form type &optional (mode :in) nullable) &body body) (check-type mode (member :in :out :inout)) (multiple-value-bind (type constantp) (eval-if-constantp type) (if constantp (expand-callback-dynamic-extent var pointer-form body (make-instance 'reference-type :type (parse-typespec type) :mode mode :nullable (not (null nullable)))) (with-gensyms (pointer type-var) `(progv (when *handle-cycles* '(*readen-values* *written-values* *cleaned-values*)) (when *handle-cycles* '(() () ())) (let ((,pointer ,pointer-form) (,type-var (parse-typespec ,type))) (declare (type pointer ,pointer)) ,(let ((expansion (ecase mode (:in `(let ((,var (read-value ,pointer nil ,type-var))) ,@body)) (:out `(let ((,var (prototype ,type-var))) (prog1 (progn ,@body) (write-value ,var ,pointer ,type-var)))) (:inout `(let ((,var (read-value ,pointer nil ,type-var))) (prog1 (progn ,@body) (write-value ,var ,pointer ,type-var))))))) (if nullable `(if (&? ,pointer) ,expansion (let ((,var void)) ,@body)) expansion)))))))) (defmacro with-values ((&rest specs) &body body) (if (endp specs) `(progn ,@body) `(with-value ,(first specs) (with-values ,(rest specs) ,@body))))
null
https://raw.githubusercontent.com/Lovesan/virgil/ab650955b939fba0c7f5c3fd945d3580fbf756c1/src/references.lisp
lisp
-*- Mode: lisp; indent-tabs-mode: nil -*- Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS 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.
Copyright ( C ) 2010 - 2012 , < > files ( the " Software " ) , to deal in the Software without of the Software , and to permit persons to whom the Software is included in all copies or substantial portions of the Software . THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , (in-package #:virgil) (define-immediate-type reference-type () ((referenced-type :initarg :type :initform nil :reader rtype-type) (mode :initarg :mode :initform :in :reader rtype-mode) (nullable-p :initarg :nullable :initform nil :reader rtype-nullable-p)) (:base-type pointer) (:lisp-type (type) (let ((rtype (lisp-type (rtype-type type)))) (if (rtype-nullable-p type) `(or void ,rtype) rtype))) (:prototype (type) (if (rtype-nullable-p type) void (prototype (rtype-type type)))) (:prototype-expansion (type) (if (rtype-nullable-p type) 'void (expand-prototype (rtype-type type)))) (:allocator-expansion (value type) `(raw-alloc ,(compute-fixed-size type))) (:deallocator-expansion (pointer type) `(raw-free ,pointer)) (:dynamic-extent-expansion (var value-var body type) (let ((nullable (rtype-nullable-p type)) (fbody (intern (symbol-name (gensym (string 'body))) :virgil))) `(flet ((,fbody (,var) ,@body)) ,(let ((expansion (expand-reference-dynamic-extent var (gensym) value-var `((,fbody ,var)) (rtype-mode type) (rtype-type type)))) (if nullable `(if (voidp ,value-var) (let ((,var &0)) (prog1 (,fbody ,var) ,(when (member (rtype-mode type) '(:out :inout)) `(setf ,value-var void)))) ,expansion) expansion))))) (:callback-dynamic-extent-expansion (var raw-value body type) (let ((mode (rtype-mode type)) (rtype (rtype-type type)) (nullable (rtype-nullable-p type))) (if (eq mode :in) (call-next-method) (with-gensyms (pointer) `(let ((,pointer ,raw-value)) (declare (type pointer ,pointer)) (let ((,var ,(if (eq mode :out) (expand-prototype type) (expand-translate-value pointer type)))) (declare (type ,(lisp-type type) ,var)) (prog1 (progn ,@body) ,(if nullable `(when (and (&? ,pointer) (not (voidp ,var))) ,(expand-write-value var pointer rtype)) (expand-write-value var pointer rtype)))))))))) (defmethod convert-value (value (type reference-type)) (let ((rtype (rtype-type type)) (nullable (rtype-nullable-p type))) (labels ((alloc-ref (value) (let ((pointer (allocate-value value rtype))) (write-value value pointer rtype) pointer)) (convert-ref (value) (if (and *handle-cycles* (not (immediate-type-p rtype))) (or (cdr (assoc value *written-values* :test #'eq)) (alloc-ref value)) (alloc-ref value)))) (if nullable (if (voidp value) &0 (convert-ref value)) (convert-ref value))))) (defmethod expand-convert-value (value (type reference-type)) (let ((rtype (rtype-type type)) (nullable (rtype-nullable-p type))) (once-only ((value `(the ,(lisp-type type) ,value))) `(flet ((alloc-ref (,value) ,(with-gensyms (pointer) `(let ((,pointer ,(expand-allocate-value value rtype))) (declare (type pointer ,pointer)) ,(expand-write-value value pointer rtype) ,pointer)))) (flet ((convert-ref (,value) ,(if (immediate-type-p rtype) `(alloc-ref ,value) `(if *handle-cycles* (or (cdr (assoc ,value *written-values* :test #'eq)) (alloc-ref ,value)) (alloc-ref ,value))))) ,(if nullable `(if (voidp ,value) &0 (convert-ref ,value)) `(convert-ref ,value))))))) (defmethod translate-value (pointer (type reference-type)) (let ((rtype (rtype-type type)) (nullable (rtype-nullable-p type))) (labels ((translate-ref (pointer) (read-value pointer nil rtype))) (if nullable (if (&? pointer) (translate-ref pointer) void) (translate-ref pointer))))) (defmethod expand-translate-value (pointer (type reference-type)) (let ((rtype (rtype-type type)) (nullable (rtype-nullable-p type))) (once-only ((pointer `(the pointer ,pointer))) `(flet ((read-ref (,pointer) ,(expand-read-value pointer nil rtype))) ,(if nullable `(if (&? ,pointer) (read-ref ,pointer) void) `(read-ref ,pointer)))))) (defmethod clean-value (pointer value (type reference-type)) (let ((rtype (rtype-type type)) (nullable (rtype-nullable-p type))) (labels ((clean-ref (reference value) (if (and *handle-cycles* (not (immediate-type-p rtype))) (unless (member reference *cleaned-values* :test #'&=) (clean-value reference value rtype) (free-value reference rtype)) (progn (clean-value reference value rtype) (free-value reference rtype))))) (let ((reference (deref pointer 'pointer))) (if nullable (when (&? reference) (clean-ref reference value)) (clean-ref reference value)))))) (defmethod expand-clean-value (pointer value (type reference-type)) (let ((rtype (rtype-type type)) (nullable (rtype-nullable-p type)) (reference (gensym (string 'reference)))) (once-only ((pointer `(the pointer ,pointer)) (value `(the ,(lisp-type type) ,value))) `(flet ((clean-ref (,reference ,value) ,(expand-clean-value reference value rtype) ,(expand-free-value reference rtype))) ,(let ((expansion (if (immediate-type-p rtype) `(clean-ref ,reference ,value) `(if *handle-cycles* (unless (member ,reference *cleaned-values* :test #'&=) (clean-ref ,reference ,value)) (clean-ref ,reference ,value))))) `(let ((,reference (deref ,pointer 'pointer))) (declare (type pointer ,reference)) ,(if nullable `(when (&? ,reference) ,expansion) expansion))))))) (defmethod expand-reference-dynamic-extent (var size-var value-var body mode (type reference-type)) (with-gensyms (pointer-var) `(with-raw-pointer (,var ,(compute-fixed-size type) ,size-var) ,(expand-reference-dynamic-extent pointer-var (gensym) value-var `((setf (deref ,var '*) ,pointer-var) nil ,@body) mode (rtype-type type))))) (define-type-parser & (referenced-type &optional (mode :in) nullable) (check-type mode (member :in :out :inout)) (make-instance 'reference-type :type (parse-typespec referenced-type) :mode mode :nullable nullable)) (defmethod unparse-type ((type reference-type)) (list* '& (unparse-type (rtype-type type)) (rtype-mode type) (ensure-list (rtype-nullable-p type)))) (defun ensure-var-spec (spec) (destructuring-bind (var &optional (size-var (gensym)) &rest rest) (ensure-list spec) (if (and (not (constantp var)) (not (constantp size-var)) (symbolp var) (symbolp size-var) (not (eq var size-var)) (null rest)) (values var size-var) (error "Ill-formed variable spec: ~s" spec)))) (defmacro with-reference ((var value-var type &optional (mode :in) nullable) &body body) (check-type mode (member :in :out :inout)) (check-type value-var symbol) (assert (not (constantp value-var)) (value-var)) (multiple-value-bind (type constantp) (eval-if-constantp type) (multiple-value-bind (var size-var) (ensure-var-spec var) (let ((expansion (if constantp (expand-reference-dynamic-extent var size-var value-var body mode (parse-typespec type)) (with-gensyms (type-var pointer-var) `(progv (when *handle-cycles* '(*readen-values* *written-values* *cleaned-values*)) (when *handle-cycles* '(() () ())) (let* ((,type-var (parse-typespec ,type)) (,size-var (compute-size ,value-var ,type-var)) (,pointer-var (allocate-value ,value-var ,type-var)) (,var ,pointer-var)) (declare (type pointer ,var ,pointer-var) (type non-negative-fixnum ,size-var) (ignorable ,size-var)) (unwind-protect ,(case mode (:in `(progn (write-value ,value-var ,pointer-var ,type-var) ,@body)) (:out `(prog1 (progn ,@body) (setf ,value-var (read-value ,pointer-var ,value-var ,type-var)))) (:inout `(progn (write-value ,value-var ,pointer-var ,type-var) (prog1 (progn ,@body) (setf ,value-var (read-value ,pointer-var ,value-var ,type-var)))))) (progn (clean-value ,pointer-var ,value-var ,type-var) (free-value ,pointer-var ,type-var))))))))) (if nullable `(if (voidp ,value-var) (let ((,var &0) (,size-var 0)) (declare (ignorable ,size-var)) (prog1 (progn ,@body) ,(when (member mode '(:out :inout)) `(setf ,value-var void)))) ,expansion) expansion))))) (defmacro with-references ((&rest specs) &body body) (if (endp specs) `(progn ,@body) `(with-reference ,(first specs) (with-references ,(rest specs) ,@body)))) (defmacro with-pointer ((var value type &optional (mode :in) nullable) &body body) (with-gensyms (value-var) `(let ((,value-var ,value)) (declare (ignorable ,value-var)) (with-reference (,var ,value-var ,type ,mode ,nullable) ,@body)))) (defmacro with-pointers ((&rest specs) &body body) (if (endp specs) `(progn ,@body) `(with-pointer ,(first specs) (with-pointers ,(rest specs) ,@body)))) (defmacro with-value ((var pointer-form type &optional (mode :in) nullable) &body body) (check-type mode (member :in :out :inout)) (multiple-value-bind (type constantp) (eval-if-constantp type) (if constantp (expand-callback-dynamic-extent var pointer-form body (make-instance 'reference-type :type (parse-typespec type) :mode mode :nullable (not (null nullable)))) (with-gensyms (pointer type-var) `(progv (when *handle-cycles* '(*readen-values* *written-values* *cleaned-values*)) (when *handle-cycles* '(() () ())) (let ((,pointer ,pointer-form) (,type-var (parse-typespec ,type))) (declare (type pointer ,pointer)) ,(let ((expansion (ecase mode (:in `(let ((,var (read-value ,pointer nil ,type-var))) ,@body)) (:out `(let ((,var (prototype ,type-var))) (prog1 (progn ,@body) (write-value ,var ,pointer ,type-var)))) (:inout `(let ((,var (read-value ,pointer nil ,type-var))) (prog1 (progn ,@body) (write-value ,var ,pointer ,type-var))))))) (if nullable `(if (&? ,pointer) ,expansion (let ((,var void)) ,@body)) expansion)))))))) (defmacro with-values ((&rest specs) &body body) (if (endp specs) `(progn ,@body) `(with-value ,(first specs) (with-values ,(rest specs) ,@body))))
3dd9cb952dbc4f60557c5c1ce452c26e793f2e3aa21d6b00ce889ffcb2a19a01
ocsigen/eliom
eliom_monitor.mli
Ocsigen * * Copyright ( C ) 2014 Hugo Heuzard * * This program 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 , with linking exception ; * either version 2.1 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 Lesser General Public License for more details . * * You should have received a copy of the GNU Lesser General Public License * along with this program ; if not , write to the Free Software * Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA . * * Copyright (C) 2014 Hugo Heuzard * * This program 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, with linking exception; * either version 2.1 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *) val uptime : unit -> float val pid : unit -> int val fd : pid:int -> [`Ok of int | `Error of string] val content_div : unit -> [> Html_types.div] Eliom_content.Html.elt Lwt.t val content_html : unit -> [> Html_types.html] Eliom_content.Html.elt Lwt.t
null
https://raw.githubusercontent.com/ocsigen/eliom/c3e0eea5bef02e0af3942b6d27585add95d01d6c/src/lib/server/monitor/eliom_monitor.mli
ocaml
Ocsigen * * Copyright ( C ) 2014 Hugo Heuzard * * This program 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 , with linking exception ; * either version 2.1 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 Lesser General Public License for more details . * * You should have received a copy of the GNU Lesser General Public License * along with this program ; if not , write to the Free Software * Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA . * * Copyright (C) 2014 Hugo Heuzard * * This program 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, with linking exception; * either version 2.1 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *) val uptime : unit -> float val pid : unit -> int val fd : pid:int -> [`Ok of int | `Error of string] val content_div : unit -> [> Html_types.div] Eliom_content.Html.elt Lwt.t val content_html : unit -> [> Html_types.html] Eliom_content.Html.elt Lwt.t
04d699b8562bfc2be454545e4926286ec44790f50c96d8c996358bd0f324c5d7
j-mie6/ParsleyHaskell
Parsers.hs
module Parsley.Applicative.Parsers where
null
https://raw.githubusercontent.com/j-mie6/ParsleyHaskell/045ab78ed7af0cbb52cf8b42b6aeef5dd7f91ab2/parsley/test/Parsley/Applicative/Parsers.hs
haskell
module Parsley.Applicative.Parsers where
617919edda9f8ab26b6734e80b4ae797341f34a4231fec82ba3332428264190c
ocaml-ppx/ppx_tools_versioned
ppx_metaquot_409.ml
open Migrate_parsetree.Ast_409 (* This file is part of the ppx_tools package. It is released *) under the terms of the MIT license ( see LICENSE file ) . Copyright 2013 and LexiFi A -ppx rewriter to be used to write Parsetree - generating code ( including other -ppx rewriters ) using concrete syntax . We support the following extensions in expression position : [ % expr ... ] maps to code which creates the expression represented by ... [ % pat ? ... ] maps to code which creates the pattern represented by ... [ % str ... ] maps to code which creates the structure represented by ... [ % stri ... ] maps to code which creates the structure item represented by ... [ % sig : ... ] maps to code which creates the signature represented by ... [ % sigi : ... ] maps to code which creates the signature item represented by ... [ % type : ... ] maps to code which creates the core type represented by ... Quoted code can refer to expressions representing AST fragments , using the following extensions : [ % e ... ] where ... is an expression of type Parsetree.expression [ % t ... ] where ... is an expression of type Parsetree.core_type [ % p ... ] where ... is an expression of type Parsetree.pattern [ % % s ... ] where ... is an expression of type Parsetree.structure or Parsetree.signature depending on the context . All locations generated by the meta quotation are by default set to [ Ast_helper.default_loc ] . This can be overriden by providing a custom expression which will be inserted whereever a location is required in the generated AST . This expression can be specified globally ( for the current structure ) as a structure item attribute : ; ; [ @@metaloc ... ] or locally for the scope of an expression : e [ @metaloc ... ] Support is also provided to use concrete syntax in pattern position . The location and attribute fields are currently ignored by patterns generated from meta quotations . We support the following extensions in pattern position : [ % expr ... ] maps to code which creates the expression represented by ... [ % pat ? ... ] maps to code which creates the pattern represented by ... [ % str ... ] maps to code which creates the structure represented by ... [ % type : ... ] maps to code which creates the core type represented by ... Quoted code can refer to expressions representing AST fragments , using the following extensions : [ % e ? ... ] where ... is a pattern of type Parsetree.expression [ % t ? ... ] where ... is a pattern of type Parsetree.core_type [ % p ? ... ] where ... is a pattern of type Parsetree.pattern (including other -ppx rewriters) using concrete syntax. We support the following extensions in expression position: [%expr ...] maps to code which creates the expression represented by ... [%pat? ...] maps to code which creates the pattern represented by ... [%str ...] maps to code which creates the structure represented by ... [%stri ...] maps to code which creates the structure item represented by ... [%sig: ...] maps to code which creates the signature represented by ... [%sigi: ...] maps to code which creates the signature item represented by ... [%type: ...] maps to code which creates the core type represented by ... Quoted code can refer to expressions representing AST fragments, using the following extensions: [%e ...] where ... is an expression of type Parsetree.expression [%t ...] where ... is an expression of type Parsetree.core_type [%p ...] where ... is an expression of type Parsetree.pattern [%%s ...] where ... is an expression of type Parsetree.structure or Parsetree.signature depending on the context. All locations generated by the meta quotation are by default set to [Ast_helper.default_loc]. This can be overriden by providing a custom expression which will be inserted whereever a location is required in the generated AST. This expression can be specified globally (for the current structure) as a structure item attribute: ;;[@@metaloc ...] or locally for the scope of an expression: e [@metaloc ...] Support is also provided to use concrete syntax in pattern position. The location and attribute fields are currently ignored by patterns generated from meta quotations. We support the following extensions in pattern position: [%expr ...] maps to code which creates the expression represented by ... [%pat? ...] maps to code which creates the pattern represented by ... [%str ...] maps to code which creates the structure represented by ... [%type: ...] maps to code which creates the core type represented by ... Quoted code can refer to expressions representing AST fragments, using the following extensions: [%e? ...] where ... is a pattern of type Parsetree.expression [%t? ...] where ... is a pattern of type Parsetree.core_type [%p? ...] where ... is a pattern of type Parsetree.pattern *) module Main : sig end = struct open Asttypes open Parsetree open Ast_helper open Ast_convenience_409 let prefix ty s = let open Longident in match parse ty with | Ldot(m, _) -> String.concat "." (Longident.flatten m) ^ "." ^ s | _ -> s let append ?loc ?attrs e e' = let fn = Location.mknoloc (Longident.(Ldot (Lident "List", "append"))) in Exp.apply ?loc ?attrs (Exp.ident fn) [Nolabel, e; Nolabel, e'] class exp_builder = object method record ty x = record (List.map (fun (l, e) -> prefix ty l, e) x) method constr ty (c, args) = constr (prefix ty c) args method list l = list l method tuple l = tuple l method int i = int i method string s = str s method char c = char c method int32 x = Exp.constant (Const.int32 x) method int64 x = Exp.constant (Const.int64 x) method nativeint x = Exp.constant (Const.nativeint x) end class pat_builder = object method record ty x = precord ~closed:Closed (List.map (fun (l, e) -> prefix ty l, e) x) method constr ty (c, args) = pconstr (prefix ty c) args method list l = plist l method tuple l = ptuple l method int i = pint i method string s = pstr s method char c = pchar c method int32 x = Pat.constant (Const.int32 x) method int64 x = Pat.constant (Const.int64 x) method nativeint x = Pat.constant (Const.nativeint x) end let get_exp loc = function | PStr [ {pstr_desc=Pstr_eval (e, _); _} ] -> e | _ -> Format.eprintf "%aError: Expression expected@." Location.print_loc loc; exit 2 let get_typ loc = function | PTyp t -> t | _ -> Format.eprintf "%aError: Type expected@." Location.print_loc loc; exit 2 let get_pat loc = function | PPat (t, None) -> t | _ -> Format.eprintf "%aError: Pattern expected@." Location.print_loc loc; exit 2 let exp_lifter loc map = let map = map.Ast_mapper.expr map in object inherit [_] Ast_lifter_409.lifter as super inherit exp_builder Special support for location in the generated AST method! lift_Location_t _ = loc (* Support for antiquotations *) method! lift_Parsetree_expression = function | {pexp_desc=Pexp_extension({txt="e";loc}, e); _} -> map (get_exp loc e) | x -> super # lift_Parsetree_expression x method! lift_Parsetree_pattern = function | {ppat_desc=Ppat_extension({txt="p";loc}, e); _} -> map (get_exp loc e) | x -> super # lift_Parsetree_pattern x method! lift_Parsetree_structure str = List.fold_right (function | {pstr_desc=Pstr_extension(({txt="s";loc}, e), _); _} -> append (get_exp loc e) | x -> cons (super # lift_Parsetree_structure_item x)) str (nil ()) method! lift_Parsetree_signature sign = List.fold_right (function | {psig_desc=Psig_extension(({txt="s";loc}, e), _); _} -> append (get_exp loc e) | x -> cons (super # lift_Parsetree_signature_item x)) sign (nil ()) method! lift_Parsetree_core_type = function | {ptyp_desc=Ptyp_extension({txt="t";loc}, e); _} -> map (get_exp loc e) | x -> super # lift_Parsetree_core_type x end let pat_lifter map = let map = map.Ast_mapper.pat map in object inherit [_] Ast_lifter_409.lifter as super inherit pat_builder Special support for location and attributes in the generated AST method! lift_Location_t _ = Pat.any () method! lift_Parsetree_attributes _ = Pat.any () method! lift_loc_stack _ = Pat.any () (* Support for antiquotations *) method! lift_Parsetree_expression = function | {pexp_desc=Pexp_extension({txt="e";loc}, e); _} -> map (get_pat loc e) | x -> super # lift_Parsetree_expression x method! lift_Parsetree_pattern = function | {ppat_desc=Ppat_extension({txt="p";loc}, e); _} -> map (get_pat loc e) | x -> super # lift_Parsetree_pattern x method! lift_Parsetree_core_type = function | {ptyp_desc=Ptyp_extension({txt="t";loc}, e); _} -> map (get_pat loc e) | x -> super # lift_Parsetree_core_type x end let loc = ref (Exp.field (evar "Ast_helper.default_loc") (lid "contents")) let handle_attr = function | { attr_name = {txt="metaloc";loc=l} ; attr_payload = e ; attr_loc = _ } -> loc := get_exp l e | _ -> () let with_loc ?(attrs = []) f = let old_loc = !loc in List.iter handle_attr attrs; let r = f () in loc := old_loc; r let expander _config _cookies = let open Ast_mapper in let super = default_mapper in let expr this e = with_loc ~attrs:e.pexp_attributes (fun () -> match e.pexp_desc with | Pexp_extension({txt="expr";loc=l}, e) -> (exp_lifter !loc this) # lift_Parsetree_expression (get_exp l e) | Pexp_extension({txt="pat";loc=l}, e) -> (exp_lifter !loc this) # lift_Parsetree_pattern (get_pat l e) | Pexp_extension({txt="str";_}, PStr e) -> (exp_lifter !loc this) # lift_Parsetree_structure e | Pexp_extension({txt="stri";_}, PStr [e]) -> (exp_lifter !loc this) # lift_Parsetree_structure_item e | Pexp_extension({txt="sig";_}, PSig e) -> (exp_lifter !loc this) # lift_Parsetree_signature e | Pexp_extension({txt="sigi";_}, PSig [e]) -> (exp_lifter !loc this) # lift_Parsetree_signature_item e | Pexp_extension({txt="type";loc=l}, e) -> (exp_lifter !loc this) # lift_Parsetree_core_type (get_typ l e) | _ -> super.expr this e ) and pat this p = with_loc ~attrs:p.ppat_attributes (fun () -> match p.ppat_desc with | Ppat_extension({txt="expr";loc=l}, e) -> (pat_lifter this) # lift_Parsetree_expression (get_exp l e) | Ppat_extension({txt="pat";loc=l}, e) -> (pat_lifter this) # lift_Parsetree_pattern (get_pat l e) | Ppat_extension({txt="str";_}, PStr e) -> (pat_lifter this) # lift_Parsetree_structure e | Ppat_extension({txt="stri";_}, PStr [e]) -> (pat_lifter this) # lift_Parsetree_structure_item e | Ppat_extension({txt="sig";_}, PSig e) -> (pat_lifter this) # lift_Parsetree_signature e | Ppat_extension({txt="sigi";_}, PSig [e]) -> (pat_lifter this) # lift_Parsetree_signature_item e | Ppat_extension({txt="type";loc=l}, e) -> (pat_lifter this) # lift_Parsetree_core_type (get_typ l e) | _ -> super.pat this p ) and structure this l = with_loc (fun () -> super.structure this l) and structure_item this x = begin match x.pstr_desc with | Pstr_attribute x -> handle_attr x | _ -> () end; super.structure_item this x and signature this l = with_loc (fun () -> super.signature this l) and signature_item this x = begin match x.psig_desc with | Psig_attribute x -> handle_attr x | _ -> () end; super.signature_item this x in {super with expr; pat; structure; structure_item; signature; signature_item} let () = let open Migrate_parsetree in Driver.register ~name:"metaquot_409" Versions.ocaml_409 expander end
null
https://raw.githubusercontent.com/ocaml-ppx/ppx_tools_versioned/00a0150cdabfa7f0dad2c5e0e6b32230d22295ca/ppx_metaquot_409.ml
ocaml
This file is part of the ppx_tools package. It is released Support for antiquotations Support for antiquotations
open Migrate_parsetree.Ast_409 under the terms of the MIT license ( see LICENSE file ) . Copyright 2013 and LexiFi A -ppx rewriter to be used to write Parsetree - generating code ( including other -ppx rewriters ) using concrete syntax . We support the following extensions in expression position : [ % expr ... ] maps to code which creates the expression represented by ... [ % pat ? ... ] maps to code which creates the pattern represented by ... [ % str ... ] maps to code which creates the structure represented by ... [ % stri ... ] maps to code which creates the structure item represented by ... [ % sig : ... ] maps to code which creates the signature represented by ... [ % sigi : ... ] maps to code which creates the signature item represented by ... [ % type : ... ] maps to code which creates the core type represented by ... Quoted code can refer to expressions representing AST fragments , using the following extensions : [ % e ... ] where ... is an expression of type Parsetree.expression [ % t ... ] where ... is an expression of type Parsetree.core_type [ % p ... ] where ... is an expression of type Parsetree.pattern [ % % s ... ] where ... is an expression of type Parsetree.structure or Parsetree.signature depending on the context . All locations generated by the meta quotation are by default set to [ Ast_helper.default_loc ] . This can be overriden by providing a custom expression which will be inserted whereever a location is required in the generated AST . This expression can be specified globally ( for the current structure ) as a structure item attribute : ; ; [ @@metaloc ... ] or locally for the scope of an expression : e [ @metaloc ... ] Support is also provided to use concrete syntax in pattern position . The location and attribute fields are currently ignored by patterns generated from meta quotations . We support the following extensions in pattern position : [ % expr ... ] maps to code which creates the expression represented by ... [ % pat ? ... ] maps to code which creates the pattern represented by ... [ % str ... ] maps to code which creates the structure represented by ... [ % type : ... ] maps to code which creates the core type represented by ... Quoted code can refer to expressions representing AST fragments , using the following extensions : [ % e ? ... ] where ... is a pattern of type Parsetree.expression [ % t ? ... ] where ... is a pattern of type Parsetree.core_type [ % p ? ... ] where ... is a pattern of type Parsetree.pattern (including other -ppx rewriters) using concrete syntax. We support the following extensions in expression position: [%expr ...] maps to code which creates the expression represented by ... [%pat? ...] maps to code which creates the pattern represented by ... [%str ...] maps to code which creates the structure represented by ... [%stri ...] maps to code which creates the structure item represented by ... [%sig: ...] maps to code which creates the signature represented by ... [%sigi: ...] maps to code which creates the signature item represented by ... [%type: ...] maps to code which creates the core type represented by ... Quoted code can refer to expressions representing AST fragments, using the following extensions: [%e ...] where ... is an expression of type Parsetree.expression [%t ...] where ... is an expression of type Parsetree.core_type [%p ...] where ... is an expression of type Parsetree.pattern [%%s ...] where ... is an expression of type Parsetree.structure or Parsetree.signature depending on the context. All locations generated by the meta quotation are by default set to [Ast_helper.default_loc]. This can be overriden by providing a custom expression which will be inserted whereever a location is required in the generated AST. This expression can be specified globally (for the current structure) as a structure item attribute: ;;[@@metaloc ...] or locally for the scope of an expression: e [@metaloc ...] Support is also provided to use concrete syntax in pattern position. The location and attribute fields are currently ignored by patterns generated from meta quotations. We support the following extensions in pattern position: [%expr ...] maps to code which creates the expression represented by ... [%pat? ...] maps to code which creates the pattern represented by ... [%str ...] maps to code which creates the structure represented by ... [%type: ...] maps to code which creates the core type represented by ... Quoted code can refer to expressions representing AST fragments, using the following extensions: [%e? ...] where ... is a pattern of type Parsetree.expression [%t? ...] where ... is a pattern of type Parsetree.core_type [%p? ...] where ... is a pattern of type Parsetree.pattern *) module Main : sig end = struct open Asttypes open Parsetree open Ast_helper open Ast_convenience_409 let prefix ty s = let open Longident in match parse ty with | Ldot(m, _) -> String.concat "." (Longident.flatten m) ^ "." ^ s | _ -> s let append ?loc ?attrs e e' = let fn = Location.mknoloc (Longident.(Ldot (Lident "List", "append"))) in Exp.apply ?loc ?attrs (Exp.ident fn) [Nolabel, e; Nolabel, e'] class exp_builder = object method record ty x = record (List.map (fun (l, e) -> prefix ty l, e) x) method constr ty (c, args) = constr (prefix ty c) args method list l = list l method tuple l = tuple l method int i = int i method string s = str s method char c = char c method int32 x = Exp.constant (Const.int32 x) method int64 x = Exp.constant (Const.int64 x) method nativeint x = Exp.constant (Const.nativeint x) end class pat_builder = object method record ty x = precord ~closed:Closed (List.map (fun (l, e) -> prefix ty l, e) x) method constr ty (c, args) = pconstr (prefix ty c) args method list l = plist l method tuple l = ptuple l method int i = pint i method string s = pstr s method char c = pchar c method int32 x = Pat.constant (Const.int32 x) method int64 x = Pat.constant (Const.int64 x) method nativeint x = Pat.constant (Const.nativeint x) end let get_exp loc = function | PStr [ {pstr_desc=Pstr_eval (e, _); _} ] -> e | _ -> Format.eprintf "%aError: Expression expected@." Location.print_loc loc; exit 2 let get_typ loc = function | PTyp t -> t | _ -> Format.eprintf "%aError: Type expected@." Location.print_loc loc; exit 2 let get_pat loc = function | PPat (t, None) -> t | _ -> Format.eprintf "%aError: Pattern expected@." Location.print_loc loc; exit 2 let exp_lifter loc map = let map = map.Ast_mapper.expr map in object inherit [_] Ast_lifter_409.lifter as super inherit exp_builder Special support for location in the generated AST method! lift_Location_t _ = loc method! lift_Parsetree_expression = function | {pexp_desc=Pexp_extension({txt="e";loc}, e); _} -> map (get_exp loc e) | x -> super # lift_Parsetree_expression x method! lift_Parsetree_pattern = function | {ppat_desc=Ppat_extension({txt="p";loc}, e); _} -> map (get_exp loc e) | x -> super # lift_Parsetree_pattern x method! lift_Parsetree_structure str = List.fold_right (function | {pstr_desc=Pstr_extension(({txt="s";loc}, e), _); _} -> append (get_exp loc e) | x -> cons (super # lift_Parsetree_structure_item x)) str (nil ()) method! lift_Parsetree_signature sign = List.fold_right (function | {psig_desc=Psig_extension(({txt="s";loc}, e), _); _} -> append (get_exp loc e) | x -> cons (super # lift_Parsetree_signature_item x)) sign (nil ()) method! lift_Parsetree_core_type = function | {ptyp_desc=Ptyp_extension({txt="t";loc}, e); _} -> map (get_exp loc e) | x -> super # lift_Parsetree_core_type x end let pat_lifter map = let map = map.Ast_mapper.pat map in object inherit [_] Ast_lifter_409.lifter as super inherit pat_builder Special support for location and attributes in the generated AST method! lift_Location_t _ = Pat.any () method! lift_Parsetree_attributes _ = Pat.any () method! lift_loc_stack _ = Pat.any () method! lift_Parsetree_expression = function | {pexp_desc=Pexp_extension({txt="e";loc}, e); _} -> map (get_pat loc e) | x -> super # lift_Parsetree_expression x method! lift_Parsetree_pattern = function | {ppat_desc=Ppat_extension({txt="p";loc}, e); _} -> map (get_pat loc e) | x -> super # lift_Parsetree_pattern x method! lift_Parsetree_core_type = function | {ptyp_desc=Ptyp_extension({txt="t";loc}, e); _} -> map (get_pat loc e) | x -> super # lift_Parsetree_core_type x end let loc = ref (Exp.field (evar "Ast_helper.default_loc") (lid "contents")) let handle_attr = function | { attr_name = {txt="metaloc";loc=l} ; attr_payload = e ; attr_loc = _ } -> loc := get_exp l e | _ -> () let with_loc ?(attrs = []) f = let old_loc = !loc in List.iter handle_attr attrs; let r = f () in loc := old_loc; r let expander _config _cookies = let open Ast_mapper in let super = default_mapper in let expr this e = with_loc ~attrs:e.pexp_attributes (fun () -> match e.pexp_desc with | Pexp_extension({txt="expr";loc=l}, e) -> (exp_lifter !loc this) # lift_Parsetree_expression (get_exp l e) | Pexp_extension({txt="pat";loc=l}, e) -> (exp_lifter !loc this) # lift_Parsetree_pattern (get_pat l e) | Pexp_extension({txt="str";_}, PStr e) -> (exp_lifter !loc this) # lift_Parsetree_structure e | Pexp_extension({txt="stri";_}, PStr [e]) -> (exp_lifter !loc this) # lift_Parsetree_structure_item e | Pexp_extension({txt="sig";_}, PSig e) -> (exp_lifter !loc this) # lift_Parsetree_signature e | Pexp_extension({txt="sigi";_}, PSig [e]) -> (exp_lifter !loc this) # lift_Parsetree_signature_item e | Pexp_extension({txt="type";loc=l}, e) -> (exp_lifter !loc this) # lift_Parsetree_core_type (get_typ l e) | _ -> super.expr this e ) and pat this p = with_loc ~attrs:p.ppat_attributes (fun () -> match p.ppat_desc with | Ppat_extension({txt="expr";loc=l}, e) -> (pat_lifter this) # lift_Parsetree_expression (get_exp l e) | Ppat_extension({txt="pat";loc=l}, e) -> (pat_lifter this) # lift_Parsetree_pattern (get_pat l e) | Ppat_extension({txt="str";_}, PStr e) -> (pat_lifter this) # lift_Parsetree_structure e | Ppat_extension({txt="stri";_}, PStr [e]) -> (pat_lifter this) # lift_Parsetree_structure_item e | Ppat_extension({txt="sig";_}, PSig e) -> (pat_lifter this) # lift_Parsetree_signature e | Ppat_extension({txt="sigi";_}, PSig [e]) -> (pat_lifter this) # lift_Parsetree_signature_item e | Ppat_extension({txt="type";loc=l}, e) -> (pat_lifter this) # lift_Parsetree_core_type (get_typ l e) | _ -> super.pat this p ) and structure this l = with_loc (fun () -> super.structure this l) and structure_item this x = begin match x.pstr_desc with | Pstr_attribute x -> handle_attr x | _ -> () end; super.structure_item this x and signature this l = with_loc (fun () -> super.signature this l) and signature_item this x = begin match x.psig_desc with | Psig_attribute x -> handle_attr x | _ -> () end; super.signature_item this x in {super with expr; pat; structure; structure_item; signature; signature_item} let () = let open Migrate_parsetree in Driver.register ~name:"metaquot_409" Versions.ocaml_409 expander end
487289597a4e71cfdec15df7bea193ad4a1b32bc94fb1301b00e3bc76c9c421a
cmahon/interactive-brokers
IB.hs
-- | -- This module provides an interface for communicating with the Interactive -- Brokers API. module API.IB ( module IB , module Currency ) where import API.IB.Builder as IB import API.IB.Connection as IB import API.IB.Data as IB import API.IB.Enum as IB import API.IB.Monadic as IB import Currency
null
https://raw.githubusercontent.com/cmahon/interactive-brokers/cf6c1128b3f44559b868bc346e76354f8ca4add6/library/API/IB.hs
haskell
| This module provides an interface for communicating with the Interactive Brokers API.
module API.IB ( module IB , module Currency ) where import API.IB.Builder as IB import API.IB.Connection as IB import API.IB.Data as IB import API.IB.Enum as IB import API.IB.Monadic as IB import Currency
708e448982678b5425d4e4026ab3ee7b2b933ac6948a84a1f59f0303dc828917
penpot/penpot
fonts.cljs
This Source Code Form is subject to the terms of the Mozilla Public License , v. 2.0 . If a copy of the MPL was not distributed with this file , You can obtain one at /. ;; ;; Copyright (c) KALEIDOS INC (ns app.main.ui.dashboard.fonts (:require [app.common.media :as cm] [app.main.data.fonts :as df] [app.main.data.modal :as modal] [app.main.refs :as refs] [app.main.repo :as rp] [app.main.store :as st] [app.main.ui.components.context-menu :refer [context-menu]] [app.main.ui.components.file-uploader :refer [file-uploader]] [app.main.ui.icons :as i] [app.util.dom :as dom] [app.util.i18n :as i18n :refer [tr]] [app.util.keyboard :as kbd] [beicon.core :as rx] [cuerdas.core :as str] [rumext.v2 :as mf])) (defn- use-set-page-title [team section] (mf/use-effect (mf/deps team) (fn [] (when team (let [tname (if (:is-default team) (tr "dashboard.your-penpot") (:name team))] (case section :fonts (dom/set-html-title (tr "title.dashboard.fonts" tname)) :providers (dom/set-html-title (tr "title.dashboard.font-providers" tname)))))))) (mf/defc header {::mf/wrap [mf/memo]} [{:keys [section team] :as props}] ;; (let [go-fonts ;; (mf/use-callback ( mf / team ) ;; #(st/emit! (rt/nav :dashboard-fonts {:team-id (:id team)}))) ;; go-providers ;; (mf/use-callback ( mf / team ) ;; #(st/emit! (rt/nav :dashboard-font-providers {:team-id (:id team)})))] (use-set-page-title team section) [:header.dashboard-header [:div.dashboard-title#dashboard-fonts-title [:h1 (tr "labels.fonts")]] [:nav #_[:ul [:li {:class (when (= section :fonts) "active")} [:a {:on-click go-fonts} (tr "labels.custom-fonts")]] [:li {:class (when (= section :providers) "active")} [:a {:on-click go-providers} (tr "labels.font-providers")]]]] [:div]]) (mf/defc font-variant-display-name [{:keys [variant]}] [:* [:span (cm/font-weight->name (:font-weight variant))] (when (not= "normal" (:font-style variant)) [:span " " (str/capital (:font-style variant))])]) (mf/defc fonts-upload [{:keys [team installed-fonts] :as props}] (let [fonts (mf/use-state {}) input-ref (mf/use-ref) uploading (mf/use-state #{}) on-click (mf/use-callback #(dom/click (mf/ref-val input-ref))) on-selected (mf/use-callback (mf/deps team installed-fonts) (fn [blobs] (->> (df/process-upload blobs (:id team)) (rx/subs (fn [result] (swap! fonts df/merge-and-group-fonts installed-fonts result)) (fn [error] (js/console.error "error" error)))))) on-upload (mf/use-callback (mf/deps team) (fn [item] (swap! uploading conj (:id item)) (->> (rp/cmd! :create-font-variant item) (rx/delay-at-least 2000) (rx/subs (fn [font] (swap! fonts dissoc (:id item)) (swap! uploading disj (:id item)) (st/emit! (df/add-font font))) (fn [error] (js/console.log "error" error)))))) on-upload-all (fn [items] (run! on-upload items)) on-blur-name (fn [id event] (let [name (dom/get-target-val event)] (swap! fonts df/rename-and-regroup id name installed-fonts))) on-delete (mf/use-callback (mf/deps team) (fn [{:keys [id] :as item}] (swap! fonts dissoc id))) on-dismiss-all (fn [items] (run! on-delete items)) problematic-fonts? (some :height-warning? (vals @fonts))] [:div.dashboard-fonts-upload [:div.dashboard-fonts-hero [:div.desc [:h2 (tr "labels.upload-custom-fonts")] [:& i18n/tr-html {:label "dashboard.fonts.hero-text1"}] [:div.banner [:div.icon i/msg-info] [:div.content [:& i18n/tr-html {:tag-name "span" :label "dashboard.fonts.hero-text2"}]]] (when problematic-fonts? [:div.banner.warning [:div.icon i/msg-warning] [:div.content [:& i18n/tr-html {:tag-name "span" :label "dashboard.fonts.warning-text"}]]])] [:button.btn-primary {:on-click on-click :tab-index "0"} [:span (tr "labels.add-custom-font")] [:& file-uploader {:input-id "font-upload" :accept cm/str-font-types :multi true :ref input-ref :on-selected on-selected}]]] [:* (when (some? (vals @fonts)) [:div.font-item.table-row [:span (tr "dashboard.fonts.fonts-added" (i18n/c (count (vals @fonts))))] [:div.table-field.options [:div.btn-primary {:on-click #(on-upload-all (vals @fonts)) :data-test "upload-all"} [:span (tr "dashboard.fonts.upload-all")]] [:div.btn-secondary {:on-click #(on-dismiss-all (vals @fonts)) :data-test "dismiss-all"} [:span (tr "dashboard.fonts.dismiss-all")]]]]) (for [item (sort-by :font-family (vals @fonts))] (let [uploading? (contains? @uploading (:id item))] [:div.font-item.table-row {:key (:id item)} [:div.table-field.family [:input {:type "text" :on-blur #(on-blur-name (:id item) %) :default-value (:font-family item)}]] [:div.table-field.variants [:span.label [:& font-variant-display-name {:variant item}]]] [:div.table-field.filenames (for [item (:names item)] [:span item])] [:div.table-field.options (when (:height-warning? item) [:span.icon.failure i/msg-warning]) [:button.btn-primary.upload-button {:on-click #(on-upload item) :class (dom/classnames :disabled uploading?) :disabled uploading?} (if uploading? (tr "labels.uploading") (tr "labels.upload"))] [:span.icon.close {:on-click #(on-delete item)} i/close]]]))]])) (mf/defc installed-font [{:keys [font-id variants] :as props}] (let [font (first variants) variants (sort-by (fn [item] [(:font-weight item) (if (= "normal" (:font-style item)) 1 2)]) variants) open-menu? (mf/use-state false) edit? (mf/use-state false) state (mf/use-var (:font-family font)) on-change (fn [event] (reset! state (dom/get-target-val event))) on-save (fn [_] (let [font-family @state] (when-not (str/blank? font-family) (st/emit! (df/update-font {:id font-id :name font-family}))) (reset! edit? false))) on-key-down (fn [event] (when (kbd/enter? event) (on-save event))) on-cancel (fn [_] (reset! edit? false) (reset! state (:font-family font))) delete-font-fn (fn [] (st/emit! (df/delete-font font-id))) delete-variant-fn (fn [id] (st/emit! (df/delete-font-variant id))) on-delete (fn [] (st/emit! (modal/show {:type :confirm :title (tr "modals.delete-font.title") :message (tr "modals.delete-font.message") :accept-label (tr "labels.delete") :on-accept (fn [_props] (delete-font-fn))}))) on-delete-variant (fn [id] (st/emit! (modal/show {:type :confirm :title (tr "modals.delete-font-variant.title") :message (tr "modals.delete-font-variant.message") :accept-label (tr "labels.delete") :on-accept (fn [_props] (delete-variant-fn id))})))] [:div.font-item.table-row [:div.table-field.family (if @edit? [:input {:type "text" :default-value @state :on-key-down on-key-down :on-change on-change}] [:span (:font-family font)])] [:div.table-field.variants (for [item variants] [:div.variant [:span.label [:& font-variant-display-name {:variant item}]] [:span.icon.close {:on-click #(on-delete-variant (:id item))} i/plus]])] [:div] (if @edit? [:div.table-field.options [:button.btn-primary {:disabled (str/blank? @state) :on-click on-save :class (dom/classnames :btn-disabled (str/blank? @state))} (tr "labels.save")] [:span.icon.close {:on-click on-cancel} i/close]] [:div.table-field.options [:span.icon {:on-click #(reset! open-menu? true)} i/actions] [:& context-menu {:on-close #(reset! open-menu? false) :show @open-menu? :fixed? false :top -15 :left -115 :options [[(tr "labels.edit") #(reset! edit? true) nil "font-edit"] [(tr "labels.delete") on-delete nil "font-delete"]]}]])])) (mf/defc installed-fonts [{:keys [fonts] :as props}] (let [sterm (mf/use-state "") matches? #(str/includes? (str/lower (:font-family %)) @sterm) on-change (mf/use-callback (fn [event] (let [val (dom/get-target-val event)] (reset! sterm (str/lower val)))))] [:div.dashboard-installed-fonts [:h3 (tr "labels.installed-fonts")] [:div.installed-fonts-header [:div.table-field.family (tr "labels.font-family")] [:div.table-field.variants (tr "labels.font-variants")] [:div] [:div.table-field.search-input [:input {:placeholder (tr "labels.search-font") :default-value "" :on-change on-change}]]] (cond (seq fonts) (for [[font-id variants] (->> (vals fonts) (filter matches?) (group-by :font-id))] [:& installed-font {:key (str font-id) :font-id font-id :variants variants}]) (nil? fonts) [:div.fonts-placeholder [:div.icon i/loader] [:div.label (tr "dashboard.loading-fonts")]] :else [:div.fonts-placeholder [:div.icon i/text] [:div.label (tr "dashboard.fonts.empty-placeholder")]])])) (mf/defc fonts-page [{:keys [team] :as props}] (let [fonts (mf/deref refs/dashboard-fonts)] [:* [:& header {:team team :section :fonts}] [:section.dashboard-container.dashboard-fonts [:& fonts-upload {:team team :installed-fonts fonts}] [:& installed-fonts {:team team :fonts fonts}]]])) (mf/defc font-providers-page [{:keys [team] :as props}] [:* [:& header {:team team :section :providers}] [:section.dashboard-container [:span "font providers"]]])
null
https://raw.githubusercontent.com/penpot/penpot/50ee0ad3fd4627b000841fa2eb4ee13ae9d93a9a/frontend/src/app/main/ui/dashboard/fonts.cljs
clojure
Copyright (c) KALEIDOS INC (let [go-fonts (mf/use-callback #(st/emit! (rt/nav :dashboard-fonts {:team-id (:id team)}))) go-providers (mf/use-callback #(st/emit! (rt/nav :dashboard-font-providers {:team-id (:id team)})))]
This Source Code Form is subject to the terms of the Mozilla Public License , v. 2.0 . If a copy of the MPL was not distributed with this file , You can obtain one at /. (ns app.main.ui.dashboard.fonts (:require [app.common.media :as cm] [app.main.data.fonts :as df] [app.main.data.modal :as modal] [app.main.refs :as refs] [app.main.repo :as rp] [app.main.store :as st] [app.main.ui.components.context-menu :refer [context-menu]] [app.main.ui.components.file-uploader :refer [file-uploader]] [app.main.ui.icons :as i] [app.util.dom :as dom] [app.util.i18n :as i18n :refer [tr]] [app.util.keyboard :as kbd] [beicon.core :as rx] [cuerdas.core :as str] [rumext.v2 :as mf])) (defn- use-set-page-title [team section] (mf/use-effect (mf/deps team) (fn [] (when team (let [tname (if (:is-default team) (tr "dashboard.your-penpot") (:name team))] (case section :fonts (dom/set-html-title (tr "title.dashboard.fonts" tname)) :providers (dom/set-html-title (tr "title.dashboard.font-providers" tname)))))))) (mf/defc header {::mf/wrap [mf/memo]} [{:keys [section team] :as props}] ( mf / team ) ( mf / team ) (use-set-page-title team section) [:header.dashboard-header [:div.dashboard-title#dashboard-fonts-title [:h1 (tr "labels.fonts")]] [:nav #_[:ul [:li {:class (when (= section :fonts) "active")} [:a {:on-click go-fonts} (tr "labels.custom-fonts")]] [:li {:class (when (= section :providers) "active")} [:a {:on-click go-providers} (tr "labels.font-providers")]]]] [:div]]) (mf/defc font-variant-display-name [{:keys [variant]}] [:* [:span (cm/font-weight->name (:font-weight variant))] (when (not= "normal" (:font-style variant)) [:span " " (str/capital (:font-style variant))])]) (mf/defc fonts-upload [{:keys [team installed-fonts] :as props}] (let [fonts (mf/use-state {}) input-ref (mf/use-ref) uploading (mf/use-state #{}) on-click (mf/use-callback #(dom/click (mf/ref-val input-ref))) on-selected (mf/use-callback (mf/deps team installed-fonts) (fn [blobs] (->> (df/process-upload blobs (:id team)) (rx/subs (fn [result] (swap! fonts df/merge-and-group-fonts installed-fonts result)) (fn [error] (js/console.error "error" error)))))) on-upload (mf/use-callback (mf/deps team) (fn [item] (swap! uploading conj (:id item)) (->> (rp/cmd! :create-font-variant item) (rx/delay-at-least 2000) (rx/subs (fn [font] (swap! fonts dissoc (:id item)) (swap! uploading disj (:id item)) (st/emit! (df/add-font font))) (fn [error] (js/console.log "error" error)))))) on-upload-all (fn [items] (run! on-upload items)) on-blur-name (fn [id event] (let [name (dom/get-target-val event)] (swap! fonts df/rename-and-regroup id name installed-fonts))) on-delete (mf/use-callback (mf/deps team) (fn [{:keys [id] :as item}] (swap! fonts dissoc id))) on-dismiss-all (fn [items] (run! on-delete items)) problematic-fonts? (some :height-warning? (vals @fonts))] [:div.dashboard-fonts-upload [:div.dashboard-fonts-hero [:div.desc [:h2 (tr "labels.upload-custom-fonts")] [:& i18n/tr-html {:label "dashboard.fonts.hero-text1"}] [:div.banner [:div.icon i/msg-info] [:div.content [:& i18n/tr-html {:tag-name "span" :label "dashboard.fonts.hero-text2"}]]] (when problematic-fonts? [:div.banner.warning [:div.icon i/msg-warning] [:div.content [:& i18n/tr-html {:tag-name "span" :label "dashboard.fonts.warning-text"}]]])] [:button.btn-primary {:on-click on-click :tab-index "0"} [:span (tr "labels.add-custom-font")] [:& file-uploader {:input-id "font-upload" :accept cm/str-font-types :multi true :ref input-ref :on-selected on-selected}]]] [:* (when (some? (vals @fonts)) [:div.font-item.table-row [:span (tr "dashboard.fonts.fonts-added" (i18n/c (count (vals @fonts))))] [:div.table-field.options [:div.btn-primary {:on-click #(on-upload-all (vals @fonts)) :data-test "upload-all"} [:span (tr "dashboard.fonts.upload-all")]] [:div.btn-secondary {:on-click #(on-dismiss-all (vals @fonts)) :data-test "dismiss-all"} [:span (tr "dashboard.fonts.dismiss-all")]]]]) (for [item (sort-by :font-family (vals @fonts))] (let [uploading? (contains? @uploading (:id item))] [:div.font-item.table-row {:key (:id item)} [:div.table-field.family [:input {:type "text" :on-blur #(on-blur-name (:id item) %) :default-value (:font-family item)}]] [:div.table-field.variants [:span.label [:& font-variant-display-name {:variant item}]]] [:div.table-field.filenames (for [item (:names item)] [:span item])] [:div.table-field.options (when (:height-warning? item) [:span.icon.failure i/msg-warning]) [:button.btn-primary.upload-button {:on-click #(on-upload item) :class (dom/classnames :disabled uploading?) :disabled uploading?} (if uploading? (tr "labels.uploading") (tr "labels.upload"))] [:span.icon.close {:on-click #(on-delete item)} i/close]]]))]])) (mf/defc installed-font [{:keys [font-id variants] :as props}] (let [font (first variants) variants (sort-by (fn [item] [(:font-weight item) (if (= "normal" (:font-style item)) 1 2)]) variants) open-menu? (mf/use-state false) edit? (mf/use-state false) state (mf/use-var (:font-family font)) on-change (fn [event] (reset! state (dom/get-target-val event))) on-save (fn [_] (let [font-family @state] (when-not (str/blank? font-family) (st/emit! (df/update-font {:id font-id :name font-family}))) (reset! edit? false))) on-key-down (fn [event] (when (kbd/enter? event) (on-save event))) on-cancel (fn [_] (reset! edit? false) (reset! state (:font-family font))) delete-font-fn (fn [] (st/emit! (df/delete-font font-id))) delete-variant-fn (fn [id] (st/emit! (df/delete-font-variant id))) on-delete (fn [] (st/emit! (modal/show {:type :confirm :title (tr "modals.delete-font.title") :message (tr "modals.delete-font.message") :accept-label (tr "labels.delete") :on-accept (fn [_props] (delete-font-fn))}))) on-delete-variant (fn [id] (st/emit! (modal/show {:type :confirm :title (tr "modals.delete-font-variant.title") :message (tr "modals.delete-font-variant.message") :accept-label (tr "labels.delete") :on-accept (fn [_props] (delete-variant-fn id))})))] [:div.font-item.table-row [:div.table-field.family (if @edit? [:input {:type "text" :default-value @state :on-key-down on-key-down :on-change on-change}] [:span (:font-family font)])] [:div.table-field.variants (for [item variants] [:div.variant [:span.label [:& font-variant-display-name {:variant item}]] [:span.icon.close {:on-click #(on-delete-variant (:id item))} i/plus]])] [:div] (if @edit? [:div.table-field.options [:button.btn-primary {:disabled (str/blank? @state) :on-click on-save :class (dom/classnames :btn-disabled (str/blank? @state))} (tr "labels.save")] [:span.icon.close {:on-click on-cancel} i/close]] [:div.table-field.options [:span.icon {:on-click #(reset! open-menu? true)} i/actions] [:& context-menu {:on-close #(reset! open-menu? false) :show @open-menu? :fixed? false :top -15 :left -115 :options [[(tr "labels.edit") #(reset! edit? true) nil "font-edit"] [(tr "labels.delete") on-delete nil "font-delete"]]}]])])) (mf/defc installed-fonts [{:keys [fonts] :as props}] (let [sterm (mf/use-state "") matches? #(str/includes? (str/lower (:font-family %)) @sterm) on-change (mf/use-callback (fn [event] (let [val (dom/get-target-val event)] (reset! sterm (str/lower val)))))] [:div.dashboard-installed-fonts [:h3 (tr "labels.installed-fonts")] [:div.installed-fonts-header [:div.table-field.family (tr "labels.font-family")] [:div.table-field.variants (tr "labels.font-variants")] [:div] [:div.table-field.search-input [:input {:placeholder (tr "labels.search-font") :default-value "" :on-change on-change}]]] (cond (seq fonts) (for [[font-id variants] (->> (vals fonts) (filter matches?) (group-by :font-id))] [:& installed-font {:key (str font-id) :font-id font-id :variants variants}]) (nil? fonts) [:div.fonts-placeholder [:div.icon i/loader] [:div.label (tr "dashboard.loading-fonts")]] :else [:div.fonts-placeholder [:div.icon i/text] [:div.label (tr "dashboard.fonts.empty-placeholder")]])])) (mf/defc fonts-page [{:keys [team] :as props}] (let [fonts (mf/deref refs/dashboard-fonts)] [:* [:& header {:team team :section :fonts}] [:section.dashboard-container.dashboard-fonts [:& fonts-upload {:team team :installed-fonts fonts}] [:& installed-fonts {:team team :fonts fonts}]]])) (mf/defc font-providers-page [{:keys [team] :as props}] [:* [:& header {:team team :section :providers}] [:section.dashboard-container [:span "font providers"]]])
371610db226a374b5b8140151fc2cf43ecba0bb9c7c5faa95ccaa417157ad9e4
metabase/metabase
params.clj
(ns metabase.driver.bigquery-cloud-sdk.params (:require [java-time :as t] [metabase.util.date-2 :as u.date] [metabase.util.log :as log]) (:import (com.google.cloud.bigquery QueryJobConfiguration$Builder QueryParameterValue StandardSQLTypeName))) (set! *warn-on-reflection* true) (defn- param ^QueryParameterValue [type-name v] (.build (doto (QueryParameterValue/newBuilder) (.setType (StandardSQLTypeName/valueOf type-name)) (.setValue (some-> v str))))) (defmulti ^:private ->QueryParameterValue {:arglists '(^QueryParameterValue [v])} class) (defmethod ->QueryParameterValue :default [v] (param "STRING" v)) ;; See -types for type mappings ;; `nil` still has to be given a type (this determines the type it comes back as in cases like `["SELECT ?" nil]`) -- AFAIK this only affects native queries because ` NULL ` is usually spliced into the compiled SQL directly in MBQL ;; queries. Unfortunately we don't know the actual type we should set here so `STRING` is going to have to do for now. ;; This shouldn't really matter anyways since `WHERE field = NULL` generally doesn't work (we have to do `WHERE FIELD ;; IS NULL` instead) (defmethod ->QueryParameterValue nil [_] (param "STRING" nil)) (defmethod ->QueryParameterValue String [v] (param "STRING" v)) (defmethod ->QueryParameterValue Boolean [v] (param "BOOL" v)) (defmethod ->QueryParameterValue Integer [v] (param "INT64" v)) (defmethod ->QueryParameterValue Long [v] (param "INT64" v)) (defmethod ->QueryParameterValue Short [v] (param "INT64" v)) (defmethod ->QueryParameterValue Byte [v] (param "INT64" v)) (defmethod ->QueryParameterValue clojure.lang.BigInt [v] (param "INT64" v)) (defmethod ->QueryParameterValue Float [v] (param "FLOAT64" v)) (defmethod ->QueryParameterValue Double [v] (param "FLOAT64" v)) use the min and values for the NUMERIC types to figure out if we need to set decimal params as NUMERIC or BIGNUMERIC (def ^:private ^:const ^BigDecimal max-bq-numeric-val (bigdec "9.9999999999999999999999999999999999999E+28")) (def ^:private ^:const ^BigDecimal min-bq-numeric-val (.negate max-bq-numeric-val)) (defmethod ->QueryParameterValue java.math.BigDecimal [^BigDecimal v] (if (or (and (< 0 (.signum v)) (< 0 (.compareTo v min-bq-numeric-val))) (and (> 0 (.signum v)) (> 0 (.compareTo v max-bq-numeric-val)))) (param "BIGNUMERIC" v) (param "NUMERIC" v))) (defmethod ->QueryParameterValue java.time.LocalDate [t] (param "DATE" (u.date/format t))) (defmethod ->QueryParameterValue java.time.LocalDateTime [t] (param "DATETIME" (u.date/format t))) (defmethod ->QueryParameterValue java.time.LocalTime [t] (param "TIME" (u.date/format t))) (defmethod ->QueryParameterValue java.time.OffsetTime [t] (param "TIME" (->> (t/zone-offset 0) (t/with-offset-same-instant t) t/local-time u.date/format))) (defmethod ->QueryParameterValue java.time.OffsetDateTime [t] (param "TIMESTAMP" (u.date/format t))) (defmethod ->QueryParameterValue java.time.ZonedDateTime [t] (param "TIMESTAMP" (->> (t/zone-id "UTC") (t/with-zone-same-instant t) t/offset-date-time u.date/format))) (defn- query-parameter ^QueryParameterValue [value] (let [param (->QueryParameterValue value)] (log/tracef "Set parameter ^%s %s -> %s" (some-> value class .getCanonicalName) (pr-str value) (pr-str param)) param)) (defn set-parameters! "Set the `parameters` (i.e., values for `?` positional placeholders in the SQL) for a `query` request. Equivalent to JDBC `.setObject()` and the like." ^QueryJobConfiguration$Builder [^QueryJobConfiguration$Builder query parameters] (doseq [p parameters] (.addPositionalParameter query (query-parameter p))) query)
null
https://raw.githubusercontent.com/metabase/metabase/7e3048bf73f6cb7527579446166d054292166163/modules/drivers/bigquery-cloud-sdk/src/metabase/driver/bigquery_cloud_sdk/params.clj
clojure
See -types for type mappings `nil` still has to be given a type (this determines the type it comes back as in cases like `["SELECT ?" nil]`) -- queries. Unfortunately we don't know the actual type we should set here so `STRING` is going to have to do for now. This shouldn't really matter anyways since `WHERE field = NULL` generally doesn't work (we have to do `WHERE FIELD IS NULL` instead)
(ns metabase.driver.bigquery-cloud-sdk.params (:require [java-time :as t] [metabase.util.date-2 :as u.date] [metabase.util.log :as log]) (:import (com.google.cloud.bigquery QueryJobConfiguration$Builder QueryParameterValue StandardSQLTypeName))) (set! *warn-on-reflection* true) (defn- param ^QueryParameterValue [type-name v] (.build (doto (QueryParameterValue/newBuilder) (.setType (StandardSQLTypeName/valueOf type-name)) (.setValue (some-> v str))))) (defmulti ^:private ->QueryParameterValue {:arglists '(^QueryParameterValue [v])} class) (defmethod ->QueryParameterValue :default [v] (param "STRING" v)) AFAIK this only affects native queries because ` NULL ` is usually spliced into the compiled SQL directly in MBQL (defmethod ->QueryParameterValue nil [_] (param "STRING" nil)) (defmethod ->QueryParameterValue String [v] (param "STRING" v)) (defmethod ->QueryParameterValue Boolean [v] (param "BOOL" v)) (defmethod ->QueryParameterValue Integer [v] (param "INT64" v)) (defmethod ->QueryParameterValue Long [v] (param "INT64" v)) (defmethod ->QueryParameterValue Short [v] (param "INT64" v)) (defmethod ->QueryParameterValue Byte [v] (param "INT64" v)) (defmethod ->QueryParameterValue clojure.lang.BigInt [v] (param "INT64" v)) (defmethod ->QueryParameterValue Float [v] (param "FLOAT64" v)) (defmethod ->QueryParameterValue Double [v] (param "FLOAT64" v)) use the min and values for the NUMERIC types to figure out if we need to set decimal params as NUMERIC or BIGNUMERIC (def ^:private ^:const ^BigDecimal max-bq-numeric-val (bigdec "9.9999999999999999999999999999999999999E+28")) (def ^:private ^:const ^BigDecimal min-bq-numeric-val (.negate max-bq-numeric-val)) (defmethod ->QueryParameterValue java.math.BigDecimal [^BigDecimal v] (if (or (and (< 0 (.signum v)) (< 0 (.compareTo v min-bq-numeric-val))) (and (> 0 (.signum v)) (> 0 (.compareTo v max-bq-numeric-val)))) (param "BIGNUMERIC" v) (param "NUMERIC" v))) (defmethod ->QueryParameterValue java.time.LocalDate [t] (param "DATE" (u.date/format t))) (defmethod ->QueryParameterValue java.time.LocalDateTime [t] (param "DATETIME" (u.date/format t))) (defmethod ->QueryParameterValue java.time.LocalTime [t] (param "TIME" (u.date/format t))) (defmethod ->QueryParameterValue java.time.OffsetTime [t] (param "TIME" (->> (t/zone-offset 0) (t/with-offset-same-instant t) t/local-time u.date/format))) (defmethod ->QueryParameterValue java.time.OffsetDateTime [t] (param "TIMESTAMP" (u.date/format t))) (defmethod ->QueryParameterValue java.time.ZonedDateTime [t] (param "TIMESTAMP" (->> (t/zone-id "UTC") (t/with-zone-same-instant t) t/offset-date-time u.date/format))) (defn- query-parameter ^QueryParameterValue [value] (let [param (->QueryParameterValue value)] (log/tracef "Set parameter ^%s %s -> %s" (some-> value class .getCanonicalName) (pr-str value) (pr-str param)) param)) (defn set-parameters! "Set the `parameters` (i.e., values for `?` positional placeholders in the SQL) for a `query` request. Equivalent to JDBC `.setObject()` and the like." ^QueryJobConfiguration$Builder [^QueryJobConfiguration$Builder query parameters] (doseq [p parameters] (.addPositionalParameter query (query-parameter p))) query)
25717021b92423baeb9809e1b9f4f26534f0ea70719978e89c53aaabeae698a9
cronburg/antlr-haskell
ATN.hs
# LANGUAGE ScopedTypeVariables , , DeriveGeneric , FlexibleContexts , UndecidableInstances , StandaloneDeriving , OverloadedStrings # , FlexibleContexts, UndecidableInstances, StandaloneDeriving , OverloadedStrings #-} | Module : Text . ANTLR.Allstar . ATN Description : Augmented recursive transition network algorithms Copyright : ( c ) , 2018 License : BSD3 Maintainer : Stability : experimental Portability : POSIX Module : Text.ANTLR.Allstar.ATN Description : Augmented recursive transition network algorithms Copyright : (c) Karl Cronburg, 2018 License : BSD3 Maintainer : Stability : experimental Portability : POSIX -} module Text.ANTLR.Allstar.ATN where -- Augmented recursive Transition Network import Text.ANTLR.Grammar import Text . ANTLR.Allstar . GSS hiding ( Edge , ) import Text.ANTLR.Allstar.Stacks import Text.ANTLR.Set (Set(..), empty, fromList, toList, Hashable, Generic) import Text.ANTLR.Pretty | Graph - structured stack over ATN states . type Gamma nt = Stacks (ATNState nt) | An ATN defining some language we wish to parse data ATN s nt t = ATN { _Δ :: Set (Transition s nt t) -- ^ The transition function } deriving (Eq, Ord, Show) instance (Prettify s, Prettify nt, Prettify t, Hashable nt, Hashable t, Eq nt, Eq t) => Prettify (ATN s nt t) where prettify atn = do pLine "_Δ:" incrIndent 4 prettify $ _Δ atn incrIndent (-4) | Tuple corresponding to a distinct transition in the ATN : type Transition s nt t = (ATNState nt, Edge s nt t, ATNState nt) | The possible subscripts from Figure 8 of the ALL ( * ) paper data ATNState nt = Start nt | Middle nt Int Int | Accept nt deriving (Eq, Generic, Hashable, Ord, Show) | LaTeX style ATN states . TODO : check length of NT printed and put curly braces around it if more than one character . instance (Prettify nt) => Prettify (ATNState nt) where prettify (Start nt) = pStr "p_" >> prettify nt prettify (Accept nt) = pStr "p'_" >> prettify nt prettify (Middle nt i j) = do pStr "p_{" prettify i pStr "," prettify j pStr "}" | An edge in an ATN . data Edge s nt t = ^ Nonterminal edge | TE t -- ^ Terminal edge | PE (Predicate ()) -- ^ Predicated edge with no state | ME (Mutator ()) -- ^ Mutator edge with no state ^ Nondeterministic edge parsing nothing deriving (Eq, Generic, Hashable, Ord, Show) instance (Prettify s, Prettify nt, Prettify t) => Prettify (Edge s nt t) where prettify x = do pStr "--" case x of NTE nt -> prettify nt TE t -> prettify t PE p -> prettify p ME m -> prettify m Epsilon -> pStr "ε" pStr "-->" | Convert a G4 grammar into an ATN for parsing with ALL ( * ) atnOf :: forall nt t s dt. (Eq nt, Eq t, Hashable nt, Hashable t) => Grammar s nt t dt -> ATN s nt t atnOf g = let _Δ :: Int -> Production s nt t dt -> [Transition s nt t] _Δ i (Production lhs rhs _) = let --(Prod _α)) = let Construct an internal production state from the given ATN identifier st :: nt -> Int -> Int -> ATNState nt st = Middle Create the transition for the k^th production element in the i^th -- production: _Δ' :: Int -> ProdElem nt t -> Transition s nt t _Δ' k (NT nt) = (st lhs i (k - 1), NTE nt, st lhs i k) _Δ' k (T t) = (st lhs i (k - 1), TE t, st lhs i k) -- The epsilon (or mu) transition for the accepting / final state: sϵ = (Start lhs, Epsilon, Middle lhs i 0) fϵ _α = (Middle lhs i (length _α), Epsilon, Accept lhs) sem_state _α = Middle lhs i (length _α + 1) sϵ_sem _π _α = [(Start lhs, Epsilon, sem_state _α), (sem_state _α, PE _π, Middle lhs i 0)] fϵ_sem = fϵ sϵ_mut = sϵ fϵ_mut _μ = (Middle lhs i 0, ME _μ, Accept lhs) in (case rhs of (Prod Pass _α) -> [sϵ, fϵ _α] ++ zipWith _Δ' [1..(length _α)] _α (Prod (Sem _π) _α) -> sϵ_sem _π _α ++ [fϵ_sem _α] ++ zipWith _Δ' [1..(length _α)] _α (Prod (Action _μ) _) -> [sϵ_mut, fϵ_mut _μ] ) in ATN { _Δ = fromList $ concat $ zipWith _Δ [0..length (ps g)] $ ps g }
null
https://raw.githubusercontent.com/cronburg/antlr-haskell/7a9367038eaa58f9764f2ff694269245fbebc155/src/Text/ANTLR/Allstar/ATN.hs
haskell
Augmented recursive Transition Network ^ The transition function ^ Terminal edge ^ Predicated edge with no state ^ Mutator edge with no state (Prod _α)) = let production: The epsilon (or mu) transition for the accepting / final state:
# LANGUAGE ScopedTypeVariables , , DeriveGeneric , FlexibleContexts , UndecidableInstances , StandaloneDeriving , OverloadedStrings # , FlexibleContexts, UndecidableInstances, StandaloneDeriving , OverloadedStrings #-} | Module : Text . ANTLR.Allstar . ATN Description : Augmented recursive transition network algorithms Copyright : ( c ) , 2018 License : BSD3 Maintainer : Stability : experimental Portability : POSIX Module : Text.ANTLR.Allstar.ATN Description : Augmented recursive transition network algorithms Copyright : (c) Karl Cronburg, 2018 License : BSD3 Maintainer : Stability : experimental Portability : POSIX -} module Text.ANTLR.Allstar.ATN where import Text.ANTLR.Grammar import Text . ANTLR.Allstar . GSS hiding ( Edge , ) import Text.ANTLR.Allstar.Stacks import Text.ANTLR.Set (Set(..), empty, fromList, toList, Hashable, Generic) import Text.ANTLR.Pretty | Graph - structured stack over ATN states . type Gamma nt = Stacks (ATNState nt) | An ATN defining some language we wish to parse data ATN s nt t = ATN } deriving (Eq, Ord, Show) instance (Prettify s, Prettify nt, Prettify t, Hashable nt, Hashable t, Eq nt, Eq t) => Prettify (ATN s nt t) where prettify atn = do pLine "_Δ:" incrIndent 4 prettify $ _Δ atn incrIndent (-4) | Tuple corresponding to a distinct transition in the ATN : type Transition s nt t = (ATNState nt, Edge s nt t, ATNState nt) | The possible subscripts from Figure 8 of the ALL ( * ) paper data ATNState nt = Start nt | Middle nt Int Int | Accept nt deriving (Eq, Generic, Hashable, Ord, Show) | LaTeX style ATN states . TODO : check length of NT printed and put curly braces around it if more than one character . instance (Prettify nt) => Prettify (ATNState nt) where prettify (Start nt) = pStr "p_" >> prettify nt prettify (Accept nt) = pStr "p'_" >> prettify nt prettify (Middle nt i j) = do pStr "p_{" prettify i pStr "," prettify j pStr "}" | An edge in an ATN . data Edge s nt t = ^ Nonterminal edge ^ Nondeterministic edge parsing nothing deriving (Eq, Generic, Hashable, Ord, Show) instance (Prettify s, Prettify nt, Prettify t) => Prettify (Edge s nt t) where prettify x = do pStr "--" case x of NTE nt -> prettify nt TE t -> prettify t PE p -> prettify p ME m -> prettify m Epsilon -> pStr "ε" pStr "-->" | Convert a G4 grammar into an ATN for parsing with ALL ( * ) atnOf :: forall nt t s dt. (Eq nt, Eq t, Hashable nt, Hashable t) => Grammar s nt t dt -> ATN s nt t atnOf g = let _Δ :: Int -> Production s nt t dt -> [Transition s nt t] _Δ i (Production lhs rhs _) = let Construct an internal production state from the given ATN identifier st :: nt -> Int -> Int -> ATNState nt st = Middle Create the transition for the k^th production element in the i^th _Δ' :: Int -> ProdElem nt t -> Transition s nt t _Δ' k (NT nt) = (st lhs i (k - 1), NTE nt, st lhs i k) _Δ' k (T t) = (st lhs i (k - 1), TE t, st lhs i k) sϵ = (Start lhs, Epsilon, Middle lhs i 0) fϵ _α = (Middle lhs i (length _α), Epsilon, Accept lhs) sem_state _α = Middle lhs i (length _α + 1) sϵ_sem _π _α = [(Start lhs, Epsilon, sem_state _α), (sem_state _α, PE _π, Middle lhs i 0)] fϵ_sem = fϵ sϵ_mut = sϵ fϵ_mut _μ = (Middle lhs i 0, ME _μ, Accept lhs) in (case rhs of (Prod Pass _α) -> [sϵ, fϵ _α] ++ zipWith _Δ' [1..(length _α)] _α (Prod (Sem _π) _α) -> sϵ_sem _π _α ++ [fϵ_sem _α] ++ zipWith _Δ' [1..(length _α)] _α (Prod (Action _μ) _) -> [sϵ_mut, fϵ_mut _μ] ) in ATN { _Δ = fromList $ concat $ zipWith _Δ [0..length (ps g)] $ ps g }
2915a7780b0ed3e10552f20f8fa0bdd757bf6c59366d7f83342a49b533806851
ayazhafiz/plts
example.ml
let n = read_int () (* Original translated source *) let choice flip fail = let rec loop n k1 k2 = if n < 1 then fail () k1 k2 else flip () (fun x k3 -> if x then k1 n k3 else loop (n - 1) k1 k3) k2 in loop let handled_choice n = let flip () k = k true @ k false in let fail () k1 k2 = k2 [] in let lifted_flip () k1 k2 = flip () (fun x -> k1 x k2) in choice lifted_flip fail n (fun x1 k2 -> k2 [ x1 ]) (fun x2 -> x2) let _ = let r = handled_choice n in List.iter (Printf.printf "%d ") r; print_endline "" Source with three continuations let choice flip fail const = let rec loop n k1 k2 k3 = if n < 1 then fail () k1 k2 k3 else if n == 6 then const () k1 k2 k3 else flip () (fun x k4 k5 -> if x then k1 n k4 k5 else loop (n - 1) k1 k4 k5) k2 k3 in loop let handled_choice n = let flip () k = k true @ k false in let fail () k1 k2 = k2 [] in let const () k1 k2 = k2 [ 141; 252; 363 ] in let lifted_flip x k k' = (fun x k k' -> flip x (fun y -> k y k')) x (fun y -> k y k') in let lifted_fail x k k' = fail x (fun y -> k y k') in choice lifted_flip lifted_fail const n lift all non - terminal continuations by exactly one lambda (fun x1 k -> k [ x1 ]) (fun x2 k -> k x2) (fun x3 -> x3) let _ = let r = handled_choice n in List.iter (Printf.printf "%d ") r
null
https://raw.githubusercontent.com/ayazhafiz/plts/6dfa9340457ec897ddf40a87feee44dd6200921a/fx_cap/paper-test/example.ml
ocaml
Original translated source
let n = read_int () let choice flip fail = let rec loop n k1 k2 = if n < 1 then fail () k1 k2 else flip () (fun x k3 -> if x then k1 n k3 else loop (n - 1) k1 k3) k2 in loop let handled_choice n = let flip () k = k true @ k false in let fail () k1 k2 = k2 [] in let lifted_flip () k1 k2 = flip () (fun x -> k1 x k2) in choice lifted_flip fail n (fun x1 k2 -> k2 [ x1 ]) (fun x2 -> x2) let _ = let r = handled_choice n in List.iter (Printf.printf "%d ") r; print_endline "" Source with three continuations let choice flip fail const = let rec loop n k1 k2 k3 = if n < 1 then fail () k1 k2 k3 else if n == 6 then const () k1 k2 k3 else flip () (fun x k4 k5 -> if x then k1 n k4 k5 else loop (n - 1) k1 k4 k5) k2 k3 in loop let handled_choice n = let flip () k = k true @ k false in let fail () k1 k2 = k2 [] in let const () k1 k2 = k2 [ 141; 252; 363 ] in let lifted_flip x k k' = (fun x k k' -> flip x (fun y -> k y k')) x (fun y -> k y k') in let lifted_fail x k k' = fail x (fun y -> k y k') in choice lifted_flip lifted_fail const n lift all non - terminal continuations by exactly one lambda (fun x1 k -> k [ x1 ]) (fun x2 k -> k x2) (fun x3 -> x3) let _ = let r = handled_choice n in List.iter (Printf.printf "%d ") r
9aefcd9d02f32f3c3f37429e9767082d31fb2869bb30e056bce5408c5799fb1b
vivid-inc/ash-ra-template
output_path_test.clj
; Copyright 2020 Vivid Inc. ; 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 vivid.art.cli.output-path-test (:require [clojure.string] [clojure.test :refer :all] [farolero.core :as farolero] [vivid.art.cli.exec] [vivid.art.cli.usage]) (:import (java.io File))) (deftest output-dir-cli-args (are [args ^String dir] (= (.getAbsoluteFile (File. dir)) (-> (vivid.art.cli.args/cli-args->batch args vivid.art.cli.usage/cli-options) :output-dir)) ["test-resources/empty.art" "--output-dir" "/"] "/" ["test-resources/empty.art" "--output-dir" ".."] ".." ["test-resources/empty.art" "--output-dir" "."] "." ["--output-dir" "target" "test-resources/empty.art"] "target" ["--output-dir" "../here/there" "test-resources/empty.art"] "../here/there")) (deftest cli-empty-output-dir (= 'validate-output-dir (farolero/handler-case (vivid.art.cli.args/cli-args->batch ["--output-dir" "" "test-resources/empty.art"] vivid.art.cli.usage/cli-options) (:vivid.art.cli/error [_ {:keys [step]}] step)))) (deftest template-paths (are [^String base-path ^String template-file dest-rel-path] (= {:src-path (File. ^String template-file) :dest-rel-path (File. ^String dest-rel-path)} (vivid.art.cli.args/->template-path (File. base-path) (File. template-file))) "a.csv.art" "a.csv.art" "a.csv" "/a.csv.art" "/a.csv.art" "a.csv" "templates" "templates/b.txt.art" "b.txt" "templates/" "templates/b.txt.art" "b.txt" "/templates" "/templates/c.txt.art" "c.txt" "/templates/" "/templates/c.txt.art" "c.txt" "site/source" "site/source/about/d.properties.art" "about/d.properties" "a/b/c" "a/b/c/d/e/f/g/h.sql.art" "d/e/f/g/h.sql" "a/b/c/d/e" "a/b/c/d/e/recipe.xml.art" "recipe.xml"))
null
https://raw.githubusercontent.com/vivid-inc/ash-ra-template/f64be7efd6f52ccd451cddb851f02511d1665b11/art-cli/test/vivid/art/cli/output_path_test.clj
clojure
Copyright 2020 Vivid Inc. 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.
distributed under the License is distributed on an " AS IS " BASIS , (ns vivid.art.cli.output-path-test (:require [clojure.string] [clojure.test :refer :all] [farolero.core :as farolero] [vivid.art.cli.exec] [vivid.art.cli.usage]) (:import (java.io File))) (deftest output-dir-cli-args (are [args ^String dir] (= (.getAbsoluteFile (File. dir)) (-> (vivid.art.cli.args/cli-args->batch args vivid.art.cli.usage/cli-options) :output-dir)) ["test-resources/empty.art" "--output-dir" "/"] "/" ["test-resources/empty.art" "--output-dir" ".."] ".." ["test-resources/empty.art" "--output-dir" "."] "." ["--output-dir" "target" "test-resources/empty.art"] "target" ["--output-dir" "../here/there" "test-resources/empty.art"] "../here/there")) (deftest cli-empty-output-dir (= 'validate-output-dir (farolero/handler-case (vivid.art.cli.args/cli-args->batch ["--output-dir" "" "test-resources/empty.art"] vivid.art.cli.usage/cli-options) (:vivid.art.cli/error [_ {:keys [step]}] step)))) (deftest template-paths (are [^String base-path ^String template-file dest-rel-path] (= {:src-path (File. ^String template-file) :dest-rel-path (File. ^String dest-rel-path)} (vivid.art.cli.args/->template-path (File. base-path) (File. template-file))) "a.csv.art" "a.csv.art" "a.csv" "/a.csv.art" "/a.csv.art" "a.csv" "templates" "templates/b.txt.art" "b.txt" "templates/" "templates/b.txt.art" "b.txt" "/templates" "/templates/c.txt.art" "c.txt" "/templates/" "/templates/c.txt.art" "c.txt" "site/source" "site/source/about/d.properties.art" "about/d.properties" "a/b/c" "a/b/c/d/e/f/g/h.sql.art" "d/e/f/g/h.sql" "a/b/c/d/e" "a/b/c/d/e/recipe.xml.art" "recipe.xml"))
16af30d220380fc602a6281d1c0e98f1905a953b1dcc991d835aff5ff3ba964e
ivan-m/graphviz
Instances.hs
# OPTIONS_GHC -fno - warn - orphans # {-# LANGUAGE OverloadedStrings #-} | Module : Data . GraphViz . Testing . Instances Description : ' Arbitrary ' instances for graphviz . Copyright : ( c ) License : 3 - Clause BSD - style Maintainer : This module exports the ' Arbitrary ' instances for the various types used to represent Graphviz Dot code . Note that they do not generally generate /sensible/ values for the various types ; in particular , there 's no guarantee that the ' Attributes ' chosen for a particular value type are indeed legal for that type . Module : Data.GraphViz.Testing.Instances Description : 'Arbitrary' instances for graphviz. Copyright : (c) Ivan Lazar Miljenovic License : 3-Clause BSD-style Maintainer : This module exports the 'Arbitrary' instances for the various types used to represent Graphviz Dot code. Note that they do not generally generate /sensible/ values for the various types; in particular, there's no guarantee that the 'Attributes' chosen for a particular value type are indeed legal for that type. -} module Data.GraphViz.Testing.Instances() where import Data.Graph.Inductive.Arbitrary () import Data.GraphViz.Testing.Instances.Canonical () import Data.GraphViz.Testing.Instances.Generalised () import Data.GraphViz.Testing.Instances.Graph () -- -----------------------------------------------------------------------------
null
https://raw.githubusercontent.com/ivan-m/graphviz/42dbb6312d7edf789d7055079de7b4fa099a4acc/tests/Data/GraphViz/Testing/Instances.hs
haskell
# LANGUAGE OverloadedStrings # -----------------------------------------------------------------------------
# OPTIONS_GHC -fno - warn - orphans # | Module : Data . GraphViz . Testing . Instances Description : ' Arbitrary ' instances for graphviz . Copyright : ( c ) License : 3 - Clause BSD - style Maintainer : This module exports the ' Arbitrary ' instances for the various types used to represent Graphviz Dot code . Note that they do not generally generate /sensible/ values for the various types ; in particular , there 's no guarantee that the ' Attributes ' chosen for a particular value type are indeed legal for that type . Module : Data.GraphViz.Testing.Instances Description : 'Arbitrary' instances for graphviz. Copyright : (c) Ivan Lazar Miljenovic License : 3-Clause BSD-style Maintainer : This module exports the 'Arbitrary' instances for the various types used to represent Graphviz Dot code. Note that they do not generally generate /sensible/ values for the various types; in particular, there's no guarantee that the 'Attributes' chosen for a particular value type are indeed legal for that type. -} module Data.GraphViz.Testing.Instances() where import Data.Graph.Inductive.Arbitrary () import Data.GraphViz.Testing.Instances.Canonical () import Data.GraphViz.Testing.Instances.Generalised () import Data.GraphViz.Testing.Instances.Graph ()
8a822637c783fc57c63d3446e55968ed12774cef703ea2c8ec082f5ab4c2ef62
puppetlabs/jruby-utils
jruby_pool_manager_core.clj
(ns puppetlabs.services.jruby-pool-manager.impl.jruby-pool-manager-core (:require [schema.core :as schema] [puppetlabs.services.jruby-pool-manager.jruby-schemas :as jruby-schemas] [puppetlabs.services.jruby-pool-manager.impl.jruby-agents :as jruby-agents] [puppetlabs.services.protocols.jruby-pool :as pool-protocol] [puppetlabs.services.jruby-pool-manager.impl.reference-pool] [puppetlabs.services.jruby-pool-manager.impl.instance-pool] [puppetlabs.services.jruby-pool-manager.impl.jruby-internal :as jruby-internal]) (:import (puppetlabs.services.jruby_pool_manager.jruby_schemas ReferencePool InstancePool))) (schema/defn ^:always-validate create-pool-context :- jruby-schemas/PoolContext "Creates a new JRuby pool context with an empty pool. Once the JRuby pool object has been created, it will need to be filled using `prime-pool!`." [config :- jruby-schemas/JRubyConfig] (let [shutdown-on-error-fn (get-in config [:lifecycle :shutdown-on-error]) internal {:modify-instance-agent (jruby-agents/pool-agent shutdown-on-error-fn) :pool-state (atom (jruby-internal/create-pool-from-config config)) :event-callbacks (atom [])}] (if (:multithreaded config) (ReferencePool. config internal (atom 0)) (InstancePool. config internal)))) (schema/defn ^:always-validate create-pool :- jruby-schemas/PoolContext [config :- jruby-schemas/JRubyConfig] (let [pool-context (create-pool-context config)] (pool-protocol/fill pool-context) pool-context))
null
https://raw.githubusercontent.com/puppetlabs/jruby-utils/7b53c3c6a0c61635362402313bcec809abf5a856/src/clj/puppetlabs/services/jruby_pool_manager/impl/jruby_pool_manager_core.clj
clojure
(ns puppetlabs.services.jruby-pool-manager.impl.jruby-pool-manager-core (:require [schema.core :as schema] [puppetlabs.services.jruby-pool-manager.jruby-schemas :as jruby-schemas] [puppetlabs.services.jruby-pool-manager.impl.jruby-agents :as jruby-agents] [puppetlabs.services.protocols.jruby-pool :as pool-protocol] [puppetlabs.services.jruby-pool-manager.impl.reference-pool] [puppetlabs.services.jruby-pool-manager.impl.instance-pool] [puppetlabs.services.jruby-pool-manager.impl.jruby-internal :as jruby-internal]) (:import (puppetlabs.services.jruby_pool_manager.jruby_schemas ReferencePool InstancePool))) (schema/defn ^:always-validate create-pool-context :- jruby-schemas/PoolContext "Creates a new JRuby pool context with an empty pool. Once the JRuby pool object has been created, it will need to be filled using `prime-pool!`." [config :- jruby-schemas/JRubyConfig] (let [shutdown-on-error-fn (get-in config [:lifecycle :shutdown-on-error]) internal {:modify-instance-agent (jruby-agents/pool-agent shutdown-on-error-fn) :pool-state (atom (jruby-internal/create-pool-from-config config)) :event-callbacks (atom [])}] (if (:multithreaded config) (ReferencePool. config internal (atom 0)) (InstancePool. config internal)))) (schema/defn ^:always-validate create-pool :- jruby-schemas/PoolContext [config :- jruby-schemas/JRubyConfig] (let [pool-context (create-pool-context config)] (pool-protocol/fill pool-context) pool-context))
d51834466218a81a652415f9016ec0de631e973300af6d25061a3abdbd1b7cc9
input-output-hk/project-icarus-importer
RequestSpec.hs
module RequestSpec (spec) where import Universum import Data.Either (isLeft) import Formatting (build, sformat) import Test.Hspec import Cardano.Wallet.API.Request.Filter import Cardano.Wallet.API.Request.Sort import Cardano.Wallet.API.V1.Types import qualified Pos.Core as Core spec :: Spec spec = describe "Request" $ do describe "Sort" sortSpec describe "Filter" filterSpec sortSpec :: Spec sortSpec = describe "parseSortOperation" $ do describe "Transaction" $ do let ptimestamp = Proxy @(V1 Core.Timestamp) pt = Proxy @Transaction it "knows the query param" $ do parseSortOperation pt ptimestamp "ASC[created_at]" `shouldBe` Right (SortByIndex SortAscending ptimestamp) it "infers DESC for nonspecified sort" $ parseSortOperation pt ptimestamp "created_at" `shouldBe` Right (SortByIndex SortDescending ptimestamp) it "fails if the param name is wrong" $ do parseSortOperation pt ptimestamp "ASC[balance]" `shouldSatisfy` isLeft it "fails if the syntax is wrong" $ do parseSortOperation pt ptimestamp "ASC[created_at" `shouldSatisfy` isLeft filterSpec :: Spec filterSpec = do describe "parseFilterOperation" $ do describe "Wallet" $ do let pw = Proxy @Wallet pwid = Proxy @WalletId pcoin = Proxy @Core.Coin it "supports index" $ do parseFilterOperation pw pwid "asdf" `shouldBe` Right (FilterByIndex (WalletId "asdf")) forM_ [minBound .. maxBound] $ \p -> it ("supports predicate: " <> show p) $ do parseFilterOperation pw pwid (sformat build p <> "[asdf]") `shouldBe` Right (FilterByPredicate p (WalletId "asdf")) it "supports range" $ do parseFilterOperation pw pcoin "RANGE[123,456]" `shouldBe` Right (FilterByRange (Core.mkCoin 123) (Core.mkCoin 456)) it "fails if the thing can't be parsed" $ do parseFilterOperation pw pcoin "nope" `shouldSatisfy` isLeft it "supports IN" $ do parseFilterOperation pw pcoin "IN[1,2,3]" `shouldBe` Right (FilterIn (map Core.mkCoin [1,2,3])) describe "toQueryString" $ do let ops = FilterByRange (Core.mkCoin 2345) (Core.mkCoin 2348) `FilterOp` FilterByIndex (WalletId "hello") `FilterOp` NoFilters :: FilterOperations Wallet it "does what you'd want it to do" $ do toQueryString ops `shouldBe` [ ("balance", Just "RANGE[2345,2348]") , ("id", Just "hello") ] describe "toFilterOperations" $ do let params :: [(Text, Maybe Text)] params = [ ("id", Just "3") , ("balance", Just "RANGE[10,50]") ] fops :: FilterOperations Wallet fops = FilterByIndex (WalletId "3") `FilterOp` FilterByRange (Core.mkCoin 10) (Core.mkCoin 50) `FilterOp` NoFilters prxy :: Proxy '[WalletId, Core.Coin] prxy = Proxy it "can parse the thing" $ do toFilterOperations params prxy `shouldBe` fops
null
https://raw.githubusercontent.com/input-output-hk/project-icarus-importer/36342f277bcb7f1902e677a02d1ce93e4cf224f0/wallet-new/test/RequestSpec.hs
haskell
module RequestSpec (spec) where import Universum import Data.Either (isLeft) import Formatting (build, sformat) import Test.Hspec import Cardano.Wallet.API.Request.Filter import Cardano.Wallet.API.Request.Sort import Cardano.Wallet.API.V1.Types import qualified Pos.Core as Core spec :: Spec spec = describe "Request" $ do describe "Sort" sortSpec describe "Filter" filterSpec sortSpec :: Spec sortSpec = describe "parseSortOperation" $ do describe "Transaction" $ do let ptimestamp = Proxy @(V1 Core.Timestamp) pt = Proxy @Transaction it "knows the query param" $ do parseSortOperation pt ptimestamp "ASC[created_at]" `shouldBe` Right (SortByIndex SortAscending ptimestamp) it "infers DESC for nonspecified sort" $ parseSortOperation pt ptimestamp "created_at" `shouldBe` Right (SortByIndex SortDescending ptimestamp) it "fails if the param name is wrong" $ do parseSortOperation pt ptimestamp "ASC[balance]" `shouldSatisfy` isLeft it "fails if the syntax is wrong" $ do parseSortOperation pt ptimestamp "ASC[created_at" `shouldSatisfy` isLeft filterSpec :: Spec filterSpec = do describe "parseFilterOperation" $ do describe "Wallet" $ do let pw = Proxy @Wallet pwid = Proxy @WalletId pcoin = Proxy @Core.Coin it "supports index" $ do parseFilterOperation pw pwid "asdf" `shouldBe` Right (FilterByIndex (WalletId "asdf")) forM_ [minBound .. maxBound] $ \p -> it ("supports predicate: " <> show p) $ do parseFilterOperation pw pwid (sformat build p <> "[asdf]") `shouldBe` Right (FilterByPredicate p (WalletId "asdf")) it "supports range" $ do parseFilterOperation pw pcoin "RANGE[123,456]" `shouldBe` Right (FilterByRange (Core.mkCoin 123) (Core.mkCoin 456)) it "fails if the thing can't be parsed" $ do parseFilterOperation pw pcoin "nope" `shouldSatisfy` isLeft it "supports IN" $ do parseFilterOperation pw pcoin "IN[1,2,3]" `shouldBe` Right (FilterIn (map Core.mkCoin [1,2,3])) describe "toQueryString" $ do let ops = FilterByRange (Core.mkCoin 2345) (Core.mkCoin 2348) `FilterOp` FilterByIndex (WalletId "hello") `FilterOp` NoFilters :: FilterOperations Wallet it "does what you'd want it to do" $ do toQueryString ops `shouldBe` [ ("balance", Just "RANGE[2345,2348]") , ("id", Just "hello") ] describe "toFilterOperations" $ do let params :: [(Text, Maybe Text)] params = [ ("id", Just "3") , ("balance", Just "RANGE[10,50]") ] fops :: FilterOperations Wallet fops = FilterByIndex (WalletId "3") `FilterOp` FilterByRange (Core.mkCoin 10) (Core.mkCoin 50) `FilterOp` NoFilters prxy :: Proxy '[WalletId, Core.Coin] prxy = Proxy it "can parse the thing" $ do toFilterOperations params prxy `shouldBe` fops
5c53be2faa6bd95578f18c7f3297484617b853573c96f912b8c7e0955037e23d
immutant/feature-demo
caching.clj
(ns demo.caching (:require [immutant.caching :as c] [immutant.caching.core-memoize :as cmemo] [immutant.scheduling :as sch])) ;; Caches implement org.infinispan.Cache and java.util.concurrent . (comment writing "Various ways of putting entries in a cache" (def foo (c/cache "foo")) ;; The swap-in! function atomically updates cache entries ;; by applying a function to the current value or nil, if the key is ;; missing. The function should be side-effect free. = > 1 (c/swap-in! foo :b (constantly "foo")) ;=> "foo" = > 2 ;; Internally, swap-in! uses the ConcurrentMap methods, ;; replace, i.e. "compare and set", and putIfAbsent, to provide a ;; consistent view of the cache to callers. Of course, you can invoke these and other methods directly using plain ol' Java ;; interop... ;; Put an entry in the cache (.put foo :a 1) ;; Add all the entries in the map to the cache (.putAll foo {:b 2, :c 3}) ;; Put it in only if key is not already present = > 2 (.putIfAbsent foo :d 4) ;=> nil ;; Put it in only if key is already present (.replace foo :e 5) ;=> nil = > 2 ;; Replace for specific key and value (compare-and-set) (.replace foo :b 2 0) ;=> false (.replace foo :b 6 0) ;=> true ) (comment reading "Caches are just Maps, so core clojure functions work fine" (def bar (c/cache "bar")) (.putAll bar {:a 1, :b {:c 3, :d 4}}) ;; Use get to obtain associated values = > 1 (get bar :x) ;=> nil = > 42 ;; Keywords look up their value = > 1 = > 42 ;; Nested structures work as you would expect = > 3 ;; Use find to return entries = > [: a 1 ] ;; Use contains? to check membership (contains? bar :a) ;=> true (contains? bar :x) ;=> false ) (comment removing "Expiration, eviction, and explicit removal" (def baz (c/cache "baz", :ttl [5 :minutes], :idle [1 :minute] ; expiration :max-entries 3, :eviction :lru)) ; eviction (.putAll baz {:a 1 :b 2 :c 3}) ;; Eviction = > 1 = > { : c 3 , : b 2 } (.put baz :d 4) (:a baz) ;=> nil ;; You can easily override the cache's expiration settings, ;; time-to-live and/or max idle time, for all subsequent writes (let [c (c/with-expiration baz :ttl [1 :hour] :idle [20 :minutes])] (.put c :a 1) (c/swap-in! c :a dec) (.putAll c {:b 2, :c 3}) (.putIfAbsent c :f 6) (.replace c :f 5)) ;; Removing a missing key is harmless (.remove baz :missing) ;=> nil ;; Removing an existing key returns its value = > 2 ;; If value is passed, both must match for remove to succeed (.remove baz :c 2) ;=> false (.remove baz :c 3) ;=> true ;; Clear all entries (.clear baz) ) (comment encoding "Cache entries are not encoded by default, but may be decorated with a codec. Provided codecs include :edn, :json, and :fressian. The latter two require additional dependencies: 'cheshire' and 'org.clojure/data.fressian', respectively." (def ham (c/cache "ham")) (def encoded (c/with-codec ham :edn)) (.put encoded :a {:b 42}) = > { : b 42 } Access via non - encoded caches still possible (get ham :a) ;=> nil = > " { : b 42 } " ;; Infinispan caches don't allow null keys or values (try (.put ham nil :a) ;=> Null keys are not supported! (.put ham :b nil) ;=> Null values are not supported! (catch NullPointerException _ "ERROR!")) ;; But nil keys and values are fine in an encoded cache (.put encoded nil :a) (.put encoded :b nil) (get encoded nil) ;=> :a (:b encoded) ;=> nil (contains? encoded :b) ;=> true (contains? ham "nil") ;=> true ) (comment memoization "Caches will implement clojure.core.memoize/PluggableMemoization when you require immutant.caching.core-memoize, but it's up to you to ensure core.memoize is on the classpath" (defn slow-fn [& _] (Thread/sleep 5000) 42) ;; Other than the function to be memoized, arguments are the same as ;; for the cache function. (def memoized-fn (cmemo/memo slow-fn "memo", :ttl [5 :minutes])) ;; Invoking the memoized function fills the cache with the result from the slow function the first time it is called . = > 42 ;; Subsequent invocations with the same parameters return the result ;; from the cache, avoiding the overhead of the slow function = > 42 ;; It's possible to manipulate the cache backing the memoized ;; function by referring to its name (def c (c/cache "memo")) = > 42 ) (defn -main [& args] "Schedule a counter" (let [c (c/cache "counter") f #(println "Updating count to" (c/swap-in! c :count (fnil inc 0)))] (sch/schedule f :id "counter" :every [10 :seconds] :singleton false)))
null
https://raw.githubusercontent.com/immutant/feature-demo/151fb330601421a23a1bdfd71f724afcdba0900c/src/demo/caching.clj
clojure
Caches implement org.infinispan.Cache and The swap-in! function atomically updates cache entries by applying a function to the current value or nil, if the key is missing. The function should be side-effect free. => "foo" Internally, swap-in! uses the ConcurrentMap methods, replace, i.e. "compare and set", and putIfAbsent, to provide a consistent view of the cache to callers. Of course, you can interop... Put an entry in the cache Add all the entries in the map to the cache Put it in only if key is not already present => nil Put it in only if key is already present => nil Replace for specific key and value (compare-and-set) => false => true Use get to obtain associated values => nil Keywords look up their value Nested structures work as you would expect Use find to return entries Use contains? to check membership => true => false expiration eviction Eviction => nil You can easily override the cache's expiration settings, time-to-live and/or max idle time, for all subsequent writes Removing a missing key is harmless => nil Removing an existing key returns its value If value is passed, both must match for remove to succeed => false => true Clear all entries => nil Infinispan caches don't allow null keys or values => Null keys are not supported! => Null values are not supported! But nil keys and values are fine in an encoded cache => :a => nil => true => true Other than the function to be memoized, arguments are the same as for the cache function. Invoking the memoized function fills the cache with the result Subsequent invocations with the same parameters return the result from the cache, avoiding the overhead of the slow function It's possible to manipulate the cache backing the memoized function by referring to its name
(ns demo.caching (:require [immutant.caching :as c] [immutant.caching.core-memoize :as cmemo] [immutant.scheduling :as sch])) java.util.concurrent . (comment writing "Various ways of putting entries in a cache" (def foo (c/cache "foo")) = > 1 = > 2 invoke these and other methods directly using plain ol' Java (.put foo :a 1) (.putAll foo {:b 2, :c 3}) = > 2 = > 2 ) (comment reading "Caches are just Maps, so core clojure functions work fine" (def bar (c/cache "bar")) (.putAll bar {:a 1, :b {:c 3, :d 4}}) = > 1 = > 42 = > 1 = > 42 = > 3 = > [: a 1 ] ) (comment removing "Expiration, eviction, and explicit removal" (def baz (c/cache "baz", (.putAll baz {:a 1 :b 2 :c 3}) = > 1 = > { : c 3 , : b 2 } (.put baz :d 4) (let [c (c/with-expiration baz :ttl [1 :hour] :idle [20 :minutes])] (.put c :a 1) (c/swap-in! c :a dec) (.putAll c {:b 2, :c 3}) (.putIfAbsent c :f 6) (.replace c :f 5)) = > 2 (.clear baz) ) (comment encoding "Cache entries are not encoded by default, but may be decorated with a codec. Provided codecs include :edn, :json, and :fressian. The latter two require additional dependencies: 'cheshire' and 'org.clojure/data.fressian', respectively." (def ham (c/cache "ham")) (def encoded (c/with-codec ham :edn)) (.put encoded :a {:b 42}) = > { : b 42 } Access via non - encoded caches still possible = > " { : b 42 } " (try (catch NullPointerException _ "ERROR!")) (.put encoded nil :a) (.put encoded :b nil) ) (comment memoization "Caches will implement clojure.core.memoize/PluggableMemoization when you require immutant.caching.core-memoize, but it's up to you to ensure core.memoize is on the classpath" (defn slow-fn [& _] (Thread/sleep 5000) 42) (def memoized-fn (cmemo/memo slow-fn "memo", :ttl [5 :minutes])) from the slow function the first time it is called . = > 42 = > 42 (def c (c/cache "memo")) = > 42 ) (defn -main [& args] "Schedule a counter" (let [c (c/cache "counter") f #(println "Updating count to" (c/swap-in! c :count (fnil inc 0)))] (sch/schedule f :id "counter" :every [10 :seconds] :singleton false)))
74defac8e8cd30b3d00719cd7707bcd69587c0cf2385f3b2c23daa58c211ff13
kaizhang/SciFlow
Types.hs
# LANGUAGE FlexibleInstances # # LANGUAGE DeriveGeneric # # LANGUAGE TemplateHaskell # {-# LANGUAGE DeriveLift #-} {-# LANGUAGE GADTs #-} module Control.Workflow.Types ( SciFlow(..) , NodeLabel(..) , FunctionTable(..) , ResourceConfig(..) , Resource(..) , Job(..) , Action(..) , Flow(..) , Env , step , ustep ) where import Data.Binary (Binary) import Control.Monad.Reader import GHC.Generics (Generic) import qualified Data.Text as T import Data.Typeable (Typeable) import Control.Arrow.Free (Free, Choice, effect) import qualified Data.Graph.Inductive as G import qualified Data.ByteString.Lazy as B import qualified Data.HashMap.Strict as M import Control.Distributed.Process.Serializable (SerializableDict) import Control.Distributed.Process (Process, RemoteTable, Closure, Static) import Language.Haskell.TH.Syntax (Lift) -- | The core type, containing the workflow represented as a free arrow and -- a function table for remote execution. data SciFlow env = SciFlow { _flow :: Free (Flow env) () () , _function_table :: FunctionTable , _graph :: G.Gr NodeLabel ()} data NodeLabel = NodeLabel { _label :: T.Text , _descr :: T.Text , _parallel :: Bool , _uncached :: Bool } deriving (Show, Generic, Lift) -- | The function table that can be sent to remote. data FunctionTable = FunctionTable { _table :: (T.Text, B.ByteString, B.ByteString) -> Closure (Process (Either String B.ByteString)) , _dict :: Static (SerializableDict (Either String B.ByteString)) , _rtable :: RemoteTable } -- | Global job specific resource configuration. This will overwrite any -- existing configuration. newtype ResourceConfig = ResourceConfig { _resource_config :: M.HashMap T.Text Resource } -- TODO: This should be implemented using dependent type in future. -- | The basic component/step of a workflow. data Job env i o = Job { _job_name :: T.Text -- ^ The name of the job , _job_descr :: T.Text -- ^ The description of the job , _job_resource :: Maybe Resource -- ^ The computational resource needed , _job_parallel :: Bool -- ^ Whether to run this step in parallel , _job_action :: Choice (Action env) i o } -- ^ The action to run type Env env = ReaderT env IO data Action env i o where Action :: (Typeable i, Typeable o, Binary i, Binary o, Show i, Show o) => { _unAction :: i -> Env env o -- ^ The function to run } -> Action env i o -- | Free arrow side effect. data Flow env i o where Step :: (Binary i, Binary o) => Job env i o -> Flow env i o -- ^ A cached step UStep :: T.Text -> (i -> Env env o) -> Flow env i o -- ^ An uncached step step :: (Binary i, Binary o) => Job env i o -> Free (Flow env) i o step job = effect $ Step job # INLINE step # ustep :: T.Text -> (i -> Env env o) -> Free (Flow env) i o ustep nid job = effect $ UStep nid job {-# INLINE ustep #-} -- | Computational resource data Resource = Resource { _num_cpu :: Maybe Int -- ^ The number of CPU needed ^ Memory in GB , _submit_params :: Maybe String -- ^ Job submitting queue } deriving (Eq, Generic, Show, Lift) instance Binary Resource
null
https://raw.githubusercontent.com/kaizhang/SciFlow/c9d85008e9db598d2addc8fe999e1abad9147e1c/SciFlow/src/Control/Workflow/Types.hs
haskell
# LANGUAGE DeriveLift # # LANGUAGE GADTs # | The core type, containing the workflow represented as a free arrow and a function table for remote execution. | The function table that can be sent to remote. | Global job specific resource configuration. This will overwrite any existing configuration. TODO: This should be implemented using dependent type in future. | The basic component/step of a workflow. ^ The name of the job ^ The description of the job ^ The computational resource needed ^ Whether to run this step in parallel ^ The action to run ^ The function to run | Free arrow side effect. ^ A cached step ^ An uncached step # INLINE ustep # | Computational resource ^ The number of CPU needed ^ Job submitting queue
# LANGUAGE FlexibleInstances # # LANGUAGE DeriveGeneric # # LANGUAGE TemplateHaskell # module Control.Workflow.Types ( SciFlow(..) , NodeLabel(..) , FunctionTable(..) , ResourceConfig(..) , Resource(..) , Job(..) , Action(..) , Flow(..) , Env , step , ustep ) where import Data.Binary (Binary) import Control.Monad.Reader import GHC.Generics (Generic) import qualified Data.Text as T import Data.Typeable (Typeable) import Control.Arrow.Free (Free, Choice, effect) import qualified Data.Graph.Inductive as G import qualified Data.ByteString.Lazy as B import qualified Data.HashMap.Strict as M import Control.Distributed.Process.Serializable (SerializableDict) import Control.Distributed.Process (Process, RemoteTable, Closure, Static) import Language.Haskell.TH.Syntax (Lift) data SciFlow env = SciFlow { _flow :: Free (Flow env) () () , _function_table :: FunctionTable , _graph :: G.Gr NodeLabel ()} data NodeLabel = NodeLabel { _label :: T.Text , _descr :: T.Text , _parallel :: Bool , _uncached :: Bool } deriving (Show, Generic, Lift) data FunctionTable = FunctionTable { _table :: (T.Text, B.ByteString, B.ByteString) -> Closure (Process (Either String B.ByteString)) , _dict :: Static (SerializableDict (Either String B.ByteString)) , _rtable :: RemoteTable } newtype ResourceConfig = ResourceConfig { _resource_config :: M.HashMap T.Text Resource } data Job env i o = Job type Env env = ReaderT env IO data Action env i o where Action :: (Typeable i, Typeable o, Binary i, Binary o, Show i, Show o) => } -> Action env i o data Flow env i o where step :: (Binary i, Binary o) => Job env i o -> Free (Flow env) i o step job = effect $ Step job # INLINE step # ustep :: T.Text -> (i -> Env env o) -> Free (Flow env) i o ustep nid job = effect $ UStep nid job data Resource = Resource ^ Memory in GB } deriving (Eq, Generic, Show, Lift) instance Binary Resource
2a1531e285050fefc205c547d0a3f3af24fbd2ace278189bf1a4596e9cf6a021
openmusic-project/openmusic
rythme.lisp
;========================================================================= OpenMusic : Visual Programming Language for Music Composition ; Copyright ( c ) 1997- ... IRCAM - Centre , Paris , France . ; This file is part of the OpenMusic environment sources ; OpenMusic 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. ; OpenMusic 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 OpenMusic . If not , see < / > . ; ;========================================================================= Music package ;========================================================================= (in-package :om) ;;; =============================================================================================== ;;; ;;; OPERATIONS RYTHMIQUES ELEMENTAIRES ;;; ;;; OLIVIER DELERUE ;;; ;;; =============================================================================================== ;;;; PROVISOIRE !!! (defun fraction-minimale (&rest x) (apply 'cLcm x)) (defun fraction-minimale-commune (&rest x) (apply 'cLcm x)) (defun DUPLIQUE-STRUCTURE-MUSICALE (&rest x) (apply 'copy-container x)) (defun reduit-qvalue (&rest x) (apply 'QNormalize x)) ;;; =============================================================================================== ASSEMBLAGE DE STRUCTURES MUSICALES : on les met en parallle dans un objet vertical ( poly ) . ;;; =============================================================================================== (defmethod om-assemble ((s1 poly) (s2 poly)) (let ((frac-min (fraction-minimale-commune s1 s2)) (ss1 (duplique-structure-musicale s1)) (ss2 (duplique-structure-musicale s2))) (change-qvalue ss1 frac-min) (change-qvalue ss2 frac-min) (mki'poly :empty t :offset 0 :qvalue frac-min :extent (max (extent ss1) (extent ss2)) :inside (append (inside ss1) (inside ss2)) ) ) ) (defmethod om-assemble ((s1 voice) (s2 poly)) (let ((frac-min (fraction-minimale-commune s1 s2)) (ss1 (duplique-structure-musicale s1)) (ss2 (duplique-structure-musicale s2))) (setf (offset ss1) 0 ) (change-qvalue ss1 frac-min) (change-qvalue ss2 frac-min) (setf (inside ss2) (append (inside ss2) (list ss1))) ss2 ) ) (defmethod om-assemble ((s1 poly) (s2 voice)) (om-assemble s2 s1) ) (defmethod om-assemble ((s1 voice) (s2 voice)) (let ((frac-min (fraction-minimale-commune s1 s2) ) (ss1 (duplique-structure-musicale s1)) (ss2 (duplique-structure-musicale s2))) (change-qvalue ss1 frac-min) (change-qvalue ss2 frac-min) (setf (offset ss1) 0) (setf (offset ss2) 0) (mki'poly :empty t :offset 0 :qvalue frac-min :extent (max (extent ss1) (extent ss2)) :inside (list ss1 ss2) ) ) ) ces methodes assemblent a l'interieur ( et modifient ) un poly existant . (defmethod om-assemble-into-poly ((self poly) (s2 voice)) (let ((frac-min (fraction-minimale-commune self s2)) (ss2 (duplique-structure-musicale s2))) (change-qvalue self frac-min) (change-qvalue ss2 frac-min) (setf (slot-value self 'offset) 0 (slot-value self 'qvalue) frac-min (slot-value self 'extent) (max (extent self) (extent ss2)) (slot-value self 'inside) (append (inside self) (list ss2))) self)) (defmethod om-assemble-into-poly ((self poly) (s2 poly)) (let ((frac-min (fraction-minimale-commune self s2)) (ss2 (duplique-structure-musicale s2))) (change-qvalue self frac-min) (change-qvalue ss2 frac-min) (setf (slot-value self 'offset) 0 (slot-value self 'qvalue) frac-min (slot-value self 'extent) (max (extent self) (extent ss2)) (slot-value self 'inside) (append (inside self) (inside ss2))) self)) ;;; =============================================================================================== ;;; MERGE DE STRUCTURES MUSICALES ;;; =============================================================================================== c'est la plus longue des deux structures (defmethod om-merge ((v1 voice) (v2 voice)) (let ((frac-min (fraction-minimale-commune v1 v2))) (let ((new-fringe (fringe-or (get-fringe v1 :frac-min frac-min :w-rest ()) (get-fringe v2 :frac-min frac-min :w-rest ()) )) (new-structure (smart-structure v1 v2)) ) (setf new-fringe (insert-rests new-fringe)) (applique-liste-structure new-structure new-fringe) (automatic-chord-insert new-structure) (delete-useless-containers new-structure ) (do-grouping new-structure ) new-structure ) ) ) (defmethod om-merge ((v1 measure) (v2 measure)) (voice->measure (om-merge (measure->voice v1) (measure->voice v2)) 0 ) ) ;;; =============================================================================================== ;;; MASQUAGE DE STRUCTURES MUSICALES ;;; =============================================================================================== ;;; v1 est la voix originale et v2 est le masque. ;;; le resultat est la voix v1 masquŽe par v2. ;;; masque et demasque (defmethod om-masque ((v1 voice) (v2 voice) &key (mode 'masque)) (let ((frac-min (fraction-minimale-commune v1 v2))) (let ((new-fringe (fringe-masque (get-fringe v1 :frac-min frac-min :w-rest ()) (get-fringe v2 :frac-min frac-min :w-rest ()) :mode mode ) ) (new-structure (smart-structure v1 v2)) ) (applique-liste-structure new-structure new-fringe) (automatic-chord-insert new-structure) (blank-fill new-structure ) (delete-useless-containers new-structure ) (do-grouping new-structure ) new-structure ) ) ) (defmethod get-fringe-activity ((fringe list)) (if (cdr fringe ) (let ((resultat (get-fringe-activity (cdr fringe)))) (if (>= (+ (offset (car fringe)) (extent (car fringe))) (caar resultat)) (cons (list (offset (car fringe)) (cadar resultat)) (cdr resultat)) (if (= (offset (car fringe)) (caar resultat)) resultat (cons (list (offset (car fringe)) (+ (offset (car fringe)) (extent (car fringe)))) resultat ) ) ) ) (list (list (offset (car fringe)) (+ (offset (car fringe)) (extent (car fringe))))) ) ) (defmethod get-fringe-inactivity ((fringe list)) (append (list (list 0 (offset (car fringe)))) (loop for item1 in fringe for item2 in (cdr fringe ) when (> (offset item2) (+ (offset item1) (extent item1))) collect (list (+ (offset item1) (extent item1)) (offset item2) ) ) (let ((last-item (car (last fringe)))) (list (list (+ (offset last-item) (extent last-item)) 100000000))) ) ) (defmethod fringe-masque ((fringe1 list) (fringe2 list) &key (mode 'masque)) (let ((mask (if (eq mode 'masque ) (get-fringe-activity fringe2) (if (eq mode 'demasque ) (get-fringe-inactivity fringe2) () ) ))) ;;(print mask ) (loop for item in fringe1 append (masquage item mask )) ) ) (defmethod masquage ((self note) (activity list) ) (loop for item in activity when (and (< (offset self) (cadr item)) (> (+ (offset self) (extent self)) (car item)) ) collect (let ((new-note (copy-container self))) (setf (offset new-note) (max (car item) (offset self)) ) (setf (extent new-note) (- (min (cadr item) (+ (extent self) (offset self)) ) (max (car item) (offset self)) ) ) new-note ) ) ) ;;; =============================================================================================== ;;; LEGATO ;;; =============================================================================================== transformation legato : elle remplace les silences par une note liee a la precedente legato modifie la structure et s'applique au premier simple - container de la structure ;; do-legato s'appplique a une structure complete, et rend une nouvelle structure. (defmethod do-legato ((self simple-container)) (let ((new-struct (Qreduce (duplique-structure-musicale self)))) (legato (first-simple-container new-struct )) (delete-useless-containers new-struct) (do-grouping new-struct) (setf (tree new-struct) nil) ;; here to force recomputation of the tree new-struct ) ) (defmethod legato ((self simple-container)) (let ((next-one (next-simple-container self))) (if next-one (if (rest-p next-one) (let ((new-next-one (replace-simple-container self next-one ) )) (setf (tie new-next-one ) (cond ((eq (tie self) 'nil ) 'end ) ((eq (tie self) 'begin ) 'continue ) ((eq (tie self) 'end ) 'end ) ((eq (tie self) 'continue ) 'continue ) ) ) (setf (tie self ) (cond ((eq (tie self) 'nil ) 'begin ) ((eq (tie self) 'begin ) 'begin ) ((eq (tie self) 'end ) 'continue ) ((eq (tie self) 'continue ) 'continue ) ) ) (legato new-next-one) ) (legato next-one) ) () ) ) ) (defmethod legato ((self chord)) (let ((next-one (next-simple-container self))) (if next-one (if (rest-p next-one) (let ((new-next-one (replace-simple-container self next-one ) )) (loop for note in (inside self) do (progn (setf (tie (corresponding-note new-next-one note ) ) (cond ((eq (tie note) 'nil ) 'end ) ((eq (tie note) 'begin ) 'continue ) ((eq (tie note) 'end ) 'end ) ((eq (tie note) 'continue ) 'continue ) ) ) (setf (tie note ) (cond ((eq (tie note) 'nil ) 'begin ) ((eq (tie note) 'begin ) 'begin ) ((eq (tie note) 'end ) 'continue ) ((eq (tie note) 'continue ) 'continue ) ) ) ) ) (legato new-next-one) ) (legato next-one) ) () ) ) ) ;;; =============================================================================================== ;;; SPLIT TIME ;;; =============================================================================================== (defmethod split-time ((self container) tree ) (let ((new-struct (duplique-structure-musicale self)) (temp-group (make-instance 'group :tree tree))) (do-split-time (first-simple-container new-struct ) temp-group) (setf (tree new-struct) nil) new-struct ) ) (defmethod splitit ((self container) (temp-group group)) (let ((new-struct (duplique-structure-musicale self)) ) (do-split-time (first-simple-container new-struct ) temp-group) (setf (tree new-struct) nil) new-struct ) ) (defmethod do-split-time ((self note ) temp-group) (let ((new-simple-container (replace-simple-container (transpose temp-group (- (midic self) 6000 ) ) self) )) (if (next-simple-container new-simple-container) (do-split-time (next-simple-container new-simple-container) temp-group ) () ) ) ) (defmethod do-split-time ((self rest) temp-group) (if (next-simple-container self) (do-split-time (next-simple-container self) temp-group ) () ) ) il reste un probleme pour la transposition dans le cas de l'accord ... ;; j'ai mis un zero rapidement... (defmethod do-split-time ((self chord ) temp-group) (let ((new-simple-container (replace-simple-container ;; c'est ici qu'il faut faire quelque chose mais quoi ? (transpose temp-group (- (midic (car (inside self))) 6000 ) ) ( splitit temp - group self ) self) )) (if (next-simple-container new-simple-container) (do-split-time (next-simple-container new-simple-container) temp-group ) () ) ) ) ;;; =============================================================================================== ;;; POUR REDUIRE UN POLY EN UNE SEULE VOICE ;;; =============================================================================================== (defmethod om-merge-down ((self poly)) (merge-down-voices (inside self)) ) (defmethod merge-down-voices (list-of-voices) (if (cdr list-of-voices) (om-merge (car list-of-voices) (merge-down-voices (cdr list-of-voices))) (car list-of-voices) ) ) on cherche une structure commune sans casser les groupes pour eviter d'avoir des tuplets a cheval sur deux mesures (defmethod smart-structure ((v1 voice) (v2 voice)) (let ((frac-min (fraction-minimale-commune v1 v2)) (st1 (get-structure v1) ) (st2 (get-structure v2) )) (change-qvalue st1 frac-min) (change-qvalue st2 frac-min) (let ((structure-longue (if (< (extent st1) (extent st2) ) st2 st1) ) (structure-courte (if (< (extent st1) (extent st2) ) st1 st2) )) (loop for item in (tuplet-collection structure-courte) do (propage-subdivision structure-longue (car item) (cadr item))) ( applique - liste - structure structure - longue ( tuplet - collection - old structure - courte ) ) ; structure-longue ) ) ) (defmethod propage-subdivision ((self container) (sub integer) (c container) &optional (running-offset 0) ) (if (inside self) (loop for item in (inside self) do (propage-subdivision item sub c (+ running-offset (offset self)))) (let ((start-self (+ (offset self) running-offset)) (end-self (+ running-offset (offset self) (extent self))) (start-c (offset c)) (end-c (+ (offset c) (extent c))) ) (if (and (or (and (>= start-c start-self) (< start-c end-self)) (and (> end-c start-self) (<= end-c end-self)) (and (< start-c start-self) (> end-c end-self)) ) (zerop (mod (extent self) sub)) ) (setf (inside self) (loop for compteur from 1 to sub by ( / (extent self) sub ) collect (mki 'group :empty t :parent self :extent ( / (extent self) sub ) ;; sub :offset (* (- compteur 1) ( / (extent self) sub ) ) :qvalue (qvalue self ) ) ) ) () ) ) ) ) (defmethod tuplet-collection ((self container) &optional (running-offset 0) ) (let ((tp (tuplet-p self))) (if tp (let ((new-tup (copy-container self))) (setf (offset new-tup) (+ (offset self) running-offset)) (setf (inside new-tup) ()) (cons (list tp new-tup) (loop for item in (inside self) append (tuplet-collection item ))) ) (loop for item in (inside self) append (tuplet-collection item (+ running-offset (offset self)))) ) ) ) (defmethod tuplet-collection ((self simple-container) &optional (running-offset 0) ) () ) (defmethod do-grouping ((self container)) (setf (inside self) (loop for item in (grouping-formated-list (inside self)) when (eq (length item ) 1) collect (car item) when (> (length item) 1 ) collect (list->group item ) ) ) (loop for item in (inside self) when (and (container-p item) (not (chord-p item))) do (do-grouping item) ) ) (defmethod list->group (item-list) "effectue le regroupement d'un ensemble de simple-containers" (if (chord-p (car item-list)) (let ((new-extent (* (loop for sc in item-list sum (/ (extent sc ) (qvalue sc))) (qvalue (car item-list))))) (setf (extent (car item-list )) new-extent ) (loop for note in (inside (car item-list)) do (progn (setf (tie note) (tie-remplacement note (corresponding-note (car (last item-list)) note ))) (setf (extent note) new-extent ) ) ) (car item-list) ) (let ((new-extent (* (loop for sc in item-list sum (/ (extent sc ) (qvalue sc))) (qvalue (car item-list))))) (setf (extent (car item-list )) new-extent ) (if (note-p (car item-list)) (setf (tie (car item-list)) (tie-remplacement (car item-list) (car (last item-list)))) ()) (car item-list) ) ) ) (defmethod tie-remplacement ((n1 note) (n2 note)) "Donne la nouvelle valeur de tie pour deux notes consecutives qui vont etre regroupees" (cond ((and (eq (tie n1) 'begin ) (eq (tie n2) 'end )) ()) ((and (eq (tie n1) 'begin ) (eq (tie n2) 'continue )) 'begin) ((and (eq (tie n1) 'continue ) (eq (tie n2) 'continue )) 'continue) ((and (eq (tie n1) 'continue ) (eq (tie n2) 'end )) 'end) ) ) (defmethod corresponding-note ( (c1 chord) (c2 note) ) (loop for item in (inside c1) thereis (and (eq (midic item) (midic c2)) item ) ) ) (defmethod grouping-formated-list ( item-list ) "formate en sous listes des elements consecutifs qui peuvent etre regroupes " (if (cdr item-list) (if (regroupables (car item-list) (cadr item-list ) ) (let ((temp (grouping-formated-list (cdr item-list)))) (cons (cons (car item-list) (car temp)) (cdr temp)) ) (cons (list (car item-list)) (grouping-formated-list (cdr item-list))) ) (list item-list) ) ) ;(trace grouping-formated-list ) dans le predicat regroupables , on suppose que c2 suit c1 . (defmethod regroupables ((c1 note) (c2 note)) (and (= (offset c2) (+ (offset c1) (extent c1))) (or (eq (tie c1) 'begin ) (eq (tie c1) 'continue ) ) (or (power-of-two-p (gcd (extent c1) (extent c2))) (eq (extent c1) (extent c2))) ) ) (defmethod regroupables ((c1 rest) (c2 rest)) (and (= (offset c2) (+ (offset c1) (extent c1))) (or (power-of-two-p (gcd (extent c1) (extent c2)))` (eq (extent c1) (extent c2))) ) ) (defmethod regroupables ((c1 chord) (c2 chord )) (and (= (offset c2) (+ (offset c1) (extent c1))) (or (power-of-two-p (gcd (extent c1) (extent c2))) (eq (extent c1) (extent c2))) (loop for item in (inside c1) with logvar = t do (setf logvar (and logvar (or (eq (tie item) 'begin ) (eq (tie item) 'continue ) ) )) finally (return logvar ) ) (eq (length (inside c1)) (length (inside c2))) ) ) (defmethod regroupables ((c1 t) (c2 t ) ) () ) (defmethod merge-first-two-voices ((self poly )) (voice->poly (om-merge (poly->voice self 0) (poly->voice self 1))) ) ;;; =============================================================================================== CONCATENATION DE STRUCTURES MUSICALES ;;; ;;; concat s'applique a des structures horizontales ;;; ;;; =============================================================================================== (defmethod om-concat ((s1 measure) (s2 measure)) (let ((frac-min (fraction-minimale-commune s1 s2)) (ss1 (duplique-structure-musicale s1)) (ss2 (duplique-structure-musicale s2))) (change-qvalue ss1 frac-min) (change-qvalue ss2 frac-min) (loop for item in (inside ss2) do (setf (offset item) (+ (offset item) (extent ss1)))) (mki 'measure :empty t :offset 0 :extent (+ (extent ss1) (extent ss2)) :qvalue frac-min :inside (append (inside ss1) (inside ss2)) ) ) ) (defmethod om-concat ((s1 voice) (s2 voice)) (let ((frac-min (fraction-minimale-commune s1 s2)) (ss1 (duplique-structure-musicale s1)) (ss2 (duplique-structure-musicale s2))) (change-qvalue ss1 frac-min) (change-qvalue ss2 frac-min) (loop for item in (inside ss2) do (setf (offset item) (+ (offset item) (extent ss1)))) (mki 'voice :empty t :offset 0 :extent (+ (extent ss1) (extent ss2)) :qvalue frac-min :inside (append (inside ss1) (inside ss2)) ) ) ) ;;; =============================================================================================== GET - STRUCTURE DUPLIQUE TOUTE LA STRUCTURE SAUF LES OBJETS TERMINAUX ;;; =============================================================================================== (defmethod get-structure ((self container) &optional (pere ()) ) (let ((new-container (copy-container self)) ( tp ( tuplet - p self ) ) ) (setf (parent new-container) pere) (setf (inside new-container) (loop for cont in (inside self) collect (get-structure cont new-container ) ) ) new-container ) ) (defmethod get-structure ((self metric-sequence) &optional (pere ()) ) (let ((sequence (call-next-method ))) (setf (slot-value sequence 'tree) nil) sequence )) (defmethod get-structure ((self simple-container) &optional (pere ()) ) (mki 'group :empty t :parent pere :offset (offset self) :extent (extent self) :qvalue (qvalue self) :inside () ) ) (defmethod get-structure ((self chord) &optional (pere ()) ) (mki 'group :empty t :parent pere :offset (offset self) :extent (extent self) :qvalue (qvalue self) :inside () ) ) n - list - intersection ne sert plus a rien , ... (defun n-list-intersection (list-of-lists ) (if (cdr list-of-lists ) (intersection (car list-of-lists) (n-list-intersection (cdr list-of-lists))) (car list-of-lists) ) ) (defmethod applique-liste-structure ((self poly) liste-objets &optional (running-offset 0) ) (loop for sous-structure in (inside self) for sous-liste in liste-objets do (applique-liste-structure sous-structure sous-liste running-offset) ) self ) (defmethod applique-liste-structure ((self container) liste-objets &optional (running-offset 0)) ;;; on commence par distribuer des elements aux eventuelles sous structures de self (let ((reste-liste (if (inside self) (loop for item in (inside self ) with sub-liste = liste-objets when (container-p item) do (setf sub-liste (applique-liste-structure item sub-liste (+ running-offset (offset self))) ) finally (return sub-liste) ) liste-objets ))) il reste a prendre maintenant ce qui revient a self ( ce qui n'a pas ete pris par une sous structure ) ;;; b- veut dire begin et e- end... (loop for item in reste-liste for b-item = (offset item) for e-item = (+ (offset item) (extent item)) for b-self = (+ running-offset (offset self) ) for e-self = (+ running-offset (offset self) (extent self)) quand l'objet rentre completement on le garde when (and (>= b-item b-self ) (<= e-item e-self )) do (progn (setf (offset item) (- (offset item) b-self )) (setf (inside self) (append (inside self) (list item))) (setf (parent item) self) ) quand l'objet ne rentre pas du tout on le rejette when (or (>= b-item e-self ) (<= e-item b-self )) collect item into rejected-elements quand l'objet rentre a moitie ( item > est dans le container < self > ) when (and (>= b-item b-self ) (< b-item e-self ) (> e-item e-self)) on rejette la moitie qui ne rentre pas collect (let ((apres (duplique-structure-musicale item))) (setf (offset apres) e-self ) (setf (extent apres) (- e-item e-self)) (if (note-p item) (setf (tie apres) (get-new-tie (tie item) 'apres)) () ) apres ) into rejected-elements et on prend la moitie qui rentre (setf (offset item) (- (offset item) (+ running-offset (offset self))) ) (setf (extent item) (- (extent self) (offset item) )) (setf (inside self) (cons item (inside self) )) ;; la on prend l'element (setf (parent item) self) (if (note-p item) (setf (tie item) (get-new-tie (tie item) 'avant)) ) ) quand l'objet rentre a moitie ( la sortie de < item > est dans le container < self > ) when (and (< b-item b-self ) (> e-item b-self ) (<= e-item e-self)) on rejette la premiere moitie qui ne rentre pas collect (let ((avant (duplique-structure-musicale item))) (setf (extent avant) (- b-self b-item )) (if (note-p item) (setf (tie avant) (get-new-tie (tie item) 'avant)) ()) avant ) into rejected-elements et on prend la moitie qui rentre (setf (extent item) (- e-item b-self)) (setf (offset item) 0) (setf (inside self) (cons item (inside self) )) ;; ici on prend l'element (setf (parent item) self) (if (note-p item) (setf (tie item) (get-new-tie (tie item) 'apres)) ()) ) ; quand l'objet <item> est a cheval sur <self> when (and (< b-item b-self ) (> e-item e-self ) ) collect (let ((avant (duplique-structure-musicale item))) (setf (extent avant) (- b-self b-item)) (if (note-p item) (setf (tie avant) (get-new-tie (tie item) 'avant)) ()) avant ) into rejected-elements and collect (let ((apres (duplique-structure-musicale item))) (setf (offset apres) e-self ) (setf (extent apres) (- e-item e-self ) ) (if (note-p item) (setf (tie apres) (get-new-tie (tie item) 'apres)) ()) apres ) into rejected-elements et on prend la moitie qui rentre (setf (offset item) 0) (setf (extent item) (extent self)) (setf (inside self) (cons item (inside self) )) ;; ici on prend l'element (setf (parent item) self) (if (note-p item) (setf (tie item) 'continue) ()) ) finally (progn (setf (inside self) (sort (inside self) #'< :key #'offset )) (return rejected-elements) ) ) ) ) (defmethod get-new-tie (old-tie type ) (if (eq type 'avant) (cond ((eq old-tie 'begin) 'begin) ((eq old-tie 'end) 'continue) ((eq old-tie 'continue) 'continue) (t 'begin )) (if (eq type 'apres) (cond ((eq old-tie 'begin) 'continue) ((eq old-tie 'end) 'end) ((eq old-tie 'continue) 'continue) (t 'end)) () ) ) ) ;;; =============================================================================================== PARCOURT LA STRUCTURE ET INSERE UN ACCORD QUAND DEUX NOTES TOMBENT SIMULTANEMENT ;;; =============================================================================================== (defmethod automatic-chord-insert ((self container)) (let ((note-list (loop for item in (inside self) when (note-p item) collect item))) (if note-list (setf (inside self) (append (set-difference (inside self) note-list) ;; la structure (loop for item in (chord-formated-list note-list) when (eq (length item) 1) collect (car item) when (> (length item) 1) collect (list->chord item) ) )) () ) (setf (inside self) (sort (inside self) #'< :key #'offset )) (loop for item in (inside self) a changer do (automatic-chord-insert item) ) ) ) UNE BIDOUILLE NECESSAIRE ET IMPOSSIBLE A COMMENTER (defun chord-formated-list ( note-list) (if (cdr note-list) (if (eq (offset (car note-list)) (offset (cadr note-list))) (let ((temp (chord-formated-list (cdr note-list)))) (cons (cons (car note-list) (car temp)) (cdr temp)) ) (cons (list (car note-list)) (chord-formated-list (cdr note-list))) ) (list note-list) ) ) ;;; =============================================================================================== TRANSFORME UN ENSEMBLE DE NOTES SIMULTANEES EN UN ACCORD ;;; =============================================================================================== (defmethod list->chord (list-of-notes) (let ((new-chord (mki 'chord :empty t))) (setf (inside new-chord) list-of-notes ) (setf (qvalue new-chord) (qvalue (car list-of-notes))) (setf (extent new-chord) (extent (car list-of-notes))) (setf (offset new-chord) (offset (car list-of-notes))) (loop for item in list-of-notes do (setf (parent item) new-chord)) new-chord ) ) ;;; =============================================================================================== ;;; INSERTION AUTOMATIQUE DES SILENCES * * * NE SERT PLUS A RIEN : J'UTILISE LA FONCTION SERA UTILE LORSQUE L'ON VOUDRA VERIFIER L'INTEGRITE D'UNE STRUCTURE ;;; =============================================================================================== ;;; n'est pas utilisee pour l'instant. Atention, elle n'ajoute pas de silence en debut et fin de container (defmethod automatic-rest-insert ((self container)) (let ((fringe (get-fringe self :frac-min (fraction-minimale self) :w-rest t)) (frac-min (fraction-minimale self))) (change-qvalue self frac-min) (let ((new-rests (loop for i1 in fringe for i2 in (cdr fringe) when (> (offset i2) (+ (offset i1) (extent i1))) collect (mki 'rest :offset (+ (offset i1) (extent i1)) :extent (- (offset i2) (+ (offset i1) (extent i1))) :qvalue frac-min ) ))) ;(print new-rests) ;(print self) (if new-rests (applique-liste-structure self new-rests ) () ) ) ) ) ;;; =============================================================================================== ;;; INSERTION AUTOMATIQUE DES SILENCES INSERE DES FRANGE DE MANIERE A CE QU'ELLE SOIT PLEINE ... PEUT ETRE DES PROBLEMES A LA FIN DE LA FRANGE ... - > IMPLIQUE D'UTILISER EGALEMENT LA FONCTION PRECEDENTE ;;; =============================================================================================== (defmethod insert-rests ((fringe list)) (sort (append fringe (loop for n1 in fringe for n2 in (cdr fringe ) when (> (offset n2) (+ (offset n1) (extent n1) )) collect (mki 'rest :offset (+ (offset n1) (extent n1)) :extent (- (offset n2) (+ (offset n1) (extent n1))) :qvalue (qvalue n1) ) ) ) #'< :key #'offset ) ) ;;; =============================================================================================== ;;; TRANSFORMATIONS RYTHMIQUES ;;; =============================================================================================== (defmethod strech ((self container) (num integer) (denom integer) &optional parent) (let ((temp (copy-container self))) (setf (extent temp) (* (extent self) num ) ) (setf (Qvalue temp) (* (Qvalue self) denom ) ) (setf (offset temp) (* (offset self) num ) ) (setf (parent temp) (if parent parent ()) ) (setf (inside temp) (loop for item in (inside self) collect (strech item num denom temp))) temp ) ) (defmethod strech ((self simple-container) (num integer) (denom integer) &optional parent ) (let ((temp (copy-container self))) (setf (extent temp) (* (extent self) num ) ) (setf (Qvalue temp) (* (Qvalue self) denom ) ) (setf (offset temp) (* (offset self) num ) ) (setf (parent temp) (if parent parent ()) ) temp )) (defmethod change-qvalue ((self simple-container) (new-qvalue integer) &optional (previous-qvalue 1)) (let ((new-q (if (eq (mod new-qvalue (fraction-minimale self)) 0) new-qvalue (fraction-minimale self)))) (if (container-p self) (loop for item in (inside self ) do (change-qvalue item new-q (qvalue self) ) ) () ) (setf (offset self) (/ (* (offset self) new-q ) previous-qvalue )) (setf (extent self) (/ (* (extent self) new-q ) (qvalue self) ) ) (setf (qvalue self) new-q) ) ) ;;; =============================================================================================== TRANSFORMATIONS SUR LES HAUTEURS ;;; =============================================================================================== (defmethod transpose ((self simple-container) trans &optional (pere ())) (let ((temp-cont (copy-container self) )) (setf (parent temp-cont) pere ) (if (container-p self) (setf (inside temp-cont) (loop for item in (inside self) collect (transpose item trans self) ) ) (if (eq (type-of temp-cont) 'note) (setf (midic temp-cont) (+ (midic temp-cont) trans )) () ) ) temp-cont ) ) POUR L'INSTANT MODIFIE LA STRUCTURE AU LIEU DE LA DUPLIQUER . (defmethod random-pitch ((self simple-container)) (if (container-p self) (loop for item in (inside self) do (random-pitch item)) (if (note-p self) (setf (midic self) (+ (* (om-random-value 15) 100) 6000)) () ) ) ) ;;; =============================================================================================== ;;; =============================================================================================== (defmethod quantify ((self simple-container) (new-qvalue integer)) (change-qvalue self (fraction-minimale self)) (let ((resultat (quantify2 self new-qvalue) )) (reduit-qvalue resultat ) resultat ) ) (defmethod quantify2 ((self simple-container) (new-qvalue integer)) (let ((temp-cont (copy-container self))) (setf (offset temp-cont) (round (/ (* (offset self) new-qvalue) (qvalue self)))) (setf (extent temp-cont) (round (/ (* (extent self) new-qvalue) (qvalue self)))) (setf (qvalue temp-cont) new-qvalue) (if (zerop (extent temp-cont)) () (if (container-p temp-cont) (progn (setf (inside temp-cont) (loop for item in (inside self) collect (quantify2 item new-qvalue) ) ) (if (inside temp-cont) temp-cont () ) ) temp-cont ) ) ) )
null
https://raw.githubusercontent.com/openmusic-project/openmusic/0bd8613a844a382e5db7185be1b5a5d026d66b20/OPENMUSIC/code/projects/musicproject/container/rythme/rythme.lisp
lisp
========================================================================= (at your option) any later version. 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. ========================================================================= ========================================================================= =============================================================================================== OPERATIONS RYTHMIQUES ELEMENTAIRES OLIVIER DELERUE =============================================================================================== PROVISOIRE !!! =============================================================================================== =============================================================================================== =============================================================================================== MERGE DE STRUCTURES MUSICALES =============================================================================================== =============================================================================================== MASQUAGE DE STRUCTURES MUSICALES =============================================================================================== v1 est la voix originale et v2 est le masque. le resultat est la voix v1 masquŽe par v2. masque et demasque (print mask ) =============================================================================================== LEGATO =============================================================================================== do-legato s'appplique a une structure complete, et rend une nouvelle structure. here to force recomputation of the tree =============================================================================================== SPLIT TIME =============================================================================================== j'ai mis un zero rapidement... c'est ici qu'il faut faire quelque chose mais quoi ? =============================================================================================== POUR REDUIRE UN POLY EN UNE SEULE VOICE =============================================================================================== sub (trace grouping-formated-list ) =============================================================================================== concat s'applique a des structures horizontales =============================================================================================== =============================================================================================== =============================================================================================== on commence par distribuer des elements aux eventuelles sous structures de self b- veut dire begin et e- end... la on prend l'element ici on prend l'element quand l'objet <item> est a cheval sur <self> ici on prend l'element =============================================================================================== =============================================================================================== la structure =============================================================================================== =============================================================================================== =============================================================================================== INSERTION AUTOMATIQUE DES SILENCES =============================================================================================== n'est pas utilisee pour l'instant. Atention, elle n'ajoute pas de silence en debut et fin de container (print new-rests) (print self) =============================================================================================== INSERTION AUTOMATIQUE DES SILENCES =============================================================================================== =============================================================================================== TRANSFORMATIONS RYTHMIQUES =============================================================================================== =============================================================================================== =============================================================================================== =============================================================================================== ===============================================================================================
OpenMusic : Visual Programming Language for Music Composition Copyright ( c ) 1997- ... IRCAM - Centre , Paris , France . This file is part of the OpenMusic environment sources OpenMusic 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 OpenMusic is distributed in the hope that it will be useful , You should have received a copy of the GNU General Public License along with OpenMusic . If not , see < / > . Music package (in-package :om) (defun fraction-minimale (&rest x) (apply 'cLcm x)) (defun fraction-minimale-commune (&rest x) (apply 'cLcm x)) (defun DUPLIQUE-STRUCTURE-MUSICALE (&rest x) (apply 'copy-container x)) (defun reduit-qvalue (&rest x) (apply 'QNormalize x)) ASSEMBLAGE DE STRUCTURES MUSICALES : on les met en parallle dans un objet vertical ( poly ) . (defmethod om-assemble ((s1 poly) (s2 poly)) (let ((frac-min (fraction-minimale-commune s1 s2)) (ss1 (duplique-structure-musicale s1)) (ss2 (duplique-structure-musicale s2))) (change-qvalue ss1 frac-min) (change-qvalue ss2 frac-min) (mki'poly :empty t :offset 0 :qvalue frac-min :extent (max (extent ss1) (extent ss2)) :inside (append (inside ss1) (inside ss2)) ) ) ) (defmethod om-assemble ((s1 voice) (s2 poly)) (let ((frac-min (fraction-minimale-commune s1 s2)) (ss1 (duplique-structure-musicale s1)) (ss2 (duplique-structure-musicale s2))) (setf (offset ss1) 0 ) (change-qvalue ss1 frac-min) (change-qvalue ss2 frac-min) (setf (inside ss2) (append (inside ss2) (list ss1))) ss2 ) ) (defmethod om-assemble ((s1 poly) (s2 voice)) (om-assemble s2 s1) ) (defmethod om-assemble ((s1 voice) (s2 voice)) (let ((frac-min (fraction-minimale-commune s1 s2) ) (ss1 (duplique-structure-musicale s1)) (ss2 (duplique-structure-musicale s2))) (change-qvalue ss1 frac-min) (change-qvalue ss2 frac-min) (setf (offset ss1) 0) (setf (offset ss2) 0) (mki'poly :empty t :offset 0 :qvalue frac-min :extent (max (extent ss1) (extent ss2)) :inside (list ss1 ss2) ) ) ) ces methodes assemblent a l'interieur ( et modifient ) un poly existant . (defmethod om-assemble-into-poly ((self poly) (s2 voice)) (let ((frac-min (fraction-minimale-commune self s2)) (ss2 (duplique-structure-musicale s2))) (change-qvalue self frac-min) (change-qvalue ss2 frac-min) (setf (slot-value self 'offset) 0 (slot-value self 'qvalue) frac-min (slot-value self 'extent) (max (extent self) (extent ss2)) (slot-value self 'inside) (append (inside self) (list ss2))) self)) (defmethod om-assemble-into-poly ((self poly) (s2 poly)) (let ((frac-min (fraction-minimale-commune self s2)) (ss2 (duplique-structure-musicale s2))) (change-qvalue self frac-min) (change-qvalue ss2 frac-min) (setf (slot-value self 'offset) 0 (slot-value self 'qvalue) frac-min (slot-value self 'extent) (max (extent self) (extent ss2)) (slot-value self 'inside) (append (inside self) (inside ss2))) self)) c'est la plus longue des deux structures (defmethod om-merge ((v1 voice) (v2 voice)) (let ((frac-min (fraction-minimale-commune v1 v2))) (let ((new-fringe (fringe-or (get-fringe v1 :frac-min frac-min :w-rest ()) (get-fringe v2 :frac-min frac-min :w-rest ()) )) (new-structure (smart-structure v1 v2)) ) (setf new-fringe (insert-rests new-fringe)) (applique-liste-structure new-structure new-fringe) (automatic-chord-insert new-structure) (delete-useless-containers new-structure ) (do-grouping new-structure ) new-structure ) ) ) (defmethod om-merge ((v1 measure) (v2 measure)) (voice->measure (om-merge (measure->voice v1) (measure->voice v2)) 0 ) ) (defmethod om-masque ((v1 voice) (v2 voice) &key (mode 'masque)) (let ((frac-min (fraction-minimale-commune v1 v2))) (let ((new-fringe (fringe-masque (get-fringe v1 :frac-min frac-min :w-rest ()) (get-fringe v2 :frac-min frac-min :w-rest ()) :mode mode ) ) (new-structure (smart-structure v1 v2)) ) (applique-liste-structure new-structure new-fringe) (automatic-chord-insert new-structure) (blank-fill new-structure ) (delete-useless-containers new-structure ) (do-grouping new-structure ) new-structure ) ) ) (defmethod get-fringe-activity ((fringe list)) (if (cdr fringe ) (let ((resultat (get-fringe-activity (cdr fringe)))) (if (>= (+ (offset (car fringe)) (extent (car fringe))) (caar resultat)) (cons (list (offset (car fringe)) (cadar resultat)) (cdr resultat)) (if (= (offset (car fringe)) (caar resultat)) resultat (cons (list (offset (car fringe)) (+ (offset (car fringe)) (extent (car fringe)))) resultat ) ) ) ) (list (list (offset (car fringe)) (+ (offset (car fringe)) (extent (car fringe))))) ) ) (defmethod get-fringe-inactivity ((fringe list)) (append (list (list 0 (offset (car fringe)))) (loop for item1 in fringe for item2 in (cdr fringe ) when (> (offset item2) (+ (offset item1) (extent item1))) collect (list (+ (offset item1) (extent item1)) (offset item2) ) ) (let ((last-item (car (last fringe)))) (list (list (+ (offset last-item) (extent last-item)) 100000000))) ) ) (defmethod fringe-masque ((fringe1 list) (fringe2 list) &key (mode 'masque)) (let ((mask (if (eq mode 'masque ) (get-fringe-activity fringe2) (if (eq mode 'demasque ) (get-fringe-inactivity fringe2) () ) ))) (loop for item in fringe1 append (masquage item mask )) ) ) (defmethod masquage ((self note) (activity list) ) (loop for item in activity when (and (< (offset self) (cadr item)) (> (+ (offset self) (extent self)) (car item)) ) collect (let ((new-note (copy-container self))) (setf (offset new-note) (max (car item) (offset self)) ) (setf (extent new-note) (- (min (cadr item) (+ (extent self) (offset self)) ) (max (car item) (offset self)) ) ) new-note ) ) ) transformation legato : elle remplace les silences par une note liee a la precedente legato modifie la structure et s'applique au premier simple - container de la structure (defmethod do-legato ((self simple-container)) (let ((new-struct (Qreduce (duplique-structure-musicale self)))) (legato (first-simple-container new-struct )) (delete-useless-containers new-struct) (do-grouping new-struct) new-struct ) ) (defmethod legato ((self simple-container)) (let ((next-one (next-simple-container self))) (if next-one (if (rest-p next-one) (let ((new-next-one (replace-simple-container self next-one ) )) (setf (tie new-next-one ) (cond ((eq (tie self) 'nil ) 'end ) ((eq (tie self) 'begin ) 'continue ) ((eq (tie self) 'end ) 'end ) ((eq (tie self) 'continue ) 'continue ) ) ) (setf (tie self ) (cond ((eq (tie self) 'nil ) 'begin ) ((eq (tie self) 'begin ) 'begin ) ((eq (tie self) 'end ) 'continue ) ((eq (tie self) 'continue ) 'continue ) ) ) (legato new-next-one) ) (legato next-one) ) () ) ) ) (defmethod legato ((self chord)) (let ((next-one (next-simple-container self))) (if next-one (if (rest-p next-one) (let ((new-next-one (replace-simple-container self next-one ) )) (loop for note in (inside self) do (progn (setf (tie (corresponding-note new-next-one note ) ) (cond ((eq (tie note) 'nil ) 'end ) ((eq (tie note) 'begin ) 'continue ) ((eq (tie note) 'end ) 'end ) ((eq (tie note) 'continue ) 'continue ) ) ) (setf (tie note ) (cond ((eq (tie note) 'nil ) 'begin ) ((eq (tie note) 'begin ) 'begin ) ((eq (tie note) 'end ) 'continue ) ((eq (tie note) 'continue ) 'continue ) ) ) ) ) (legato new-next-one) ) (legato next-one) ) () ) ) ) (defmethod split-time ((self container) tree ) (let ((new-struct (duplique-structure-musicale self)) (temp-group (make-instance 'group :tree tree))) (do-split-time (first-simple-container new-struct ) temp-group) (setf (tree new-struct) nil) new-struct ) ) (defmethod splitit ((self container) (temp-group group)) (let ((new-struct (duplique-structure-musicale self)) ) (do-split-time (first-simple-container new-struct ) temp-group) (setf (tree new-struct) nil) new-struct ) ) (defmethod do-split-time ((self note ) temp-group) (let ((new-simple-container (replace-simple-container (transpose temp-group (- (midic self) 6000 ) ) self) )) (if (next-simple-container new-simple-container) (do-split-time (next-simple-container new-simple-container) temp-group ) () ) ) ) (defmethod do-split-time ((self rest) temp-group) (if (next-simple-container self) (do-split-time (next-simple-container self) temp-group ) () ) ) il reste un probleme pour la transposition dans le cas de l'accord ... (defmethod do-split-time ((self chord ) temp-group) (let ((new-simple-container (replace-simple-container (transpose temp-group (- (midic (car (inside self))) 6000 ) ) ( splitit temp - group self ) self) )) (if (next-simple-container new-simple-container) (do-split-time (next-simple-container new-simple-container) temp-group ) () ) ) ) (defmethod om-merge-down ((self poly)) (merge-down-voices (inside self)) ) (defmethod merge-down-voices (list-of-voices) (if (cdr list-of-voices) (om-merge (car list-of-voices) (merge-down-voices (cdr list-of-voices))) (car list-of-voices) ) ) on cherche une structure commune sans casser les groupes pour eviter d'avoir des tuplets a cheval sur deux mesures (defmethod smart-structure ((v1 voice) (v2 voice)) (let ((frac-min (fraction-minimale-commune v1 v2)) (st1 (get-structure v1) ) (st2 (get-structure v2) )) (change-qvalue st1 frac-min) (change-qvalue st2 frac-min) (let ((structure-longue (if (< (extent st1) (extent st2) ) st2 st1) ) (structure-courte (if (< (extent st1) (extent st2) ) st1 st2) )) (loop for item in (tuplet-collection structure-courte) do (propage-subdivision structure-longue (car item) (cadr item))) structure-longue ) ) ) (defmethod propage-subdivision ((self container) (sub integer) (c container) &optional (running-offset 0) ) (if (inside self) (loop for item in (inside self) do (propage-subdivision item sub c (+ running-offset (offset self)))) (let ((start-self (+ (offset self) running-offset)) (end-self (+ running-offset (offset self) (extent self))) (start-c (offset c)) (end-c (+ (offset c) (extent c))) ) (if (and (or (and (>= start-c start-self) (< start-c end-self)) (and (> end-c start-self) (<= end-c end-self)) (and (< start-c start-self) (> end-c end-self)) ) (zerop (mod (extent self) sub)) ) (setf (inside self) (loop for compteur from 1 to sub by ( / (extent self) sub ) collect (mki 'group :empty t :parent self :offset (* (- compteur 1) ( / (extent self) sub ) ) :qvalue (qvalue self ) ) ) ) () ) ) ) ) (defmethod tuplet-collection ((self container) &optional (running-offset 0) ) (let ((tp (tuplet-p self))) (if tp (let ((new-tup (copy-container self))) (setf (offset new-tup) (+ (offset self) running-offset)) (setf (inside new-tup) ()) (cons (list tp new-tup) (loop for item in (inside self) append (tuplet-collection item ))) ) (loop for item in (inside self) append (tuplet-collection item (+ running-offset (offset self)))) ) ) ) (defmethod tuplet-collection ((self simple-container) &optional (running-offset 0) ) () ) (defmethod do-grouping ((self container)) (setf (inside self) (loop for item in (grouping-formated-list (inside self)) when (eq (length item ) 1) collect (car item) when (> (length item) 1 ) collect (list->group item ) ) ) (loop for item in (inside self) when (and (container-p item) (not (chord-p item))) do (do-grouping item) ) ) (defmethod list->group (item-list) "effectue le regroupement d'un ensemble de simple-containers" (if (chord-p (car item-list)) (let ((new-extent (* (loop for sc in item-list sum (/ (extent sc ) (qvalue sc))) (qvalue (car item-list))))) (setf (extent (car item-list )) new-extent ) (loop for note in (inside (car item-list)) do (progn (setf (tie note) (tie-remplacement note (corresponding-note (car (last item-list)) note ))) (setf (extent note) new-extent ) ) ) (car item-list) ) (let ((new-extent (* (loop for sc in item-list sum (/ (extent sc ) (qvalue sc))) (qvalue (car item-list))))) (setf (extent (car item-list )) new-extent ) (if (note-p (car item-list)) (setf (tie (car item-list)) (tie-remplacement (car item-list) (car (last item-list)))) ()) (car item-list) ) ) ) (defmethod tie-remplacement ((n1 note) (n2 note)) "Donne la nouvelle valeur de tie pour deux notes consecutives qui vont etre regroupees" (cond ((and (eq (tie n1) 'begin ) (eq (tie n2) 'end )) ()) ((and (eq (tie n1) 'begin ) (eq (tie n2) 'continue )) 'begin) ((and (eq (tie n1) 'continue ) (eq (tie n2) 'continue )) 'continue) ((and (eq (tie n1) 'continue ) (eq (tie n2) 'end )) 'end) ) ) (defmethod corresponding-note ( (c1 chord) (c2 note) ) (loop for item in (inside c1) thereis (and (eq (midic item) (midic c2)) item ) ) ) (defmethod grouping-formated-list ( item-list ) "formate en sous listes des elements consecutifs qui peuvent etre regroupes " (if (cdr item-list) (if (regroupables (car item-list) (cadr item-list ) ) (let ((temp (grouping-formated-list (cdr item-list)))) (cons (cons (car item-list) (car temp)) (cdr temp)) ) (cons (list (car item-list)) (grouping-formated-list (cdr item-list))) ) (list item-list) ) ) dans le predicat regroupables , on suppose que c2 suit c1 . (defmethod regroupables ((c1 note) (c2 note)) (and (= (offset c2) (+ (offset c1) (extent c1))) (or (eq (tie c1) 'begin ) (eq (tie c1) 'continue ) ) (or (power-of-two-p (gcd (extent c1) (extent c2))) (eq (extent c1) (extent c2))) ) ) (defmethod regroupables ((c1 rest) (c2 rest)) (and (= (offset c2) (+ (offset c1) (extent c1))) (or (power-of-two-p (gcd (extent c1) (extent c2)))` (eq (extent c1) (extent c2))) ) ) (defmethod regroupables ((c1 chord) (c2 chord )) (and (= (offset c2) (+ (offset c1) (extent c1))) (or (power-of-two-p (gcd (extent c1) (extent c2))) (eq (extent c1) (extent c2))) (loop for item in (inside c1) with logvar = t do (setf logvar (and logvar (or (eq (tie item) 'begin ) (eq (tie item) 'continue ) ) )) finally (return logvar ) ) (eq (length (inside c1)) (length (inside c2))) ) ) (defmethod regroupables ((c1 t) (c2 t ) ) () ) (defmethod merge-first-two-voices ((self poly )) (voice->poly (om-merge (poly->voice self 0) (poly->voice self 1))) ) CONCATENATION DE STRUCTURES MUSICALES (defmethod om-concat ((s1 measure) (s2 measure)) (let ((frac-min (fraction-minimale-commune s1 s2)) (ss1 (duplique-structure-musicale s1)) (ss2 (duplique-structure-musicale s2))) (change-qvalue ss1 frac-min) (change-qvalue ss2 frac-min) (loop for item in (inside ss2) do (setf (offset item) (+ (offset item) (extent ss1)))) (mki 'measure :empty t :offset 0 :extent (+ (extent ss1) (extent ss2)) :qvalue frac-min :inside (append (inside ss1) (inside ss2)) ) ) ) (defmethod om-concat ((s1 voice) (s2 voice)) (let ((frac-min (fraction-minimale-commune s1 s2)) (ss1 (duplique-structure-musicale s1)) (ss2 (duplique-structure-musicale s2))) (change-qvalue ss1 frac-min) (change-qvalue ss2 frac-min) (loop for item in (inside ss2) do (setf (offset item) (+ (offset item) (extent ss1)))) (mki 'voice :empty t :offset 0 :extent (+ (extent ss1) (extent ss2)) :qvalue frac-min :inside (append (inside ss1) (inside ss2)) ) ) ) GET - STRUCTURE DUPLIQUE TOUTE LA STRUCTURE SAUF LES OBJETS TERMINAUX (defmethod get-structure ((self container) &optional (pere ()) ) (let ((new-container (copy-container self)) ( tp ( tuplet - p self ) ) ) (setf (parent new-container) pere) (setf (inside new-container) (loop for cont in (inside self) collect (get-structure cont new-container ) ) ) new-container ) ) (defmethod get-structure ((self metric-sequence) &optional (pere ()) ) (let ((sequence (call-next-method ))) (setf (slot-value sequence 'tree) nil) sequence )) (defmethod get-structure ((self simple-container) &optional (pere ()) ) (mki 'group :empty t :parent pere :offset (offset self) :extent (extent self) :qvalue (qvalue self) :inside () ) ) (defmethod get-structure ((self chord) &optional (pere ()) ) (mki 'group :empty t :parent pere :offset (offset self) :extent (extent self) :qvalue (qvalue self) :inside () ) ) n - list - intersection ne sert plus a rien , ... (defun n-list-intersection (list-of-lists ) (if (cdr list-of-lists ) (intersection (car list-of-lists) (n-list-intersection (cdr list-of-lists))) (car list-of-lists) ) ) (defmethod applique-liste-structure ((self poly) liste-objets &optional (running-offset 0) ) (loop for sous-structure in (inside self) for sous-liste in liste-objets do (applique-liste-structure sous-structure sous-liste running-offset) ) self ) (defmethod applique-liste-structure ((self container) liste-objets &optional (running-offset 0)) (let ((reste-liste (if (inside self) (loop for item in (inside self ) with sub-liste = liste-objets when (container-p item) do (setf sub-liste (applique-liste-structure item sub-liste (+ running-offset (offset self))) ) finally (return sub-liste) ) liste-objets ))) il reste a prendre maintenant ce qui revient a self ( ce qui n'a pas ete pris par une sous structure ) (loop for item in reste-liste for b-item = (offset item) for e-item = (+ (offset item) (extent item)) for b-self = (+ running-offset (offset self) ) for e-self = (+ running-offset (offset self) (extent self)) quand l'objet rentre completement on le garde when (and (>= b-item b-self ) (<= e-item e-self )) do (progn (setf (offset item) (- (offset item) b-self )) (setf (inside self) (append (inside self) (list item))) (setf (parent item) self) ) quand l'objet ne rentre pas du tout on le rejette when (or (>= b-item e-self ) (<= e-item b-self )) collect item into rejected-elements quand l'objet rentre a moitie ( item > est dans le container < self > ) when (and (>= b-item b-self ) (< b-item e-self ) (> e-item e-self)) on rejette la moitie qui ne rentre pas collect (let ((apres (duplique-structure-musicale item))) (setf (offset apres) e-self ) (setf (extent apres) (- e-item e-self)) (if (note-p item) (setf (tie apres) (get-new-tie (tie item) 'apres)) () ) apres ) into rejected-elements et on prend la moitie qui rentre (setf (offset item) (- (offset item) (+ running-offset (offset self))) ) (setf (extent item) (- (extent self) (offset item) )) (setf (parent item) self) (if (note-p item) (setf (tie item) (get-new-tie (tie item) 'avant)) ) ) quand l'objet rentre a moitie ( la sortie de < item > est dans le container < self > ) when (and (< b-item b-self ) (> e-item b-self ) (<= e-item e-self)) on rejette la premiere moitie qui ne rentre pas collect (let ((avant (duplique-structure-musicale item))) (setf (extent avant) (- b-self b-item )) (if (note-p item) (setf (tie avant) (get-new-tie (tie item) 'avant)) ()) avant ) into rejected-elements et on prend la moitie qui rentre (setf (extent item) (- e-item b-self)) (setf (offset item) 0) (setf (parent item) self) (if (note-p item) (setf (tie item) (get-new-tie (tie item) 'apres)) ()) ) when (and (< b-item b-self ) (> e-item e-self ) ) collect (let ((avant (duplique-structure-musicale item))) (setf (extent avant) (- b-self b-item)) (if (note-p item) (setf (tie avant) (get-new-tie (tie item) 'avant)) ()) avant ) into rejected-elements and collect (let ((apres (duplique-structure-musicale item))) (setf (offset apres) e-self ) (setf (extent apres) (- e-item e-self ) ) (if (note-p item) (setf (tie apres) (get-new-tie (tie item) 'apres)) ()) apres ) into rejected-elements et on prend la moitie qui rentre (setf (offset item) 0) (setf (extent item) (extent self)) (setf (parent item) self) (if (note-p item) (setf (tie item) 'continue) ()) ) finally (progn (setf (inside self) (sort (inside self) #'< :key #'offset )) (return rejected-elements) ) ) ) ) (defmethod get-new-tie (old-tie type ) (if (eq type 'avant) (cond ((eq old-tie 'begin) 'begin) ((eq old-tie 'end) 'continue) ((eq old-tie 'continue) 'continue) (t 'begin )) (if (eq type 'apres) (cond ((eq old-tie 'begin) 'continue) ((eq old-tie 'end) 'end) ((eq old-tie 'continue) 'continue) (t 'end)) () ) ) ) PARCOURT LA STRUCTURE ET INSERE UN ACCORD QUAND DEUX NOTES TOMBENT SIMULTANEMENT (defmethod automatic-chord-insert ((self container)) (let ((note-list (loop for item in (inside self) when (note-p item) collect item))) (if note-list (loop for item in (chord-formated-list note-list) when (eq (length item) 1) collect (car item) when (> (length item) 1) collect (list->chord item) ) )) () ) (setf (inside self) (sort (inside self) #'< :key #'offset )) (loop for item in (inside self) a changer do (automatic-chord-insert item) ) ) ) UNE BIDOUILLE NECESSAIRE ET IMPOSSIBLE A COMMENTER (defun chord-formated-list ( note-list) (if (cdr note-list) (if (eq (offset (car note-list)) (offset (cadr note-list))) (let ((temp (chord-formated-list (cdr note-list)))) (cons (cons (car note-list) (car temp)) (cdr temp)) ) (cons (list (car note-list)) (chord-formated-list (cdr note-list))) ) (list note-list) ) ) TRANSFORME UN ENSEMBLE DE NOTES SIMULTANEES EN UN ACCORD (defmethod list->chord (list-of-notes) (let ((new-chord (mki 'chord :empty t))) (setf (inside new-chord) list-of-notes ) (setf (qvalue new-chord) (qvalue (car list-of-notes))) (setf (extent new-chord) (extent (car list-of-notes))) (setf (offset new-chord) (offset (car list-of-notes))) (loop for item in list-of-notes do (setf (parent item) new-chord)) new-chord ) ) * * * NE SERT PLUS A RIEN : J'UTILISE LA FONCTION SERA UTILE LORSQUE L'ON VOUDRA VERIFIER L'INTEGRITE D'UNE STRUCTURE (defmethod automatic-rest-insert ((self container)) (let ((fringe (get-fringe self :frac-min (fraction-minimale self) :w-rest t)) (frac-min (fraction-minimale self))) (change-qvalue self frac-min) (let ((new-rests (loop for i1 in fringe for i2 in (cdr fringe) when (> (offset i2) (+ (offset i1) (extent i1))) collect (mki 'rest :offset (+ (offset i1) (extent i1)) :extent (- (offset i2) (+ (offset i1) (extent i1))) :qvalue frac-min ) ))) (if new-rests (applique-liste-structure self new-rests ) () ) ) ) ) INSERE DES FRANGE DE MANIERE A CE QU'ELLE SOIT PLEINE ... PEUT ETRE DES PROBLEMES A LA FIN DE LA FRANGE ... - > IMPLIQUE D'UTILISER EGALEMENT LA FONCTION PRECEDENTE (defmethod insert-rests ((fringe list)) (sort (append fringe (loop for n1 in fringe for n2 in (cdr fringe ) when (> (offset n2) (+ (offset n1) (extent n1) )) collect (mki 'rest :offset (+ (offset n1) (extent n1)) :extent (- (offset n2) (+ (offset n1) (extent n1))) :qvalue (qvalue n1) ) ) ) #'< :key #'offset ) ) (defmethod strech ((self container) (num integer) (denom integer) &optional parent) (let ((temp (copy-container self))) (setf (extent temp) (* (extent self) num ) ) (setf (Qvalue temp) (* (Qvalue self) denom ) ) (setf (offset temp) (* (offset self) num ) ) (setf (parent temp) (if parent parent ()) ) (setf (inside temp) (loop for item in (inside self) collect (strech item num denom temp))) temp ) ) (defmethod strech ((self simple-container) (num integer) (denom integer) &optional parent ) (let ((temp (copy-container self))) (setf (extent temp) (* (extent self) num ) ) (setf (Qvalue temp) (* (Qvalue self) denom ) ) (setf (offset temp) (* (offset self) num ) ) (setf (parent temp) (if parent parent ()) ) temp )) (defmethod change-qvalue ((self simple-container) (new-qvalue integer) &optional (previous-qvalue 1)) (let ((new-q (if (eq (mod new-qvalue (fraction-minimale self)) 0) new-qvalue (fraction-minimale self)))) (if (container-p self) (loop for item in (inside self ) do (change-qvalue item new-q (qvalue self) ) ) () ) (setf (offset self) (/ (* (offset self) new-q ) previous-qvalue )) (setf (extent self) (/ (* (extent self) new-q ) (qvalue self) ) ) (setf (qvalue self) new-q) ) ) TRANSFORMATIONS SUR LES HAUTEURS (defmethod transpose ((self simple-container) trans &optional (pere ())) (let ((temp-cont (copy-container self) )) (setf (parent temp-cont) pere ) (if (container-p self) (setf (inside temp-cont) (loop for item in (inside self) collect (transpose item trans self) ) ) (if (eq (type-of temp-cont) 'note) (setf (midic temp-cont) (+ (midic temp-cont) trans )) () ) ) temp-cont ) ) POUR L'INSTANT MODIFIE LA STRUCTURE AU LIEU DE LA DUPLIQUER . (defmethod random-pitch ((self simple-container)) (if (container-p self) (loop for item in (inside self) do (random-pitch item)) (if (note-p self) (setf (midic self) (+ (* (om-random-value 15) 100) 6000)) () ) ) ) (defmethod quantify ((self simple-container) (new-qvalue integer)) (change-qvalue self (fraction-minimale self)) (let ((resultat (quantify2 self new-qvalue) )) (reduit-qvalue resultat ) resultat ) ) (defmethod quantify2 ((self simple-container) (new-qvalue integer)) (let ((temp-cont (copy-container self))) (setf (offset temp-cont) (round (/ (* (offset self) new-qvalue) (qvalue self)))) (setf (extent temp-cont) (round (/ (* (extent self) new-qvalue) (qvalue self)))) (setf (qvalue temp-cont) new-qvalue) (if (zerop (extent temp-cont)) () (if (container-p temp-cont) (progn (setf (inside temp-cont) (loop for item in (inside self) collect (quantify2 item new-qvalue) ) ) (if (inside temp-cont) temp-cont () ) ) temp-cont ) ) ) )
c314179df9a670f7c50ecd7a8ed0b6ae4305842f3111a803d247f80e2cd303f8
sunshineclt/Racket-Helper
homework2-04.rkt
#lang racket (define (average x y) (/ (+ x y) 2)) (define (iterative-improve good-enough improve) (define (iterater now) (if (good-enough now) now (iterater (improve now)))) iterater) (define (sqrt a) (define (gd x) (< (abs (- x (average x (/ a x)))) 0.0001)) (define (im x) (average x (/ a x))) ((iterative-improve gd im) 1)) (define (myloop) (let ((n (read))) (if (eq? n eof) (void) (begin (display (sqrt n)) (newline) (myloop))))) (myloop)
null
https://raw.githubusercontent.com/sunshineclt/Racket-Helper/bf85f38dd8d084db68265bb98d8c38bada6494ec/%E9%99%88%E4%B9%90%E5%A4%A9/Week2/homework2-04.rkt
racket
#lang racket (define (average x y) (/ (+ x y) 2)) (define (iterative-improve good-enough improve) (define (iterater now) (if (good-enough now) now (iterater (improve now)))) iterater) (define (sqrt a) (define (gd x) (< (abs (- x (average x (/ a x)))) 0.0001)) (define (im x) (average x (/ a x))) ((iterative-improve gd im) 1)) (define (myloop) (let ((n (read))) (if (eq? n eof) (void) (begin (display (sqrt n)) (newline) (myloop))))) (myloop)
c74177a3bc8bb527f2068df2b97856450cbf5f47ba38519a824a79782f348d23
inaka/erlang-github
egithub_SUITE.erl
-module(egithub_SUITE). -export([ all/0, init_per_suite/1, end_per_suite/1 ]). -export([ pull_reqs/1, issue_comments/1, pr_review/1, issues/1, files/1, users/1, orgs/1, repos/1, teams/1, hooks/1, collaborators/1, statuses/1, releases/1, branches/1, tags/1, custom_host/1 ]). -record(client, {}). -define(EXCLUDED_FUNS, [ module_info, all, test, init_per_suite, end_per_suite ]). -type config() :: [{atom(), term()}]. -type result() :: ok | {ok, term()} | {error, term()}. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Common test %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -spec all() -> [atom()]. all() -> Exports = ?MODULE:module_info(exports), [F || {F, _} <- Exports, not lists:member(F, ?EXCLUDED_FUNS)]. -spec init_per_suite(config()) -> config(). init_per_suite(Config) -> {ok, _} = egithub:start(), Config. -spec end_per_suite(config()) -> config(). end_per_suite(Config) -> ok = application:stop(egithub), Config. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Test cases %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -spec pull_reqs(config()) -> result(). pull_reqs(_Config) -> Credentials = github_credentials(), meck:new(hackney, [passthrough]), try BodyReturnFun = fun(_) -> {ok, <<"[]">>} end, PRsUrl = "/repos/user/repo/pulls?direction=asc&page=1&sort=created" "&state=open", AllOpenPRFun = match_fun(PRsUrl, get), meck:expect(hackney, body, BodyReturnFun), meck:expect(hackney, request, AllOpenPRFun), {ok, _} = egithub:pull_reqs(Credentials, "user/repo", #{state => "open"}), SinglePRFun = match_fun("/repos/user/repo/pulls/1", get), meck:expect(hackney, body, BodyReturnFun), meck:expect(hackney, request, SinglePRFun), {ok, _} = egithub:pull_req(Credentials, "user/repo", 1), PRFilesFun = match_fun("/repos/user/repo/pulls/1/files", get), meck:expect(hackney, body, BodyReturnFun), meck:expect(hackney, request, PRFilesFun), {ok, _} = egithub:pull_req_files(Credentials, "user/repo", 1), PRCommentLineFun = match_fun("/repos/user/repo/pulls/1/comments", post), meck:expect(hackney, request, PRCommentLineFun), {ok, _} = egithub:pull_req_comment_line(Credentials, "user/repo", 1, "SHA", <<"file-path">>, 5, "comment text"), Self = self(), PRCommentLineQueueFun = fun(_, _, _, _) -> Self ! ok, {ok, 200, [], #client{}} end, meck:expect(hackney, request, PRCommentLineQueueFun), ok = egithub:pull_req_comment_line(Credentials, "user/repo", 1, "SHA", <<"file-path">>, 5, "comment text", #{post_method => queue}), ok = receive ok -> ok after 5000 -> timeout end, PRCommentsFun = match_fun("/repos/user/repo/pulls/1/comments", get), meck:expect(hackney, request, PRCommentsFun), {ok, _} = egithub:pull_req_comments(Credentials, "user/repo", 1) after meck:unload(hackney) end. -spec issue_comments(config()) -> result(). issue_comments(_Config) -> Credentials = github_credentials(), meck:new(hackney, [passthrough]), try IssueCommentFun = match_fun("/repos/user/repo/issues/1/comments", post), meck:expect(hackney, request, IssueCommentFun), BodyReturnFun = fun(_) -> {ok, <<"[]">>} end, meck:expect(hackney, body, BodyReturnFun), {ok, _} = egithub:issue_comment(Credentials, "user/repo", 1, "txt"), Self = self(), IssueCommentQueueFun = fun(post, Url, _, _) -> <<"/" "repos/user/repo/issues/1/comments">> = Url, Self ! ok, {ok, 200, [], #client{}} end, meck:expect(hackney, request, IssueCommentQueueFun), ok = egithub:issue_comment(Credentials, "user/repo", 1, "txt", #{post_method => queue}), ok = receive ok -> ok after 5000 -> timeout end, IssueCommentsFun = match_fun("/repos/user/repo/issues/1/comments", get), meck:expect(hackney, request, IssueCommentsFun), {ok, _} = egithub:issue_comments(Credentials, "user/repo", 1) after meck:unload(hackney) end. -spec pr_review(config()) -> result(). pr_review(_Config) -> Credentials = github_credentials(), meck:new(hackney, [passthrough]), try Self = self(), PrReviewQueueFun = fun(post, Url, _, _) -> <<"/" "repos/user/repo/pulls/1/reviews">> = Url, Self ! ok, {ok, 200, [], #client{}} end, meck:expect(hackney, request, PrReviewQueueFun), ReqBody = #{body => <<>>, comments => [#{path => <<"/path/to/file">>, position => 20, body => <<"bad function naming">>}], commit_id => <<"c0m1tt1d">>, event => <<"REQUEST_CHANGES">>}, ok = egithub:pr_review(Credentials, "user/repo", 1, ReqBody, #{post_method => queue}), ok = receive ok -> ok after 5000 -> timeout end after meck:unload(hackney) end. -spec issues(config()) -> result(). issues(_Config) -> Credentials = github_credentials(), meck:new(hackney, [passthrough]), try BodyReturnFun = fun(_) -> {ok, <<"[]">>} end, meck:expect(hackney, body, BodyReturnFun), CreateIssueFun = match_fun("/repos/user/repo/issues", post), meck:expect(hackney, request, CreateIssueFun), {ok, _} = egithub:create_issue(Credentials, "user", "repo", "title", "text", "user", ["bug"]), AllIssuesFun = match_fun("/issues", get), meck:expect(hackney, request, AllIssuesFun), {ok, _} = egithub:all_issues(Credentials, #{}), AllRepoIssuesFun = match_fun("/repos/user/repo/issues", get), meck:expect(hackney, request, AllRepoIssuesFun), {ok, _} = egithub:all_issues(Credentials, "user/repo", #{}), IssueUrl = "/issues?direction=asc&filter=assigned&" "sort=created&state=open", AllIssuesOpenFun = match_fun(IssueUrl, get), meck:expect(hackney, request, AllIssuesOpenFun), {ok, _} = egithub:all_issues(Credentials, #{state => "open"}), UserIssuesFun = match_fun("/user/issues", get), meck:expect(hackney, request, UserIssuesFun), {ok, _} = egithub:issues_user(Credentials, #{}), OrgIssuesFun = match_fun("/orgs/foo/issues", get), meck:expect(hackney, request, OrgIssuesFun), {ok, _} = egithub:issues_org(Credentials, "foo", #{}), SingleIssueFun = match_fun("/repos/user/repo/issues/1", get), meck:expect(hackney, request, SingleIssueFun), {ok, _} = egithub:issue(Credentials, "user/repo", 1) after meck:unload(hackney) end. -spec files(config()) -> result(). files(_Config) -> Credentials = github_credentials(), meck:new(hackney, [passthrough]), try FileContentFun = match_fun("/repos/user/repo/contents/file?ref=SHA", get), meck:expect(hackney, request, FileContentFun), BodyReturnFun = fun(_) -> {ok, <<"{\"content\" : \"\"}">>} end, meck:expect(hackney, body, BodyReturnFun), {ok, _} = egithub:file_content(Credentials, "user/repo", "SHA", "file") after meck:unload(hackney) end. -spec users(config()) -> result(). users(_Config) -> Credentials = github_credentials(), meck:new(hackney, [passthrough]), try BodyReturnFun = fun(_) -> {ok, <<"[]">>} end, meck:expect(hackney, body, BodyReturnFun), UserFun = match_fun("/user", get), meck:expect(hackney, request, UserFun), {ok, _} = egithub:user(Credentials), GadgetCIFun = match_fun("/users/gadgetci", get), meck:expect(hackney, request, GadgetCIFun), {ok, _} = egithub:user(Credentials, "gadgetci"), EmailsFun = match_fun("/user/emails", get), meck:expect(hackney, request, EmailsFun), {ok, _} = egithub:user_emails(Credentials) after meck:unload(hackney) end. -spec orgs(config()) -> result(). orgs(_Config) -> Credentials = github_credentials(), meck:new(hackney, [passthrough]), try BodyReturnFun = fun(_) -> {ok, <<"[]">>} end, meck:expect(hackney, body, BodyReturnFun), OrgsFun = match_fun("/user/orgs", get), meck:expect(hackney, request, OrgsFun), {ok, _} = egithub:orgs(Credentials), OrgsUserFun = match_fun("/users/gadgetci/orgs", get), meck:expect(hackney, request, OrgsUserFun), {ok, _} = egithub:orgs(Credentials, "gadgetci"), OrgMembershipFun = match_fun("/user/memberships/orgs/some-organization", get), meck:expect(hackney, request, OrgMembershipFun), {ok, _} = egithub:org_membership(Credentials, "some-organization") after meck:unload(hackney) end. -spec repos(config()) -> result(). repos(_Config) -> Credentials = github_credentials(), meck:new(hackney, [passthrough]), try RepoFun = match_fun("/repos/inaka/whatever", get), meck:expect(hackney, request, RepoFun), BodyReturnFun = fun(_) -> {ok, <<"[]">>} end, meck:expect(hackney, body, BodyReturnFun), {ok, _} = egithub:repo(Credentials, "inaka/whatever"), ReposFun = match_fun("/user/repos?" "direction=asc&page=1&sort=full_name&type=all", get), meck:expect(hackney, request, ReposFun), {ok, _} = egithub:repos(Credentials, #{}), ReposUserFun = match_fun("/users/gadgetci/repos?page=1", get), meck:expect(hackney, request, ReposUserFun), {ok, _} = egithub:repos(Credentials, "gadgetci", #{}), AllReposFun = match_fun("/user/repos?" "direction=asc&page=1&sort=full_name&type=all", get), meck:expect(hackney, request, AllReposFun), {ok, _} = egithub:all_repos(Credentials, #{}), BodyReturn1Fun = fun(_) -> {ok, <<"[1]">>} end, BodyReturnEmptyFun = fun(_) -> {ok, <<"[]">>} end, AllReposUserFun = fun(get, Url, _, _) -> case Url of <<"">> -> meck:expect(hackney, body, BodyReturn1Fun), {ok, 200, [], #client{}}; <<"">> -> meck:expect(hackney, body, BodyReturnEmptyFun), {ok, 200, [], #client{}} end end, meck:expect(hackney, request, AllReposUserFun), {ok, _} = egithub:all_repos(Credentials, "gadgetci", #{}), AllReposErrorFun = fun(get, Url, _, _) -> case Url of <<"">> -> meck:expect(hackney, body, BodyReturn1Fun), {ok, 200, [], #client{}}; <<"">> -> meck:expect(hackney, body, BodyReturnEmptyFun), {ok, 400, [], #client{}} end end, meck:expect(hackney, request, AllReposErrorFun), {error, _} = egithub:all_repos(Credentials, "gadgetci", #{}), OrgReposFun = match_fun("/orgs/some-org/repos?page=1&per_page=100", get), meck:expect(hackney, request, OrgReposFun), meck:expect(hackney, body, BodyReturnEmptyFun), {ok, _} = egithub:org_repos(Credentials, "some-org", #{}), AllOrgReposFun = fun(get, Url, _, _) -> case Url of <<"" "/orgs/some-org/repos?page=1&per_page=100">> -> meck:expect(hackney, body, BodyReturn1Fun), {ok, 200, [], #client{}}; <<"" "/orgs/some-org/repos?page=2&per_page=100">> -> meck:expect(hackney, body, BodyReturnEmptyFun), {ok, 200, [], #client{}} end end, meck:expect(hackney, request, AllOrgReposFun), {ok, _} = egithub:all_org_repos(Credentials, "some-org", #{}), AllOrgReposErrorFun = fun(get, Url, _, _) -> case Url of <<"" "/orgs/some-org/repos?page=1&per_page=100">> -> meck:expect(hackney, body, BodyReturn1Fun), {ok, 200, [], #client{}}; <<"" "/orgs/some-org/repos?page=2&per_page=100">> -> meck:expect(hackney, body, BodyReturnEmptyFun), {ok, 400, [], #client{}} end end, meck:expect(hackney, request, AllOrgReposErrorFun), {error, _} = egithub:all_org_repos(Credentials, "some-org", #{}) after meck:unload(hackney) end. -spec teams(config()) -> pending. teams(_Config) -> Credentials = github_credentials(), meck:new(hackney, [passthrough]), try BodyReturnFun = fun(_) -> {ok, <<"[]">>} end, meck:expect(hackney, body, BodyReturnFun), TeamsFun = match_fun("/orgs/some-org/teams", get), meck:expect(hackney, request, TeamsFun), {ok, _} = egithub:teams(Credentials, "some-org"), CreateTeamFun = match_fun("/orgs/some-org/teams", post), meck:expect(hackney, request, CreateTeamFun), {ok, _} = egithub:create_team(Credentials, "some-org", "Team", "", []), CreateTeam422Fun = fun(post, <<"-org/teams">>, _, _) -> {error, {422, [{<<"Server">>, <<"GitHub.com">>}], <<"error">>}} end, meck:expect(hackney, request, CreateTeam422Fun), {ok, already_exists} = egithub:create_team(Credentials, "some-org", "Team", "", ["some-org/repo"]), AddTeamRepoFun = match_fun("/teams/1/repos/user/repo", put), meck:expect(hackney, request, AddTeamRepoFun), ok = egithub:add_team_repository(Credentials, 1, "user/repo"), AddTeamMemberFun = match_fun("/teams/1/members/gadgetci", put), meck:expect(hackney, request, AddTeamMemberFun), ok = egithub:add_team_member(Credentials, 1, "gadgetci"), DeleteTeamMemberFun = match_fun("/teams/1/members/gadgetci", delete), meck:expect(hackney, request, DeleteTeamMemberFun), ok = egithub:delete_team_member(Credentials, 1, "gadgetci"), TeamMembershipFun = match_fun("/teams/1/memberships/gadgetci", get), meck:expect(hackney, request, TeamMembershipFun), TeamMembershipBodyFun = fun(_) -> {ok, <<"{\"state\" : \"pending\"}">>} end, meck:expect(hackney, body, TeamMembershipBodyFun), pending = egithub:team_membership(Credentials, 1, "gadgetci") after meck:unload(hackney) end. -spec hooks(config()) -> result(). hooks(_Config) -> Credentials = github_credentials(), meck:new(hackney, [passthrough]), try BodyReturnFun = fun(_) -> {ok, <<"[]">>} end, meck:expect(hackney, body, BodyReturnFun), HooksFun = match_fun("/repos/some-repo/hooks", get), meck:expect(hackney, request, HooksFun), {ok, _} = egithub:hooks(Credentials, "some-repo"), CreateHookFun = match_fun("/repos/some-repo/hooks", post), meck:expect(hackney, request, CreateHookFun), {ok, _} = egithub:create_webhook(Credentials, "some-repo", "url", ["pull_request"]), DeleteHookFun = match_fun("/repos/some-repo/hooks/url", delete), meck:expect(hackney, request, DeleteHookFun), ok = egithub:delete_webhook(Credentials, "some-repo", "url") after meck:unload(hackney) end. -spec collaborators(config()) -> result(). collaborators(_Config) -> Credentials = github_credentials(), meck:new(hackney, [passthrough]), try BodyReturnFun = fun(_) -> {ok, <<"[]">>} end, meck:expect(hackney, body, BodyReturnFun), CollaboratorsFun = match_fun("/repos/some-repo/collaborators", get), meck:expect(hackney, request, CollaboratorsFun), {ok, _} = egithub:collaborators(Credentials, "some-repo"), AddCollabFun = match_fun("/repos/some-repo/collaborators/username", put), meck:expect(hackney, request, AddCollabFun), ok = egithub:add_collaborator(Credentials, "some-repo", "username"), DeleteCollabFun = match_fun("/repos/some-repo/collaborators/username", delete), meck:expect(hackney, request, DeleteCollabFun), ok = egithub:remove_collaborator(Credentials, "some-repo", "username") after meck:unload(hackney) end. -spec statuses(config()) -> result(). statuses(_Config) -> Credentials = github_credentials(), meck:new(hackney, [passthrough]), try StatusesFun = match_fun("/repos/some-repo/commits/ref/statuses", get), BodyReturnFun = fun(_) -> {ok, <<"[]">>} end, meck:expect(hackney, body, BodyReturnFun), meck:expect(hackney, request, StatusesFun), {ok, _} = egithub:statuses(Credentials, "some-repo", "ref"), CreateStatusFun = match_fun("/repos/some-repo/statuses/SHA", post), meck:expect(hackney, request, CreateStatusFun), {ok, _} = egithub:create_status(Credentials, "some-repo", "SHA", pending, "description", "context"), CreateStatusUrlFun = match_fun("/repos/some-repo/statuses/SHA", post), meck:expect(hackney, request, CreateStatusUrlFun), {ok, _} = egithub:create_status(Credentials, "some-repo", "SHA", pending, "description", "context", "url"), CombinedStatusFun = match_fun("/repos/some-repo/commits/ref/status", get), meck:expect(hackney, request, CombinedStatusFun), {ok, _} = egithub:combined_status(Credentials, "some-repo", "ref") after meck:unload(hackney) end. -spec releases(config()) -> result(). releases(_Config) -> Credentials = github_credentials(), meck:new(hackney, [passthrough]), try BodyReturnFun = fun(_) -> {ok, <<"[]">>} end, meck:expect(hackney, body, BodyReturnFun), ReleaseFun = match_fun("/repos/inaka/whatever/releases/1", get), meck:expect(hackney, request, ReleaseFun), {ok, _} = egithub:release(Credentials, "inaka/whatever", 1), ReleasesFun = match_fun("/repos/inaka/whatever/releases", get), meck:expect(hackney, request, ReleasesFun), {ok, _} = egithub:releases(Credentials, "inaka/whatever"), ReleasesPageFun = match_fun("/repos/inaka/whatever/releases?page=2", get), meck:expect(hackney, request, ReleasesPageFun), {ok, _} = egithub:releases(Credentials, "inaka/whatever", #{page => 2}), LatestReleaseFun = match_fun("/repos/inaka/whatever/releases/latest", get), meck:expect(hackney, request, LatestReleaseFun), {ok, _} = egithub:release_latest(Credentials, "inaka/whatever") after meck:unload(hackney) end. -spec branches(config()) -> result(). branches(_Config) -> Credentials = github_credentials(), meck:new(hackney, [passthrough]), try BodyReturnFun = fun(_) -> {ok, <<"[]">>} end, meck:expect(hackney, body, BodyReturnFun), BranchFun = match_fun("/repos/inaka/whatever/branches/master", get), meck:expect(hackney, request, BranchFun), {ok, _} = egithub:branch(Credentials, "inaka/whatever", "master"), BranchesUrl = "/repos/inaka/whatever/branches?page=1&protected=false", BranchesFun = match_fun(BranchesUrl, get), meck:expect(hackney, request, BranchesFun), {ok, _} = egithub:branches(Credentials, "inaka/whatever", #{}), BranchesUrl2 = "/repos/inaka/whatever/branches?page=2&protected=true", BranchesFun2 = match_fun(BranchesUrl2, get), meck:expect(hackney, request, BranchesFun2), {ok, _} = egithub:branches(Credentials, "inaka/whatever", #{page => 2, protected => true}) after meck:unload(hackney) end. -spec tags(config()) -> result(). tags(_Config) -> Credentials = github_credentials(), meck:new(hackney, [passthrough]), try BodyReturnFun = fun(_) -> {ok, <<"[]">>} end, meck:expect(hackney, body, BodyReturnFun), TagFun = match_fun( "/repos/inaka/whatever/tags/940bd336248efae0f9ee5bc7b2d5c985887b16ac", get), meck:expect(hackney, request, TagFun), {ok, _} = egithub:tag(Credentials, "inaka/whatever", "940bd336248efae0f9ee5bc7b2d5c985887b16ac"), TagsUrl = "/repos/inaka/whatever/tags?page=1", TagsFun = match_fun(TagsUrl, get), meck:expect(hackney, request, TagsFun), {ok, _} = egithub:tags(Credentials, "inaka/whatever", #{}), TagsUrl2 = "/repos/inaka/whatever/tags?page=2", TagsFun2 = match_fun(TagsUrl2, get), meck:expect(hackney, request, TagsFun2), {ok, _} = egithub:tags(Credentials, "inaka/whatever", #{page => 2}) after meck:unload(hackney) end. -spec custom_host(config()) -> result(). custom_host(_Config) -> Credentials = github_credentials(), meck:new(hackney, [passthrough]), try application:set_env(egithub, egithub_host, <<"github.inaka-enterprise-api.com">>), RepoFun = match_fun("/repos/inaka/whatever", get), meck:expect(hackney, request, RepoFun), BodyReturnFun = fun(_) -> {ok, <<"[]">>} end, meck:expect(hackney, body, BodyReturnFun), {ok, _} = egithub:repo(Credentials, "inaka/whatever"), <<"-enterprise-api.com/repos/inaka/whatever">> = meck:capture(first, hackney, request, '_', 2), ok after meck:unload(hackney) end. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Helper %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -spec github_credentials() -> {'basic', string(), string()}. github_credentials() -> egithub:basic_auth("username", "password"). match_fun(Url, Method) -> Host = application:get_env(egithub, egithub_host, <<"api.github.com">>), UrlBin = iolist_to_binary(["https://", Host, Url]), fun(MethodParam, UrlParam, _, _) -> UrlBin = UrlParam, Method = MethodParam, RespHeaders = [], ClientRef = #client{}, {ok, 200, RespHeaders, ClientRef} end.
null
https://raw.githubusercontent.com/inaka/erlang-github/90592ab381e9a5c8486305a08090ad71673735d0/test/egithub_SUITE.erl
erlang
Common test Test cases Helper
-module(egithub_SUITE). -export([ all/0, init_per_suite/1, end_per_suite/1 ]). -export([ pull_reqs/1, issue_comments/1, pr_review/1, issues/1, files/1, users/1, orgs/1, repos/1, teams/1, hooks/1, collaborators/1, statuses/1, releases/1, branches/1, tags/1, custom_host/1 ]). -record(client, {}). -define(EXCLUDED_FUNS, [ module_info, all, test, init_per_suite, end_per_suite ]). -type config() :: [{atom(), term()}]. -type result() :: ok | {ok, term()} | {error, term()}. -spec all() -> [atom()]. all() -> Exports = ?MODULE:module_info(exports), [F || {F, _} <- Exports, not lists:member(F, ?EXCLUDED_FUNS)]. -spec init_per_suite(config()) -> config(). init_per_suite(Config) -> {ok, _} = egithub:start(), Config. -spec end_per_suite(config()) -> config(). end_per_suite(Config) -> ok = application:stop(egithub), Config. -spec pull_reqs(config()) -> result(). pull_reqs(_Config) -> Credentials = github_credentials(), meck:new(hackney, [passthrough]), try BodyReturnFun = fun(_) -> {ok, <<"[]">>} end, PRsUrl = "/repos/user/repo/pulls?direction=asc&page=1&sort=created" "&state=open", AllOpenPRFun = match_fun(PRsUrl, get), meck:expect(hackney, body, BodyReturnFun), meck:expect(hackney, request, AllOpenPRFun), {ok, _} = egithub:pull_reqs(Credentials, "user/repo", #{state => "open"}), SinglePRFun = match_fun("/repos/user/repo/pulls/1", get), meck:expect(hackney, body, BodyReturnFun), meck:expect(hackney, request, SinglePRFun), {ok, _} = egithub:pull_req(Credentials, "user/repo", 1), PRFilesFun = match_fun("/repos/user/repo/pulls/1/files", get), meck:expect(hackney, body, BodyReturnFun), meck:expect(hackney, request, PRFilesFun), {ok, _} = egithub:pull_req_files(Credentials, "user/repo", 1), PRCommentLineFun = match_fun("/repos/user/repo/pulls/1/comments", post), meck:expect(hackney, request, PRCommentLineFun), {ok, _} = egithub:pull_req_comment_line(Credentials, "user/repo", 1, "SHA", <<"file-path">>, 5, "comment text"), Self = self(), PRCommentLineQueueFun = fun(_, _, _, _) -> Self ! ok, {ok, 200, [], #client{}} end, meck:expect(hackney, request, PRCommentLineQueueFun), ok = egithub:pull_req_comment_line(Credentials, "user/repo", 1, "SHA", <<"file-path">>, 5, "comment text", #{post_method => queue}), ok = receive ok -> ok after 5000 -> timeout end, PRCommentsFun = match_fun("/repos/user/repo/pulls/1/comments", get), meck:expect(hackney, request, PRCommentsFun), {ok, _} = egithub:pull_req_comments(Credentials, "user/repo", 1) after meck:unload(hackney) end. -spec issue_comments(config()) -> result(). issue_comments(_Config) -> Credentials = github_credentials(), meck:new(hackney, [passthrough]), try IssueCommentFun = match_fun("/repos/user/repo/issues/1/comments", post), meck:expect(hackney, request, IssueCommentFun), BodyReturnFun = fun(_) -> {ok, <<"[]">>} end, meck:expect(hackney, body, BodyReturnFun), {ok, _} = egithub:issue_comment(Credentials, "user/repo", 1, "txt"), Self = self(), IssueCommentQueueFun = fun(post, Url, _, _) -> <<"/" "repos/user/repo/issues/1/comments">> = Url, Self ! ok, {ok, 200, [], #client{}} end, meck:expect(hackney, request, IssueCommentQueueFun), ok = egithub:issue_comment(Credentials, "user/repo", 1, "txt", #{post_method => queue}), ok = receive ok -> ok after 5000 -> timeout end, IssueCommentsFun = match_fun("/repos/user/repo/issues/1/comments", get), meck:expect(hackney, request, IssueCommentsFun), {ok, _} = egithub:issue_comments(Credentials, "user/repo", 1) after meck:unload(hackney) end. -spec pr_review(config()) -> result(). pr_review(_Config) -> Credentials = github_credentials(), meck:new(hackney, [passthrough]), try Self = self(), PrReviewQueueFun = fun(post, Url, _, _) -> <<"/" "repos/user/repo/pulls/1/reviews">> = Url, Self ! ok, {ok, 200, [], #client{}} end, meck:expect(hackney, request, PrReviewQueueFun), ReqBody = #{body => <<>>, comments => [#{path => <<"/path/to/file">>, position => 20, body => <<"bad function naming">>}], commit_id => <<"c0m1tt1d">>, event => <<"REQUEST_CHANGES">>}, ok = egithub:pr_review(Credentials, "user/repo", 1, ReqBody, #{post_method => queue}), ok = receive ok -> ok after 5000 -> timeout end after meck:unload(hackney) end. -spec issues(config()) -> result(). issues(_Config) -> Credentials = github_credentials(), meck:new(hackney, [passthrough]), try BodyReturnFun = fun(_) -> {ok, <<"[]">>} end, meck:expect(hackney, body, BodyReturnFun), CreateIssueFun = match_fun("/repos/user/repo/issues", post), meck:expect(hackney, request, CreateIssueFun), {ok, _} = egithub:create_issue(Credentials, "user", "repo", "title", "text", "user", ["bug"]), AllIssuesFun = match_fun("/issues", get), meck:expect(hackney, request, AllIssuesFun), {ok, _} = egithub:all_issues(Credentials, #{}), AllRepoIssuesFun = match_fun("/repos/user/repo/issues", get), meck:expect(hackney, request, AllRepoIssuesFun), {ok, _} = egithub:all_issues(Credentials, "user/repo", #{}), IssueUrl = "/issues?direction=asc&filter=assigned&" "sort=created&state=open", AllIssuesOpenFun = match_fun(IssueUrl, get), meck:expect(hackney, request, AllIssuesOpenFun), {ok, _} = egithub:all_issues(Credentials, #{state => "open"}), UserIssuesFun = match_fun("/user/issues", get), meck:expect(hackney, request, UserIssuesFun), {ok, _} = egithub:issues_user(Credentials, #{}), OrgIssuesFun = match_fun("/orgs/foo/issues", get), meck:expect(hackney, request, OrgIssuesFun), {ok, _} = egithub:issues_org(Credentials, "foo", #{}), SingleIssueFun = match_fun("/repos/user/repo/issues/1", get), meck:expect(hackney, request, SingleIssueFun), {ok, _} = egithub:issue(Credentials, "user/repo", 1) after meck:unload(hackney) end. -spec files(config()) -> result(). files(_Config) -> Credentials = github_credentials(), meck:new(hackney, [passthrough]), try FileContentFun = match_fun("/repos/user/repo/contents/file?ref=SHA", get), meck:expect(hackney, request, FileContentFun), BodyReturnFun = fun(_) -> {ok, <<"{\"content\" : \"\"}">>} end, meck:expect(hackney, body, BodyReturnFun), {ok, _} = egithub:file_content(Credentials, "user/repo", "SHA", "file") after meck:unload(hackney) end. -spec users(config()) -> result(). users(_Config) -> Credentials = github_credentials(), meck:new(hackney, [passthrough]), try BodyReturnFun = fun(_) -> {ok, <<"[]">>} end, meck:expect(hackney, body, BodyReturnFun), UserFun = match_fun("/user", get), meck:expect(hackney, request, UserFun), {ok, _} = egithub:user(Credentials), GadgetCIFun = match_fun("/users/gadgetci", get), meck:expect(hackney, request, GadgetCIFun), {ok, _} = egithub:user(Credentials, "gadgetci"), EmailsFun = match_fun("/user/emails", get), meck:expect(hackney, request, EmailsFun), {ok, _} = egithub:user_emails(Credentials) after meck:unload(hackney) end. -spec orgs(config()) -> result(). orgs(_Config) -> Credentials = github_credentials(), meck:new(hackney, [passthrough]), try BodyReturnFun = fun(_) -> {ok, <<"[]">>} end, meck:expect(hackney, body, BodyReturnFun), OrgsFun = match_fun("/user/orgs", get), meck:expect(hackney, request, OrgsFun), {ok, _} = egithub:orgs(Credentials), OrgsUserFun = match_fun("/users/gadgetci/orgs", get), meck:expect(hackney, request, OrgsUserFun), {ok, _} = egithub:orgs(Credentials, "gadgetci"), OrgMembershipFun = match_fun("/user/memberships/orgs/some-organization", get), meck:expect(hackney, request, OrgMembershipFun), {ok, _} = egithub:org_membership(Credentials, "some-organization") after meck:unload(hackney) end. -spec repos(config()) -> result(). repos(_Config) -> Credentials = github_credentials(), meck:new(hackney, [passthrough]), try RepoFun = match_fun("/repos/inaka/whatever", get), meck:expect(hackney, request, RepoFun), BodyReturnFun = fun(_) -> {ok, <<"[]">>} end, meck:expect(hackney, body, BodyReturnFun), {ok, _} = egithub:repo(Credentials, "inaka/whatever"), ReposFun = match_fun("/user/repos?" "direction=asc&page=1&sort=full_name&type=all", get), meck:expect(hackney, request, ReposFun), {ok, _} = egithub:repos(Credentials, #{}), ReposUserFun = match_fun("/users/gadgetci/repos?page=1", get), meck:expect(hackney, request, ReposUserFun), {ok, _} = egithub:repos(Credentials, "gadgetci", #{}), AllReposFun = match_fun("/user/repos?" "direction=asc&page=1&sort=full_name&type=all", get), meck:expect(hackney, request, AllReposFun), {ok, _} = egithub:all_repos(Credentials, #{}), BodyReturn1Fun = fun(_) -> {ok, <<"[1]">>} end, BodyReturnEmptyFun = fun(_) -> {ok, <<"[]">>} end, AllReposUserFun = fun(get, Url, _, _) -> case Url of <<"">> -> meck:expect(hackney, body, BodyReturn1Fun), {ok, 200, [], #client{}}; <<"">> -> meck:expect(hackney, body, BodyReturnEmptyFun), {ok, 200, [], #client{}} end end, meck:expect(hackney, request, AllReposUserFun), {ok, _} = egithub:all_repos(Credentials, "gadgetci", #{}), AllReposErrorFun = fun(get, Url, _, _) -> case Url of <<"">> -> meck:expect(hackney, body, BodyReturn1Fun), {ok, 200, [], #client{}}; <<"">> -> meck:expect(hackney, body, BodyReturnEmptyFun), {ok, 400, [], #client{}} end end, meck:expect(hackney, request, AllReposErrorFun), {error, _} = egithub:all_repos(Credentials, "gadgetci", #{}), OrgReposFun = match_fun("/orgs/some-org/repos?page=1&per_page=100", get), meck:expect(hackney, request, OrgReposFun), meck:expect(hackney, body, BodyReturnEmptyFun), {ok, _} = egithub:org_repos(Credentials, "some-org", #{}), AllOrgReposFun = fun(get, Url, _, _) -> case Url of <<"" "/orgs/some-org/repos?page=1&per_page=100">> -> meck:expect(hackney, body, BodyReturn1Fun), {ok, 200, [], #client{}}; <<"" "/orgs/some-org/repos?page=2&per_page=100">> -> meck:expect(hackney, body, BodyReturnEmptyFun), {ok, 200, [], #client{}} end end, meck:expect(hackney, request, AllOrgReposFun), {ok, _} = egithub:all_org_repos(Credentials, "some-org", #{}), AllOrgReposErrorFun = fun(get, Url, _, _) -> case Url of <<"" "/orgs/some-org/repos?page=1&per_page=100">> -> meck:expect(hackney, body, BodyReturn1Fun), {ok, 200, [], #client{}}; <<"" "/orgs/some-org/repos?page=2&per_page=100">> -> meck:expect(hackney, body, BodyReturnEmptyFun), {ok, 400, [], #client{}} end end, meck:expect(hackney, request, AllOrgReposErrorFun), {error, _} = egithub:all_org_repos(Credentials, "some-org", #{}) after meck:unload(hackney) end. -spec teams(config()) -> pending. teams(_Config) -> Credentials = github_credentials(), meck:new(hackney, [passthrough]), try BodyReturnFun = fun(_) -> {ok, <<"[]">>} end, meck:expect(hackney, body, BodyReturnFun), TeamsFun = match_fun("/orgs/some-org/teams", get), meck:expect(hackney, request, TeamsFun), {ok, _} = egithub:teams(Credentials, "some-org"), CreateTeamFun = match_fun("/orgs/some-org/teams", post), meck:expect(hackney, request, CreateTeamFun), {ok, _} = egithub:create_team(Credentials, "some-org", "Team", "", []), CreateTeam422Fun = fun(post, <<"-org/teams">>, _, _) -> {error, {422, [{<<"Server">>, <<"GitHub.com">>}], <<"error">>}} end, meck:expect(hackney, request, CreateTeam422Fun), {ok, already_exists} = egithub:create_team(Credentials, "some-org", "Team", "", ["some-org/repo"]), AddTeamRepoFun = match_fun("/teams/1/repos/user/repo", put), meck:expect(hackney, request, AddTeamRepoFun), ok = egithub:add_team_repository(Credentials, 1, "user/repo"), AddTeamMemberFun = match_fun("/teams/1/members/gadgetci", put), meck:expect(hackney, request, AddTeamMemberFun), ok = egithub:add_team_member(Credentials, 1, "gadgetci"), DeleteTeamMemberFun = match_fun("/teams/1/members/gadgetci", delete), meck:expect(hackney, request, DeleteTeamMemberFun), ok = egithub:delete_team_member(Credentials, 1, "gadgetci"), TeamMembershipFun = match_fun("/teams/1/memberships/gadgetci", get), meck:expect(hackney, request, TeamMembershipFun), TeamMembershipBodyFun = fun(_) -> {ok, <<"{\"state\" : \"pending\"}">>} end, meck:expect(hackney, body, TeamMembershipBodyFun), pending = egithub:team_membership(Credentials, 1, "gadgetci") after meck:unload(hackney) end. -spec hooks(config()) -> result(). hooks(_Config) -> Credentials = github_credentials(), meck:new(hackney, [passthrough]), try BodyReturnFun = fun(_) -> {ok, <<"[]">>} end, meck:expect(hackney, body, BodyReturnFun), HooksFun = match_fun("/repos/some-repo/hooks", get), meck:expect(hackney, request, HooksFun), {ok, _} = egithub:hooks(Credentials, "some-repo"), CreateHookFun = match_fun("/repos/some-repo/hooks", post), meck:expect(hackney, request, CreateHookFun), {ok, _} = egithub:create_webhook(Credentials, "some-repo", "url", ["pull_request"]), DeleteHookFun = match_fun("/repos/some-repo/hooks/url", delete), meck:expect(hackney, request, DeleteHookFun), ok = egithub:delete_webhook(Credentials, "some-repo", "url") after meck:unload(hackney) end. -spec collaborators(config()) -> result(). collaborators(_Config) -> Credentials = github_credentials(), meck:new(hackney, [passthrough]), try BodyReturnFun = fun(_) -> {ok, <<"[]">>} end, meck:expect(hackney, body, BodyReturnFun), CollaboratorsFun = match_fun("/repos/some-repo/collaborators", get), meck:expect(hackney, request, CollaboratorsFun), {ok, _} = egithub:collaborators(Credentials, "some-repo"), AddCollabFun = match_fun("/repos/some-repo/collaborators/username", put), meck:expect(hackney, request, AddCollabFun), ok = egithub:add_collaborator(Credentials, "some-repo", "username"), DeleteCollabFun = match_fun("/repos/some-repo/collaborators/username", delete), meck:expect(hackney, request, DeleteCollabFun), ok = egithub:remove_collaborator(Credentials, "some-repo", "username") after meck:unload(hackney) end. -spec statuses(config()) -> result(). statuses(_Config) -> Credentials = github_credentials(), meck:new(hackney, [passthrough]), try StatusesFun = match_fun("/repos/some-repo/commits/ref/statuses", get), BodyReturnFun = fun(_) -> {ok, <<"[]">>} end, meck:expect(hackney, body, BodyReturnFun), meck:expect(hackney, request, StatusesFun), {ok, _} = egithub:statuses(Credentials, "some-repo", "ref"), CreateStatusFun = match_fun("/repos/some-repo/statuses/SHA", post), meck:expect(hackney, request, CreateStatusFun), {ok, _} = egithub:create_status(Credentials, "some-repo", "SHA", pending, "description", "context"), CreateStatusUrlFun = match_fun("/repos/some-repo/statuses/SHA", post), meck:expect(hackney, request, CreateStatusUrlFun), {ok, _} = egithub:create_status(Credentials, "some-repo", "SHA", pending, "description", "context", "url"), CombinedStatusFun = match_fun("/repos/some-repo/commits/ref/status", get), meck:expect(hackney, request, CombinedStatusFun), {ok, _} = egithub:combined_status(Credentials, "some-repo", "ref") after meck:unload(hackney) end. -spec releases(config()) -> result(). releases(_Config) -> Credentials = github_credentials(), meck:new(hackney, [passthrough]), try BodyReturnFun = fun(_) -> {ok, <<"[]">>} end, meck:expect(hackney, body, BodyReturnFun), ReleaseFun = match_fun("/repos/inaka/whatever/releases/1", get), meck:expect(hackney, request, ReleaseFun), {ok, _} = egithub:release(Credentials, "inaka/whatever", 1), ReleasesFun = match_fun("/repos/inaka/whatever/releases", get), meck:expect(hackney, request, ReleasesFun), {ok, _} = egithub:releases(Credentials, "inaka/whatever"), ReleasesPageFun = match_fun("/repos/inaka/whatever/releases?page=2", get), meck:expect(hackney, request, ReleasesPageFun), {ok, _} = egithub:releases(Credentials, "inaka/whatever", #{page => 2}), LatestReleaseFun = match_fun("/repos/inaka/whatever/releases/latest", get), meck:expect(hackney, request, LatestReleaseFun), {ok, _} = egithub:release_latest(Credentials, "inaka/whatever") after meck:unload(hackney) end. -spec branches(config()) -> result(). branches(_Config) -> Credentials = github_credentials(), meck:new(hackney, [passthrough]), try BodyReturnFun = fun(_) -> {ok, <<"[]">>} end, meck:expect(hackney, body, BodyReturnFun), BranchFun = match_fun("/repos/inaka/whatever/branches/master", get), meck:expect(hackney, request, BranchFun), {ok, _} = egithub:branch(Credentials, "inaka/whatever", "master"), BranchesUrl = "/repos/inaka/whatever/branches?page=1&protected=false", BranchesFun = match_fun(BranchesUrl, get), meck:expect(hackney, request, BranchesFun), {ok, _} = egithub:branches(Credentials, "inaka/whatever", #{}), BranchesUrl2 = "/repos/inaka/whatever/branches?page=2&protected=true", BranchesFun2 = match_fun(BranchesUrl2, get), meck:expect(hackney, request, BranchesFun2), {ok, _} = egithub:branches(Credentials, "inaka/whatever", #{page => 2, protected => true}) after meck:unload(hackney) end. -spec tags(config()) -> result(). tags(_Config) -> Credentials = github_credentials(), meck:new(hackney, [passthrough]), try BodyReturnFun = fun(_) -> {ok, <<"[]">>} end, meck:expect(hackney, body, BodyReturnFun), TagFun = match_fun( "/repos/inaka/whatever/tags/940bd336248efae0f9ee5bc7b2d5c985887b16ac", get), meck:expect(hackney, request, TagFun), {ok, _} = egithub:tag(Credentials, "inaka/whatever", "940bd336248efae0f9ee5bc7b2d5c985887b16ac"), TagsUrl = "/repos/inaka/whatever/tags?page=1", TagsFun = match_fun(TagsUrl, get), meck:expect(hackney, request, TagsFun), {ok, _} = egithub:tags(Credentials, "inaka/whatever", #{}), TagsUrl2 = "/repos/inaka/whatever/tags?page=2", TagsFun2 = match_fun(TagsUrl2, get), meck:expect(hackney, request, TagsFun2), {ok, _} = egithub:tags(Credentials, "inaka/whatever", #{page => 2}) after meck:unload(hackney) end. -spec custom_host(config()) -> result(). custom_host(_Config) -> Credentials = github_credentials(), meck:new(hackney, [passthrough]), try application:set_env(egithub, egithub_host, <<"github.inaka-enterprise-api.com">>), RepoFun = match_fun("/repos/inaka/whatever", get), meck:expect(hackney, request, RepoFun), BodyReturnFun = fun(_) -> {ok, <<"[]">>} end, meck:expect(hackney, body, BodyReturnFun), {ok, _} = egithub:repo(Credentials, "inaka/whatever"), <<"-enterprise-api.com/repos/inaka/whatever">> = meck:capture(first, hackney, request, '_', 2), ok after meck:unload(hackney) end. -spec github_credentials() -> {'basic', string(), string()}. github_credentials() -> egithub:basic_auth("username", "password"). match_fun(Url, Method) -> Host = application:get_env(egithub, egithub_host, <<"api.github.com">>), UrlBin = iolist_to_binary(["https://", Host, Url]), fun(MethodParam, UrlParam, _, _) -> UrlBin = UrlParam, Method = MethodParam, RespHeaders = [], ClientRef = #client{}, {ok, 200, RespHeaders, ClientRef} end.
f12d9dfeb12c07ff196af9d9a7fbc817a4efa1decbd856603f1625eeac81c470
fragnix/fragnix
SameTypeDifferentInstance1.hs
module SameTypeDifferentInstance1 where data SameTypeDifferentInstance = SameTypeDifferentInstance instance Eq SameTypeDifferentInstance where (==) SameTypeDifferentInstance SameTypeDifferentInstance = True instance Show SameTypeDifferentInstance where show SameTypeDifferentInstance = "SameTypeDifferentInstance"
null
https://raw.githubusercontent.com/fragnix/fragnix/b9969e9c6366e2917a782f3ac4e77cce0835448b/tests/quick/SameTypeDifferentInstance/SameTypeDifferentInstance1.hs
haskell
module SameTypeDifferentInstance1 where data SameTypeDifferentInstance = SameTypeDifferentInstance instance Eq SameTypeDifferentInstance where (==) SameTypeDifferentInstance SameTypeDifferentInstance = True instance Show SameTypeDifferentInstance where show SameTypeDifferentInstance = "SameTypeDifferentInstance"
10cf3ddeb4f54235d5a50203f3555bb462bfc5a9f5625952a43dc164acdbe7e3
vlaaad/reveal
view.clj
(ns vlaaad.reveal.view (:require [vlaaad.reveal.output-panel :as output-panel] [vlaaad.reveal.action-popup :as action-popup] [vlaaad.reveal.event :as event] [vlaaad.reveal.stream :as stream] [vlaaad.reveal.action :as action] vlaaad.reveal.doc [vlaaad.reveal.fx :as rfx] [cljfx.api :as fx] [cljfx.prop :as fx.prop] [cljfx.mutator :as fx.mutator] [cljfx.lifecycle :as fx.lifecycle] [cljfx.component :as fx.component] [clojure.main :as m] [cljfx.ext.tree-view :as fx.ext.tree-view] [cljfx.fx.anchor-pane :as fx.anchor-pane] [cljfx.fx.table-cell :as fx.table-cell] [cljfx.fx.group :as fx.group] [cljfx.fx.number-axis :as fx.number-axis] [cljfx.fx.line-chart :as fx.line-chart] [cljfx.fx.category-axis :as fx.category-axis] [cljfx.fx.xy-chart-data :as fx.xy-chart-data] [cljfx.fx.bar-chart :as fx.bar-chart] [cljfx.fx.pie-chart :as fx.pie-chart] [cljfx.fx.xy-chart-series :as fx.xy-chart-series] [cljfx.fx.scatter-chart :as fx.scatter-chart] [cljfx.fx.table-view :as fx.table-view] [cljfx.fx.table-column :as fx.table-column] [cljfx.fx.pie-chart-data :as fx.pie-chart-data] [cljfx.fx.label :as fx.label] [cljfx.fx.web-view :as fx.web-view] [cljfx.fx.region :as fx.region] [cljfx.fx.tree-item :as fx.tree-item] [cljfx.fx.tree-view :as fx.tree-view] [cljfx.fx.tree-cell :as fx.tree-cell]) (:import [clojure.lang IRef IFn] [java.util.concurrent ArrayBlockingQueue TimeUnit BlockingQueue] [javafx.scene.control TableView TablePosition TableColumn$SortType TreeView TreeCell TreeItem] [javafx.scene Node] [javafx.css PseudoClass] [java.net URL URI] [javafx.event Event EventDispatcher] [javafx.scene.paint Color] [javafx.scene.input KeyEvent KeyCode Clipboard ClipboardContent] [java.beans Introspector PropertyDescriptor] [java.lang.reflect Modifier Field] [java.util UUID])) (defn- runduce! ([xf x] (runduce! xf identity x)) ([xf f x] (let [rf (xf (completing #(f %2)))] (rf (rf nil x))))) (defmethod event/handle ::dispose-state [{:keys [id]}] #(dissoc % id)) (defmethod event/handle ::create-view-state [{:keys [id state]}] #(assoc % id (assoc state :id id))) (defn- process-queue! [id ^BlockingQueue queue handler] (handler {::event/type ::create-view-state :id id :state (output-panel/make)}) (let [*running (volatile! true) add-lines! #(handler {::event/type ::output-panel/on-add-lines :id id :fx/event %}) xform (comp stream/stream-xf (partition-all 128) (take-while (fn [_] @*running))) f (event/daemon-future (while @*running (let [x (.take queue)] (runduce! xform add-lines! ({::nil nil} x x)))))] #(do (handler {::event/type ::dispose-state :id id}) (future-cancel f) (vreset! *running false)))) (defn queue [{:keys [^BlockingQueue queue id] :or {id ::rfx/undefined}}] {:fx/type rfx/ext-with-process :id id :start process-queue! :args queue :desc {:fx/type output-panel/view}}) (defn- process-value! [id value handler] (handler {::event/type ::create-view-state :id id :state (output-panel/make {:autoscroll false})}) (let [*running (volatile! true) add-lines! #(handler {::event/type ::output-panel/on-add-lines :id id :fx/event %}) xform (comp stream/stream-xf (partition-all 128) (take-while (fn [_] @*running)))] (event/daemon-future (runduce! xform add-lines! value)) #(do (vreset! *running false) (handler {::event/type ::dispose-state :id id})))) (defn value [{:keys [value]}] {:fx/type rfx/ext-with-process :start process-value! :args value :desc {:fx/type output-panel/view}}) (defn- view? [x] (try (not= (:fx/type x ::not-found) ::not-found) ;; sorted maps with non-keyword keys throw class cast exceptions (catch Exception _ false))) (defn ->desc [x] (if (view? x) x {:fx/type value :value x})) (defn- watch! [id *ref handler] (handler {::event/type ::create-view-state :id id :state (output-panel/make {:autoscroll false})}) (let [*running (volatile! true) out-queue (ArrayBlockingQueue. 1024) submit! #(.put out-queue ({nil ::nil} % %)) watch-key (gensym "vlaaad.reveal.view/watcher") f (event/daemon-future (while @*running (when-some [x (loop [x (.poll out-queue 1 TimeUnit/SECONDS) found nil] (if (some? x) (recur (.poll out-queue) x) found))] (handler {::event/type ::output-panel/on-clear-lines :id id}) (runduce! (comp stream/stream-xf (partition-all 128) (take-while (fn [_] (and @*running (nil? (.peek out-queue)))))) #(handler {::event/type ::output-panel/on-add-lines :fx/event % :id id}) ({::nil nil} x x)))))] (submit! @*ref) (add-watch *ref watch-key #(submit! %4)) #(do (remove-watch *ref watch-key) (vreset! *running false) (future-cancel f) (handler {::event/type ::dispose-state :id id})))) (defn ref-watch-latest [{:keys [ref]}] {:fx/type rfx/ext-with-process :start watch! :args ref :desc {:fx/type output-panel/view}}) (action/defaction ::action/view [v] (when (:fx/type v) (constantly v))) (action/defaction ::action/watch:latest [v] (when (instance? IRef v) (constantly {:fx/type ref-watch-latest :ref v}))) (defn- log! [id {:keys [subscribe result-factory]} handler] (handler {::event/type ::create-view-state :id id :state (output-panel/make)}) (let [*running (volatile! true) out-queue (ArrayBlockingQueue. 1024) submit! #(.put out-queue ({nil ::nil} % %)) next-result (result-factory) f (event/daemon-future (while @*running (let [x (.take out-queue)] (runduce! (comp stream/stream-xf (partition-all 128) (take-while (fn [_] @*running))) #(handler {::event/type ::output-panel/on-add-lines :fx/event % :id id}) (stream/horizontal (stream/raw-string (next-result) {:fill :util}) stream/separator (stream/stream ({::nil nil} x x))))))) unsubscribe (subscribe submit!)] #(do (when (fn? unsubscribe) (unsubscribe)) (vreset! *running false) (future-cancel f) (handler {::event/type ::dispose-state :id id})))) (defrecord RefSubscribe [ref] IFn (invoke [_ notify] (notify @ref) (let [watch-key (gensym "vlaaad.reveal.view/ref-subscribe")] (add-watch ref watch-key #(notify %4)) #(remove-watch ref watch-key)))) (defn counter-factory [] (let [counter (volatile! -1)] #(format "%4d:" (vswap! counter inc)))) (defrecord ConstResultFactory [str] IFn (invoke [_] (constantly str))) (defn str-result-factory [str] (->ConstResultFactory str)) (defn ref-watch-all [{:keys [ref subscribe result-factory id] :or {result-factory counter-factory id ::rfx/undefined}}] {:fx/type rfx/ext-with-process :start log! :id id :args {:subscribe (if ref (->RefSubscribe ref) subscribe) :result-factory result-factory} :desc {:fx/type output-panel/view}}) (action/defaction ::action/watch:all [v] (when (instance? IRef v) (constantly {:fx/type ref-watch-all :ref v}))) (defn- deref! [id blocking-deref handler] (handler {::event/type ::create-view-state :id id :state {:state ::waiting}}) (let [f (event/daemon-future (try (handler {::event/type ::create-view-state :id id :state {:state ::value :value @blocking-deref}}) (catch Throwable e (handler {::event/type ::create-view-state :id id :state {:state ::exception :exception e}}))))] #(do (future-cancel f) (handler {::event/type ::dispose-state :id id})))) (defn- blocking-deref-view [{:keys [state] :as props}] (case state ::waiting {:fx/type fx.label/lifecycle :focus-traversable true :text "Loading..."} ::value (->desc (:value props)) ::exception (->desc (stream/override-style (stream/stream (:exception props)) assoc :fill :error)))) (defn derefable [{:keys [derefable]}] {:fx/type rfx/ext-with-process :start deref! :args derefable :desc {:fx/type blocking-deref-view}}) (defn summary [{:keys [value max-length] :or {max-length 48}}] {:fx/type fx.group/lifecycle :children [(stream/fx-summary max-length value)]}) (defn- describe-cell [x] {:content-display :graphic-only :style-class "reveal-table-cell" :graphic {:fx/type summary :value x :max-length 64}}) (defn- initialize-table! [^TableView view] (let [dispatcher (.getEventDispatcher view)] (.setEventDispatcher view (reify EventDispatcher (dispatchEvent [_ e next] (if (and (instance? KeyEvent e) (.isShortcutDown ^KeyEvent e) (#{KeyCode/UP KeyCode/DOWN KeyCode/LEFT KeyCode/RIGHT} (.getCode ^KeyEvent e))) e (.dispatchEvent dispatcher e next)))))) (.selectFirst (.getSelectionModel view)) (.setCellSelectionEnabled (.getSelectionModel view) true)) (defn- select-bounds-and-value! [^Event event] (let [^TableView view (.getSource event)] (when-let [^TablePosition pos (first (.getSelectedCells (.getSelectionModel view)))] (when-let [cell (->> (.lookupAll view ".reveal-table-cell:selected") (some #(when (contains? (.getPseudoClassStates ^Node %) (PseudoClass/getPseudoClass "selected")) %)))] {:bounds (.localToScreen cell (.getBoundsInLocal cell)) :annotation {::row-value #(deref (fx/on-fx-thread (-> view .getSelectionModel .getSelectedItem second))) ::table-value #(deref (fx/on-fx-thread (-> view .getProperties (.get ::items))))} :value (.getCellData (.getTableColumn pos) (.getRow pos))})))) (action/defaction ::action/view:row-value [x ann] (when-let [f (::row-value ann)] f)) (action/defaction ::action/view:table-value [x ann] (when-let [f (::table-value ann)] f)) (defmethod event/handle ::on-table-key-pressed [{:keys [^KeyEvent fx/event]}] (cond (.isAltDown event) (when-let [sort-type ({KeyCode/UP TableColumn$SortType/ASCENDING KeyCode/DOWN TableColumn$SortType/DESCENDING} (.getCode event))] (let [^TableView table (.getTarget event) sm (.getSelectionModel table) col (.getTableColumn ^TablePosition (first (.getSelectedCells sm)))] (when (.isSortable col) (.setSortType col sort-type) (.setAll (.getSortOrder table) [col]) (.clearAndSelect sm 0 col)))) (and (.isShortcutDown event) (= KeyCode/C (.getCode event))) (let [^TableView table (.getTarget event) ^TablePosition pos (first (.getSelectedCells (.getSelectionModel table)))] (fx/on-fx-thread (.setContent (Clipboard/getSystemClipboard) (doto (ClipboardContent.) (.putString (stream/->str (.getCellData (.getTableColumn pos) (.getRow pos))))))))) identity) (defn- make-column [{:keys [header fn columns] :or {header ::not-found} :as props}] (into {:fx/type fx.table-column/lifecycle :style-class "reveal-table-column" :min-width 40 :graphic {:fx/type summary :max-length 64 :value (if (= header ::not-found) fn header)} :cell-factory {:fx/cell-type fx.table-cell/lifecycle :describe describe-cell} :cell-value-factory #(try (fn (peek %)) (catch Throwable e (let [{:clojure.error/keys [cause class]} (-> e Throwable->map m/ex-triage)] (stream/as e (stream/raw-string (or cause class) {:fill :error}))))) :columns (mapv #(-> % (update :fn comp fn) (cond-> (= ::not-found (:header % ::not-found)) (assoc :header (:fn %))) (make-column)) columns)} (dissoc props :header :fn :columns))) (def ext-with-items-prop (fx/make-ext-with-props {::items (rfx/property-prop ::items)})) (defn table [{:keys [items columns] :as props}] {:fx/type fx/ext-on-instance-lifecycle :on-created initialize-table! :desc {:fx/type action-popup/ext :select select-bounds-and-value! :desc {:fx/type ext-with-items-prop :props {::items items} :desc (into {:fx/type fx.table-view/lifecycle :on-key-pressed {::event/type ::on-table-key-pressed} :style-class "reveal-table" :columns (mapv make-column columns) :items (into [] (map-indexed vector) items)} (dissoc props :items :columns))}}}) (def ^:private no-val (stream/as nil (stream/raw-string "-" {:fill :util}))) (defn- infer-columns [sample] (and (seq sample) (condp every? sample (some-fn map? nil?) (let [all-keys (mapcat keys sample) columns (distinct all-keys) column-count (count columns) cells (* (count sample) column-count)] (when (and (<= (/ cells 2) (count all-keys)) (<= 1 column-count 32)) (for [k columns] {:header k :fn #(get % k no-val)}))) map-entry? [{:header 'key :fn key} {:header 'val :fn val}] sequential? (let [counts (map count sample) column-count (apply max counts) cell-count (* (count sample) column-count)] (when (and (<= (/ cell-count 2) (reduce + counts)) (<= 1 column-count 32)) (for [i (range column-count)] {:header i :fn #(nth % i no-val)}))) nil))) (defn- recursive-columns [sample depth] (when (pos? depth) (seq (for [col (infer-columns sample)] (assoc col :columns (recursive-columns (map (:fn col) sample) (dec depth))))))) (action/defaction ::action/view:table [v] (when (and (some? v) (not (string? v)) (seqable? v)) (fn [] {:fx/type table :items v :columns (or (recursive-columns (take 16 v) 4) [{:header 'item :fn identity}])}))) (action/defaction ::action/browse:internal [v] (when (or (and (instance? URI v) (or (#{"http" "https"} (.getScheme ^URI v)) (and (= "file" (.getScheme ^URI v)) (.endsWith (.getPath ^URI v) ".html")))) (instance? URL v) (and (string? v) (re-matches #"^https?://.+" v))) (constantly {:fx/type fx.web-view/lifecycle :url (str v)}))) (defn- request-source-focus! [^Event e] (.requestFocus ^Node (.getSource e))) (defn- labeled->values [labeled] (cond-> labeled (map? labeled) vals)) (defn- labeled->label+values [labeled] (cond (map? labeled) labeled (set? labeled) (map vector labeled labeled) :else (map-indexed vector labeled))) (defn- labeled? "Check if every value in a coll of specified size has uniquely identifying label" [x pred & {:keys [min max] :or {min 1 max 32}}] (and (or (map? x) (set? x) (sequential? x)) (<= min (bounded-count (inc max) x) max) (every? pred (labeled->values x)))) (defn pie-chart [{:keys [data]}] {:fx/type fx.pie-chart/lifecycle :style-class "reveal-chart" :on-mouse-pressed request-source-focus! :animated false :data (for [[k v] (labeled->label+values data)] {:fx/type fx.pie-chart-data/lifecycle :name (stream/str-summary k) :pie-value v})}) (action/defaction ::action/view:pie-chart [x] (when (labeled? x number? :min 2) (constantly {:fx/type pie-chart :data x}))) (def ^:private ext-with-value-on-node (fx/make-ext-with-props {::value (fx.prop/make (fx.mutator/setter (fn [^Node node value] (if (some? value) (.put (.getProperties node) ::value value) (.remove (.getProperties node) ::value)))) fx.lifecycle/scalar)})) (defn- select-chart-node! [^Event event] (let [^Node node (.getTarget event)] (when-let [value (::value (.getProperties node))] {:value value :bounds (.localToScreen node (.getBoundsInLocal node))}))) (defn- numbered? [x] (or (number? x) (and (vector? x) (= 2 (count x)) (number? (x 0))))) (defn- numbered->number [numbered] (cond-> numbered (not (number? numbered)) first)) (defn bar-chart [{:keys [data]}] {:fx/type action-popup/ext :select select-chart-node! :desc {:fx/type fx.bar-chart/lifecycle :style-class "reveal-chart" :on-mouse-pressed request-source-focus! :animated false :x-axis {:fx/type fx.category-axis/lifecycle :label "key"} :y-axis {:fx/type fx.number-axis/lifecycle :label "value"} :data (for [[series v] (labeled->label+values data)] {:fx/type fx.xy-chart-series/lifecycle :name (stream/str-summary series) :data (for [[key value] (labeled->label+values v)] {:fx/type fx.xy-chart-data/lifecycle :x-value (stream/->str key) :y-value (numbered->number value) :node {:fx/type ext-with-value-on-node :props {::value {:value value :key key :series series}} :desc {:fx/type fx.region/lifecycle}}})})}}) (action/defaction ::action/view:bar-chart [x] (when-let [data (cond (labeled? x numbered?) {x x} (labeled? x #(labeled? % numbered?)) x)] (constantly {:fx/type bar-chart :data data}))) (defn- numbereds? [x] (and (sequential? x) (<= 2 (bounded-count 1025 x) 1024) (every? numbered? x))) (def ext-recreate-on-key-changed (reify fx.lifecycle/Lifecycle (create [_ {:keys [key desc]} opts] (with-meta {:key key :child (fx.lifecycle/create fx.lifecycle/dynamic desc opts)} {`fx.component/instance #(-> % :child fx.component/instance)})) (advance [this component {:keys [key desc] :as this-desc} opts] (if (= (:key component) key) (update component :child #(fx.lifecycle/advance fx.lifecycle/dynamic % desc opts)) (do (fx.lifecycle/delete this component opts) (fx.lifecycle/create this this-desc opts)))) (delete [_ component opts] (fx.lifecycle/delete fx.lifecycle/dynamic (:child component) opts)))) (defn line-chart [{:keys [data]}] {:fx/type action-popup/ext :select select-chart-node! :desc {:fx/type fx.line-chart/lifecycle :style-class "reveal-chart" :on-mouse-pressed request-source-focus! :animated false :x-axis {:fx/type fx.number-axis/lifecycle :label "index" :auto-ranging false :lower-bound 0 :upper-bound (dec (transduce (comp (map second) (map count)) max 0 (labeled->label+values data))) :tick-unit 10 :minor-tick-count 10} :y-axis {:fx/type fx.number-axis/lifecycle :label "value" :force-zero-in-range false} :data (for [[series numbers] (labeled->label+values data)] {:fx/type ext-recreate-on-key-changed :key (count numbers) :desc {:fx/type fx.xy-chart-series/lifecycle :name (stream/str-summary series) :data (->> numbers (map-indexed (fn [index value] {:fx/type fx.xy-chart-data/lifecycle :x-value index :y-value (numbered->number value) :node {:fx/type ext-with-value-on-node :props {::value {:value value :index index :series series}} :desc {:fx/type fx.region/lifecycle}}})))}})}}) (action/defaction ::action/view:line-chart [x] (when-let [data (cond (numbereds? x) {x x} (labeled? x numbereds?) x)] (constantly {:fx/type line-chart :data data}))) (defn- coordinate? [x] (and (sequential? x) (= 2 (bounded-count 3 x)) (number? (nth x 0)) (number? (nth x 1)))) (defn- scattered? [x] (or (coordinate? x) (and (vector? x) (= 2 (count x)) (coordinate? (x 0))))) (defn- scattered->coordinate [x] (let [f (first x)] (if (sequential? f) f x))) (defn- scattereds? [x] (and (coll? x) (<= 1 (bounded-count 1025 x) 1024) (every? scattered? x))) (defn scatter-chart [{:keys [data]}] {:fx/type action-popup/ext :select select-chart-node! :desc {:fx/type fx.scatter-chart/lifecycle :style-class "reveal-chart" :on-mouse-pressed request-source-focus! :animated false :x-axis {:fx/type fx.number-axis/lifecycle :label "x" :force-zero-in-range false} :y-axis {:fx/type fx.number-axis/lifecycle :label "y" :force-zero-in-range false} :data (for [[series places] (labeled->label+values data)] {:fx/type fx.xy-chart-series/lifecycle :name (stream/str-summary series) :data (for [value places :let [[x y :as с] (scattered->coordinate value)]] {:fx/type fx.xy-chart-data/lifecycle :x-value x :y-value y :node {:fx/type ext-with-value-on-node :props {::value {:value value :coordinate с :series series}} :desc {:fx/type fx.region/lifecycle}}})})}}) (action/defaction ::action/view:scatter-chart [x] (when-let [data (cond (labeled? x scattereds?) x (scattereds? x) {x x})] (constantly {:fx/type scatter-chart :data data}))) (action/defaction ::action/view:color [v] (when-let [color (cond (instance? Color v) v (string? v) (Color/valueOf v) (keyword? v) (Color/valueOf (name v)))] (constantly {:fx/type fx.region/lifecycle :background {:fills [{:fill color}]}}))) (action/defaction ::action/view:value [x ann] (when (::stream/hidden ann) (constantly {:fx/type value :value x}))) (defn- default-tree-item-render [x] (if (view? x) x {:fx/type summary :value x :max-length 256})) (defn- as-util-string [x] (stream/raw-string x {:fill :util})) (defn- as-error-string [e] (let [{:clojure.error/keys [cause class]} (-> e Throwable->map m/ex-triage)] (stream/raw-string (or cause class) {:fill :error}))) (defn- get-in-tree-state [state path] (get-in state (concat (interleave (repeat :children) path) [:state]))) (defn- tree-item-view [{:keys [state on-expanded-changed branch? root path render valuate annotate] :or {render identity valuate identity annotate {}} :as props}] (if (branch? root) (let [expanded-state (get-in-tree-state state path)] {:fx/type fx.tree-item/lifecycle :value {:value root :render render :valuate valuate :annotate annotate} :expanded (some? expanded-state) :on-expanded-changed (assoc on-expanded-changed :path path :root root) :children (case (:state expanded-state) :loading [{:fx/type fx.tree-item/lifecycle :value {:value "Loading..." :render as-util-string :disable-popup true}}] :done (map-indexed (fn [i child] (assoc props :fx/type tree-item-view :root child :path (conj path i))) (:children expanded-state)) :failed [{:fx/type fx.tree-item/lifecycle :value {:value (:error expanded-state) :render as-error-string :valuate identity :annotate {}}}] [{:fx/type fx.tree-item/lifecycle :value {:value ::hidden :render render :valuate valuate :annotate annotate}}])}) {:fx/type fx.tree-item/lifecycle :value {:value root :render render :valuate valuate :annotate annotate}})) (defn- select-tree-bounds-and-value! [^Event e] (let [^TreeView view (.getSource e)] (when-let [^TreeCell cell (->> (.lookupAll view ".tree-cell:selected") (some #(when (contains? (.getPseudoClassStates ^Node %) (PseudoClass/getPseudoClass "selected")) %)))] (when-let [^Node node (.lookup cell ".tree-cell > .reveal-tree-cell-content")] (let [item (.getItem cell)] (if (:disable-popup item) (.consume e) (let [{:keys [value valuate annotate]} item] {:bounds (.localToScreen node (.getBoundsInLocal node)) :value (valuate value) :annotation (annotate value)}))))))) (defn- init-tree-view! [^TreeView tree-view] (let [dispatcher (.getEventDispatcher tree-view)] (-> tree-view (.setEventDispatcher (reify EventDispatcher (dispatchEvent [_ e next] (if (and (instance? KeyEvent e) (= KeyEvent/KEY_PRESSED (.getEventType e))) (let [^KeyEvent e e] (cond (.isShortcutDown e) (condp = (.getCode e) KeyCode/C (do (fx/on-fx-thread (let [{:keys [value valuate]} (-> tree-view .getSelectionModel ^TreeItem .getSelectedItem .getValue)] (.setContent (Clipboard/getSystemClipboard) (doto (ClipboardContent.) (.putString (stream/->str (valuate value))))))) e) e) (#{KeyCode/ESCAPE} (.getCode e)) e :else (.dispatchEvent dispatcher e next))) (.dispatchEvent dispatcher e next)))))))) (defn- describe-tree-cell [{:keys [value render]}] (let [v (try (render value) (catch Exception e e))] {:graphic {:fx/type fx.anchor-pane/lifecycle :max-width :use-pref-size :style-class "reveal-tree-cell-content" :children [(if (view? v) v {:fx/type summary :value v :max-length 256})]}})) (defn- tree-view-impl [props] {:fx/type action-popup/ext :select select-tree-bounds-and-value! :desc {:fx/type fx/ext-on-instance-lifecycle :on-created init-tree-view! :desc {:fx/type fx.ext.tree-view/with-selection-props :props {:selected-index 0} :desc {:fx/type fx.tree-view/lifecycle :cell-factory {:fx/cell-type fx.tree-cell/lifecycle :describe describe-tree-cell} :root (assoc props :fx/type tree-item-view :path [])}}}}) (defmethod event/handle ::update-state [{:keys [id fn]}] #(cond-> % (contains? % id) (update id fn))) (defmethod event/handle ::change-expanded [{:keys [load-fn] :as e}] (load-fn e) identity) (defn- set-in-tree-state [state path v] (assoc-in state (concat (interleave (repeat :children) path) [:state]) v)) (defn- update-in-tree-state-if-exists [state path f & args] (let [full-path (concat (interleave (repeat :children) path) [:state]) up (fn up [m ks f args] (let [[k & ks] ks] (if ks (assoc m k (up (get m k) ks f args)) (if (contains? m k) (assoc m k (apply f (get m k) args)) m))))] (up state full-path f args))) (defn- get-in-tree-state [state path] (get-in state (concat (interleave (repeat :children) path) [:state]))) (defn- remove-from-tree-state [state path] (let [full-path (interleave (repeat :children) path)] (if (seq full-path) (update-in state full-path dissoc :state :children) (dissoc state :state :children)))) (defn- init-tree-view-state! [id {:keys [branch? children root]} handler] (let [load-fn (fn [{:keys [path root fx/event]}] (if event (let [request (UUID/randomUUID) loading-state {:state :loading :request request}] (handler {::event/type ::update-state :id id :fn #(update % :state set-in-tree-state path loading-state)}) (event/daemon-future (try (let [children (children root)] (if (seqable? children) (doall children) (throw (ex-info "Children are not seqable" {:root root :children children}))) (handler {::event/type ::update-state :id id :fn #(update % :state update-in-tree-state-if-exists path (fn [m] (if (= loading-state m) {:state :done :children children} m)))})) (catch Exception e (handler {::event/type ::update-state :id id :fn #(update % :state update-in-tree-state-if-exists path (fn [m] (if (= loading-state m) {:state :failed :error e} m)))}))))) (handler {::event/type ::update-state :id id :fn #(update % :state remove-from-tree-state path)})))] (handler {::event/type ::create-view-state :id id :state {:state {} :on-expanded-changed {::event/type ::change-expanded :load-fn load-fn}}}) (when (branch? root) (load-fn {:path [] :root root :fx/event true})) #(handler {::event/type ::dispose-state :id id}))) (defn tree-view [props] {:fx/type rfx/ext-with-process :start init-tree-view-state! :args props :desc (assoc props :fx/type tree-view-impl)}) (action/defaction ::action/java-bean [x] (when (some? x) (fn [] (let [reflect (fn [value] (let [props (->> value class (Introspector/getBeanInfo) (.getPropertyDescriptors) (keep (fn [^PropertyDescriptor descriptor] (when-let [read-meth (.getReadMethod descriptor)] (try (.setAccessible read-meth true) (merge {:name (.getName descriptor) :sort 1 :key descriptor} (try {:value (.invoke read-meth value (object-array 0))} (catch Exception e {:error e}))) (catch Throwable _ nil)))))) fields (->> value class (iterate #(.getSuperclass ^Class %)) (take-while some?) (mapcat #(.getDeclaredFields ^Class %)) (remove #(Modifier/isStatic (.getModifiers ^Field %))) (keep (fn [^Field field] (try (.setAccessible field true) (merge {:name (.getName field) :sort -1 :key field} (try {:value (.get field value)} (catch Exception e {:error e}))) (catch Throwable _ nil))))) items (when (.isArray (class value)) (cons {:name "length" :sort 2 :value (count value)} (->> value (take 1000) (map-indexed (fn [i v] {:name i :key i :sort -3 :value v}))))) all (concat fields props items) pad (->> all (map #(-> % :name str count)) (reduce max 0))] (->> all (map #(assoc % :pad pad)) (into (sorted-set-by (fn [a b] (let [v (juxt :sort :name)] (compare (v a) (v b)))))))))] {:fx/type tree-view :valuate (some-fn :error :value) :annotate #(when-let [k (:key %)] {::action/java-bean:key k}) :branch? #(-> % :value some?) :children #(-> % :value reflect) :root {:value x} :render (fn [{:keys [value error name sort pad]}] (apply stream/horizontal (concat (when name [(stream/raw-string (format (str "%-" pad "s") name) {:fill (if (neg? sort) :symbol :util)}) stream/separator]) [(if error (let [{:clojure.error/keys [cause class]} (-> error Throwable->map m/ex-triage)] (stream/raw-string (or cause class) {:fill :error})) (stream/stream value))])))})))) (action/defaction ::action/java-bean:key [x ann] (when-let [k (::action/java-bean:key ann)] (constantly k))) (deftype Observable [*ref f] IRef (deref [_] (f @*ref)) (addWatch [this key callback] (add-watch *ref [this key] #(callback key this (f %3) (f %4)))) (removeWatch [this key] (remove-watch *ref [this key]))) (def ext-try (reify fx.lifecycle/Lifecycle (create [_ {:keys [desc]} opts] (try (with-meta {:child (fx.lifecycle/create fx.lifecycle/dynamic desc opts)} {`fx.component/instance #(-> % :child fx.component/instance)}) (catch Exception e (with-meta {:exception e :desc desc :child (fx.lifecycle/create fx.lifecycle/dynamic {:fx/type value :value e} opts)} {`fx.component/instance #(-> % :child fx.component/instance)})))) (advance [this component {:keys [desc] :as this-desc} opts] (if-let [e (:exception component)] (if (= (:desc component) desc) (update component :child #(fx.lifecycle/advance fx.lifecycle/dynamic % {:fx/type value :value e} opts)) (do (fx.lifecycle/delete this component opts) (fx.lifecycle/create this this-desc opts))) (try (update component :child #(fx.lifecycle/advance fx.lifecycle/dynamic % desc opts)) (catch Exception e (assoc component :exception e :desc desc :child (fx.lifecycle/create fx.lifecycle/dynamic {:fx/type value :value e} opts)))))) (delete [_ component opts] (fx.lifecycle/delete fx.lifecycle/dynamic (:child component) opts)))) (defn- subscribe! [id subscribe handler] (let [notifier #(handler {::event/type ::create-view-state :id id :state {:val %}}) _ (notifier ::not-found) unsubscribe (subscribe notifier)] #(do (when (fn? unsubscribe) (unsubscribe)) (handler {::event/type ::dispose-state :id id})))) (defn- observable-view-impl-try [{:keys [fn val]}] (if (= val ::not-found) {:fx/type fx.label/lifecycle :focus-traversable true :text "Waiting..."} (fn val))) (defn- observable-view-impl [props] {:fx/type ext-try :desc (assoc props :fx/type observable-view-impl-try)}) (defn observable-view [{:keys [ref fn subscribe]}] {:fx/type rfx/ext-with-process :start subscribe! :args (if ref (->RefSubscribe ref) subscribe) :desc {:fx/type observable-view-impl :fn fn}})
null
https://raw.githubusercontent.com/vlaaad/reveal/87282c6f617cde47a5524c3a17c8bb8f2f62c853/src/vlaaad/reveal/view.clj
clojure
sorted maps with non-keyword keys throw class cast exceptions
(ns vlaaad.reveal.view (:require [vlaaad.reveal.output-panel :as output-panel] [vlaaad.reveal.action-popup :as action-popup] [vlaaad.reveal.event :as event] [vlaaad.reveal.stream :as stream] [vlaaad.reveal.action :as action] vlaaad.reveal.doc [vlaaad.reveal.fx :as rfx] [cljfx.api :as fx] [cljfx.prop :as fx.prop] [cljfx.mutator :as fx.mutator] [cljfx.lifecycle :as fx.lifecycle] [cljfx.component :as fx.component] [clojure.main :as m] [cljfx.ext.tree-view :as fx.ext.tree-view] [cljfx.fx.anchor-pane :as fx.anchor-pane] [cljfx.fx.table-cell :as fx.table-cell] [cljfx.fx.group :as fx.group] [cljfx.fx.number-axis :as fx.number-axis] [cljfx.fx.line-chart :as fx.line-chart] [cljfx.fx.category-axis :as fx.category-axis] [cljfx.fx.xy-chart-data :as fx.xy-chart-data] [cljfx.fx.bar-chart :as fx.bar-chart] [cljfx.fx.pie-chart :as fx.pie-chart] [cljfx.fx.xy-chart-series :as fx.xy-chart-series] [cljfx.fx.scatter-chart :as fx.scatter-chart] [cljfx.fx.table-view :as fx.table-view] [cljfx.fx.table-column :as fx.table-column] [cljfx.fx.pie-chart-data :as fx.pie-chart-data] [cljfx.fx.label :as fx.label] [cljfx.fx.web-view :as fx.web-view] [cljfx.fx.region :as fx.region] [cljfx.fx.tree-item :as fx.tree-item] [cljfx.fx.tree-view :as fx.tree-view] [cljfx.fx.tree-cell :as fx.tree-cell]) (:import [clojure.lang IRef IFn] [java.util.concurrent ArrayBlockingQueue TimeUnit BlockingQueue] [javafx.scene.control TableView TablePosition TableColumn$SortType TreeView TreeCell TreeItem] [javafx.scene Node] [javafx.css PseudoClass] [java.net URL URI] [javafx.event Event EventDispatcher] [javafx.scene.paint Color] [javafx.scene.input KeyEvent KeyCode Clipboard ClipboardContent] [java.beans Introspector PropertyDescriptor] [java.lang.reflect Modifier Field] [java.util UUID])) (defn- runduce! ([xf x] (runduce! xf identity x)) ([xf f x] (let [rf (xf (completing #(f %2)))] (rf (rf nil x))))) (defmethod event/handle ::dispose-state [{:keys [id]}] #(dissoc % id)) (defmethod event/handle ::create-view-state [{:keys [id state]}] #(assoc % id (assoc state :id id))) (defn- process-queue! [id ^BlockingQueue queue handler] (handler {::event/type ::create-view-state :id id :state (output-panel/make)}) (let [*running (volatile! true) add-lines! #(handler {::event/type ::output-panel/on-add-lines :id id :fx/event %}) xform (comp stream/stream-xf (partition-all 128) (take-while (fn [_] @*running))) f (event/daemon-future (while @*running (let [x (.take queue)] (runduce! xform add-lines! ({::nil nil} x x)))))] #(do (handler {::event/type ::dispose-state :id id}) (future-cancel f) (vreset! *running false)))) (defn queue [{:keys [^BlockingQueue queue id] :or {id ::rfx/undefined}}] {:fx/type rfx/ext-with-process :id id :start process-queue! :args queue :desc {:fx/type output-panel/view}}) (defn- process-value! [id value handler] (handler {::event/type ::create-view-state :id id :state (output-panel/make {:autoscroll false})}) (let [*running (volatile! true) add-lines! #(handler {::event/type ::output-panel/on-add-lines :id id :fx/event %}) xform (comp stream/stream-xf (partition-all 128) (take-while (fn [_] @*running)))] (event/daemon-future (runduce! xform add-lines! value)) #(do (vreset! *running false) (handler {::event/type ::dispose-state :id id})))) (defn value [{:keys [value]}] {:fx/type rfx/ext-with-process :start process-value! :args value :desc {:fx/type output-panel/view}}) (defn- view? [x] (try (not= (:fx/type x ::not-found) ::not-found) (catch Exception _ false))) (defn ->desc [x] (if (view? x) x {:fx/type value :value x})) (defn- watch! [id *ref handler] (handler {::event/type ::create-view-state :id id :state (output-panel/make {:autoscroll false})}) (let [*running (volatile! true) out-queue (ArrayBlockingQueue. 1024) submit! #(.put out-queue ({nil ::nil} % %)) watch-key (gensym "vlaaad.reveal.view/watcher") f (event/daemon-future (while @*running (when-some [x (loop [x (.poll out-queue 1 TimeUnit/SECONDS) found nil] (if (some? x) (recur (.poll out-queue) x) found))] (handler {::event/type ::output-panel/on-clear-lines :id id}) (runduce! (comp stream/stream-xf (partition-all 128) (take-while (fn [_] (and @*running (nil? (.peek out-queue)))))) #(handler {::event/type ::output-panel/on-add-lines :fx/event % :id id}) ({::nil nil} x x)))))] (submit! @*ref) (add-watch *ref watch-key #(submit! %4)) #(do (remove-watch *ref watch-key) (vreset! *running false) (future-cancel f) (handler {::event/type ::dispose-state :id id})))) (defn ref-watch-latest [{:keys [ref]}] {:fx/type rfx/ext-with-process :start watch! :args ref :desc {:fx/type output-panel/view}}) (action/defaction ::action/view [v] (when (:fx/type v) (constantly v))) (action/defaction ::action/watch:latest [v] (when (instance? IRef v) (constantly {:fx/type ref-watch-latest :ref v}))) (defn- log! [id {:keys [subscribe result-factory]} handler] (handler {::event/type ::create-view-state :id id :state (output-panel/make)}) (let [*running (volatile! true) out-queue (ArrayBlockingQueue. 1024) submit! #(.put out-queue ({nil ::nil} % %)) next-result (result-factory) f (event/daemon-future (while @*running (let [x (.take out-queue)] (runduce! (comp stream/stream-xf (partition-all 128) (take-while (fn [_] @*running))) #(handler {::event/type ::output-panel/on-add-lines :fx/event % :id id}) (stream/horizontal (stream/raw-string (next-result) {:fill :util}) stream/separator (stream/stream ({::nil nil} x x))))))) unsubscribe (subscribe submit!)] #(do (when (fn? unsubscribe) (unsubscribe)) (vreset! *running false) (future-cancel f) (handler {::event/type ::dispose-state :id id})))) (defrecord RefSubscribe [ref] IFn (invoke [_ notify] (notify @ref) (let [watch-key (gensym "vlaaad.reveal.view/ref-subscribe")] (add-watch ref watch-key #(notify %4)) #(remove-watch ref watch-key)))) (defn counter-factory [] (let [counter (volatile! -1)] #(format "%4d:" (vswap! counter inc)))) (defrecord ConstResultFactory [str] IFn (invoke [_] (constantly str))) (defn str-result-factory [str] (->ConstResultFactory str)) (defn ref-watch-all [{:keys [ref subscribe result-factory id] :or {result-factory counter-factory id ::rfx/undefined}}] {:fx/type rfx/ext-with-process :start log! :id id :args {:subscribe (if ref (->RefSubscribe ref) subscribe) :result-factory result-factory} :desc {:fx/type output-panel/view}}) (action/defaction ::action/watch:all [v] (when (instance? IRef v) (constantly {:fx/type ref-watch-all :ref v}))) (defn- deref! [id blocking-deref handler] (handler {::event/type ::create-view-state :id id :state {:state ::waiting}}) (let [f (event/daemon-future (try (handler {::event/type ::create-view-state :id id :state {:state ::value :value @blocking-deref}}) (catch Throwable e (handler {::event/type ::create-view-state :id id :state {:state ::exception :exception e}}))))] #(do (future-cancel f) (handler {::event/type ::dispose-state :id id})))) (defn- blocking-deref-view [{:keys [state] :as props}] (case state ::waiting {:fx/type fx.label/lifecycle :focus-traversable true :text "Loading..."} ::value (->desc (:value props)) ::exception (->desc (stream/override-style (stream/stream (:exception props)) assoc :fill :error)))) (defn derefable [{:keys [derefable]}] {:fx/type rfx/ext-with-process :start deref! :args derefable :desc {:fx/type blocking-deref-view}}) (defn summary [{:keys [value max-length] :or {max-length 48}}] {:fx/type fx.group/lifecycle :children [(stream/fx-summary max-length value)]}) (defn- describe-cell [x] {:content-display :graphic-only :style-class "reveal-table-cell" :graphic {:fx/type summary :value x :max-length 64}}) (defn- initialize-table! [^TableView view] (let [dispatcher (.getEventDispatcher view)] (.setEventDispatcher view (reify EventDispatcher (dispatchEvent [_ e next] (if (and (instance? KeyEvent e) (.isShortcutDown ^KeyEvent e) (#{KeyCode/UP KeyCode/DOWN KeyCode/LEFT KeyCode/RIGHT} (.getCode ^KeyEvent e))) e (.dispatchEvent dispatcher e next)))))) (.selectFirst (.getSelectionModel view)) (.setCellSelectionEnabled (.getSelectionModel view) true)) (defn- select-bounds-and-value! [^Event event] (let [^TableView view (.getSource event)] (when-let [^TablePosition pos (first (.getSelectedCells (.getSelectionModel view)))] (when-let [cell (->> (.lookupAll view ".reveal-table-cell:selected") (some #(when (contains? (.getPseudoClassStates ^Node %) (PseudoClass/getPseudoClass "selected")) %)))] {:bounds (.localToScreen cell (.getBoundsInLocal cell)) :annotation {::row-value #(deref (fx/on-fx-thread (-> view .getSelectionModel .getSelectedItem second))) ::table-value #(deref (fx/on-fx-thread (-> view .getProperties (.get ::items))))} :value (.getCellData (.getTableColumn pos) (.getRow pos))})))) (action/defaction ::action/view:row-value [x ann] (when-let [f (::row-value ann)] f)) (action/defaction ::action/view:table-value [x ann] (when-let [f (::table-value ann)] f)) (defmethod event/handle ::on-table-key-pressed [{:keys [^KeyEvent fx/event]}] (cond (.isAltDown event) (when-let [sort-type ({KeyCode/UP TableColumn$SortType/ASCENDING KeyCode/DOWN TableColumn$SortType/DESCENDING} (.getCode event))] (let [^TableView table (.getTarget event) sm (.getSelectionModel table) col (.getTableColumn ^TablePosition (first (.getSelectedCells sm)))] (when (.isSortable col) (.setSortType col sort-type) (.setAll (.getSortOrder table) [col]) (.clearAndSelect sm 0 col)))) (and (.isShortcutDown event) (= KeyCode/C (.getCode event))) (let [^TableView table (.getTarget event) ^TablePosition pos (first (.getSelectedCells (.getSelectionModel table)))] (fx/on-fx-thread (.setContent (Clipboard/getSystemClipboard) (doto (ClipboardContent.) (.putString (stream/->str (.getCellData (.getTableColumn pos) (.getRow pos))))))))) identity) (defn- make-column [{:keys [header fn columns] :or {header ::not-found} :as props}] (into {:fx/type fx.table-column/lifecycle :style-class "reveal-table-column" :min-width 40 :graphic {:fx/type summary :max-length 64 :value (if (= header ::not-found) fn header)} :cell-factory {:fx/cell-type fx.table-cell/lifecycle :describe describe-cell} :cell-value-factory #(try (fn (peek %)) (catch Throwable e (let [{:clojure.error/keys [cause class]} (-> e Throwable->map m/ex-triage)] (stream/as e (stream/raw-string (or cause class) {:fill :error}))))) :columns (mapv #(-> % (update :fn comp fn) (cond-> (= ::not-found (:header % ::not-found)) (assoc :header (:fn %))) (make-column)) columns)} (dissoc props :header :fn :columns))) (def ext-with-items-prop (fx/make-ext-with-props {::items (rfx/property-prop ::items)})) (defn table [{:keys [items columns] :as props}] {:fx/type fx/ext-on-instance-lifecycle :on-created initialize-table! :desc {:fx/type action-popup/ext :select select-bounds-and-value! :desc {:fx/type ext-with-items-prop :props {::items items} :desc (into {:fx/type fx.table-view/lifecycle :on-key-pressed {::event/type ::on-table-key-pressed} :style-class "reveal-table" :columns (mapv make-column columns) :items (into [] (map-indexed vector) items)} (dissoc props :items :columns))}}}) (def ^:private no-val (stream/as nil (stream/raw-string "-" {:fill :util}))) (defn- infer-columns [sample] (and (seq sample) (condp every? sample (some-fn map? nil?) (let [all-keys (mapcat keys sample) columns (distinct all-keys) column-count (count columns) cells (* (count sample) column-count)] (when (and (<= (/ cells 2) (count all-keys)) (<= 1 column-count 32)) (for [k columns] {:header k :fn #(get % k no-val)}))) map-entry? [{:header 'key :fn key} {:header 'val :fn val}] sequential? (let [counts (map count sample) column-count (apply max counts) cell-count (* (count sample) column-count)] (when (and (<= (/ cell-count 2) (reduce + counts)) (<= 1 column-count 32)) (for [i (range column-count)] {:header i :fn #(nth % i no-val)}))) nil))) (defn- recursive-columns [sample depth] (when (pos? depth) (seq (for [col (infer-columns sample)] (assoc col :columns (recursive-columns (map (:fn col) sample) (dec depth))))))) (action/defaction ::action/view:table [v] (when (and (some? v) (not (string? v)) (seqable? v)) (fn [] {:fx/type table :items v :columns (or (recursive-columns (take 16 v) 4) [{:header 'item :fn identity}])}))) (action/defaction ::action/browse:internal [v] (when (or (and (instance? URI v) (or (#{"http" "https"} (.getScheme ^URI v)) (and (= "file" (.getScheme ^URI v)) (.endsWith (.getPath ^URI v) ".html")))) (instance? URL v) (and (string? v) (re-matches #"^https?://.+" v))) (constantly {:fx/type fx.web-view/lifecycle :url (str v)}))) (defn- request-source-focus! [^Event e] (.requestFocus ^Node (.getSource e))) (defn- labeled->values [labeled] (cond-> labeled (map? labeled) vals)) (defn- labeled->label+values [labeled] (cond (map? labeled) labeled (set? labeled) (map vector labeled labeled) :else (map-indexed vector labeled))) (defn- labeled? "Check if every value in a coll of specified size has uniquely identifying label" [x pred & {:keys [min max] :or {min 1 max 32}}] (and (or (map? x) (set? x) (sequential? x)) (<= min (bounded-count (inc max) x) max) (every? pred (labeled->values x)))) (defn pie-chart [{:keys [data]}] {:fx/type fx.pie-chart/lifecycle :style-class "reveal-chart" :on-mouse-pressed request-source-focus! :animated false :data (for [[k v] (labeled->label+values data)] {:fx/type fx.pie-chart-data/lifecycle :name (stream/str-summary k) :pie-value v})}) (action/defaction ::action/view:pie-chart [x] (when (labeled? x number? :min 2) (constantly {:fx/type pie-chart :data x}))) (def ^:private ext-with-value-on-node (fx/make-ext-with-props {::value (fx.prop/make (fx.mutator/setter (fn [^Node node value] (if (some? value) (.put (.getProperties node) ::value value) (.remove (.getProperties node) ::value)))) fx.lifecycle/scalar)})) (defn- select-chart-node! [^Event event] (let [^Node node (.getTarget event)] (when-let [value (::value (.getProperties node))] {:value value :bounds (.localToScreen node (.getBoundsInLocal node))}))) (defn- numbered? [x] (or (number? x) (and (vector? x) (= 2 (count x)) (number? (x 0))))) (defn- numbered->number [numbered] (cond-> numbered (not (number? numbered)) first)) (defn bar-chart [{:keys [data]}] {:fx/type action-popup/ext :select select-chart-node! :desc {:fx/type fx.bar-chart/lifecycle :style-class "reveal-chart" :on-mouse-pressed request-source-focus! :animated false :x-axis {:fx/type fx.category-axis/lifecycle :label "key"} :y-axis {:fx/type fx.number-axis/lifecycle :label "value"} :data (for [[series v] (labeled->label+values data)] {:fx/type fx.xy-chart-series/lifecycle :name (stream/str-summary series) :data (for [[key value] (labeled->label+values v)] {:fx/type fx.xy-chart-data/lifecycle :x-value (stream/->str key) :y-value (numbered->number value) :node {:fx/type ext-with-value-on-node :props {::value {:value value :key key :series series}} :desc {:fx/type fx.region/lifecycle}}})})}}) (action/defaction ::action/view:bar-chart [x] (when-let [data (cond (labeled? x numbered?) {x x} (labeled? x #(labeled? % numbered?)) x)] (constantly {:fx/type bar-chart :data data}))) (defn- numbereds? [x] (and (sequential? x) (<= 2 (bounded-count 1025 x) 1024) (every? numbered? x))) (def ext-recreate-on-key-changed (reify fx.lifecycle/Lifecycle (create [_ {:keys [key desc]} opts] (with-meta {:key key :child (fx.lifecycle/create fx.lifecycle/dynamic desc opts)} {`fx.component/instance #(-> % :child fx.component/instance)})) (advance [this component {:keys [key desc] :as this-desc} opts] (if (= (:key component) key) (update component :child #(fx.lifecycle/advance fx.lifecycle/dynamic % desc opts)) (do (fx.lifecycle/delete this component opts) (fx.lifecycle/create this this-desc opts)))) (delete [_ component opts] (fx.lifecycle/delete fx.lifecycle/dynamic (:child component) opts)))) (defn line-chart [{:keys [data]}] {:fx/type action-popup/ext :select select-chart-node! :desc {:fx/type fx.line-chart/lifecycle :style-class "reveal-chart" :on-mouse-pressed request-source-focus! :animated false :x-axis {:fx/type fx.number-axis/lifecycle :label "index" :auto-ranging false :lower-bound 0 :upper-bound (dec (transduce (comp (map second) (map count)) max 0 (labeled->label+values data))) :tick-unit 10 :minor-tick-count 10} :y-axis {:fx/type fx.number-axis/lifecycle :label "value" :force-zero-in-range false} :data (for [[series numbers] (labeled->label+values data)] {:fx/type ext-recreate-on-key-changed :key (count numbers) :desc {:fx/type fx.xy-chart-series/lifecycle :name (stream/str-summary series) :data (->> numbers (map-indexed (fn [index value] {:fx/type fx.xy-chart-data/lifecycle :x-value index :y-value (numbered->number value) :node {:fx/type ext-with-value-on-node :props {::value {:value value :index index :series series}} :desc {:fx/type fx.region/lifecycle}}})))}})}}) (action/defaction ::action/view:line-chart [x] (when-let [data (cond (numbereds? x) {x x} (labeled? x numbereds?) x)] (constantly {:fx/type line-chart :data data}))) (defn- coordinate? [x] (and (sequential? x) (= 2 (bounded-count 3 x)) (number? (nth x 0)) (number? (nth x 1)))) (defn- scattered? [x] (or (coordinate? x) (and (vector? x) (= 2 (count x)) (coordinate? (x 0))))) (defn- scattered->coordinate [x] (let [f (first x)] (if (sequential? f) f x))) (defn- scattereds? [x] (and (coll? x) (<= 1 (bounded-count 1025 x) 1024) (every? scattered? x))) (defn scatter-chart [{:keys [data]}] {:fx/type action-popup/ext :select select-chart-node! :desc {:fx/type fx.scatter-chart/lifecycle :style-class "reveal-chart" :on-mouse-pressed request-source-focus! :animated false :x-axis {:fx/type fx.number-axis/lifecycle :label "x" :force-zero-in-range false} :y-axis {:fx/type fx.number-axis/lifecycle :label "y" :force-zero-in-range false} :data (for [[series places] (labeled->label+values data)] {:fx/type fx.xy-chart-series/lifecycle :name (stream/str-summary series) :data (for [value places :let [[x y :as с] (scattered->coordinate value)]] {:fx/type fx.xy-chart-data/lifecycle :x-value x :y-value y :node {:fx/type ext-with-value-on-node :props {::value {:value value :coordinate с :series series}} :desc {:fx/type fx.region/lifecycle}}})})}}) (action/defaction ::action/view:scatter-chart [x] (when-let [data (cond (labeled? x scattereds?) x (scattereds? x) {x x})] (constantly {:fx/type scatter-chart :data data}))) (action/defaction ::action/view:color [v] (when-let [color (cond (instance? Color v) v (string? v) (Color/valueOf v) (keyword? v) (Color/valueOf (name v)))] (constantly {:fx/type fx.region/lifecycle :background {:fills [{:fill color}]}}))) (action/defaction ::action/view:value [x ann] (when (::stream/hidden ann) (constantly {:fx/type value :value x}))) (defn- default-tree-item-render [x] (if (view? x) x {:fx/type summary :value x :max-length 256})) (defn- as-util-string [x] (stream/raw-string x {:fill :util})) (defn- as-error-string [e] (let [{:clojure.error/keys [cause class]} (-> e Throwable->map m/ex-triage)] (stream/raw-string (or cause class) {:fill :error}))) (defn- get-in-tree-state [state path] (get-in state (concat (interleave (repeat :children) path) [:state]))) (defn- tree-item-view [{:keys [state on-expanded-changed branch? root path render valuate annotate] :or {render identity valuate identity annotate {}} :as props}] (if (branch? root) (let [expanded-state (get-in-tree-state state path)] {:fx/type fx.tree-item/lifecycle :value {:value root :render render :valuate valuate :annotate annotate} :expanded (some? expanded-state) :on-expanded-changed (assoc on-expanded-changed :path path :root root) :children (case (:state expanded-state) :loading [{:fx/type fx.tree-item/lifecycle :value {:value "Loading..." :render as-util-string :disable-popup true}}] :done (map-indexed (fn [i child] (assoc props :fx/type tree-item-view :root child :path (conj path i))) (:children expanded-state)) :failed [{:fx/type fx.tree-item/lifecycle :value {:value (:error expanded-state) :render as-error-string :valuate identity :annotate {}}}] [{:fx/type fx.tree-item/lifecycle :value {:value ::hidden :render render :valuate valuate :annotate annotate}}])}) {:fx/type fx.tree-item/lifecycle :value {:value root :render render :valuate valuate :annotate annotate}})) (defn- select-tree-bounds-and-value! [^Event e] (let [^TreeView view (.getSource e)] (when-let [^TreeCell cell (->> (.lookupAll view ".tree-cell:selected") (some #(when (contains? (.getPseudoClassStates ^Node %) (PseudoClass/getPseudoClass "selected")) %)))] (when-let [^Node node (.lookup cell ".tree-cell > .reveal-tree-cell-content")] (let [item (.getItem cell)] (if (:disable-popup item) (.consume e) (let [{:keys [value valuate annotate]} item] {:bounds (.localToScreen node (.getBoundsInLocal node)) :value (valuate value) :annotation (annotate value)}))))))) (defn- init-tree-view! [^TreeView tree-view] (let [dispatcher (.getEventDispatcher tree-view)] (-> tree-view (.setEventDispatcher (reify EventDispatcher (dispatchEvent [_ e next] (if (and (instance? KeyEvent e) (= KeyEvent/KEY_PRESSED (.getEventType e))) (let [^KeyEvent e e] (cond (.isShortcutDown e) (condp = (.getCode e) KeyCode/C (do (fx/on-fx-thread (let [{:keys [value valuate]} (-> tree-view .getSelectionModel ^TreeItem .getSelectedItem .getValue)] (.setContent (Clipboard/getSystemClipboard) (doto (ClipboardContent.) (.putString (stream/->str (valuate value))))))) e) e) (#{KeyCode/ESCAPE} (.getCode e)) e :else (.dispatchEvent dispatcher e next))) (.dispatchEvent dispatcher e next)))))))) (defn- describe-tree-cell [{:keys [value render]}] (let [v (try (render value) (catch Exception e e))] {:graphic {:fx/type fx.anchor-pane/lifecycle :max-width :use-pref-size :style-class "reveal-tree-cell-content" :children [(if (view? v) v {:fx/type summary :value v :max-length 256})]}})) (defn- tree-view-impl [props] {:fx/type action-popup/ext :select select-tree-bounds-and-value! :desc {:fx/type fx/ext-on-instance-lifecycle :on-created init-tree-view! :desc {:fx/type fx.ext.tree-view/with-selection-props :props {:selected-index 0} :desc {:fx/type fx.tree-view/lifecycle :cell-factory {:fx/cell-type fx.tree-cell/lifecycle :describe describe-tree-cell} :root (assoc props :fx/type tree-item-view :path [])}}}}) (defmethod event/handle ::update-state [{:keys [id fn]}] #(cond-> % (contains? % id) (update id fn))) (defmethod event/handle ::change-expanded [{:keys [load-fn] :as e}] (load-fn e) identity) (defn- set-in-tree-state [state path v] (assoc-in state (concat (interleave (repeat :children) path) [:state]) v)) (defn- update-in-tree-state-if-exists [state path f & args] (let [full-path (concat (interleave (repeat :children) path) [:state]) up (fn up [m ks f args] (let [[k & ks] ks] (if ks (assoc m k (up (get m k) ks f args)) (if (contains? m k) (assoc m k (apply f (get m k) args)) m))))] (up state full-path f args))) (defn- get-in-tree-state [state path] (get-in state (concat (interleave (repeat :children) path) [:state]))) (defn- remove-from-tree-state [state path] (let [full-path (interleave (repeat :children) path)] (if (seq full-path) (update-in state full-path dissoc :state :children) (dissoc state :state :children)))) (defn- init-tree-view-state! [id {:keys [branch? children root]} handler] (let [load-fn (fn [{:keys [path root fx/event]}] (if event (let [request (UUID/randomUUID) loading-state {:state :loading :request request}] (handler {::event/type ::update-state :id id :fn #(update % :state set-in-tree-state path loading-state)}) (event/daemon-future (try (let [children (children root)] (if (seqable? children) (doall children) (throw (ex-info "Children are not seqable" {:root root :children children}))) (handler {::event/type ::update-state :id id :fn #(update % :state update-in-tree-state-if-exists path (fn [m] (if (= loading-state m) {:state :done :children children} m)))})) (catch Exception e (handler {::event/type ::update-state :id id :fn #(update % :state update-in-tree-state-if-exists path (fn [m] (if (= loading-state m) {:state :failed :error e} m)))}))))) (handler {::event/type ::update-state :id id :fn #(update % :state remove-from-tree-state path)})))] (handler {::event/type ::create-view-state :id id :state {:state {} :on-expanded-changed {::event/type ::change-expanded :load-fn load-fn}}}) (when (branch? root) (load-fn {:path [] :root root :fx/event true})) #(handler {::event/type ::dispose-state :id id}))) (defn tree-view [props] {:fx/type rfx/ext-with-process :start init-tree-view-state! :args props :desc (assoc props :fx/type tree-view-impl)}) (action/defaction ::action/java-bean [x] (when (some? x) (fn [] (let [reflect (fn [value] (let [props (->> value class (Introspector/getBeanInfo) (.getPropertyDescriptors) (keep (fn [^PropertyDescriptor descriptor] (when-let [read-meth (.getReadMethod descriptor)] (try (.setAccessible read-meth true) (merge {:name (.getName descriptor) :sort 1 :key descriptor} (try {:value (.invoke read-meth value (object-array 0))} (catch Exception e {:error e}))) (catch Throwable _ nil)))))) fields (->> value class (iterate #(.getSuperclass ^Class %)) (take-while some?) (mapcat #(.getDeclaredFields ^Class %)) (remove #(Modifier/isStatic (.getModifiers ^Field %))) (keep (fn [^Field field] (try (.setAccessible field true) (merge {:name (.getName field) :sort -1 :key field} (try {:value (.get field value)} (catch Exception e {:error e}))) (catch Throwable _ nil))))) items (when (.isArray (class value)) (cons {:name "length" :sort 2 :value (count value)} (->> value (take 1000) (map-indexed (fn [i v] {:name i :key i :sort -3 :value v}))))) all (concat fields props items) pad (->> all (map #(-> % :name str count)) (reduce max 0))] (->> all (map #(assoc % :pad pad)) (into (sorted-set-by (fn [a b] (let [v (juxt :sort :name)] (compare (v a) (v b)))))))))] {:fx/type tree-view :valuate (some-fn :error :value) :annotate #(when-let [k (:key %)] {::action/java-bean:key k}) :branch? #(-> % :value some?) :children #(-> % :value reflect) :root {:value x} :render (fn [{:keys [value error name sort pad]}] (apply stream/horizontal (concat (when name [(stream/raw-string (format (str "%-" pad "s") name) {:fill (if (neg? sort) :symbol :util)}) stream/separator]) [(if error (let [{:clojure.error/keys [cause class]} (-> error Throwable->map m/ex-triage)] (stream/raw-string (or cause class) {:fill :error})) (stream/stream value))])))})))) (action/defaction ::action/java-bean:key [x ann] (when-let [k (::action/java-bean:key ann)] (constantly k))) (deftype Observable [*ref f] IRef (deref [_] (f @*ref)) (addWatch [this key callback] (add-watch *ref [this key] #(callback key this (f %3) (f %4)))) (removeWatch [this key] (remove-watch *ref [this key]))) (def ext-try (reify fx.lifecycle/Lifecycle (create [_ {:keys [desc]} opts] (try (with-meta {:child (fx.lifecycle/create fx.lifecycle/dynamic desc opts)} {`fx.component/instance #(-> % :child fx.component/instance)}) (catch Exception e (with-meta {:exception e :desc desc :child (fx.lifecycle/create fx.lifecycle/dynamic {:fx/type value :value e} opts)} {`fx.component/instance #(-> % :child fx.component/instance)})))) (advance [this component {:keys [desc] :as this-desc} opts] (if-let [e (:exception component)] (if (= (:desc component) desc) (update component :child #(fx.lifecycle/advance fx.lifecycle/dynamic % {:fx/type value :value e} opts)) (do (fx.lifecycle/delete this component opts) (fx.lifecycle/create this this-desc opts))) (try (update component :child #(fx.lifecycle/advance fx.lifecycle/dynamic % desc opts)) (catch Exception e (assoc component :exception e :desc desc :child (fx.lifecycle/create fx.lifecycle/dynamic {:fx/type value :value e} opts)))))) (delete [_ component opts] (fx.lifecycle/delete fx.lifecycle/dynamic (:child component) opts)))) (defn- subscribe! [id subscribe handler] (let [notifier #(handler {::event/type ::create-view-state :id id :state {:val %}}) _ (notifier ::not-found) unsubscribe (subscribe notifier)] #(do (when (fn? unsubscribe) (unsubscribe)) (handler {::event/type ::dispose-state :id id})))) (defn- observable-view-impl-try [{:keys [fn val]}] (if (= val ::not-found) {:fx/type fx.label/lifecycle :focus-traversable true :text "Waiting..."} (fn val))) (defn- observable-view-impl [props] {:fx/type ext-try :desc (assoc props :fx/type observable-view-impl-try)}) (defn observable-view [{:keys [ref fn subscribe]}] {:fx/type rfx/ext-with-process :start subscribe! :args (if ref (->RefSubscribe ref) subscribe) :desc {:fx/type observable-view-impl :fn fn}})
eecfaa9965bd02850e2a06a6b723a631c14d7d19535129a4313cf0c009da65c4
tjammer/raylib-ocaml
raylib.ml
include Ctypes_reexports include Raylib_types include Functions module Rlgl = Rlgl
null
https://raw.githubusercontent.com/tjammer/raylib-ocaml/c705cab2c85605d3c62e3937b8b17df9a4486501/src/raylib/raylib.ml
ocaml
include Ctypes_reexports include Raylib_types include Functions module Rlgl = Rlgl
7518e3a5ae29263813fa9cb0b03094a5bb344964d481e12bf23906a6800977ab
schemeway/idyl
env.scm
;; ---------------------------------------------------------------------- ;; FICHIER : env.scm ; ; DATE DE CREATION : Mon May 29 09:36:42 1995 ; ; DERNIERE MODIFICATION : Fri Jun 2 11:29:04 1995 ; ; ;; ---------------------------------------------------------------------- ;; Copyright ( c ) 1995 ; ; ;; ---------------------------------------------------------------------- ;; ;; This file contains all the stuff for environment creation, lookup, ;; ;; etc. ;; ;; ---------------------------------------------------------------------- ;; ;; *********************************************************************** ;; INTERFACE : ;; . *global-environment* : Variable contenant l'environnement global. ;; . env:make-binding : Fonction construisant une liaison. . env : set - global ! : Initialise l'environnement global . . env : add - global - env ! : Fonction ajoutant une liaison à l'environnement ;; global. ;; . env:extend-env : Fonction ajoutant des liaisons à un environnement. . env : set ! : Fonction qui change la valeur d'une variable ;; dans un environnement. ;; *********************************************************************** (define *global-environment* '()) (define (env:make-binding name type value constant?) (error:check-type value type) (make-binding name value type constant?)) (define (env:add-global-env! binding) (let ((name (binding-name binding))) (if (vassoc name *global-environment*) (dylan:error "Cannot redefine module variable: %=" (predef:make-symbol name)) (set-cdr! *global-environment* (cons binding (cdr *global-environment*)))))) (define (env:set-global! binding) (set! *global-environment* (list binding))) (define (env:extend-env env1 env2) (append env1 env2)) (define (env:lookup name env) (let ((x (vassoc name env))) (if x (binding-value x) (dylan:error "Unbound variable: %=" (predef:make-symbol name))))) (define (env:set! new-val binding) (if (binding-constant? binding) (dylan:error "Attempt to modify constant variable: %=" (predef:make-symbol (binding-name binding))) (begin (error:check-type new-val (binding-type binding)) (binding-value-set! binding new-val)))) ;; ---------------------------------------------------------------------- ;; Construction d'un bloc d'activation ... ; ; ;; ---------------------------------------------------------------------- ;; (define (link rte size) (let ((v (make-vector (+ size 1) #f))) (vector-set! v 0 rte) v)) (define (vassoc e vl) (let loop ((l vl)) (if (null? l) #f (let ((v (car l))) (if (eq? (binding-name v) e) v (loop (cdr l)))))))
null
https://raw.githubusercontent.com/schemeway/idyl/2f68a191b3e49636a30ae1f486e85e4733bcf9a0/env.scm
scheme
---------------------------------------------------------------------- ;; ; ; ; ---------------------------------------------------------------------- ;; ; ---------------------------------------------------------------------- ;; This file contains all the stuff for environment creation, lookup, ;; etc. ;; ---------------------------------------------------------------------- ;; *********************************************************************** INTERFACE : . *global-environment* : Variable contenant l'environnement global. . env:make-binding : Fonction construisant une liaison. global. . env:extend-env : Fonction ajoutant des liaisons à un environnement. dans un environnement. *********************************************************************** ---------------------------------------------------------------------- ;; ; ---------------------------------------------------------------------- ;;
. env : set - global ! : Initialise l'environnement global . . env : add - global - env ! : Fonction ajoutant une liaison à l'environnement . env : set ! : Fonction qui change la valeur d'une variable (define *global-environment* '()) (define (env:make-binding name type value constant?) (error:check-type value type) (make-binding name value type constant?)) (define (env:add-global-env! binding) (let ((name (binding-name binding))) (if (vassoc name *global-environment*) (dylan:error "Cannot redefine module variable: %=" (predef:make-symbol name)) (set-cdr! *global-environment* (cons binding (cdr *global-environment*)))))) (define (env:set-global! binding) (set! *global-environment* (list binding))) (define (env:extend-env env1 env2) (append env1 env2)) (define (env:lookup name env) (let ((x (vassoc name env))) (if x (binding-value x) (dylan:error "Unbound variable: %=" (predef:make-symbol name))))) (define (env:set! new-val binding) (if (binding-constant? binding) (dylan:error "Attempt to modify constant variable: %=" (predef:make-symbol (binding-name binding))) (begin (error:check-type new-val (binding-type binding)) (binding-value-set! binding new-val)))) (define (link rte size) (let ((v (make-vector (+ size 1) #f))) (vector-set! v 0 rte) v)) (define (vassoc e vl) (let loop ((l vl)) (if (null? l) #f (let ((v (car l))) (if (eq? (binding-name v) e) v (loop (cdr l)))))))
869e2b73c35c80016422fecdd6d76d3ca0960dbcf422f98a439e769e1c376c3f
stephenpascoe/hs-arrow
Writeable.hs
| Copyright : , and License : LGPL-2.1 Maintainer : ( ) /No description available in the introspection data./ Copyright : Will Thompson, Iñaki García Etxebarria and Jonas Platte License : LGPL-2.1 Maintainer : Iñaki García Etxebarria () /No description available in the introspection data./ -} #define ENABLE_OVERLOADING (MIN_VERSION_haskell_gi_overloading(1,0,0) \ && !defined(__HADDOCK_VERSION__)) module GI.Arrow.Interfaces.Writeable ( -- * Exported types Writeable(..) , noWriteable , IsWriteable , toWriteable , -- * Methods * * flush # method : flush # #if ENABLE_OVERLOADING WriteableFlushMethodInfo , #endif writeableFlush , -- ** write #method:write# #if ENABLE_OVERLOADING WriteableWriteMethodInfo , #endif writeableWrite , ) where import Data.GI.Base.ShortPrelude import qualified Data.GI.Base.ShortPrelude as SP import qualified Data.GI.Base.Overloading as O import qualified Prelude as P import qualified Data.GI.Base.Attributes as GI.Attributes import qualified Data.GI.Base.ManagedPtr as B.ManagedPtr import qualified Data.GI.Base.GError as B.GError import qualified Data.GI.Base.GVariant as B.GVariant import qualified Data.GI.Base.GValue as B.GValue import qualified Data.GI.Base.GParamSpec as B.GParamSpec import qualified Data.GI.Base.CallStack as B.CallStack import qualified Data.Text as T import qualified Data.ByteString.Char8 as B import qualified Data.Map as Map import qualified Foreign.Ptr as FP import qualified GI.GObject.Objects.Object as GObject.Object interface -- | Memory-managed wrapper type. newtype Writeable = Writeable (ManagedPtr Writeable) -- | A convenience alias for `Nothing` :: `Maybe` `Writeable`. noWriteable :: Maybe Writeable noWriteable = Nothing #if ENABLE_OVERLOADING type instance O.SignalList Writeable = WriteableSignalList type WriteableSignalList = ('[ '("notify", GObject.Object.ObjectNotifySignalInfo)] :: [(Symbol, *)]) #endif foreign import ccall "garrow_writeable_get_type" c_garrow_writeable_get_type :: IO GType instance GObject Writeable where gobjectType _ = c_garrow_writeable_get_type -- | Type class for types which can be safely cast to `Writeable`, for instance with `toWriteable`. class GObject o => IsWriteable o #if MIN_VERSION_base(4,9,0) instance {-# OVERLAPPABLE #-} (GObject a, O.UnknownAncestorError Writeable a) => IsWriteable a #endif instance IsWriteable Writeable instance GObject.Object.IsObject Writeable | Cast to ` Writeable ` , for types for which this is known to be safe . For general casts , use ` Data . . ManagedPtr.castTo ` . toWriteable :: (MonadIO m, IsWriteable o) => o -> m Writeable toWriteable = liftIO . unsafeCastTo Writeable #if ENABLE_OVERLOADING instance O.HasAttributeList Writeable type instance O.AttributeList Writeable = WriteableAttributeList type WriteableAttributeList = ('[ ] :: [(Symbol, *)]) #endif #if ENABLE_OVERLOADING #endif #if ENABLE_OVERLOADING type family ResolveWriteableMethod (t :: Symbol) (o :: *) :: * where ResolveWriteableMethod "bindProperty" o = GObject.Object.ObjectBindPropertyMethodInfo ResolveWriteableMethod "bindPropertyFull" o = GObject.Object.ObjectBindPropertyFullMethodInfo ResolveWriteableMethod "flush" o = WriteableFlushMethodInfo ResolveWriteableMethod "forceFloating" o = GObject.Object.ObjectForceFloatingMethodInfo ResolveWriteableMethod "freezeNotify" o = GObject.Object.ObjectFreezeNotifyMethodInfo ResolveWriteableMethod "getv" o = GObject.Object.ObjectGetvMethodInfo ResolveWriteableMethod "isFloating" o = GObject.Object.ObjectIsFloatingMethodInfo ResolveWriteableMethod "notify" o = GObject.Object.ObjectNotifyMethodInfo ResolveWriteableMethod "notifyByPspec" o = GObject.Object.ObjectNotifyByPspecMethodInfo ResolveWriteableMethod "ref" o = GObject.Object.ObjectRefMethodInfo ResolveWriteableMethod "refSink" o = GObject.Object.ObjectRefSinkMethodInfo ResolveWriteableMethod "runDispose" o = GObject.Object.ObjectRunDisposeMethodInfo ResolveWriteableMethod "stealData" o = GObject.Object.ObjectStealDataMethodInfo ResolveWriteableMethod "stealQdata" o = GObject.Object.ObjectStealQdataMethodInfo ResolveWriteableMethod "thawNotify" o = GObject.Object.ObjectThawNotifyMethodInfo ResolveWriteableMethod "unref" o = GObject.Object.ObjectUnrefMethodInfo ResolveWriteableMethod "watchClosure" o = GObject.Object.ObjectWatchClosureMethodInfo ResolveWriteableMethod "write" o = WriteableWriteMethodInfo ResolveWriteableMethod "getData" o = GObject.Object.ObjectGetDataMethodInfo ResolveWriteableMethod "getProperty" o = GObject.Object.ObjectGetPropertyMethodInfo ResolveWriteableMethod "getQdata" o = GObject.Object.ObjectGetQdataMethodInfo ResolveWriteableMethod "setData" o = GObject.Object.ObjectSetDataMethodInfo ResolveWriteableMethod "setProperty" o = GObject.Object.ObjectSetPropertyMethodInfo ResolveWriteableMethod l o = O.MethodResolutionFailed l o instance (info ~ ResolveWriteableMethod t Writeable, O.MethodInfo info Writeable p) => O.IsLabelProxy t (Writeable -> p) where fromLabelProxy _ = O.overloadedMethod (O.MethodProxy :: O.MethodProxy info) #if MIN_VERSION_base(4,9,0) instance (info ~ ResolveWriteableMethod t Writeable, O.MethodInfo info Writeable p) => O.IsLabel t (Writeable -> p) where #if MIN_VERSION_base(4,10,0) fromLabel = O.overloadedMethod (O.MethodProxy :: O.MethodProxy info) #else fromLabel _ = O.overloadedMethod (O.MethodProxy :: O.MethodProxy info) #endif #endif #endif method -- method type : OrdinaryMethod : [ Arg { argCName = " writeable " , argType = TInterface ( Name { namespace = " Arrow " , name = " " } ) , direction = DirectionIn , mayBeNull = False , argDoc = Documentation { rawDocText = Just " A # GArrowWriteable . " , sinceVersion = Nothing } , argScope = ScopeTypeInvalid , argClosure = -1 , argDestroy = -1 , argCallerAllocates = False , transfer = TransferNothing } ] -- Lengths : [] returnType : Just ( TBasicType TBoolean ) -- throws : True -- Skip return : False foreign import ccall "garrow_writeable_flush" garrow_writeable_flush :: writeable : ( Name { namespace = " Arrow " , name = " Writeable " } ) Ptr (Ptr GError) -> -- error IO CInt {- | It ensures writing all data on memory to storage. -} writeableFlush :: (B.CallStack.HasCallStack, MonadIO m, IsWriteable a) => a ^ /@writeable@/ : A ' GI.Arrow . Interfaces . Writeable . ' . -> m () ^ /(Can throw ' Data . . GError . GError')/ writeableFlush writeable = liftIO $ do writeable' <- unsafeManagedPtrCastPtr writeable onException (do _ <- propagateGError $ garrow_writeable_flush writeable' touchManagedPtr writeable return () ) (do return () ) #if ENABLE_OVERLOADING data WriteableFlushMethodInfo instance (signature ~ (m ()), MonadIO m, IsWriteable a) => O.MethodInfo WriteableFlushMethodInfo a signature where overloadedMethod _ = writeableFlush #endif method Writeable::write -- method type : OrdinaryMethod : [ Arg { argCName = " writeable " , argType = TInterface ( Name { namespace = " Arrow " , name = " " } ) , direction = DirectionIn , mayBeNull = False , argDoc = Documentation { rawDocText = Just " A # GArrowWriteable . " , sinceVersion = Nothing } , argScope = ScopeTypeInvalid , argClosure = -1 , argDestroy = -1 , argCallerAllocates = False , transfer = TransferNothing},Arg { argCName = " data " , argType = TCArray False ( -1 ) 2 ( ) , direction = DirectionIn , mayBeNull = False , argDoc = Documentation { rawDocText = Just " The data to be written . " , sinceVersion = Nothing } , argScope = ScopeTypeInvalid , argClosure = -1 , argDestroy = -1 , argCallerAllocates = False , transfer = TransferNothing},Arg { argCName = " n_bytes " , argType = , direction = DirectionIn , mayBeNull = False , argDoc = Documentation { rawDocText = Just " The number of bytes to be written . " , sinceVersion = Nothing } , argScope = ScopeTypeInvalid , argClosure = -1 , argDestroy = -1 , argCallerAllocates = False , transfer = TransferNothing } ] Lengths : [ Arg { argCName = " n_bytes " , argType = , direction = DirectionIn , mayBeNull = False , argDoc = Documentation { rawDocText = Just " The number of bytes to be written . " , sinceVersion = Nothing } , argScope = ScopeTypeInvalid , argClosure = -1 , argDestroy = -1 , argCallerAllocates = False , transfer = TransferNothing } ] returnType : Just ( TBasicType TBoolean ) -- throws : True -- Skip return : False foreign import ccall "garrow_writeable_write" garrow_writeable_write :: writeable : ( Name { namespace = " Arrow " , name = " Writeable " } ) data : TCArray False ( -1 ) 2 ( ) Int64 -> -- n_bytes : TBasicType TInt64 Ptr (Ptr GError) -> -- error IO CInt {- | /No description available in the introspection data./ -} writeableWrite :: (B.CallStack.HasCallStack, MonadIO m, IsWriteable a) => a ^ /@writeable@/ : A ' GI.Arrow . Interfaces . Writeable . ' . -> ByteString {- ^ /@data@/: The data to be written. -} -> m () ^ /(Can throw ' Data . . GError . GError')/ writeableWrite writeable data_ = liftIO $ do let nBytes = fromIntegral $ B.length data_ writeable' <- unsafeManagedPtrCastPtr writeable data_' <- packByteString data_ onException (do _ <- propagateGError $ garrow_writeable_write writeable' data_' nBytes touchManagedPtr writeable freeMem data_' return () ) (do freeMem data_' ) #if ENABLE_OVERLOADING data WriteableWriteMethodInfo instance (signature ~ (ByteString -> m ()), MonadIO m, IsWriteable a) => O.MethodInfo WriteableWriteMethodInfo a signature where overloadedMethod _ = writeableWrite #endif
null
https://raw.githubusercontent.com/stephenpascoe/hs-arrow/86c7c452a8626b1d69a3cffd277078d455823271/gi-arrow/GI/Arrow/Interfaces/Writeable.hs
haskell
* Exported types * Methods ** write #method:write# | Memory-managed wrapper type. | A convenience alias for `Nothing` :: `Maybe` `Writeable`. | Type class for types which can be safely cast to `Writeable`, for instance with `toWriteable`. # OVERLAPPABLE # method type : OrdinaryMethod Lengths : [] throws : True Skip return : False error | It ensures writing all data on memory to storage. method type : OrdinaryMethod throws : True Skip return : False n_bytes : TBasicType TInt64 error | /No description available in the introspection data./ ^ /@data@/: The data to be written.
| Copyright : , and License : LGPL-2.1 Maintainer : ( ) /No description available in the introspection data./ Copyright : Will Thompson, Iñaki García Etxebarria and Jonas Platte License : LGPL-2.1 Maintainer : Iñaki García Etxebarria () /No description available in the introspection data./ -} #define ENABLE_OVERLOADING (MIN_VERSION_haskell_gi_overloading(1,0,0) \ && !defined(__HADDOCK_VERSION__)) module GI.Arrow.Interfaces.Writeable ( Writeable(..) , noWriteable , IsWriteable , toWriteable , * * flush # method : flush # #if ENABLE_OVERLOADING WriteableFlushMethodInfo , #endif writeableFlush , #if ENABLE_OVERLOADING WriteableWriteMethodInfo , #endif writeableWrite , ) where import Data.GI.Base.ShortPrelude import qualified Data.GI.Base.ShortPrelude as SP import qualified Data.GI.Base.Overloading as O import qualified Prelude as P import qualified Data.GI.Base.Attributes as GI.Attributes import qualified Data.GI.Base.ManagedPtr as B.ManagedPtr import qualified Data.GI.Base.GError as B.GError import qualified Data.GI.Base.GVariant as B.GVariant import qualified Data.GI.Base.GValue as B.GValue import qualified Data.GI.Base.GParamSpec as B.GParamSpec import qualified Data.GI.Base.CallStack as B.CallStack import qualified Data.Text as T import qualified Data.ByteString.Char8 as B import qualified Data.Map as Map import qualified Foreign.Ptr as FP import qualified GI.GObject.Objects.Object as GObject.Object interface newtype Writeable = Writeable (ManagedPtr Writeable) noWriteable :: Maybe Writeable noWriteable = Nothing #if ENABLE_OVERLOADING type instance O.SignalList Writeable = WriteableSignalList type WriteableSignalList = ('[ '("notify", GObject.Object.ObjectNotifySignalInfo)] :: [(Symbol, *)]) #endif foreign import ccall "garrow_writeable_get_type" c_garrow_writeable_get_type :: IO GType instance GObject Writeable where gobjectType _ = c_garrow_writeable_get_type class GObject o => IsWriteable o #if MIN_VERSION_base(4,9,0) IsWriteable a #endif instance IsWriteable Writeable instance GObject.Object.IsObject Writeable | Cast to ` Writeable ` , for types for which this is known to be safe . For general casts , use ` Data . . ManagedPtr.castTo ` . toWriteable :: (MonadIO m, IsWriteable o) => o -> m Writeable toWriteable = liftIO . unsafeCastTo Writeable #if ENABLE_OVERLOADING instance O.HasAttributeList Writeable type instance O.AttributeList Writeable = WriteableAttributeList type WriteableAttributeList = ('[ ] :: [(Symbol, *)]) #endif #if ENABLE_OVERLOADING #endif #if ENABLE_OVERLOADING type family ResolveWriteableMethod (t :: Symbol) (o :: *) :: * where ResolveWriteableMethod "bindProperty" o = GObject.Object.ObjectBindPropertyMethodInfo ResolveWriteableMethod "bindPropertyFull" o = GObject.Object.ObjectBindPropertyFullMethodInfo ResolveWriteableMethod "flush" o = WriteableFlushMethodInfo ResolveWriteableMethod "forceFloating" o = GObject.Object.ObjectForceFloatingMethodInfo ResolveWriteableMethod "freezeNotify" o = GObject.Object.ObjectFreezeNotifyMethodInfo ResolveWriteableMethod "getv" o = GObject.Object.ObjectGetvMethodInfo ResolveWriteableMethod "isFloating" o = GObject.Object.ObjectIsFloatingMethodInfo ResolveWriteableMethod "notify" o = GObject.Object.ObjectNotifyMethodInfo ResolveWriteableMethod "notifyByPspec" o = GObject.Object.ObjectNotifyByPspecMethodInfo ResolveWriteableMethod "ref" o = GObject.Object.ObjectRefMethodInfo ResolveWriteableMethod "refSink" o = GObject.Object.ObjectRefSinkMethodInfo ResolveWriteableMethod "runDispose" o = GObject.Object.ObjectRunDisposeMethodInfo ResolveWriteableMethod "stealData" o = GObject.Object.ObjectStealDataMethodInfo ResolveWriteableMethod "stealQdata" o = GObject.Object.ObjectStealQdataMethodInfo ResolveWriteableMethod "thawNotify" o = GObject.Object.ObjectThawNotifyMethodInfo ResolveWriteableMethod "unref" o = GObject.Object.ObjectUnrefMethodInfo ResolveWriteableMethod "watchClosure" o = GObject.Object.ObjectWatchClosureMethodInfo ResolveWriteableMethod "write" o = WriteableWriteMethodInfo ResolveWriteableMethod "getData" o = GObject.Object.ObjectGetDataMethodInfo ResolveWriteableMethod "getProperty" o = GObject.Object.ObjectGetPropertyMethodInfo ResolveWriteableMethod "getQdata" o = GObject.Object.ObjectGetQdataMethodInfo ResolveWriteableMethod "setData" o = GObject.Object.ObjectSetDataMethodInfo ResolveWriteableMethod "setProperty" o = GObject.Object.ObjectSetPropertyMethodInfo ResolveWriteableMethod l o = O.MethodResolutionFailed l o instance (info ~ ResolveWriteableMethod t Writeable, O.MethodInfo info Writeable p) => O.IsLabelProxy t (Writeable -> p) where fromLabelProxy _ = O.overloadedMethod (O.MethodProxy :: O.MethodProxy info) #if MIN_VERSION_base(4,9,0) instance (info ~ ResolveWriteableMethod t Writeable, O.MethodInfo info Writeable p) => O.IsLabel t (Writeable -> p) where #if MIN_VERSION_base(4,10,0) fromLabel = O.overloadedMethod (O.MethodProxy :: O.MethodProxy info) #else fromLabel _ = O.overloadedMethod (O.MethodProxy :: O.MethodProxy info) #endif #endif #endif method : [ Arg { argCName = " writeable " , argType = TInterface ( Name { namespace = " Arrow " , name = " " } ) , direction = DirectionIn , mayBeNull = False , argDoc = Documentation { rawDocText = Just " A # GArrowWriteable . " , sinceVersion = Nothing } , argScope = ScopeTypeInvalid , argClosure = -1 , argDestroy = -1 , argCallerAllocates = False , transfer = TransferNothing } ] returnType : Just ( TBasicType TBoolean ) foreign import ccall "garrow_writeable_flush" garrow_writeable_flush :: writeable : ( Name { namespace = " Arrow " , name = " Writeable " } ) IO CInt writeableFlush :: (B.CallStack.HasCallStack, MonadIO m, IsWriteable a) => a ^ /@writeable@/ : A ' GI.Arrow . Interfaces . Writeable . ' . -> m () ^ /(Can throw ' Data . . GError . GError')/ writeableFlush writeable = liftIO $ do writeable' <- unsafeManagedPtrCastPtr writeable onException (do _ <- propagateGError $ garrow_writeable_flush writeable' touchManagedPtr writeable return () ) (do return () ) #if ENABLE_OVERLOADING data WriteableFlushMethodInfo instance (signature ~ (m ()), MonadIO m, IsWriteable a) => O.MethodInfo WriteableFlushMethodInfo a signature where overloadedMethod _ = writeableFlush #endif method Writeable::write : [ Arg { argCName = " writeable " , argType = TInterface ( Name { namespace = " Arrow " , name = " " } ) , direction = DirectionIn , mayBeNull = False , argDoc = Documentation { rawDocText = Just " A # GArrowWriteable . " , sinceVersion = Nothing } , argScope = ScopeTypeInvalid , argClosure = -1 , argDestroy = -1 , argCallerAllocates = False , transfer = TransferNothing},Arg { argCName = " data " , argType = TCArray False ( -1 ) 2 ( ) , direction = DirectionIn , mayBeNull = False , argDoc = Documentation { rawDocText = Just " The data to be written . " , sinceVersion = Nothing } , argScope = ScopeTypeInvalid , argClosure = -1 , argDestroy = -1 , argCallerAllocates = False , transfer = TransferNothing},Arg { argCName = " n_bytes " , argType = , direction = DirectionIn , mayBeNull = False , argDoc = Documentation { rawDocText = Just " The number of bytes to be written . " , sinceVersion = Nothing } , argScope = ScopeTypeInvalid , argClosure = -1 , argDestroy = -1 , argCallerAllocates = False , transfer = TransferNothing } ] Lengths : [ Arg { argCName = " n_bytes " , argType = , direction = DirectionIn , mayBeNull = False , argDoc = Documentation { rawDocText = Just " The number of bytes to be written . " , sinceVersion = Nothing } , argScope = ScopeTypeInvalid , argClosure = -1 , argDestroy = -1 , argCallerAllocates = False , transfer = TransferNothing } ] returnType : Just ( TBasicType TBoolean ) foreign import ccall "garrow_writeable_write" garrow_writeable_write :: writeable : ( Name { namespace = " Arrow " , name = " Writeable " } ) data : TCArray False ( -1 ) 2 ( ) IO CInt writeableWrite :: (B.CallStack.HasCallStack, MonadIO m, IsWriteable a) => a ^ /@writeable@/ : A ' GI.Arrow . Interfaces . Writeable . ' . -> ByteString -> m () ^ /(Can throw ' Data . . GError . GError')/ writeableWrite writeable data_ = liftIO $ do let nBytes = fromIntegral $ B.length data_ writeable' <- unsafeManagedPtrCastPtr writeable data_' <- packByteString data_ onException (do _ <- propagateGError $ garrow_writeable_write writeable' data_' nBytes touchManagedPtr writeable freeMem data_' return () ) (do freeMem data_' ) #if ENABLE_OVERLOADING data WriteableWriteMethodInfo instance (signature ~ (ByteString -> m ()), MonadIO m, IsWriteable a) => O.MethodInfo WriteableWriteMethodInfo a signature where overloadedMethod _ = writeableWrite #endif
cf71f882fefadcf29578e23aed29cfedddadc1c8e1899475ae2e5771643e4358
bryal/carth
Infer.hs
# LANGUAGE TemplateHaskell , DataKinds , RankNTypes # module Front.Infer (inferTopDefs, checkType, checkTConst) where import Prelude hiding (span) import Lens.Micro.Platform (makeLenses, over, view, mapped, to, Lens') import Control.Applicative hiding (Const(..)) import Control.Monad.Except import Control.Monad.Reader import Control.Monad.State.Strict import Control.Monad.Writer import Data.Bifunctor import Data.Functor import Data.Graph (SCC(..), stronglyConnComp) import Data.List hiding (span) import qualified Data.Map as Map import Data.Map (Map) import Data.Maybe import qualified Data.Set as Set import Data.Set (Set) import Control.Arrow ((>>>)) import Misc import Sizeof import Front.SrcPos import FreeVars import Front.Subst import qualified Front.Parsed as Parsed import Front.Parsed (Id(..), IdCase(..), idstr, defLhs) import Front.Err import Front.Inferred import Front.TypeAst hiding (TConst) newtype ExpectedType = Expected Type data FoundType = Found SrcPos Type unFound :: FoundType -> Type unFound (Found _ t) = t type EqConstraint = (ExpectedType, FoundType) type Constraints = ([EqConstraint], [(SrcPos, ClassConstraint)]) data Env = Env { _envTypeDefs :: TypeDefs Separarate global ( and virtual ) defs and local defs , because ` generalize ` only has to look at local defs . , _envVirtuals :: Map String Scheme , _envGlobDefs :: Map String Scheme , _envLocalDefs :: Map String Scheme -- | Maps a constructor to its variant index in the type definition it constructs, the -- signature/left-hand-side of the type definition, the types of its parameters, and the span -- (number of constructors) of the datatype , _envCtors :: Map String (VariantIx, (String, [TVar]), [Type], Span) , _freshParams :: [String] , _envDeBruijn :: [TypedVar] } makeLenses ''Env type FreshTVs = [String] type Infer a = WriterT Constraints (ReaderT Env (StateT FreshTVs (Except TypeErr))) a inferTopDefs :: TypeDefs -> Ctors -> Externs -> [Parsed.Def] -> Except TypeErr Defs inferTopDefs tdefs ctors externs defs = let initEnv = Env { _envTypeDefs = tdefs , _envVirtuals = builtinVirtuals , _envGlobDefs = fmap (Forall Set.empty Set.empty) externs , _envLocalDefs = Map.empty , _envCtors = ctors , _freshParams = freshParams , _envDeBruijn = [] } freshTvs = let ls = "abcdehjkpqrstuvxyz" ns = map show [1 :: Word .. 99] vs = [ l : n | l <- ls, n <- ns ] ++ [ l : v | l <- ls, v <- vs ] in vs freshParams = map (("generated/param" ++) . show) [0 :: Word ..] in evalStateT (runReaderT (fmap fst (runWriterT (inferDefs envGlobDefs defs))) initEnv) freshTvs where builtinVirtuals :: Map String Scheme builtinVirtuals = let tv a = TVExplicit (Parsed.Id (WithPos (SrcPos "<builtin>" 0 0 Nothing) a)) tva = tv "a" ta = TVar tva tvb = tv "b" tb = TVar tvb arithScm = Forall (Set.fromList [tva]) (Set.singleton ("Num", [ta])) (TFun [ta, ta] ta) bitwiseScm = Forall (Set.fromList [tva]) (Set.singleton ("Bitwise", [ta])) (TFun [ta, ta] ta) relScm = Forall (Set.fromList [tva]) (Set.singleton ("Ord", [ta])) (TFun [ta, ta] tBool) in Map.fromList [ ("+", arithScm) , ("-", arithScm) , ("*", arithScm) , ("/", arithScm) , ("rem", arithScm) , ("shift-l", bitwiseScm) , ("lshift-r", bitwiseScm) , ("ashift-r", bitwiseScm) , ("bit-and", bitwiseScm) , ("bit-or", bitwiseScm) , ("bit-xor", bitwiseScm) , ("=", relScm) , ("/=", relScm) , (">", relScm) , (">=", relScm) , ("<", relScm) , ("<=", relScm) , ( "transmute" , Forall (Set.fromList [tva, tvb]) (Set.singleton ("SameSize", [ta, tb])) (TFun [ta] tb) ) , ("deref", Forall (Set.fromList [tva]) Set.empty (TFun [TBox ta] ta)) , ("store", Forall (Set.fromList [tva]) Set.empty (TFun [ta, TBox ta] (TBox ta))) , ( "cast" , Forall (Set.fromList [tva, tvb]) (Set.singleton ("Cast", [ta, tb])) (TFun [ta] tb) ) ] checkType :: MonadError TypeErr m => (Parsed.TConst -> m Type) -> Parsed.Type -> m Type checkType checkTConst = go where go = \case Parsed.TVar v -> pure (TVar v) Parsed.TPrim p -> pure (TPrim p) Parsed.TConst tc -> checkTConst tc Parsed.TFun ps r -> liftA2 TFun (mapM go ps) (go r) Parsed.TBox t -> fmap TBox (go t) TODO : Include SrcPos in . Type . The ` pos ` we 're given here likely does n't quite make sense . checkType' :: SrcPos -> Parsed.Type -> Infer Type checkType' pos t = do tdefs <- view envTypeDefs checkType (checkTConst tdefs pos) t checkTConst :: MonadError TypeErr m => TypeDefs -> SrcPos -> Parsed.TConst -> m Type checkTConst tdefs pos (x, args) = case Map.lookup x tdefs of Nothing -> throwError (UndefType pos x) Just (params, Data _) -> let expectedN = length params foundN = length args in if expectedN == foundN then do args' <- mapM go args pure (TConst (x, args')) else throwError (TypeInstArityMismatch pos x expectedN foundN) Just (params, Alias _ u) -> subst (Map.fromList (zip params args)) <$> go u where go = checkType (checkTConst tdefs pos) inferDefs :: Lens' Env (Map String Scheme) -> [Parsed.Def] -> Infer Defs inferDefs envDefs defs = do checkNoDuplicateDefs Set.empty defs let ordered = orderDefs defs foldr (\scc inferRest -> do def <- inferComponent scc Topo rest <- augment envDefs (Map.fromList (defSigs def)) inferRest pure (Topo (def : rest)) ) (pure (Topo [])) ordered where checkNoDuplicateDefs :: Set String -> [Parsed.Def] -> Infer () checkNoDuplicateDefs already = uncons >>> fmap (first defLhs) >>> \case Just (Id (WithPos p x), ds) -> if Set.member x already then throwError (ConflictingVarDef p x) else checkNoDuplicateDefs (Set.insert x already) ds Nothing -> pure () -- For unification to work properly with mutually recursive functions, we need to create a -- dependency graph of non-recursive / directly-recursive functions and groups of mutual functions . We do this by creating a directed acyclic graph ( DAG ) of strongly connected -- components (SCC), where a node is a definition and an edge is a reference to another definition . For each SCC , we infer types for all the definitions / the single definition before -- generalizing. orderDefs :: [Parsed.Def] -> [SCC Parsed.Def] orderDefs = stronglyConnComp . graph where graph = map (\d -> (d, defLhs d, Set.toList (freeVars d))) inferComponent :: SCC Parsed.Def -> Infer Def inferComponent = \case AcyclicSCC vert -> fmap VarDef (inferNonrecDef vert) CyclicSCC verts -> fmap RecDefs (inferRecDefs verts) inferNonrecDef :: Parsed.Def -> Infer VarDef inferNonrecDef = \case Parsed.FunDef dpos lhs mayscm params body -> do t <- fresh mayscm' <- checkScheme (idstr lhs) mayscm (fun, cs) <- listen $ inferDef t mayscm' dpos (inferFun dpos params body) (sub, ccs) <- solve cs env <- view envLocalDefs scm <- generalize (substEnv sub env) (fmap _scmConstraints mayscm') ccs (subst sub t) let fun' = substFun sub fun pure (idstr lhs, (scm, Fun fun')) Parsed.FunMatchDef dpos lhs mayscm cases -> do t <- fresh mayscm' <- checkScheme (idstr lhs) mayscm (fun, cs) <- listen $ inferDef t mayscm' dpos (inferFunMatch dpos cases) (sub, ccs) <- solve cs env <- view envLocalDefs scm <- generalize (substEnv sub env) (fmap _scmConstraints mayscm') ccs (subst sub t) let fun' = substFun sub fun pure (idstr lhs, (scm, Fun fun')) Parsed.VarDef dpos lhs mayscm body -> do t <- fresh mayscm' <- checkScheme (idstr lhs) mayscm (body', cs) <- listen $ inferDef t mayscm' dpos (infer body) -- TODO: Can't we get rid of this somehow? It makes our solution more complex and expensive -- if we have to do nested solves. Also re-solves many constraints in vain. -- -- I think we should switch to bidirectional type checking. This will be fixed then. (sub, ccs) <- solve cs env <- view envLocalDefs scm <- generalize (substEnv sub env) (fmap _scmConstraints mayscm') ccs (subst sub t) let body'' = substExpr sub body' pure (idstr lhs, (scm, body'')) inferRecDefs :: [Parsed.Def] -> Infer RecDefs inferRecDefs ds = do (names, mayscms', ts) <- fmap unzip3 $ forM ds $ \d -> do let (name, mayscm) = first idstr $ case d of Parsed.FunDef _ x s _ _ -> (x, s) Parsed.FunMatchDef _ x s _ -> (x, s) Parsed.VarDef _ x s _ -> (x, s) t <- fresh mayscm' <- checkScheme name mayscm pure (name, mayscm', t) let dummyDefs = Map.fromList $ zip names (map (Forall Set.empty Set.empty) ts) (fs, ucs) <- listen $ augment envLocalDefs dummyDefs $ mapM (uncurry3 inferRecDef) (zip3 mayscms' ts ds) (sub, cs) <- solve ucs env <- view envLocalDefs scms <- zipWithM (\s -> generalize (substEnv sub env) (fmap _scmConstraints s) cs . subst sub) mayscms' ts let fs' = map (substFun sub) fs pure (zip names (zip scms fs')) where inferRecDef :: Maybe Scheme -> Type -> Parsed.Def -> Infer Fun inferRecDef mayscm t = \case Parsed.FunDef fpos _ _ params body -> inferDef t mayscm fpos $ inferFun fpos params body Parsed.FunMatchDef fpos _ _ cases -> inferDef t mayscm fpos $ inferFunMatch fpos cases Parsed.VarDef fpos _ _ (WithPos pos (Parsed.Fun params body)) -> inferDef t mayscm fpos (inferFun pos params body) Parsed.VarDef fpos _ _ (WithPos pos (Parsed.FunMatch cs)) -> inferDef t mayscm fpos (inferFunMatch pos cs) Parsed.VarDef _ (Id lhs) _ _ -> throwError (RecursiveVarDef lhs) inferDef :: Type -> Maybe Scheme -> SrcPos -> Infer (Type, body) -> Infer body inferDef t mayscm bodyPos inferBody = do whenJust mayscm $ \(Forall _ _ scmt) -> unify (Expected scmt) (Found bodyPos t) (t', body') <- inferBody unify (Expected t) (Found bodyPos t') pure body' -- | Verify that user-provided type signature schemes are valid checkScheme :: String -> Maybe Parsed.Scheme -> Infer (Maybe Scheme) checkScheme = curry $ \case ("main", Nothing) -> pure (Just (Forall Set.empty Set.empty mainType)) ("main", Just s@(Parsed.Forall pos vs cs t)) | Set.size vs /= 0 || Set.size cs /= 0 || t /= mainType -> throwError (WrongMainType pos s) (_, Nothing) -> pure Nothing (_, Just (Parsed.Forall pos vs cs t)) -> do t' <- checkType' pos t cs' <- mapM (secondM (mapM (uncurry checkType'))) (Set.toList cs) let s1 = Forall vs (Set.fromList cs') t' env <- view envLocalDefs s2@(Forall vs2 _ t2) <- generalize env (Just (_scmConstraints s1)) Map.empty t' if (vs, t') == (vs2, t2) then pure (Just s1) else throwError (InvalidUserTypeSig pos s1 s2) infer :: Parsed.Expr -> Infer (Type, Expr) infer (WithPos pos e) = case e of Parsed.Lit l -> pure (litType l, Lit l) Parsed.Var (Id (WithPos p "_")) -> throwError (FoundHole p) Parsed.Var x -> fmap (second Var) (lookupVar x) Parsed.App f as -> do tas <- mapM (const fresh) as tr <- fresh (tf', f') <- infer f case tf' of TFun tps _ -> unless (length tps == length tas) $ throwError (FunArityMismatch pos (length tps) (length tas)) _ -> pure () -- If it's not k (tas', as') <- unzip <$> mapM infer as unify (Expected (TFun tas tr)) (Found (getPos f) tf') forM_ (zip3 as tas tas') $ \(a, ta, ta') -> unify (Expected ta) (Found (getPos a) ta') pure (tr, App f' as' tr) Parsed.If p c a -> do (tp, p') <- infer p (tc, c') <- infer c (ta, a') <- infer a unify (Expected tBool) (Found (getPos p) tp) unify (Expected tc) (Found (getPos a) ta) pure (tc, If p' c' a') Parsed.Let1 def body -> inferLet1 pos def body Parsed.Let defs body -> -- FIXME: positions let (def, defs') = fromJust $ uncons defs in inferLet1 pos def $ foldr (\d b -> WithPos pos (Parsed.Let1 d b)) body defs' Parsed.LetRec defs b -> do Topo defs' <- inferDefs envLocalDefs defs let withDef def inferX = do (tx, x') <- withLocals (defSigs def) inferX pure (tx, Let def x') foldr withDef (infer b) defs' Parsed.TypeAscr x t -> do (tx, x') <- infer x t' <- checkType' pos t unify (Expected t') (Found (getPos x) tx) pure (t', x') Parsed.Fun param body -> fmap (second Fun) (inferFun pos param body) Parsed.DeBruijnFun nparams body -> fmap (second Fun) (inferDeBruijnFun nparams body) Parsed.DeBruijnIndex ix -> do args <- view envDeBruijn if fromIntegral ix < length args then let tv@(TypedVar _ t) = args !! fromIntegral ix in pure (t, Var (NonVirt, tv)) else throwError (DeBruijnIndexOutOfRange pos ix) Parsed.FunMatch cases -> fmap (second Fun) (inferFunMatch pos cases) Parsed.Match matchee cases -> inferMatch pos matchee cases Parsed.Ctor c -> do (variantIx, tdefLhs, cParams, cSpan) <- lookupEnvConstructor c (tdefInst, cParams') <- instantiateConstructorOfTypeDef tdefLhs cParams let tCtion = TConst tdefInst let t = if null cParams' then tCtion else TFun cParams' tCtion pure (t, Ctor variantIx cSpan tdefInst cParams') Parsed.Sizeof t -> fmap ((TPrim TNatSize, ) . Sizeof) (checkType' pos t) inferLet1 :: SrcPos -> Parsed.DefLike -> Parsed.Expr -> Infer (Type, Expr) inferLet1 pos defl body = case defl of Parsed.Def def -> do def' <- inferNonrecDef def (t, body') <- augment1 envLocalDefs (defSig def') (infer body) pure (t, Let (VarDef def') body') Parsed.Deconstr pat matchee -> inferMatch pos matchee [(pat, body)] inferMatch :: SrcPos -> Parsed.Expr -> [(Parsed.Pat, Parsed.Expr)] -> Infer (Type, Expr) inferMatch pos matchee cases = do (tmatchee, matchee') <- infer matchee (tbody, cases') <- inferCases [tmatchee] (map (first (\pat -> WithPos (getPos pat) [pat])) cases) pure (tbody, Match (WithPos pos ([matchee'], cases', [tmatchee], tbody))) inferFun :: SrcPos -> Parsed.FunPats -> Parsed.Expr -> Infer (Type, Fun) inferFun pos pats body = do (tpats, tbody, case') <- inferCase pats body let tpats' = map unFound tpats funMatchToFun pos [case'] tpats' (unFound tbody) inferDeBruijnFun :: Word -> Parsed.Expr -> Infer (Type, Fun) inferDeBruijnFun nparams body = genParams nparams $ \paramNames -> do tparams <- replicateM (fromIntegral nparams) fresh let params = zip paramNames tparams paramSigs = map (second (Forall Set.empty Set.empty)) params args = map (uncurry TypedVar) params (tbody, body') <- locallySet envDeBruijn args $ withLocals paramSigs (infer body) pure (TFun tparams tbody, (params, (body', tbody))) inferFunMatch :: SrcPos -> [(Parsed.FunPats, Parsed.Expr)] -> Infer (Type, Fun) inferFunMatch pos cases = do arity <- checkCasePatternsArity tpats <- replicateM arity fresh (tbody, cases') <- inferCases tpats cases funMatchToFun pos cases' tpats tbody where checkCasePatternsArity = case cases of [] -> ice "inferFunMatch: checkCasePatternsArity: fun* has no cases, arity 0" (pats0, _) : rest -> do let arity = length (unpos pats0) forM_ rest $ \(WithPos pos pats, _) -> unless (length pats == arity) (throwError (FunCaseArityMismatch pos arity (length pats))) pure arity funMatchToFun :: SrcPos -> Cases -> [Type] -> Type -> Infer (Type, Fun) funMatchToFun pos cases' tpats tbody = genParams (length tpats) $ \paramNames -> do let paramNames' = zipWith fromMaybe paramNames $ case cases' of [(WithPos _ ps, _)] -> flip map ps $ \(Pat _ _ p) -> case p of PVar (TypedVar x _) -> Just x _ -> Nothing _ -> repeat Nothing params = zip paramNames' tpats args = map (Var . (NonVirt, ) . uncurry TypedVar) params pure (TFun tpats tbody, (params, (Match (WithPos pos (args, cases', tpats, tbody)), tbody))) -- | All the patterns must be of the same types, and all the bodies must be of the same type. inferCases :: [Type] -- Type of matchee(s). Expected type(s) of pattern(s). -> [(WithPos [Parsed.Pat], Parsed.Expr)] -> Infer (Type, Cases) inferCases tmatchees cases = do (tpatss, tbodies, cases') <- fmap unzip3 (mapM (uncurry inferCase) cases) forM_ tpatss $ zipWithM (unify . Expected) tmatchees tbody <- fresh forM_ tbodies (unify (Expected tbody)) pure (tbody, cases') inferCase :: WithPos [Parsed.Pat] -> Parsed.Expr -> Infer ([FoundType], FoundType, (WithPos [Pat], Expr)) inferCase (WithPos pos ps) b = do (tps, ps', pvss) <- fmap unzip3 (mapM inferPat ps) let pvs' = map (bimap Parsed.idstr (Forall Set.empty Set.empty . TVar)) (Map.toList (Map.unions pvss)) (tb, b') <- withLocals pvs' (infer b) let tps' = zipWith Found (map getPos ps) tps pure (tps', Found (getPos b) tb, (WithPos pos ps', b')) | Returns the type of the pattern ; the pattern in the format that the Match module wants , -- and a Map from the variables bound in the pattern to fresh schemes. inferPat :: Parsed.Pat -> Infer (Type, Pat, Map (Id 'Small) TVar) inferPat pat = fmap (\(t, p, ss) -> (t, Pat (getPos pat) t p, ss)) (inferPat' pat) where inferPat' = \case Parsed.PConstruction pos c ps -> inferPatConstruction pos c ps Parsed.PInt _ n -> pure (TPrim TIntSize, intToPCon n 64, Map.empty) Parsed.PStr _ s -> let span' = ice "span of Con with VariantStr" p = PCon (Con (VariantStr s) span' []) [] in pure (tStr, p, Map.empty) Parsed.PVar (Id (WithPos _ "_")) -> do tv <- fresh pure (tv, PWild, Map.empty) Parsed.PVar x@(Id (WithPos _ x')) -> do tv <- fresh' pure (TVar tv, PVar (TypedVar x' (TVar tv)), Map.singleton x tv) Parsed.PBox _ p -> do (tp', p', vs) <- inferPat p pure (TBox tp', PBox p', vs) intToPCon n w = PCon (Con { variant = VariantIx (fromIntegral n), span = 2 ^ (w :: Integer), argTs = [] }) [] inferPatConstruction :: SrcPos -> Id 'Big -> [Parsed.Pat] -> Infer (Type, Pat', Map (Id 'Small) TVar) inferPatConstruction pos c cArgs = do (variantIx, tdefLhs, cParams, cSpan) <- lookupEnvConstructor c let arity = length cParams let nArgs = length cArgs unless (arity == nArgs) (throwError (CtorArityMismatch pos (idstr c) arity nArgs)) (tdefInst, cParams') <- instantiateConstructorOfTypeDef tdefLhs cParams let t = TConst tdefInst (cArgTs, cArgs', cArgsVars) <- fmap unzip3 (mapM inferPat cArgs) cArgsVars' <- nonconflictingPatVarDefs cArgsVars forM_ (zip3 cParams' cArgTs cArgs) $ \(cParamT, cArgT, cArg) -> unify (Expected cParamT) (Found (getPos cArg) cArgT) let con = Con { variant = VariantIx variantIx, span = cSpan, argTs = cArgTs } pure (t, PCon con cArgs', cArgsVars') nonconflictingPatVarDefs = flip foldM Map.empty $ \acc ks -> case listToMaybe (Map.keys (Map.intersection acc ks)) of Just (Id (WithPos pos v)) -> throwError (ConflictingPatVarDefs pos v) Nothing -> pure (Map.union acc ks) instantiateConstructorOfTypeDef :: (String, [TVar]) -> [Type] -> Infer (TConst, [Type]) instantiateConstructorOfTypeDef (tName, tParams) cParams = do tVars <- mapM (const fresh) tParams let cParams' = map (subst (Map.fromList (zip tParams tVars))) cParams pure ((tName, tVars), cParams') lookupEnvConstructor :: Id 'Big -> Infer (VariantIx, (String, [TVar]), [Type], Span) lookupEnvConstructor (Id (WithPos pos cx)) = view (envCtors . to (Map.lookup cx)) >>= maybe (throwError (UndefCtor pos cx)) pure litType :: Const -> Type litType = \case Int _ -> TPrim TIntSize F64 _ -> TPrim TF64 Str _ -> tStr lookupVar :: Id 'Small -> Infer (Type, Var) lookupVar (Id (WithPos pos x)) = do virt <- fmap (Map.lookup x) (view envVirtuals) glob <- fmap (Map.lookup x) (view envGlobDefs) local <- fmap (Map.lookup x) (view envLocalDefs) case fmap (NonVirt, ) (local <|> glob) <|> fmap (Virt, ) virt of Just (virt, scm) -> instantiate pos scm <&> \t -> (t, (virt, TypedVar x t)) Nothing -> throwError (UndefVar pos x) genParams :: Integral n => n -> ([String] -> Infer a) -> Infer a genParams n f = do ps <- view (freshParams . to (take (fromIntegral n))) locally freshParams (drop (fromIntegral n)) (f ps) withLocals :: [(String, Scheme)] -> Infer a -> Infer a withLocals = augment envLocalDefs . Map.fromList instantiate :: SrcPos -> Scheme -> Infer Type instantiate pos (Forall params constraints t) = do s <- Map.fromList <$> zipWithM (fmap . (,)) (Set.toList params) (repeat fresh) forM_ constraints $ \c -> unifyClass pos (substClassConstraint s c) pure (subst s t) generalize :: (MonadError TypeErr m) => Map String Scheme -> Maybe (Set ClassConstraint) -> Map ClassConstraint SrcPos -> Type -> m Scheme generalize env mayGivenCs allCs t = fmap (\cs -> Forall vs cs t) constraints where A constraint should be included in a signature if the type variables include at least one of the signature 's forall - qualified tvars , and the rest of the tvars exist in the surrounding -- environment. If a tvar is not from the signature or the environment, it comes from an inner -- definition, and should already have been included in that signature. -- -- TODO: Maybe we should handle the propagation of class constraints in a better way, so that -- ones belonging to inner definitions no longer exist at this point. constraints = fmap (Set.fromList . map fst) $ flip filterM (Map.toList allCs) $ \(c, pos) -> let vcs = ftvClassConstraint c belongs = any (flip Set.member vs) vcs && all (\vc -> Set.member vc vs || Set.member vc ftvEnv) vcs in if belongs then if matchesGiven c then pure True else throwError (NoClassInstance pos c) else pure False matchesGiven = case mayGivenCs of Just gcs -> flip Set.member gcs Nothing -> const True vs = Set.difference (ftv t) ftvEnv ftvEnv = Set.unions (map ftvScheme (Map.elems env)) ftvScheme (Forall tvs _ t) = Set.difference (ftv t) tvs substEnv :: Subst' -> Map String Scheme -> Map String Scheme substEnv s = over (mapped . scmBody) (subst s) ftvClassConstraint :: ClassConstraint -> Set TVar ftvClassConstraint = mconcat . map ftv . snd substClassConstraint :: Subst' -> ClassConstraint -> ClassConstraint substClassConstraint sub = second (map (subst sub)) fresh :: Infer Type fresh = fmap TVar fresh' fresh' :: Infer TVar fresh' = fmap TVImplicit (gets head <* modify tail) unify :: ExpectedType -> FoundType -> Infer () unify e f = tell ([(e, f)], []) unifyClass :: SrcPos -> ClassConstraint -> Infer () unifyClass p c = tell ([], [(p, c)]) data UnifyErr = UInfType TVar Type | UFailed Type Type -- TODO: I actually don't really like this approach of keeping the unification solver separate from -- the inferrer. The approach of doing it "inline" is, at least in some ways, more flexible, -- and probably more performant. Consider this further -- maybe there's a big con I haven't -- considered or have forgotten. Will updating the substitution map work well? How would it -- work for nested inferDefs, compared to now? solve :: Constraints -> Infer (Subst', Map ClassConstraint SrcPos) solve (eqcs, ccs) = do sub <- lift $ lift $ lift $ solveUnis Map.empty eqcs ccs' <- solveClassCs (map (second (substClassConstraint sub)) ccs) pure (sub, ccs') where solveUnis :: Subst' -> [EqConstraint] -> Except TypeErr Subst' solveUnis sub1 = \case [] -> pure sub1 (Expected et, Found pos ft) : cs -> do sub2 <- withExcept (toTypeErr pos et ft) (unifies et ft) solveUnis (composeSubsts sub2 sub1) (map (substConstraint sub2) cs) solveClassCs :: [(SrcPos, ClassConstraint)] -> Infer (Map ClassConstraint SrcPos) solveClassCs = fmap Map.unions . mapM solveClassConstraint solveClassConstraint :: (SrcPos, ClassConstraint) -> Infer (Map ClassConstraint SrcPos) solveClassConstraint (pos, c) = case c of -- Virtual classes ("SameSize", [ta, tb]) -> sameSize (ta, tb) ("Cast", [ta, tb]) -> cast (ta, tb) ("Num", [ta]) -> case ta of TPrim _ -> ok TVar _ -> propagate TConst _ -> err TFun _ _ -> err TBox _ -> err ("Bitwise", [ta]) -> case ta of TPrim p | isIntegral p -> ok TPrim _ -> err TVar _ -> propagate TConst _ -> err TFun _ _ -> err TBox _ -> err ("Ord", [ta]) -> case ta of TPrim _ -> ok TVar _ -> propagate TConst _ -> err TFun _ _ -> err TBox _ -> err -- "Real classes" -- ... TODO _ -> ice $ "solveClassCs: invalid class constraint " ++ show c where ok = pure Map.empty propagate = pure (Map.singleton c pos) err = throwError (NoClassInstance pos c) isIntegral = \case TInt _ -> True TIntSize -> True TNat _ -> True TNatSize -> True _ -> False -- TODO: Maybe we should move the check against user-provided explicit signature from -- `generalize` to here. Like, we could keep the explicit scheme (if there is one) in -- the `Env`. -- | As the name indicates , a predicate that is true / class that is instanced when two -- types are of the same size. If the size for either cannot be determined yet due to -- polymorphism, the constraint is propagated. sameSize :: (Type, Type) -> Infer (Map ClassConstraint SrcPos) sameSize (ta, tb) = do sizeof'' <- sizeof . sizeofTypeDef <$> view envTypeDefs case liftA2 (==) (sizeof'' ta) (sizeof'' tb) of _ | ta == tb -> ok Right True -> ok Right False -> err One or both of the two types are of unknown size due to polymorphism , so -- propagate the constraint to the scheme of the definition. Left _ -> propagate sizeofTypeDef tdefs (x, args) = case Map.lookup x tdefs of Just (params, Data variants) -> let sub = Map.fromList (zip params args) datas = map (map (subst sub) . snd) variants in sizeofData (sizeofTypeDef tdefs) (alignofTypeDef tdefs) datas Just (params, Alias _ t) -> let sub = Map.fromList (zip params args) in sizeof (sizeofTypeDef tdefs) (subst sub t) Nothing -> ice $ "Infer.sizeofTypeDef: undefined type " ++ show x alignofTypeDef tdefs (x, args) = case Map.lookup x tdefs of Just (params, Data variants) -> let sub = Map.fromList (zip params args) datas = map (map (subst sub) . snd) variants in alignmentofData (alignofTypeDef tdefs) datas Just (params, Alias _ t) -> let sub = Map.fromList (zip params args) in alignmentof (alignofTypeDef tdefs) (subst sub t) Nothing -> ice $ "Infer.sizeofTypeDef: undefined type " ++ show x | This class is instanced when the first type can be ` cast ` to the other . cast :: (Type, Type) -> Infer (Map ClassConstraint SrcPos) cast = \case (ta, tb) | ta == tb -> ok (TPrim _, TPrim _) -> ok (TVar _, _) -> propagate (_, TVar _) -> propagate (TConst _, _) -> err (_, TConst _) -> err (TFun _ _, _) -> err (_, TFun _ _) -> err (TBox _, _) -> err (_, TBox _) -> err substConstraint sub (Expected t1, Found pos t2) = (Expected (subst sub t1), Found pos (subst sub t2)) toTypeErr :: SrcPos -> Type -> Type -> UnifyErr -> TypeErr toTypeErr pos t1 t2 = \case UInfType a t -> InfType pos t1 t2 a t UFailed t'1 t'2 -> UnificationFailed pos t1 t2 t'1 t'2 -- FIXME: Keep track of whether we've flipped the arguments. Alternatively, keep right stuff to the -- right and vice versa. If we don't, we get confusing type errors. unifies :: Type -> Type -> Except UnifyErr Subst' unifies = curry $ \case (TPrim a, TPrim b) | a == b -> pure Map.empty (TConst (c0, ts0), TConst (c1, ts1)) | c0 == c1 -> if length ts0 /= length ts1 then ice "lengths of TConst params differ in unify" else unifiesMany (zip ts0 ts1) (TVar a, TVar b) | a == b -> pure Map.empty (TVar a, t) | occursIn a t -> throwError (UInfType a t) -- Do not allow "override" of explicit (user given) type variables. (a@(TVar (TVExplicit _)), b@(TVar (TVImplicit _))) -> unifies b a (a@(TVar (TVExplicit _)), b) -> throwError (UFailed a b) (TVar a, t) -> pure (Map.singleton a t) (t, TVar a) -> unifies (TVar a) t (t@(TFun ts1 t2), u@(TFun us1 u2)) -> if length ts1 /= length us1 then throwError (UFailed t u) else unifiesMany (zip (ts1 ++ [t2]) (us1 ++ [u2])) (TBox t, TBox u) -> unifies t u (t1, t2) -> throwError (UFailed t1 t2) where unifiesMany :: [(Type, Type)] -> Except UnifyErr Subst' unifiesMany = foldM (\s (t, u) -> fmap (flip composeSubsts s) (unifies (subst s t) (subst s u))) Map.empty occursIn :: TVar -> Type -> Bool occursIn a t = Set.member a (ftv t)
null
https://raw.githubusercontent.com/bryal/carth/0c6026c82ce8ceb1a621c15a0e7505c4e6bc8782/src/Front/Infer.hs
haskell
| Maps a constructor to its variant index in the type definition it constructs, the signature/left-hand-side of the type definition, the types of its parameters, and the span (number of constructors) of the datatype For unification to work properly with mutually recursive functions, we need to create a dependency graph of non-recursive / directly-recursive functions and groups of mutual components (SCC), where a node is a definition and an edge is a reference to another generalizing. TODO: Can't we get rid of this somehow? It makes our solution more complex and expensive if we have to do nested solves. Also re-solves many constraints in vain. I think we should switch to bidirectional type checking. This will be fixed then. | Verify that user-provided type signature schemes are valid If it's not k FIXME: positions | All the patterns must be of the same types, and all the bodies must be of the same type. Type of matchee(s). Expected type(s) of pattern(s). and a Map from the variables bound in the pattern to fresh schemes. environment. If a tvar is not from the signature or the environment, it comes from an inner definition, and should already have been included in that signature. TODO: Maybe we should handle the propagation of class constraints in a better way, so that ones belonging to inner definitions no longer exist at this point. TODO: I actually don't really like this approach of keeping the unification solver separate from the inferrer. The approach of doing it "inline" is, at least in some ways, more flexible, and probably more performant. Consider this further -- maybe there's a big con I haven't considered or have forgotten. Will updating the substitution map work well? How would it work for nested inferDefs, compared to now? Virtual classes "Real classes" ... TODO TODO: Maybe we should move the check against user-provided explicit signature from `generalize` to here. Like, we could keep the explicit scheme (if there is one) in the `Env`. types are of the same size. If the size for either cannot be determined yet due to polymorphism, the constraint is propagated. propagate the constraint to the scheme of the definition. FIXME: Keep track of whether we've flipped the arguments. Alternatively, keep right stuff to the right and vice versa. If we don't, we get confusing type errors. Do not allow "override" of explicit (user given) type variables.
# LANGUAGE TemplateHaskell , DataKinds , RankNTypes # module Front.Infer (inferTopDefs, checkType, checkTConst) where import Prelude hiding (span) import Lens.Micro.Platform (makeLenses, over, view, mapped, to, Lens') import Control.Applicative hiding (Const(..)) import Control.Monad.Except import Control.Monad.Reader import Control.Monad.State.Strict import Control.Monad.Writer import Data.Bifunctor import Data.Functor import Data.Graph (SCC(..), stronglyConnComp) import Data.List hiding (span) import qualified Data.Map as Map import Data.Map (Map) import Data.Maybe import qualified Data.Set as Set import Data.Set (Set) import Control.Arrow ((>>>)) import Misc import Sizeof import Front.SrcPos import FreeVars import Front.Subst import qualified Front.Parsed as Parsed import Front.Parsed (Id(..), IdCase(..), idstr, defLhs) import Front.Err import Front.Inferred import Front.TypeAst hiding (TConst) newtype ExpectedType = Expected Type data FoundType = Found SrcPos Type unFound :: FoundType -> Type unFound (Found _ t) = t type EqConstraint = (ExpectedType, FoundType) type Constraints = ([EqConstraint], [(SrcPos, ClassConstraint)]) data Env = Env { _envTypeDefs :: TypeDefs Separarate global ( and virtual ) defs and local defs , because ` generalize ` only has to look at local defs . , _envVirtuals :: Map String Scheme , _envGlobDefs :: Map String Scheme , _envLocalDefs :: Map String Scheme , _envCtors :: Map String (VariantIx, (String, [TVar]), [Type], Span) , _freshParams :: [String] , _envDeBruijn :: [TypedVar] } makeLenses ''Env type FreshTVs = [String] type Infer a = WriterT Constraints (ReaderT Env (StateT FreshTVs (Except TypeErr))) a inferTopDefs :: TypeDefs -> Ctors -> Externs -> [Parsed.Def] -> Except TypeErr Defs inferTopDefs tdefs ctors externs defs = let initEnv = Env { _envTypeDefs = tdefs , _envVirtuals = builtinVirtuals , _envGlobDefs = fmap (Forall Set.empty Set.empty) externs , _envLocalDefs = Map.empty , _envCtors = ctors , _freshParams = freshParams , _envDeBruijn = [] } freshTvs = let ls = "abcdehjkpqrstuvxyz" ns = map show [1 :: Word .. 99] vs = [ l : n | l <- ls, n <- ns ] ++ [ l : v | l <- ls, v <- vs ] in vs freshParams = map (("generated/param" ++) . show) [0 :: Word ..] in evalStateT (runReaderT (fmap fst (runWriterT (inferDefs envGlobDefs defs))) initEnv) freshTvs where builtinVirtuals :: Map String Scheme builtinVirtuals = let tv a = TVExplicit (Parsed.Id (WithPos (SrcPos "<builtin>" 0 0 Nothing) a)) tva = tv "a" ta = TVar tva tvb = tv "b" tb = TVar tvb arithScm = Forall (Set.fromList [tva]) (Set.singleton ("Num", [ta])) (TFun [ta, ta] ta) bitwiseScm = Forall (Set.fromList [tva]) (Set.singleton ("Bitwise", [ta])) (TFun [ta, ta] ta) relScm = Forall (Set.fromList [tva]) (Set.singleton ("Ord", [ta])) (TFun [ta, ta] tBool) in Map.fromList [ ("+", arithScm) , ("-", arithScm) , ("*", arithScm) , ("/", arithScm) , ("rem", arithScm) , ("shift-l", bitwiseScm) , ("lshift-r", bitwiseScm) , ("ashift-r", bitwiseScm) , ("bit-and", bitwiseScm) , ("bit-or", bitwiseScm) , ("bit-xor", bitwiseScm) , ("=", relScm) , ("/=", relScm) , (">", relScm) , (">=", relScm) , ("<", relScm) , ("<=", relScm) , ( "transmute" , Forall (Set.fromList [tva, tvb]) (Set.singleton ("SameSize", [ta, tb])) (TFun [ta] tb) ) , ("deref", Forall (Set.fromList [tva]) Set.empty (TFun [TBox ta] ta)) , ("store", Forall (Set.fromList [tva]) Set.empty (TFun [ta, TBox ta] (TBox ta))) , ( "cast" , Forall (Set.fromList [tva, tvb]) (Set.singleton ("Cast", [ta, tb])) (TFun [ta] tb) ) ] checkType :: MonadError TypeErr m => (Parsed.TConst -> m Type) -> Parsed.Type -> m Type checkType checkTConst = go where go = \case Parsed.TVar v -> pure (TVar v) Parsed.TPrim p -> pure (TPrim p) Parsed.TConst tc -> checkTConst tc Parsed.TFun ps r -> liftA2 TFun (mapM go ps) (go r) Parsed.TBox t -> fmap TBox (go t) TODO : Include SrcPos in . Type . The ` pos ` we 're given here likely does n't quite make sense . checkType' :: SrcPos -> Parsed.Type -> Infer Type checkType' pos t = do tdefs <- view envTypeDefs checkType (checkTConst tdefs pos) t checkTConst :: MonadError TypeErr m => TypeDefs -> SrcPos -> Parsed.TConst -> m Type checkTConst tdefs pos (x, args) = case Map.lookup x tdefs of Nothing -> throwError (UndefType pos x) Just (params, Data _) -> let expectedN = length params foundN = length args in if expectedN == foundN then do args' <- mapM go args pure (TConst (x, args')) else throwError (TypeInstArityMismatch pos x expectedN foundN) Just (params, Alias _ u) -> subst (Map.fromList (zip params args)) <$> go u where go = checkType (checkTConst tdefs pos) inferDefs :: Lens' Env (Map String Scheme) -> [Parsed.Def] -> Infer Defs inferDefs envDefs defs = do checkNoDuplicateDefs Set.empty defs let ordered = orderDefs defs foldr (\scc inferRest -> do def <- inferComponent scc Topo rest <- augment envDefs (Map.fromList (defSigs def)) inferRest pure (Topo (def : rest)) ) (pure (Topo [])) ordered where checkNoDuplicateDefs :: Set String -> [Parsed.Def] -> Infer () checkNoDuplicateDefs already = uncons >>> fmap (first defLhs) >>> \case Just (Id (WithPos p x), ds) -> if Set.member x already then throwError (ConflictingVarDef p x) else checkNoDuplicateDefs (Set.insert x already) ds Nothing -> pure () functions . We do this by creating a directed acyclic graph ( DAG ) of strongly connected definition . For each SCC , we infer types for all the definitions / the single definition before orderDefs :: [Parsed.Def] -> [SCC Parsed.Def] orderDefs = stronglyConnComp . graph where graph = map (\d -> (d, defLhs d, Set.toList (freeVars d))) inferComponent :: SCC Parsed.Def -> Infer Def inferComponent = \case AcyclicSCC vert -> fmap VarDef (inferNonrecDef vert) CyclicSCC verts -> fmap RecDefs (inferRecDefs verts) inferNonrecDef :: Parsed.Def -> Infer VarDef inferNonrecDef = \case Parsed.FunDef dpos lhs mayscm params body -> do t <- fresh mayscm' <- checkScheme (idstr lhs) mayscm (fun, cs) <- listen $ inferDef t mayscm' dpos (inferFun dpos params body) (sub, ccs) <- solve cs env <- view envLocalDefs scm <- generalize (substEnv sub env) (fmap _scmConstraints mayscm') ccs (subst sub t) let fun' = substFun sub fun pure (idstr lhs, (scm, Fun fun')) Parsed.FunMatchDef dpos lhs mayscm cases -> do t <- fresh mayscm' <- checkScheme (idstr lhs) mayscm (fun, cs) <- listen $ inferDef t mayscm' dpos (inferFunMatch dpos cases) (sub, ccs) <- solve cs env <- view envLocalDefs scm <- generalize (substEnv sub env) (fmap _scmConstraints mayscm') ccs (subst sub t) let fun' = substFun sub fun pure (idstr lhs, (scm, Fun fun')) Parsed.VarDef dpos lhs mayscm body -> do t <- fresh mayscm' <- checkScheme (idstr lhs) mayscm (body', cs) <- listen $ inferDef t mayscm' dpos (infer body) (sub, ccs) <- solve cs env <- view envLocalDefs scm <- generalize (substEnv sub env) (fmap _scmConstraints mayscm') ccs (subst sub t) let body'' = substExpr sub body' pure (idstr lhs, (scm, body'')) inferRecDefs :: [Parsed.Def] -> Infer RecDefs inferRecDefs ds = do (names, mayscms', ts) <- fmap unzip3 $ forM ds $ \d -> do let (name, mayscm) = first idstr $ case d of Parsed.FunDef _ x s _ _ -> (x, s) Parsed.FunMatchDef _ x s _ -> (x, s) Parsed.VarDef _ x s _ -> (x, s) t <- fresh mayscm' <- checkScheme name mayscm pure (name, mayscm', t) let dummyDefs = Map.fromList $ zip names (map (Forall Set.empty Set.empty) ts) (fs, ucs) <- listen $ augment envLocalDefs dummyDefs $ mapM (uncurry3 inferRecDef) (zip3 mayscms' ts ds) (sub, cs) <- solve ucs env <- view envLocalDefs scms <- zipWithM (\s -> generalize (substEnv sub env) (fmap _scmConstraints s) cs . subst sub) mayscms' ts let fs' = map (substFun sub) fs pure (zip names (zip scms fs')) where inferRecDef :: Maybe Scheme -> Type -> Parsed.Def -> Infer Fun inferRecDef mayscm t = \case Parsed.FunDef fpos _ _ params body -> inferDef t mayscm fpos $ inferFun fpos params body Parsed.FunMatchDef fpos _ _ cases -> inferDef t mayscm fpos $ inferFunMatch fpos cases Parsed.VarDef fpos _ _ (WithPos pos (Parsed.Fun params body)) -> inferDef t mayscm fpos (inferFun pos params body) Parsed.VarDef fpos _ _ (WithPos pos (Parsed.FunMatch cs)) -> inferDef t mayscm fpos (inferFunMatch pos cs) Parsed.VarDef _ (Id lhs) _ _ -> throwError (RecursiveVarDef lhs) inferDef :: Type -> Maybe Scheme -> SrcPos -> Infer (Type, body) -> Infer body inferDef t mayscm bodyPos inferBody = do whenJust mayscm $ \(Forall _ _ scmt) -> unify (Expected scmt) (Found bodyPos t) (t', body') <- inferBody unify (Expected t) (Found bodyPos t') pure body' checkScheme :: String -> Maybe Parsed.Scheme -> Infer (Maybe Scheme) checkScheme = curry $ \case ("main", Nothing) -> pure (Just (Forall Set.empty Set.empty mainType)) ("main", Just s@(Parsed.Forall pos vs cs t)) | Set.size vs /= 0 || Set.size cs /= 0 || t /= mainType -> throwError (WrongMainType pos s) (_, Nothing) -> pure Nothing (_, Just (Parsed.Forall pos vs cs t)) -> do t' <- checkType' pos t cs' <- mapM (secondM (mapM (uncurry checkType'))) (Set.toList cs) let s1 = Forall vs (Set.fromList cs') t' env <- view envLocalDefs s2@(Forall vs2 _ t2) <- generalize env (Just (_scmConstraints s1)) Map.empty t' if (vs, t') == (vs2, t2) then pure (Just s1) else throwError (InvalidUserTypeSig pos s1 s2) infer :: Parsed.Expr -> Infer (Type, Expr) infer (WithPos pos e) = case e of Parsed.Lit l -> pure (litType l, Lit l) Parsed.Var (Id (WithPos p "_")) -> throwError (FoundHole p) Parsed.Var x -> fmap (second Var) (lookupVar x) Parsed.App f as -> do tas <- mapM (const fresh) as tr <- fresh (tf', f') <- infer f case tf' of TFun tps _ -> unless (length tps == length tas) $ throwError (FunArityMismatch pos (length tps) (length tas)) (tas', as') <- unzip <$> mapM infer as unify (Expected (TFun tas tr)) (Found (getPos f) tf') forM_ (zip3 as tas tas') $ \(a, ta, ta') -> unify (Expected ta) (Found (getPos a) ta') pure (tr, App f' as' tr) Parsed.If p c a -> do (tp, p') <- infer p (tc, c') <- infer c (ta, a') <- infer a unify (Expected tBool) (Found (getPos p) tp) unify (Expected tc) (Found (getPos a) ta) pure (tc, If p' c' a') Parsed.Let1 def body -> inferLet1 pos def body Parsed.Let defs body -> let (def, defs') = fromJust $ uncons defs in inferLet1 pos def $ foldr (\d b -> WithPos pos (Parsed.Let1 d b)) body defs' Parsed.LetRec defs b -> do Topo defs' <- inferDefs envLocalDefs defs let withDef def inferX = do (tx, x') <- withLocals (defSigs def) inferX pure (tx, Let def x') foldr withDef (infer b) defs' Parsed.TypeAscr x t -> do (tx, x') <- infer x t' <- checkType' pos t unify (Expected t') (Found (getPos x) tx) pure (t', x') Parsed.Fun param body -> fmap (second Fun) (inferFun pos param body) Parsed.DeBruijnFun nparams body -> fmap (second Fun) (inferDeBruijnFun nparams body) Parsed.DeBruijnIndex ix -> do args <- view envDeBruijn if fromIntegral ix < length args then let tv@(TypedVar _ t) = args !! fromIntegral ix in pure (t, Var (NonVirt, tv)) else throwError (DeBruijnIndexOutOfRange pos ix) Parsed.FunMatch cases -> fmap (second Fun) (inferFunMatch pos cases) Parsed.Match matchee cases -> inferMatch pos matchee cases Parsed.Ctor c -> do (variantIx, tdefLhs, cParams, cSpan) <- lookupEnvConstructor c (tdefInst, cParams') <- instantiateConstructorOfTypeDef tdefLhs cParams let tCtion = TConst tdefInst let t = if null cParams' then tCtion else TFun cParams' tCtion pure (t, Ctor variantIx cSpan tdefInst cParams') Parsed.Sizeof t -> fmap ((TPrim TNatSize, ) . Sizeof) (checkType' pos t) inferLet1 :: SrcPos -> Parsed.DefLike -> Parsed.Expr -> Infer (Type, Expr) inferLet1 pos defl body = case defl of Parsed.Def def -> do def' <- inferNonrecDef def (t, body') <- augment1 envLocalDefs (defSig def') (infer body) pure (t, Let (VarDef def') body') Parsed.Deconstr pat matchee -> inferMatch pos matchee [(pat, body)] inferMatch :: SrcPos -> Parsed.Expr -> [(Parsed.Pat, Parsed.Expr)] -> Infer (Type, Expr) inferMatch pos matchee cases = do (tmatchee, matchee') <- infer matchee (tbody, cases') <- inferCases [tmatchee] (map (first (\pat -> WithPos (getPos pat) [pat])) cases) pure (tbody, Match (WithPos pos ([matchee'], cases', [tmatchee], tbody))) inferFun :: SrcPos -> Parsed.FunPats -> Parsed.Expr -> Infer (Type, Fun) inferFun pos pats body = do (tpats, tbody, case') <- inferCase pats body let tpats' = map unFound tpats funMatchToFun pos [case'] tpats' (unFound tbody) inferDeBruijnFun :: Word -> Parsed.Expr -> Infer (Type, Fun) inferDeBruijnFun nparams body = genParams nparams $ \paramNames -> do tparams <- replicateM (fromIntegral nparams) fresh let params = zip paramNames tparams paramSigs = map (second (Forall Set.empty Set.empty)) params args = map (uncurry TypedVar) params (tbody, body') <- locallySet envDeBruijn args $ withLocals paramSigs (infer body) pure (TFun tparams tbody, (params, (body', tbody))) inferFunMatch :: SrcPos -> [(Parsed.FunPats, Parsed.Expr)] -> Infer (Type, Fun) inferFunMatch pos cases = do arity <- checkCasePatternsArity tpats <- replicateM arity fresh (tbody, cases') <- inferCases tpats cases funMatchToFun pos cases' tpats tbody where checkCasePatternsArity = case cases of [] -> ice "inferFunMatch: checkCasePatternsArity: fun* has no cases, arity 0" (pats0, _) : rest -> do let arity = length (unpos pats0) forM_ rest $ \(WithPos pos pats, _) -> unless (length pats == arity) (throwError (FunCaseArityMismatch pos arity (length pats))) pure arity funMatchToFun :: SrcPos -> Cases -> [Type] -> Type -> Infer (Type, Fun) funMatchToFun pos cases' tpats tbody = genParams (length tpats) $ \paramNames -> do let paramNames' = zipWith fromMaybe paramNames $ case cases' of [(WithPos _ ps, _)] -> flip map ps $ \(Pat _ _ p) -> case p of PVar (TypedVar x _) -> Just x _ -> Nothing _ -> repeat Nothing params = zip paramNames' tpats args = map (Var . (NonVirt, ) . uncurry TypedVar) params pure (TFun tpats tbody, (params, (Match (WithPos pos (args, cases', tpats, tbody)), tbody))) inferCases -> [(WithPos [Parsed.Pat], Parsed.Expr)] -> Infer (Type, Cases) inferCases tmatchees cases = do (tpatss, tbodies, cases') <- fmap unzip3 (mapM (uncurry inferCase) cases) forM_ tpatss $ zipWithM (unify . Expected) tmatchees tbody <- fresh forM_ tbodies (unify (Expected tbody)) pure (tbody, cases') inferCase :: WithPos [Parsed.Pat] -> Parsed.Expr -> Infer ([FoundType], FoundType, (WithPos [Pat], Expr)) inferCase (WithPos pos ps) b = do (tps, ps', pvss) <- fmap unzip3 (mapM inferPat ps) let pvs' = map (bimap Parsed.idstr (Forall Set.empty Set.empty . TVar)) (Map.toList (Map.unions pvss)) (tb, b') <- withLocals pvs' (infer b) let tps' = zipWith Found (map getPos ps) tps pure (tps', Found (getPos b) tb, (WithPos pos ps', b')) | Returns the type of the pattern ; the pattern in the format that the Match module wants , inferPat :: Parsed.Pat -> Infer (Type, Pat, Map (Id 'Small) TVar) inferPat pat = fmap (\(t, p, ss) -> (t, Pat (getPos pat) t p, ss)) (inferPat' pat) where inferPat' = \case Parsed.PConstruction pos c ps -> inferPatConstruction pos c ps Parsed.PInt _ n -> pure (TPrim TIntSize, intToPCon n 64, Map.empty) Parsed.PStr _ s -> let span' = ice "span of Con with VariantStr" p = PCon (Con (VariantStr s) span' []) [] in pure (tStr, p, Map.empty) Parsed.PVar (Id (WithPos _ "_")) -> do tv <- fresh pure (tv, PWild, Map.empty) Parsed.PVar x@(Id (WithPos _ x')) -> do tv <- fresh' pure (TVar tv, PVar (TypedVar x' (TVar tv)), Map.singleton x tv) Parsed.PBox _ p -> do (tp', p', vs) <- inferPat p pure (TBox tp', PBox p', vs) intToPCon n w = PCon (Con { variant = VariantIx (fromIntegral n), span = 2 ^ (w :: Integer), argTs = [] }) [] inferPatConstruction :: SrcPos -> Id 'Big -> [Parsed.Pat] -> Infer (Type, Pat', Map (Id 'Small) TVar) inferPatConstruction pos c cArgs = do (variantIx, tdefLhs, cParams, cSpan) <- lookupEnvConstructor c let arity = length cParams let nArgs = length cArgs unless (arity == nArgs) (throwError (CtorArityMismatch pos (idstr c) arity nArgs)) (tdefInst, cParams') <- instantiateConstructorOfTypeDef tdefLhs cParams let t = TConst tdefInst (cArgTs, cArgs', cArgsVars) <- fmap unzip3 (mapM inferPat cArgs) cArgsVars' <- nonconflictingPatVarDefs cArgsVars forM_ (zip3 cParams' cArgTs cArgs) $ \(cParamT, cArgT, cArg) -> unify (Expected cParamT) (Found (getPos cArg) cArgT) let con = Con { variant = VariantIx variantIx, span = cSpan, argTs = cArgTs } pure (t, PCon con cArgs', cArgsVars') nonconflictingPatVarDefs = flip foldM Map.empty $ \acc ks -> case listToMaybe (Map.keys (Map.intersection acc ks)) of Just (Id (WithPos pos v)) -> throwError (ConflictingPatVarDefs pos v) Nothing -> pure (Map.union acc ks) instantiateConstructorOfTypeDef :: (String, [TVar]) -> [Type] -> Infer (TConst, [Type]) instantiateConstructorOfTypeDef (tName, tParams) cParams = do tVars <- mapM (const fresh) tParams let cParams' = map (subst (Map.fromList (zip tParams tVars))) cParams pure ((tName, tVars), cParams') lookupEnvConstructor :: Id 'Big -> Infer (VariantIx, (String, [TVar]), [Type], Span) lookupEnvConstructor (Id (WithPos pos cx)) = view (envCtors . to (Map.lookup cx)) >>= maybe (throwError (UndefCtor pos cx)) pure litType :: Const -> Type litType = \case Int _ -> TPrim TIntSize F64 _ -> TPrim TF64 Str _ -> tStr lookupVar :: Id 'Small -> Infer (Type, Var) lookupVar (Id (WithPos pos x)) = do virt <- fmap (Map.lookup x) (view envVirtuals) glob <- fmap (Map.lookup x) (view envGlobDefs) local <- fmap (Map.lookup x) (view envLocalDefs) case fmap (NonVirt, ) (local <|> glob) <|> fmap (Virt, ) virt of Just (virt, scm) -> instantiate pos scm <&> \t -> (t, (virt, TypedVar x t)) Nothing -> throwError (UndefVar pos x) genParams :: Integral n => n -> ([String] -> Infer a) -> Infer a genParams n f = do ps <- view (freshParams . to (take (fromIntegral n))) locally freshParams (drop (fromIntegral n)) (f ps) withLocals :: [(String, Scheme)] -> Infer a -> Infer a withLocals = augment envLocalDefs . Map.fromList instantiate :: SrcPos -> Scheme -> Infer Type instantiate pos (Forall params constraints t) = do s <- Map.fromList <$> zipWithM (fmap . (,)) (Set.toList params) (repeat fresh) forM_ constraints $ \c -> unifyClass pos (substClassConstraint s c) pure (subst s t) generalize :: (MonadError TypeErr m) => Map String Scheme -> Maybe (Set ClassConstraint) -> Map ClassConstraint SrcPos -> Type -> m Scheme generalize env mayGivenCs allCs t = fmap (\cs -> Forall vs cs t) constraints where A constraint should be included in a signature if the type variables include at least one of the signature 's forall - qualified tvars , and the rest of the tvars exist in the surrounding constraints = fmap (Set.fromList . map fst) $ flip filterM (Map.toList allCs) $ \(c, pos) -> let vcs = ftvClassConstraint c belongs = any (flip Set.member vs) vcs && all (\vc -> Set.member vc vs || Set.member vc ftvEnv) vcs in if belongs then if matchesGiven c then pure True else throwError (NoClassInstance pos c) else pure False matchesGiven = case mayGivenCs of Just gcs -> flip Set.member gcs Nothing -> const True vs = Set.difference (ftv t) ftvEnv ftvEnv = Set.unions (map ftvScheme (Map.elems env)) ftvScheme (Forall tvs _ t) = Set.difference (ftv t) tvs substEnv :: Subst' -> Map String Scheme -> Map String Scheme substEnv s = over (mapped . scmBody) (subst s) ftvClassConstraint :: ClassConstraint -> Set TVar ftvClassConstraint = mconcat . map ftv . snd substClassConstraint :: Subst' -> ClassConstraint -> ClassConstraint substClassConstraint sub = second (map (subst sub)) fresh :: Infer Type fresh = fmap TVar fresh' fresh' :: Infer TVar fresh' = fmap TVImplicit (gets head <* modify tail) unify :: ExpectedType -> FoundType -> Infer () unify e f = tell ([(e, f)], []) unifyClass :: SrcPos -> ClassConstraint -> Infer () unifyClass p c = tell ([], [(p, c)]) data UnifyErr = UInfType TVar Type | UFailed Type Type solve :: Constraints -> Infer (Subst', Map ClassConstraint SrcPos) solve (eqcs, ccs) = do sub <- lift $ lift $ lift $ solveUnis Map.empty eqcs ccs' <- solveClassCs (map (second (substClassConstraint sub)) ccs) pure (sub, ccs') where solveUnis :: Subst' -> [EqConstraint] -> Except TypeErr Subst' solveUnis sub1 = \case [] -> pure sub1 (Expected et, Found pos ft) : cs -> do sub2 <- withExcept (toTypeErr pos et ft) (unifies et ft) solveUnis (composeSubsts sub2 sub1) (map (substConstraint sub2) cs) solveClassCs :: [(SrcPos, ClassConstraint)] -> Infer (Map ClassConstraint SrcPos) solveClassCs = fmap Map.unions . mapM solveClassConstraint solveClassConstraint :: (SrcPos, ClassConstraint) -> Infer (Map ClassConstraint SrcPos) solveClassConstraint (pos, c) = case c of ("SameSize", [ta, tb]) -> sameSize (ta, tb) ("Cast", [ta, tb]) -> cast (ta, tb) ("Num", [ta]) -> case ta of TPrim _ -> ok TVar _ -> propagate TConst _ -> err TFun _ _ -> err TBox _ -> err ("Bitwise", [ta]) -> case ta of TPrim p | isIntegral p -> ok TPrim _ -> err TVar _ -> propagate TConst _ -> err TFun _ _ -> err TBox _ -> err ("Ord", [ta]) -> case ta of TPrim _ -> ok TVar _ -> propagate TConst _ -> err TFun _ _ -> err TBox _ -> err _ -> ice $ "solveClassCs: invalid class constraint " ++ show c where ok = pure Map.empty propagate = pure (Map.singleton c pos) err = throwError (NoClassInstance pos c) isIntegral = \case TInt _ -> True TIntSize -> True TNat _ -> True TNatSize -> True _ -> False | As the name indicates , a predicate that is true / class that is instanced when two sameSize :: (Type, Type) -> Infer (Map ClassConstraint SrcPos) sameSize (ta, tb) = do sizeof'' <- sizeof . sizeofTypeDef <$> view envTypeDefs case liftA2 (==) (sizeof'' ta) (sizeof'' tb) of _ | ta == tb -> ok Right True -> ok Right False -> err One or both of the two types are of unknown size due to polymorphism , so Left _ -> propagate sizeofTypeDef tdefs (x, args) = case Map.lookup x tdefs of Just (params, Data variants) -> let sub = Map.fromList (zip params args) datas = map (map (subst sub) . snd) variants in sizeofData (sizeofTypeDef tdefs) (alignofTypeDef tdefs) datas Just (params, Alias _ t) -> let sub = Map.fromList (zip params args) in sizeof (sizeofTypeDef tdefs) (subst sub t) Nothing -> ice $ "Infer.sizeofTypeDef: undefined type " ++ show x alignofTypeDef tdefs (x, args) = case Map.lookup x tdefs of Just (params, Data variants) -> let sub = Map.fromList (zip params args) datas = map (map (subst sub) . snd) variants in alignmentofData (alignofTypeDef tdefs) datas Just (params, Alias _ t) -> let sub = Map.fromList (zip params args) in alignmentof (alignofTypeDef tdefs) (subst sub t) Nothing -> ice $ "Infer.sizeofTypeDef: undefined type " ++ show x | This class is instanced when the first type can be ` cast ` to the other . cast :: (Type, Type) -> Infer (Map ClassConstraint SrcPos) cast = \case (ta, tb) | ta == tb -> ok (TPrim _, TPrim _) -> ok (TVar _, _) -> propagate (_, TVar _) -> propagate (TConst _, _) -> err (_, TConst _) -> err (TFun _ _, _) -> err (_, TFun _ _) -> err (TBox _, _) -> err (_, TBox _) -> err substConstraint sub (Expected t1, Found pos t2) = (Expected (subst sub t1), Found pos (subst sub t2)) toTypeErr :: SrcPos -> Type -> Type -> UnifyErr -> TypeErr toTypeErr pos t1 t2 = \case UInfType a t -> InfType pos t1 t2 a t UFailed t'1 t'2 -> UnificationFailed pos t1 t2 t'1 t'2 unifies :: Type -> Type -> Except UnifyErr Subst' unifies = curry $ \case (TPrim a, TPrim b) | a == b -> pure Map.empty (TConst (c0, ts0), TConst (c1, ts1)) | c0 == c1 -> if length ts0 /= length ts1 then ice "lengths of TConst params differ in unify" else unifiesMany (zip ts0 ts1) (TVar a, TVar b) | a == b -> pure Map.empty (TVar a, t) | occursIn a t -> throwError (UInfType a t) (a@(TVar (TVExplicit _)), b@(TVar (TVImplicit _))) -> unifies b a (a@(TVar (TVExplicit _)), b) -> throwError (UFailed a b) (TVar a, t) -> pure (Map.singleton a t) (t, TVar a) -> unifies (TVar a) t (t@(TFun ts1 t2), u@(TFun us1 u2)) -> if length ts1 /= length us1 then throwError (UFailed t u) else unifiesMany (zip (ts1 ++ [t2]) (us1 ++ [u2])) (TBox t, TBox u) -> unifies t u (t1, t2) -> throwError (UFailed t1 t2) where unifiesMany :: [(Type, Type)] -> Except UnifyErr Subst' unifiesMany = foldM (\s (t, u) -> fmap (flip composeSubsts s) (unifies (subst s t) (subst s u))) Map.empty occursIn :: TVar -> Type -> Bool occursIn a t = Set.member a (ftv t)
52800d8fdd4285bdff3a8a90e419fa04d22f5a0ade1098fa2878492e9f0eac90
flavioc/cl-hurd
io-get-openmodes.lisp
(in-package :hurd-translator) (def-io-interface :io-get-openmodes ((port port) (bits :pointer)) (with-lookup protid port (setf (mem-ref bits 'open-flags) (only-flags (flags (open-node protid)) +honored-get-modes+)) t))
null
https://raw.githubusercontent.com/flavioc/cl-hurd/982232f47d1a0ff4df5fde2edad03b9df871470a/translator/interfaces/io-get-openmodes.lisp
lisp
(in-package :hurd-translator) (def-io-interface :io-get-openmodes ((port port) (bits :pointer)) (with-lookup protid port (setf (mem-ref bits 'open-flags) (only-flags (flags (open-node protid)) +honored-get-modes+)) t))
7e2af83cb2b8f18a388246bc9cc556c54a9023046b6b9b2f41e0b028818f032f
dgiot/dgiot
modbus_tcp_server.erl
%%-------------------------------------------------------------------- Copyright ( c ) 2020 - 2021 DGIOT 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(modbus_tcp_server). %%-author("johnliu"). %%-include_lib("dgiot/include/dgiot_socket.hrl"). %%-include("dgiot_meter.hrl"). %%%% API %%-export([start/2]). %% %%%% TCP callback %%-export([init/1, handle_info/2, handle_cast/2, handle_call/3, terminate/2, code_change/3]). %% start(Port , State ) - > dgiot_tcp_server : child_spec(?MODULE , dgiot_utils : ) , State ) . %% %%%% ======================= %%%% tcp server start %%%% {ok, State} | {stop, Reason} %%init(TCPState) -> { ok , TCPState } . %% %%%%设备登录报文,登陆成功后,开始搜表 handle_info({tcp , DtuAddr } , # tcp{socket = Socket , state = # state{id = ChannelId , dtuaddr = < < > > } = State } = TCPState ) when byte_size(DtuAddr ) = = 15 - > ? ~p " , [ DtuAddr , ChannelId ] ) , %% DTUIP = dgiot_utils:get_ip(Socket), dgiot_meter : create_dtu(DtuAddr , ChannelId , DTUIP ) , { Ref , Step } = dgiot_smartmeter : search_meter(tcp , undefined , TCPState , 1 ) , { noreply , TCPState#tcp{buff = < < > > , state = State#state{dtuaddr = DtuAddr , ref = Ref , step = Step } } } ; %% %%%%设备登录异常报文丢弃 handle_info({tcp , } , # tcp{state = # state{dtuaddr = < < > > } } = TCPState ) - > ? LOG(info,"ErrorBuff ~p " , [ ErrorBuff ] ) , { noreply , TCPState#tcp{buff = < < > > } } ; %% %% %%%%定时器触发搜表 , # tcp{state = # state{ref = Ref } = State } = TCPState ) - > { NewRef , Step } = dgiot_smartmeter : search_meter(tcp , Ref , TCPState , 1 ) , { noreply , TCPState#tcp{buff = < < > > , state = State#state{ref = NewRef , step = Step } } } ; %% %%%%ACK报文触发搜表 handle_info({tcp , } , # tcp{socket = Socket , state = # state{id = ChannelId , , ref = Ref , step = search_meter } = State } = TCPState ) - > ? ~p " , [ dgiot_utils : binary_to_hex(Buff ) ] ) , %% lists:map(fun(X) -> %% case X of # { < < " addr " > > : = ? ~p " , [ ] ) , %% DTUIP = dgiot_utils:get_ip(Socket), dgiot_meter : create_meter(dgiot_utils : , ChannelId , DTUIP , DtuAddr ) ; %% _ -> %% pass %%异常报文丢弃 %% end end , dgiot_smartmeter : parse_frame(dlt645 , Buff , [ ] ) ) , { NewRef , Step } = dgiot_smartmeter : search_meter(tcp , Ref , TCPState , 1 ) , { noreply , TCPState#tcp{buff = < < > > , state = State#state{ref = NewRef , step = Step } } } ; %% %%%%接受抄表任务命令抄表 handle_info({deliver , _ Topic , Msg } , # tcp{state = # state{id = ChannelId , step = read_meter } } = TCPState ) - > case binary : : ) , < < $ / > > , [ global , trim ] ) of [ < < " thing " > > , _ ProductId , _ ] - > # { < < " thingdata " > > : = ThingData } = jsx : : get_payload(Msg ) , [ { labels , binary } , return_maps ] ) , %% Payload = dgiot_smartmeter:to_frame(ThingData), dgiot_bridge : send_log(ChannelId , " from_task : : ~ts " , [ _ Topic , unicode : : get_payload(Msg ) ) ] ) , %% ?LOG(info,"task->dev: Payload ~p", [dgiot_utils:binary_to_hex(Payload)]), %% dgiot_tcp_server:send(TCPState, Payload); %% _ -> %% pass %% end, { noreply , TCPState } ; %% 接收抄表任务的ACK报文 handle_info({tcp , } , # tcp{state = # state{id = ChannelId , step = read_meter } } = TCPState ) - > case dgiot_smartmeter : parse_frame(dlt645 , Buff , [ ] ) of [ # { < < " addr " > > : = , < < " value " > > : = Value } | _ ] - > case dgiot_data : get({meter , ChannelId } ) of { ProductId , _ ACL , _ Properties } - > DevAddr = dgiot_utils : , Topic = < < " thing/ " , ProductId / binary , " / " , / binary , " /post " > > , dgiot_mqtt : publish(DevAddr , Topic , : encode(Value ) ) ; %% _ -> pass %% end; %% _ -> pass %% end, { noreply , TCPState#tcp{buff = < < > > } } ; %% %%%% 异常报文丢弃 { stop , TCPState } | { stop , Reason } | { ok , TCPState } | ok | stop handle_info(_Info , TCPState ) - > { noreply , TCPState } . %% handle_call(_Msg , _ From , TCPState ) - > { reply , ok , TCPState } . %% handle_cast(_Msg , TCPState ) - > { noreply , TCPState } . %% terminate(_Reason , _ TCPState ) - > dgiot_metrics : dec(dgiot_meter , < < " dtu_login " > > , 1 ) , %% ok. %% code_change(_OldVsn , TCPState , _ Extra ) - > { ok , TCPState } .
null
https://raw.githubusercontent.com/dgiot/dgiot/c9f2f78af71692ba532e4806621b611db2afe0c9/apps/dgiot_modbus/src/modbus/modbus_tcp_server.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. -------------------------------------------------------------------- -author("johnliu"). -include_lib("dgiot/include/dgiot_socket.hrl"). -include("dgiot_meter.hrl"). API -export([start/2]). TCP callback -export([init/1, handle_info/2, handle_cast/2, handle_call/3, terminate/2, code_change/3]). ======================= tcp server start {ok, State} | {stop, Reason} init(TCPState) -> 设备登录报文,登陆成功后,开始搜表 DTUIP = dgiot_utils:get_ip(Socket), 设备登录异常报文丢弃 定时器触发搜表 ACK报文触发搜表 lists:map(fun(X) -> case X of DTUIP = dgiot_utils:get_ip(Socket), _ -> pass %%异常报文丢弃 end 接受抄表任务命令抄表 Payload = dgiot_smartmeter:to_frame(ThingData), ?LOG(info,"task->dev: Payload ~p", [dgiot_utils:binary_to_hex(Payload)]), dgiot_tcp_server:send(TCPState, Payload); _ -> pass end, _ -> pass end; _ -> pass end, 异常报文丢弃 ok.
Copyright ( c ) 2020 - 2021 DGIOT 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(modbus_tcp_server). start(Port , State ) - > dgiot_tcp_server : child_spec(?MODULE , dgiot_utils : ) , State ) . { ok , TCPState } . handle_info({tcp , DtuAddr } , # tcp{socket = Socket , state = # state{id = ChannelId , dtuaddr = < < > > } = State } = TCPState ) when byte_size(DtuAddr ) = = 15 - > ? ~p " , [ DtuAddr , ChannelId ] ) , dgiot_meter : create_dtu(DtuAddr , ChannelId , DTUIP ) , { Ref , Step } = dgiot_smartmeter : search_meter(tcp , undefined , TCPState , 1 ) , { noreply , TCPState#tcp{buff = < < > > , state = State#state{dtuaddr = DtuAddr , ref = Ref , step = Step } } } ; handle_info({tcp , } , # tcp{state = # state{dtuaddr = < < > > } } = TCPState ) - > ? LOG(info,"ErrorBuff ~p " , [ ErrorBuff ] ) , { noreply , TCPState#tcp{buff = < < > > } } ; , # tcp{state = # state{ref = Ref } = State } = TCPState ) - > { NewRef , Step } = dgiot_smartmeter : search_meter(tcp , Ref , TCPState , 1 ) , { noreply , TCPState#tcp{buff = < < > > , state = State#state{ref = NewRef , step = Step } } } ; handle_info({tcp , } , # tcp{socket = Socket , state = # state{id = ChannelId , , ref = Ref , step = search_meter } = State } = TCPState ) - > ? ~p " , [ dgiot_utils : binary_to_hex(Buff ) ] ) , # { < < " addr " > > : = ? ~p " , [ ] ) , dgiot_meter : create_meter(dgiot_utils : , ChannelId , DTUIP , DtuAddr ) ; end , dgiot_smartmeter : parse_frame(dlt645 , Buff , [ ] ) ) , { NewRef , Step } = dgiot_smartmeter : search_meter(tcp , Ref , TCPState , 1 ) , { noreply , TCPState#tcp{buff = < < > > , state = State#state{ref = NewRef , step = Step } } } ; handle_info({deliver , _ Topic , Msg } , # tcp{state = # state{id = ChannelId , step = read_meter } } = TCPState ) - > case binary : : ) , < < $ / > > , [ global , trim ] ) of [ < < " thing " > > , _ ProductId , _ ] - > # { < < " thingdata " > > : = ThingData } = jsx : : get_payload(Msg ) , [ { labels , binary } , return_maps ] ) , dgiot_bridge : send_log(ChannelId , " from_task : : ~ts " , [ _ Topic , unicode : : get_payload(Msg ) ) ] ) , { noreply , TCPState } ; 接收抄表任务的ACK报文 handle_info({tcp , } , # tcp{state = # state{id = ChannelId , step = read_meter } } = TCPState ) - > case dgiot_smartmeter : parse_frame(dlt645 , Buff , [ ] ) of [ # { < < " addr " > > : = , < < " value " > > : = Value } | _ ] - > case dgiot_data : get({meter , ChannelId } ) of { ProductId , _ ACL , _ Properties } - > DevAddr = dgiot_utils : , Topic = < < " thing/ " , ProductId / binary , " / " , / binary , " /post " > > , dgiot_mqtt : publish(DevAddr , Topic , : encode(Value ) ) ; { noreply , TCPState#tcp{buff = < < > > } } ; { stop , TCPState } | { stop , Reason } | { ok , TCPState } | ok | stop handle_info(_Info , TCPState ) - > { noreply , TCPState } . handle_call(_Msg , _ From , TCPState ) - > { reply , ok , TCPState } . handle_cast(_Msg , TCPState ) - > { noreply , TCPState } . terminate(_Reason , _ TCPState ) - > dgiot_metrics : dec(dgiot_meter , < < " dtu_login " > > , 1 ) , code_change(_OldVsn , TCPState , _ Extra ) - > { ok , TCPState } .
edcf68c011e65cf36958fb05c20b939b5311e80aeaef8170795ba275d624bcde
jrh13/hol-light
sigmacomplete.ml
(* ========================================================================= *) Sigma_1 completeness of 's axioms Q. (* ========================================================================= *) let robinson = new_definition `robinson = (!!0 (!!1 (Suc(V 0) === Suc(V 1) --> V 0 === V 1))) && (!!1 (Not(V 1 === Z) <-> ??0 (V 1 === Suc(V 0)))) && (!!1 (Z ++ V 1 === V 1)) && (!!0 (!!1 (Suc(V 0) ++ V 1 === Suc(V 0 ++ V 1)))) && (!!1 (Z ** V 1 === Z)) && (!!0 (!!1 (Suc(V 0) ** V 1 === V 1 ++ V 0 ** V 1))) && (!!0 (!!1 (V 0 <<= V 1 <-> ??2 (V 0 ++ V 2 === V 1)))) && (!!0 (!!1 (V 0 << V 1 <-> Suc(V 0) <<= V 1)))`;; (* ------------------------------------------------------------------------- *) (* Individual "axioms" and their instances. *) (* ------------------------------------------------------------------------- *) let [suc_inj; num_cases; add_0; add_suc; mul_0; mul_suc; le_def; lt_def] = CONJUNCTS(REWRITE_RULE[META_AND] (GEN_REWRITE_RULE RAND_CONV [robinson] (MATCH_MP assume (SET_RULE `robinson IN {robinson}`))));; let suc_inj' = prove (`!s t. {robinson} |-- Suc(s) === Suc(t) --> s === t`, REWRITE_TAC[specl_rule [`s:term`; `t:term`] suc_inj]);; let num_cases' = prove (`!t z. ~(z IN FVT t) ==> {robinson} |-- (Not(t === Z) <-> ??z (t === Suc(V z)))`, REPEAT STRIP_TAC THEN MP_TAC(SPEC `t:term` (MATCH_MP spec num_cases)) THEN REWRITE_TAC[formsubst] THEN CONV_TAC(ONCE_DEPTH_CONV TERMSUBST_CONV) THEN REWRITE_TAC[FV; FVT; SET_RULE `({1} UNION {0}) DELETE 0 = {1} DIFF {0}`] THEN REWRITE_TAC[IN_DIFF; IN_SING; UNWIND_THM2; GSYM CONJ_ASSOC; ASSIGN] THEN REWRITE_TAC[ARITH_EQ] THEN LET_TAC THEN MATCH_MP_TAC(REWRITE_RULE[IMP_CONJ_ALT] iff_trans) THEN SUBGOAL_THEN `~(z' IN FVT t)` ASSUME_TAC THENL [EXPAND_TAC "z'" THEN COND_CASES_TAC THEN ASM_SIMP_TAC[SET_RULE `a IN s ==> s UNION {a} = s`; VARIANT_FINITE; FVT_FINITE]; MATCH_MP_TAC imp_antisym THEN ASM_CASES_TAC `z':num = z` THEN ASM_REWRITE_TAC[imp_refl] THEN CONJ_TAC THEN MATCH_MP_TAC ichoose THEN ASM_REWRITE_TAC[FV; IN_DELETE; IN_UNION; IN_SING; FVT] THEN MATCH_MP_TAC gen THEN MATCH_MP_TAC imp_trans THENL [EXISTS_TAC `formsubst (z |=> V z') (t === Suc(V z))`; EXISTS_TAC `formsubst (z' |=> V z) (t === Suc(V z'))`] THEN REWRITE_TAC[iexists] THEN REWRITE_TAC[formsubst] THEN ASM_REWRITE_TAC[termsubst; ASSIGN] THEN MATCH_MP_TAC(MESON[imp_refl] `p = q ==> A |-- p --> q`) THEN AP_THM_TAC THEN AP_TERM_TAC THEN CONV_TAC SYM_CONV THEN MATCH_MP_TAC TERMSUBST_TRIVIAL THEN REWRITE_TAC[ASSIGN] THEN ASM_MESON_TAC[]]);; let add_0' = prove (`!t. {robinson} |-- Z ++ t === t`, REWRITE_TAC[spec_rule `t:term` add_0]);; let add_suc' = prove (`!s t. {robinson} |-- Suc(s) ++ t === Suc(s ++ t)`, REWRITE_TAC[specl_rule [`s:term`; `t:term`] add_suc]);; let mul_0' = prove (`!t. {robinson} |-- Z ** t === Z`, REWRITE_TAC[spec_rule `t:term` mul_0]);; let mul_suc' = prove (`!s t. {robinson} |-- Suc(s) ** t === t ++ s ** t`, REWRITE_TAC[specl_rule [`s:term`; `t:term`] mul_suc]);; let lt_def' = prove (`!s t. {robinson} |-- (s << t <-> Suc(s) <<= t)`, REWRITE_TAC[specl_rule [`s:term`; `t:term`] lt_def]);; (* ------------------------------------------------------------------------- *) (* All ground terms can be evaluated by proof. *) (* ------------------------------------------------------------------------- *) let SIGMA1_COMPLETE_ADD = prove (`!m n. {robinson} |-- numeral m ++ numeral n === numeral(m + n)`, INDUCT_TAC THEN REWRITE_TAC[ADD_CLAUSES; numeral] THEN ASM_MESON_TAC[add_0'; add_suc'; axiom_funcong; eq_trans; modusponens]);; let SIGMA1_COMPLETE_MUL = prove (`!m n. {robinson} |-- (numeral m ** numeral n === numeral(m * n))`, INDUCT_TAC THEN REWRITE_TAC[ADD_CLAUSES; MULT_CLAUSES; numeral] THENL [ASM_MESON_TAC[mul_0']; ALL_TAC] THEN GEN_TAC THEN MATCH_MP_TAC eq_trans_rule THEN EXISTS_TAC `numeral(n) ++ numeral(m * n)` THEN CONJ_TAC THENL [ASM_MESON_TAC[mul_suc'; eq_trans_rule; axiom_funcong; imp_trans; modusponens; imp_swap;add_assum; axiom_eqrefl]; ASM_MESON_TAC[SIGMA1_COMPLETE_ADD; ADD_SYM; eq_trans_rule]]);; let SIGMA1_COMPLETE_TERM = prove (`!v t n. FVT t = {} /\ termval v t = n ==> {robinson} |-- (t === numeral n)`, let lemma = prove(`(!n. p /\ (x = n) ==> P n) <=> p ==> P x`,MESON_TAC[]) in GEN_TAC THEN MATCH_MP_TAC term_INDUCT THEN REWRITE_TAC[termval;FVT; NOT_INSERT_EMPTY] THEN CONJ_TAC THENL [GEN_TAC THEN DISCH_THEN(SUBST1_TAC o SYM) THEN REWRITE_TAC[numeral] THEN MESON_TAC[axiom_eqrefl; add_assum]; ALL_TAC] THEN REWRITE_TAC[lemma] THEN REPEAT CONJ_TAC THEN REPEAT GEN_TAC THEN DISCH_THEN(fun th -> REPEAT STRIP_TAC THEN MP_TAC th) THEN RULE_ASSUM_TAC(REWRITE_RULE[EMPTY_UNION]) THEN ASM_REWRITE_TAC[numeral] THEN MESON_TAC[SIGMA1_COMPLETE_ADD; SIGMA1_COMPLETE_MUL; cong_suc; cong_add; cong_mul; eq_trans_rule]);; (* ------------------------------------------------------------------------- *) (* Convenient stepping theorems for atoms and other useful lemmas. *) (* ------------------------------------------------------------------------- *) let canonize_clauses = let lemma0 = MESON[imp_refl; imp_swap; modusponens; axiom_doubleneg] `!A p. A |-- (p --> False) --> False <=> A |-- p` and lemma1 = MESON[iff_imp1; iff_imp2; modusponens; imp_trans] `A |-- p <-> q ==> (A |-- p <=> A |-- q) /\ (A |-- p --> False <=> A |-- q --> False)` in itlist (CONJ o MATCH_MP lemma1 o SPEC_ALL) [axiom_true; axiom_not; axiom_and; axiom_or; iff_def; axiom_exists] lemma0 and false_imp = MESON[imp_truefalse; modusponens] `A |-- p /\ A |-- q --> False ==> A |-- (p --> q) --> False` and true_imp = MESON[axiom_addimp; modusponens; ex_falso; imp_trans] `A |-- p --> False \/ A |-- q ==> A |-- p --> q`;; let CANONIZE_TAC = REWRITE_TAC[canonize_clauses; imp_refl] THEN REPEAT((MATCH_MP_TAC false_imp THEN CONJ_TAC) ORELSE MATCH_MP_TAC true_imp THEN REWRITE_TAC[canonize_clauses; imp_refl]);; let suc_inj_eq = prove (`!s t. {robinson} |-- Suc s === Suc t <-> s === t`, MESON_TAC[suc_inj'; axiom_funcong; imp_antisym]);; let suc_le_eq = prove (`!s t. {robinson} |-- Suc s <<= Suc t <-> s <<= t`, gens_tac [0;1] THEN TRANS_TAC iff_trans `??2 (Suc(V 0) ++ V 2 === Suc(V 1))` THEN REWRITE_TAC[itlist spec_rule [`Suc(V 1)`; `Suc(V 0)`] le_def] THEN TRANS_TAC iff_trans `??2 (V 0 ++ V 2 === V 1)` THEN GEN_REWRITE_TAC RAND_CONV [iff_sym] THEN REWRITE_TAC[itlist spec_rule [`V 1`; `V 0`] le_def] THEN MATCH_MP_TAC exiff THEN TRANS_TAC iff_trans `Suc(V 0 ++ V 2) === Suc(V 1)` THEN REWRITE_TAC[suc_inj_eq] THEN MATCH_MP_TAC cong_eq THEN REWRITE_TAC[axiom_eqrefl; add_suc']);; let le_iff_lt = prove (`!s t. {robinson} |-- s <<= t <-> s << Suc t`, REPEAT GEN_TAC THEN TRANS_TAC iff_trans `Suc s <<= Suc t` THEN ONCE_REWRITE_TAC[iff_sym] THEN REWRITE_TAC[suc_le_eq; lt_def']);; let suc_lt_eq = prove (`!s t. {robinson} |-- Suc s << Suc t <-> s << t`, MESON_TAC[iff_sym; iff_trans; le_iff_lt; lt_def']);; let not_suc_eq_0 = prove (`!t. {robinson} |-- Suc t === Z --> False`, gen_tac 1 THEN SUBGOAL_THEN `{robinson} |-- Not(Suc(V 1) === Z)` MP_TAC THENL [ALL_TAC; REWRITE_TAC[canonize_clauses]] THEN SUBGOAL_THEN `{robinson} |-- ?? 0 (Suc(V 1) === Suc(V 0))` MP_TAC THENL [MATCH_MP_TAC exists_intro THEN EXISTS_TAC `V 1` THEN CONV_TAC(RAND_CONV FORMSUBST_CONV) THEN REWRITE_TAC[axiom_eqrefl]; MESON_TAC[iff_imp2; modusponens; spec_rule `Suc(V 1)` num_cases]]);; let not_suc_le_0 = prove (`!t. {robinson} |-- Suc t <<= Z --> False`, X_GEN_TAC `s:term` THEN SUBGOAL_THEN `{robinson} |-- !!0 (Suc(V 0) <<= Z --> False)` MP_TAC THENL [ALL_TAC; DISCH_THEN(ACCEPT_TAC o spec_rule `s:term`)] THEN MATCH_MP_TAC gen THEN SUBGOAL_THEN `{robinson} |-- ?? 2 (Suc (V 0) ++ V 2 === Z) --> False` MP_TAC THENL [ALL_TAC; MATCH_MP_TAC(REWRITE_RULE[IMP_CONJ] imp_trans) THEN MATCH_MP_TAC iff_imp1 THEN ACCEPT_TAC(itlist spec_rule [`Z`; `Suc(V 0)`] le_def)] THEN MATCH_MP_TAC ichoose THEN REWRITE_TAC[FV; NOT_IN_EMPTY] THEN MATCH_MP_TAC gen THEN TRANS_TAC imp_trans `Suc(V 0 ++ V 2) === Z` THEN REWRITE_TAC[not_suc_eq_0] THEN MATCH_MP_TAC iff_imp1 THEN MATCH_MP_TAC cong_eq THEN REWRITE_TAC[axiom_eqrefl] THEN REWRITE_TAC[add_suc']);; let not_lt_0 = prove (`!t. {robinson} |-- t << Z --> False`, MESON_TAC[not_suc_le_0; lt_def'; imp_trans; iff_imp1]);; (* ------------------------------------------------------------------------- *) (* Evaluation of atoms built from numerals by proof. *) (* ------------------------------------------------------------------------- *) let add_0_right = prove (`!n. {robinson} |-- numeral n ++ Z === numeral n`, GEN_TAC THEN MP_TAC(ISPECL [`n:num`; `0`] SIGMA1_COMPLETE_ADD) THEN REWRITE_TAC[numeral; ADD_CLAUSES]);; let ATOM_EQ_FALSE = prove (`!m n. ~(m = n) ==> {robinson} |-- numeral m === numeral n --> False`, ONCE_REWRITE_TAC[SWAP_FORALL_THM] THEN MATCH_MP_TAC WLOG_LT THEN REWRITE_TAC[] THEN CONJ_TAC THENL [MESON_TAC[eq_sym; imp_trans]; ALL_TAC] THEN ONCE_REWRITE_TAC[SWAP_FORALL_THM] THEN INDUCT_TAC THEN REWRITE_TAC[CONJUNCT1 LT] THEN INDUCT_TAC THEN REWRITE_TAC[numeral; not_suc_eq_0; LT_SUC; SUC_INJ] THEN ASM_MESON_TAC[suc_inj_eq; imp_trans; iff_imp1; iff_imp2]);; let ATOM_LE_FALSE = prove (`!m n. n < m ==> {robinson} |-- numeral m <<= numeral n --> False`, INDUCT_TAC THEN REWRITE_TAC[CONJUNCT1 LT] THEN INDUCT_TAC THEN REWRITE_TAC[numeral; not_suc_le_0; LT_SUC] THEN ASM_MESON_TAC[suc_le_eq; imp_trans; iff_imp1; iff_imp2]);; let ATOM_LT_FALSE = prove (`!m n. n <= m ==> {robinson} |-- numeral m << numeral n --> False`, REPEAT GEN_TAC THEN REWRITE_TAC[GSYM LT_SUC_LE] THEN DISCH_THEN(MP_TAC o MATCH_MP ATOM_LE_FALSE) THEN REWRITE_TAC[numeral] THEN ASM_MESON_TAC[lt_def'; imp_trans; iff_imp1; iff_imp2]);; let ATOM_EQ_TRUE = prove (`!m n. m = n ==> {robinson} |-- numeral m === numeral n`, MESON_TAC[axiom_eqrefl]);; let ATOM_LE_TRUE = prove (`!m n. m <= n ==> {robinson} |-- numeral m <<= numeral n`, SUBGOAL_THEN `!m n. {robinson} |-- numeral m <<= numeral(m + n)` MP_TAC THENL [ALL_TAC; MESON_TAC[LE_EXISTS]] THEN REPEAT GEN_TAC THEN MATCH_MP_TAC modusponens THEN EXISTS_TAC `?? 2 (numeral m ++ V 2 === numeral(m + n))` THEN CONJ_TAC THENL [MP_TAC(itlist spec_rule [`numeral(m + n)`; `numeral m`] le_def) THEN MESON_TAC[iff_imp2]; MATCH_MP_TAC exists_intro THEN EXISTS_TAC `numeral n` THEN CONV_TAC(RAND_CONV FORMSUBST_CONV) THEN REWRITE_TAC[SIGMA1_COMPLETE_ADD]]);; let ATOM_LT_TRUE = prove (`!m n. m < n ==> {robinson} |-- numeral m << numeral n`, REPEAT GEN_TAC THEN REWRITE_TAC[GSYM LE_SUC_LT] THEN DISCH_THEN(MP_TAC o MATCH_MP ATOM_LE_TRUE) THEN REWRITE_TAC[numeral] THEN ASM_MESON_TAC[lt_def'; modusponens; iff_imp1; iff_imp2]);; (* ------------------------------------------------------------------------- *) A kind of case analysis rule ; might make it induction in case of PA . (* ------------------------------------------------------------------------- *) let FORMSUBST_FORMSUBST_SAME_NONE = prove (`!s t x p. FVT t = {x} /\ FVT s = {} ==> formsubst (x |=> s) (formsubst (x |=> t) p) = formsubst (x |=> termsubst (x |=> s) t) p`, REWRITE_TAC[RIGHT_FORALL_IMP_THM] THEN REPEAT GEN_TAC THEN STRIP_TAC THEN SUBGOAL_THEN `!y. safe_for y (x |=> termsubst (x |=> s) t)` ASSUME_TAC THENL [GEN_TAC THEN REWRITE_TAC[SAFE_FOR_ASSIGN; TERMSUBST_FVT; ASSIGN] THEN ASM SET_TAC[FVT]; ALL_TAC] THEN MATCH_MP_TAC form_INDUCT THEN ASM_SIMP_TAC[FORMSUBST_SAFE_FOR; SAFE_FOR_ASSIGN; IN_SING; NOT_IN_EMPTY] THEN SIMP_TAC[formsubst] THEN MATCH_MP_TAC(TAUT `(p /\ q /\ r) /\ s ==> p /\ q /\ r /\ s`) THEN CONJ_TAC THENL [REPEAT STRIP_TAC THEN BINOP_TAC THEN REWRITE_TAC[TERMSUBST_TERMSUBST] THEN AP_THM_TAC THEN AP_TERM_TAC THEN REWRITE_TAC[o_DEF; FUN_EQ_THM] THEN X_GEN_TAC `y:num` THEN REWRITE_TAC[ASSIGN] THEN COND_CASES_TAC THEN ASM_REWRITE_TAC[termsubst; ASSIGN]; CONJ_TAC THEN MAP_EVERY X_GEN_TAC [`y:num`; `p:form`] THEN DISCH_TAC THEN (ASM_CASES_TAC `y:num = x` THENL [ASM_REWRITE_TAC[assign; VALMOD_VALMOD_BASIC] THEN SIMP_TAC[VALMOD_TRIVIAL; FORMSUBST_TRIV]; SUBGOAL_THEN `!u. (y |-> V y) (x |=> u) = (x |=> u)` (fun th -> ASM_REWRITE_TAC[th]) THEN GEN_TAC THEN MATCH_MP_TAC VALMOD_TRIVIAL THEN ASM_REWRITE_TAC[ASSIGN]])]);; let num_cases_rule = prove (`!p x. {robinson} |-- formsubst (x |=> Z) p /\ {robinson} |-- formsubst (x |=> Suc(V x)) p ==> {robinson} |-- p`, let lemma = prove (`!A p x t. A |-- formsubst (x |=> t) p ==> A |-- V x === t --> p`, REPEAT GEN_TAC THEN MATCH_MP_TAC(REWRITE_RULE[IMP_CONJ] modusponens) THEN MATCH_MP_TAC imp_swap THEN GEN_REWRITE_TAC (funpow 3 RAND_CONV) [GSYM FORMSUBST_TRIV] THEN CONV_TAC(funpow 3 RAND_CONV(SUBS_CONV[SYM(SPEC `x:num` ASSIGN_TRIV)])) THEN TRANS_TAC imp_trans `t === V x` THEN REWRITE_TAC[isubst; eq_sym]) in REPEAT GEN_TAC THEN GEN_REWRITE_TAC (RAND_CONV o RAND_CONV) [GSYM FORMSUBST_TRIV] THEN CONV_TAC(RAND_CONV(SUBS_CONV[SYM(SPEC `x:num` ASSIGN_TRIV)])) THEN SUBGOAL_THEN `?z. ~(z = x) /\ ~(z IN VARS p)` STRIP_ASSUME_TAC THENL [EXISTS_TAC `VARIANT(x INSERT VARS p)` THEN REWRITE_TAC[GSYM DE_MORGAN_THM; GSYM IN_INSERT] THEN MATCH_MP_TAC NOT_IN_VARIANT THEN SIMP_TAC[VARS_FINITE; FINITE_INSERT; SUBSET_REFL]; ALL_TAC] THEN FIRST_X_ASSUM(fun th -> ONCE_REWRITE_TAC[GSYM(MATCH_MP FORMSUBST_TWICE th)]) THEN SUBGOAL_THEN `~(x IN FV(formsubst (x |=> V z) p))` MP_TAC THENL [REWRITE_TAC[FORMSUBST_FV; IN_ELIM_THM; ASSIGN; NOT_EXISTS_THM] THEN GEN_TAC THEN COND_CASES_TAC THEN ASM_REWRITE_TAC[FVT] THEN ASM SET_TAC[]; ALL_TAC] THEN SPEC_TAC(`formsubst (x |=> V z) p`,`p:form`) THEN REPEAT STRIP_TAC THEN MATCH_MP_TAC spec THEN MATCH_MP_TAC gen THEN FIRST_X_ASSUM(MP_TAC o MATCH_MP lemma) THEN DISCH_THEN(MP_TAC o SPEC `x:num` o MATCH_MP gen) THEN DISCH_THEN(MP_TAC o MATCH_MP (REWRITE_RULE[IMP_CONJ] ichoose)) THEN FIRST_X_ASSUM(MP_TAC o MATCH_MP lemma) THEN ASM_REWRITE_TAC[IMP_IMP] THEN DISCH_THEN(MP_TAC o MATCH_MP ante_disj) THEN MATCH_MP_TAC(REWRITE_RULE[IMP_CONJ_ALT] modusponens) THEN MP_TAC(ISPECL [`V z`; `x:num`] num_cases') THEN ASM_REWRITE_TAC[FVT; IN_SING] THEN DISCH_THEN(MP_TAC o MATCH_MP iff_imp1) THEN REWRITE_TAC[canonize_clauses] THEN MATCH_MP_TAC(REWRITE_RULE[IMP_CONJ_ALT] imp_trans) THEN MESON_TAC[imp_swap; axiom_not; iff_imp1; imp_trans]);; (* ------------------------------------------------------------------------- *) (* Now full Sigma-1 completeness. *) (* ------------------------------------------------------------------------- *) let SIGMAPI1_COMPLETE = prove (`!v p b. sigmapi b 1 p /\ closed p ==> (b /\ holds v p ==> {robinson} |-- p) /\ (~b /\ ~holds v p ==> {robinson} |-- p --> False)`, let lemma1 = prove (`!x n p. (!m. m < n ==> {robinson} |-- formsubst (x |=> numeral m) p) ==> {robinson} |-- !!x (V x << numeral n --> p)`, GEN_TAC THEN INDUCT_TAC THEN X_GEN_TAC `p:form` THEN DISCH_TAC THEN REWRITE_TAC[numeral] THENL [ASM_MESON_TAC[gen; imp_trans; ex_falso; not_lt_0]; ALL_TAC] THEN MATCH_MP_TAC gen THEN MATCH_MP_TAC num_cases_rule THEN EXISTS_TAC `x:num` THEN CONJ_TAC THENL [ONCE_REWRITE_TAC[formsubst] THEN MATCH_MP_TAC add_assum THEN REWRITE_TAC[GSYM numeral] THEN FIRST_X_ASSUM MATCH_MP_TAC THEN ARITH_TAC; ALL_TAC] THEN REWRITE_TAC[formsubst; termsubst; TERMSUBST_NUMERAL; ASSIGN] THEN TRANS_TAC imp_trans `V x << numeral n` THEN CONJ_TAC THENL [MESON_TAC[suc_lt_eq; iff_imp1]; ALL_TAC] THEN MATCH_MP_TAC spec_var THEN EXISTS_TAC `x:num` THEN FIRST_X_ASSUM MATCH_MP_TAC THEN X_GEN_TAC `m:num` THEN DISCH_TAC THEN FIRST_X_ASSUM(MP_TAC o SPEC `SUC m`) THEN ASM_REWRITE_TAC[LT_SUC] THEN MATCH_MP_TAC EQ_IMP THEN AP_TERM_TAC THEN W(MP_TAC o PART_MATCH (lhs o rand) FORMSUBST_FORMSUBST_SAME_NONE o rand o snd) THEN REWRITE_TAC[FVT; FVT_NUMERAL] THEN DISCH_THEN SUBST1_TAC THEN REWRITE_TAC[termsubst; ASSIGN; numeral]) in let lemma2 = prove (`!x n p. (!m. m <= n ==> {robinson} |-- formsubst (x |=> numeral m) p) ==> {robinson} |-- !!x (V x <<= numeral n --> p)`, REPEAT STRIP_TAC THEN MP_TAC(ISPECL [`x:num`; `SUC n`; `p:form`] lemma1) THEN ASM_REWRITE_TAC[LT_SUC_LE] THEN DISCH_TAC THEN MATCH_MP_TAC gen THEN FIRST_ASSUM(MP_TAC o MATCH_MP spec_var) THEN REWRITE_TAC[numeral] THEN MATCH_MP_TAC(REWRITE_RULE[IMP_CONJ] imp_trans) THEN MESON_TAC[iff_imp1; le_iff_lt]) in let lemma3 = prove (`!v x t p. FVT t = {} /\ (!m. m < termval v t ==> {robinson} |-- formsubst (x |=> numeral m) p) ==> {robinson} |-- !!x (V x << t --> p)`, REPEAT STRIP_TAC THEN MATCH_MP_TAC gen THEN FIRST_ASSUM(MP_TAC o MATCH_MP spec_var o MATCH_MP lemma1) THEN MATCH_MP_TAC(REWRITE_RULE[IMP_CONJ] imp_trans) THEN MATCH_MP_TAC iff_imp1 THEN MATCH_MP_TAC cong_lt THEN REWRITE_TAC[axiom_eqrefl] THEN MATCH_MP_TAC SIGMA1_COMPLETE_TERM THEN ASM_MESON_TAC[]) and lemma4 = prove (`!v x t p. FVT t = {} /\ (!m. m <= termval v t ==> {robinson} |-- formsubst (x |=> numeral m) p) ==> {robinson} |-- !!x (V x <<= t --> p)`, REPEAT STRIP_TAC THEN MATCH_MP_TAC gen THEN FIRST_ASSUM(MP_TAC o MATCH_MP spec_var o MATCH_MP lemma2) THEN MATCH_MP_TAC(REWRITE_RULE[IMP_CONJ] imp_trans) THEN MATCH_MP_TAC iff_imp1 THEN MATCH_MP_TAC cong_le THEN REWRITE_TAC[axiom_eqrefl] THEN MATCH_MP_TAC SIGMA1_COMPLETE_TERM THEN ASM_MESON_TAC[]) and lemma5 = prove (`!A x p q. A |-- !!x (p --> Not q) ==> A |-- !!x (Not(p && q))`, REPEAT STRIP_TAC THEN MATCH_MP_TAC gen THEN FIRST_ASSUM(MP_TAC o MATCH_MP spec_var) THEN REWRITE_TAC[canonize_clauses] THEN MESON_TAC[imp_trans; axiom_not; iff_imp1; iff_imp2]) in GEN_TAC THEN GEN_TAC THEN REWRITE_TAC[closed] THEN WF_INDUCT_TAC `complexity p` THEN POP_ASSUM MP_TAC THEN SPEC_TAC(`p:form`,`p:form`) THEN MATCH_MP_TAC form_INDUCT THEN REWRITE_TAC[SIGMAPI_CLAUSES; complexity; ARITH] THEN REWRITE_TAC[MESON[] `(if p then q else F) <=> p /\ q`] THEN ONCE_REWRITE_TAC [TAUT `a /\ b /\ c /\ d /\ e /\ f /\ g /\ h /\ i /\ j /\ k /\ l <=> (a /\ b) /\ (c /\ d /\ e) /\ f /\ (g /\ h /\ i /\ j) /\ (k /\ l)`] THEN CONJ_TAC THENL [CONJ_TAC THEN DISCH_THEN(K ALL_TAC) THEN REWRITE_TAC[holds] THEN MESON_TAC[imp_refl; truth]; ALL_TAC] THEN CONJ_TAC THENL [REPEAT CONJ_TAC THEN MAP_EVERY X_GEN_TAC [`s:term`; `t:term`] THEN DISCH_THEN(K ALL_TAC) THEN X_GEN_TAC `b:bool` THEN REWRITE_TAC[FV; EMPTY_UNION] THEN STRIP_TAC THEN MP_TAC(ISPECL [`v:num->num`; `t:term`; `termval v t`] SIGMA1_COMPLETE_TERM) THEN MP_TAC(ISPECL [`v:num->num`; `s:term`; `termval v s`] SIGMA1_COMPLETE_TERM) THEN ASM_REWRITE_TAC[IMP_IMP] THENL [DISCH_THEN(MP_TAC o MATCH_MP cong_eq); DISCH_THEN(MP_TAC o MATCH_MP cong_lt); DISCH_THEN(MP_TAC o MATCH_MP cong_le)] THEN STRIP_TAC THEN REWRITE_TAC[holds; NOT_LE; NOT_LT] THEN (REPEAT STRIP_TAC THENL [FIRST_X_ASSUM(MATCH_MP_TAC o MATCH_MP(REWRITE_RULE[IMP_CONJ] modusponens) o MATCH_MP iff_imp2); FIRST_X_ASSUM(MATCH_MP_TAC o MATCH_MP(REWRITE_RULE[IMP_CONJ] imp_trans) o MATCH_MP iff_imp1)]) THEN ASM_SIMP_TAC[ATOM_EQ_FALSE; ATOM_EQ_TRUE; ATOM_LT_FALSE; ATOM_LT_TRUE; ATOM_LE_FALSE; ATOM_LE_TRUE]; ALL_TAC] THEN CONJ_TAC THENL [X_GEN_TAC `p:form` THEN DISCH_THEN(K ALL_TAC) THEN DISCH_THEN(MP_TAC o SPEC `p:form`) THEN ANTS_TAC THENL [ARITH_TAC; DISCH_TAC] THEN X_GEN_TAC `b:bool` THEN REWRITE_TAC[FV] THEN STRIP_TAC THEN FIRST_X_ASSUM(MP_TAC o SPEC `~b`) THEN ASM_REWRITE_TAC[holds] THEN BOOL_CASES_TAC `b:bool` THEN CANONIZE_TAC THEN ASM_MESON_TAC[]; ALL_TAC] THEN CONJ_TAC THENL [REPEAT CONJ_TAC THEN MAP_EVERY X_GEN_TAC [`p:form`; `q:form`] THEN DISCH_THEN(K ALL_TAC) THEN DISCH_TAC THEN X_GEN_TAC `b:bool` THEN REWRITE_TAC[FV; EMPTY_UNION] THEN STRIP_TAC THEN FIRST_X_ASSUM(fun th -> MP_TAC(SPEC `p:form` th) THEN MP_TAC(SPEC `q:form` th)) THEN (ANTS_TAC THENL [ARITH_TAC; ALL_TAC]) THEN ONCE_REWRITE_TAC[TAUT `p ==> q ==> r <=> q ==> p ==> r`] THEN (ANTS_TAC THENL [ARITH_TAC; ASM_REWRITE_TAC[IMP_IMP]]) THEN ASM_REWRITE_TAC[holds; canonize_clauses] THENL [DISCH_THEN(CONJUNCTS_THEN(MP_TAC o SPEC `b:bool`)); DISCH_THEN(CONJUNCTS_THEN(MP_TAC o SPEC `b:bool`)); DISCH_THEN(CONJUNCTS_THEN2 (MP_TAC o SPEC `~b`) (MP_TAC o SPEC `b:bool`)); DISCH_THEN(CONJUNCTS_THEN(fun th -> MP_TAC(SPEC `~b` th) THEN MP_TAC(SPEC `b:bool` th)))] THEN ASM_REWRITE_TAC[] THEN BOOL_CASES_TAC `b:bool` THEN ASM_REWRITE_TAC[] THEN REPEAT STRIP_TAC THEN CANONIZE_TAC THEN TRY(FIRST_X_ASSUM(MATCH_MP_TAC o MATCH_MP (TAUT `~(p <=> q) ==> (p /\ ~q ==> r) /\ (~p /\ q ==> s) ==> r \/ s`)) THEN REPEAT STRIP_TAC THEN CANONIZE_TAC) THEN ASM_MESON_TAC[]; ALL_TAC] THEN CONJ_TAC THEN MAP_EVERY X_GEN_TAC [`x:num`; `p:form`] THEN DISCH_THEN(K ALL_TAC) THEN REWRITE_TAC[canonize_clauses; holds] THEN DISCH_TAC THEN X_GEN_TAC `b:bool` THENL [BOOL_CASES_TAC `b:bool` THEN ASM_REWRITE_TAC[] THENL [REWRITE_TAC[IMP_IMP; GSYM CONJ_ASSOC; FV] THEN ONCE_REWRITE_TAC[IMP_CONJ] THEN REWRITE_TAC[LEFT_IMP_EXISTS_THM] THEN MAP_EVERY X_GEN_TAC [`q:form`; `t:term`] THEN DISCH_THEN (CONJUNCTS_THEN2 (DISJ_CASES_THEN SUBST_ALL_TAC) ASSUME_TAC) THEN REWRITE_TAC[SIGMAPI_CLAUSES; FV; holds] THEN (ASM_CASES_TAC `FVT t = {}` THENL [ALL_TAC; ASM SET_TAC[]]) THEN (ASM_CASES_TAC `FV(q) SUBSET {x}` THENL [ALL_TAC; ASM SET_TAC[]]) THEN DISCH_THEN(CONJUNCTS_THEN2 ASSUME_TAC (MP_TAC o CONJUNCT2)) THEN ABBREV_TAC `n = termval v t` THEN ASM_SIMP_TAC[TERMVAL_VALMOD_OTHER; termval; VALMOD] THENL [DISCH_TAC THEN MATCH_MP_TAC lemma3; DISCH_TAC THEN MATCH_MP_TAC lemma4] THEN EXISTS_TAC `v:num->num` THEN ASM_REWRITE_TAC[] THEN X_GEN_TAC `m:num` THEN DISCH_TAC THEN FIRST_X_ASSUM(MP_TAC o SPEC `formsubst (x |=> numeral m) q`) THEN REWRITE_TAC[complexity; COMPLEXITY_FORMSUBST] THEN (ANTS_TAC THENL [ARITH_TAC; DISCH_THEN(MP_TAC o SPEC `T`)]) THEN REWRITE_TAC[IMP_IMP] THEN DISCH_THEN MATCH_MP_TAC THEN ASM_SIMP_TAC[SIGMAPI_FORMSUBST] THEN REWRITE_TAC[FORMSUBST_FV; ASSIGN] THEN REPLICATE_TAC 2 (ONCE_REWRITE_TAC[COND_RAND]) THEN REWRITE_TAC[FVT_NUMERAL; NOT_IN_EMPTY; FVT; IN_SING] THEN (CONJ_TAC THENL [ASM SET_TAC[]; ALL_TAC]) THEN FIRST_X_ASSUM(MP_TAC o SPEC `m:num`) THEN ASM_REWRITE_TAC[] THEN REWRITE_TAC[HOLDS_FORMSUBST] THEN MATCH_MP_TAC EQ_IMP THEN MATCH_MP_TAC HOLDS_VALUATION THEN X_GEN_TAC `y:num` THEN (ASM_CASES_TAC `y:num = x` THENL [ALL_TAC; ASM SET_TAC[]]) THEN ASM_REWRITE_TAC[o_DEF; ASSIGN; VALMOD; TERMVAL_NUMERAL]; STRIP_TAC THEN REWRITE_TAC[NOT_FORALL_THM; LEFT_IMP_EXISTS_THM] THEN X_GEN_TAC `n:num` THEN DISCH_TAC THEN MATCH_MP_TAC imp_trans THEN EXISTS_TAC `formsubst (x |=> numeral n) p` THEN REWRITE_TAC[ispec] THEN FIRST_X_ASSUM(MP_TAC o SPEC `formsubst (x |=> numeral n) p`) THEN REWRITE_TAC[COMPLEXITY_FORMSUBST; ARITH_RULE `n < n + 1`] THEN DISCH_THEN(MP_TAC o SPEC `F`) THEN ASM_SIMP_TAC[SIGMAPI_FORMSUBST; IMP_IMP] THEN DISCH_THEN MATCH_MP_TAC THEN CONJ_TAC THENL [UNDISCH_TAC `FV (!! x p) = {}` THEN REWRITE_TAC[FV; FORMSUBST_FV; SET_RULE `s DELETE a = {} <=> s = {} \/ s = {a}`] THEN STRIP_TAC THEN ASM_REWRITE_TAC[NOT_IN_EMPTY; IN_SING; EMPTY_GSPEC; ASSIGN; UNWIND_THM2; FVT_NUMERAL]; UNDISCH_TAC `~holds((x |-> n) v) p` THEN REWRITE_TAC[HOLDS_FORMSUBST; CONTRAPOS_THM] THEN MATCH_MP_TAC EQ_IMP THEN MATCH_MP_TAC HOLDS_VALUATION THEN RULE_ASSUM_TAC(REWRITE_RULE[FV]) THEN X_GEN_TAC `y:num` THEN ASM_CASES_TAC `y:num = x` THENL [ALL_TAC; ASM SET_TAC[]] THEN ASM_REWRITE_TAC[o_THM; ASSIGN; VALMOD; TERMVAL_NUMERAL]]]; BOOL_CASES_TAC `b:bool` THEN ASM_REWRITE_TAC[] THENL [REWRITE_TAC[FV] THEN STRIP_TAC THEN DISCH_THEN(X_CHOOSE_TAC `n:num`) THEN FIRST_X_ASSUM(MP_TAC o SPEC `formsubst (x |=> numeral n) (Not p)`) THEN REWRITE_TAC[COMPLEXITY_FORMSUBST; complexity] THEN ANTS_TAC THENL [ASM_ARITH_TAC; DISCH_THEN(MP_TAC o SPEC `F`)] THEN ASM_SIMP_TAC[IMP_IMP; SIGMAPI_CLAUSES; SIGMAPI_FORMSUBST] THEN ANTS_TAC THENL [REWRITE_TAC[FORMSUBST_FV; ASSIGN] THEN REPLICATE_TAC 2 (ONCE_REWRITE_TAC[COND_RAND]) THEN REWRITE_TAC[FVT_NUMERAL; NOT_IN_EMPTY; FVT; FV; IN_SING] THEN (CONJ_TAC THENL [ASM SET_TAC[]; ALL_TAC]) THEN UNDISCH_TAC `holds ((x |-> n) v) p` THEN REWRITE_TAC[formsubst; holds; HOLDS_FORMSUBST] THEN MATCH_MP_TAC EQ_IMP THEN MATCH_MP_TAC HOLDS_VALUATION THEN RULE_ASSUM_TAC(REWRITE_RULE[FV]) THEN X_GEN_TAC `y:num` THEN ASM_CASES_TAC `y:num = x` THENL [ALL_TAC; ASM SET_TAC[]] THEN ASM_REWRITE_TAC[o_THM; ASSIGN; VALMOD; TERMVAL_NUMERAL]; MATCH_MP_TAC(REWRITE_RULE[IMP_CONJ] imp_trans) THEN REWRITE_TAC[ispec]]; REWRITE_TAC[IMP_IMP; GSYM CONJ_ASSOC; FV] THEN ONCE_REWRITE_TAC[IMP_CONJ] THEN REWRITE_TAC[LEFT_IMP_EXISTS_THM] THEN MAP_EVERY X_GEN_TAC [`q:form`; `t:term`] THEN DISCH_THEN (CONJUNCTS_THEN2 (DISJ_CASES_THEN SUBST_ALL_TAC) ASSUME_TAC) THEN REWRITE_TAC[SIGMAPI_CLAUSES; FV; holds] THEN (ASM_CASES_TAC `FVT t = {}` THENL [ALL_TAC; ASM SET_TAC[]]) THEN (ASM_CASES_TAC `FV(q) SUBSET {x}` THENL [ALL_TAC; ASM SET_TAC[]]) THEN DISCH_THEN(CONJUNCTS_THEN2 ASSUME_TAC (MP_TAC o CONJUNCT2)) THEN ABBREV_TAC `n = termval v t` THEN ASM_SIMP_TAC[TERMVAL_VALMOD_OTHER; termval; VALMOD] THEN REWRITE_TAC[NOT_EXISTS_THM; TAUT `~(p /\ q) <=> p ==> ~q`] THEN DISCH_TAC THEN MATCH_MP_TAC lemma5 THENL [MATCH_MP_TAC lemma3; MATCH_MP_TAC lemma4] THEN EXISTS_TAC `v:num->num` THEN ASM_REWRITE_TAC[] THEN X_GEN_TAC `m:num` THEN DISCH_TAC THEN FIRST_X_ASSUM(MP_TAC o SPEC `formsubst (x |=> numeral m) (Not q)`) THEN REWRITE_TAC[complexity; COMPLEXITY_FORMSUBST] THEN (ANTS_TAC THENL [ARITH_TAC; DISCH_THEN(MP_TAC o SPEC `T`)]) THEN REWRITE_TAC[IMP_IMP] THEN DISCH_THEN MATCH_MP_TAC THEN ASM_SIMP_TAC[SIGMAPI_FORMSUBST; SIGMAPI_CLAUSES] THEN REWRITE_TAC[FORMSUBST_FV; FV; ASSIGN] THEN REPLICATE_TAC 2 (ONCE_REWRITE_TAC[COND_RAND]) THEN REWRITE_TAC[FVT_NUMERAL; NOT_IN_EMPTY; FVT; IN_SING] THEN (CONJ_TAC THENL [ASM SET_TAC[]; ALL_TAC]) THEN FIRST_X_ASSUM(MP_TAC o SPEC `m:num`) THEN ASM_REWRITE_TAC[] THEN REWRITE_TAC[HOLDS_FORMSUBST; holds; CONTRAPOS_THM] THEN MATCH_MP_TAC EQ_IMP THEN MATCH_MP_TAC HOLDS_VALUATION THEN X_GEN_TAC `y:num` THEN (ASM_CASES_TAC `y:num = x` THENL [ALL_TAC; ASM SET_TAC[]]) THEN ASM_REWRITE_TAC[o_DEF; ASSIGN; VALMOD; TERMVAL_NUMERAL]]]);; (* ------------------------------------------------------------------------- *) Hence a nice alternative form of Goedel 's theorem for any consistent sigma_1 - definable axioms A that extend ( i.e. prove ) the axioms . (* ------------------------------------------------------------------------- *) let G1_ROBINSON = prove (`!A. definable_by (SIGMA 1) (IMAGE gform A) /\ consistent A /\ A |-- robinson ==> ?G. PI 1 G /\ closed G /\ true G /\ ~(A |-- G) /\ (sound_for (SIGMA 1 INTER closed) A ==> ~(A |-- Not G))`, REPEAT STRIP_TAC THEN MATCH_MP_TAC G1_TRAD THEN ASM_REWRITE_TAC[complete_for; INTER; IN_ELIM_THM] THEN X_GEN_TAC `p:form` THEN REWRITE_TAC[IN; true_def] THEN STRIP_TAC THEN MATCH_MP_TAC modusponens THEN EXISTS_TAC `robinson` THEN ASM_REWRITE_TAC[] THEN MATCH_MP_TAC PROVES_MONO THEN EXISTS_TAC `{}:form->bool` THEN REWRITE_TAC[EMPTY_SUBSET] THEN W(MP_TAC o PART_MATCH (lhs o rand) DEDUCTION o snd) THEN MP_TAC(ISPECL [`I:num->num`; `p:form`; `T`] SIGMAPI1_COMPLETE) THEN ASM_REWRITE_TAC[GSYM SIGMA] THEN DISCH_TAC THEN ASM_REWRITE_TAC[] THEN DISCH_THEN MATCH_MP_TAC THEN REWRITE_TAC[robinson; closed; FV; FVT] THEN SET_TAC[]);; (* ------------------------------------------------------------------------- *) (* More metaproperties of axioms systems now we have some derived rules. *) (* ------------------------------------------------------------------------- *) let complete = new_definition `complete A <=> !p. closed p ==> A |-- p \/ A |-- Not p`;; let sound = new_definition `sound A <=> !p. A |-- p ==> true p`;; let semcomplete = new_definition `semcomplete A <=> !p. true p ==> A |-- p`;; let generalize = new_definition `generalize vs p = ITLIST (!!) vs p`;; let closure = new_definition `closure p = generalize (list_of_set(FV p)) p`;; let TRUE_GENERALIZE = prove (`!vs p. true(generalize vs p) <=> true p`, REWRITE_TAC[generalize; true_def] THEN LIST_INDUCT_TAC THEN REWRITE_TAC[ITLIST; holds] THEN GEN_TAC THEN FIRST_X_ASSUM(fun th -> GEN_REWRITE_TAC RAND_CONV [GSYM th]) THEN MESON_TAC[VALMOD_REPEAT]);; let PROVABLE_GENERALIZE = prove (`!A p vs. A |-- generalize vs p <=> A |-- p`, GEN_TAC THEN GEN_TAC THEN REWRITE_TAC[generalize] THEN LIST_INDUCT_TAC THEN REWRITE_TAC[ITLIST] THEN FIRST_X_ASSUM(SUBST1_TAC o SYM) THEN MESON_TAC[spec; gen; FORMSUBST_TRIV; ASSIGN_TRIV]);; let FV_GENERALIZE = prove (`!p vs. FV(generalize vs p) = FV(p) DIFF (set_of_list vs)`, GEN_TAC THEN REWRITE_TAC[generalize] THEN LIST_INDUCT_TAC THEN REWRITE_TAC[set_of_list; DIFF_EMPTY; ITLIST] THEN ASM_REWRITE_TAC[FV] THEN SET_TAC[]);; let CLOSED_CLOSURE = prove (`!p. closed(closure p)`, REWRITE_TAC[closed; closure; FV_GENERALIZE] THEN SIMP_TAC[SET_OF_LIST_OF_SET; FV_FINITE; DIFF_EQ_EMPTY]);; let TRUE_CLOSURE = prove (`!p. true(closure p) <=> true p`, REWRITE_TAC[closure; TRUE_GENERALIZE]);; let PROVABLE_CLOSURE = prove (`!A p. A |-- closure p <=> A |-- p`, REWRITE_TAC[closure; PROVABLE_GENERALIZE]);; let DEFINABLE_DEFINABLE_BY = prove (`definable = definable_by (\x. T)`, REWRITE_TAC[FUN_EQ_THM; definable; definable_by]);; let DEFINABLE_ONEVAR = prove (`definable s <=> ?p x. (FV p = {x}) /\ !v. holds v p <=> (v x) IN s`, REWRITE_TAC[definable] THEN EQ_TAC THENL [ALL_TAC; MESON_TAC[]] THEN DISCH_THEN(X_CHOOSE_THEN `p:form` (X_CHOOSE_TAC `x:num`)) THEN EXISTS_TAC `(V x === V x) && formsubst (\y. if y = x then V x else Z) p` THEN EXISTS_TAC `x:num` THEN ASM_REWRITE_TAC[HOLDS_FORMSUBST; FORMSUBST_FV; FV; holds] THEN REWRITE_TAC[COND_RAND; EXTENSION; IN_ELIM_THM; IN_SING; FVT; IN_UNION; COND_EXPAND; NOT_IN_EMPTY; o_THM; termval] THEN MESON_TAC[]);; let CLOSED_TRUE_OR_FALSE = prove (`!p. closed p ==> true p \/ true(Not p)`, REWRITE_TAC[closed; true_def; holds] THEN REPEAT STRIP_TAC THEN ASM_MESON_TAC[HOLDS_VALUATION; NOT_IN_EMPTY]);; let SEMCOMPLETE_IMP_COMPLETE = prove (`!A. semcomplete A ==> complete A`, REWRITE_TAC[semcomplete; complete] THEN MESON_TAC[CLOSED_TRUE_OR_FALSE]);; let SOUND_CLOSED = prove (`sound A <=> !p. closed p /\ A |-- p ==> true p`, REWRITE_TAC[sound] THEN EQ_TAC THENL [MESON_TAC[]; ALL_TAC] THEN MESON_TAC[TRUE_CLOSURE; PROVABLE_CLOSURE; CLOSED_CLOSURE]);; let SOUND_IMP_CONSISTENT = prove (`!A. sound A ==> consistent A`, REWRITE_TAC[sound; consistent; CONSISTENT_ALT] THEN SUBGOAL_THEN `~(true False)` (fun th -> MESON_TAC[th]) THEN REWRITE_TAC[true_def; holds]);; let SEMCOMPLETE_SOUND_EQ_CONSISTENT = prove (`!A. semcomplete A ==> (sound A <=> consistent A)`, REWRITE_TAC[semcomplete] THEN REPEAT STRIP_TAC THEN EQ_TAC THEN REWRITE_TAC[SOUND_IMP_CONSISTENT] THEN REWRITE_TAC[consistent; SOUND_CLOSED] THEN ASM_MESON_TAC[CLOSED_TRUE_OR_FALSE]);;
null
https://raw.githubusercontent.com/jrh13/hol-light/d125b0ae73e546a63ed458a7891f4e14ae0409e2/Arithmetic/sigmacomplete.ml
ocaml
========================================================================= ========================================================================= ------------------------------------------------------------------------- Individual "axioms" and their instances. ------------------------------------------------------------------------- ------------------------------------------------------------------------- All ground terms can be evaluated by proof. ------------------------------------------------------------------------- ------------------------------------------------------------------------- Convenient stepping theorems for atoms and other useful lemmas. ------------------------------------------------------------------------- ------------------------------------------------------------------------- Evaluation of atoms built from numerals by proof. ------------------------------------------------------------------------- ------------------------------------------------------------------------- ------------------------------------------------------------------------- ------------------------------------------------------------------------- Now full Sigma-1 completeness. ------------------------------------------------------------------------- ------------------------------------------------------------------------- ------------------------------------------------------------------------- ------------------------------------------------------------------------- More metaproperties of axioms systems now we have some derived rules. -------------------------------------------------------------------------
Sigma_1 completeness of 's axioms Q. let robinson = new_definition `robinson = (!!0 (!!1 (Suc(V 0) === Suc(V 1) --> V 0 === V 1))) && (!!1 (Not(V 1 === Z) <-> ??0 (V 1 === Suc(V 0)))) && (!!1 (Z ++ V 1 === V 1)) && (!!0 (!!1 (Suc(V 0) ++ V 1 === Suc(V 0 ++ V 1)))) && (!!1 (Z ** V 1 === Z)) && (!!0 (!!1 (Suc(V 0) ** V 1 === V 1 ++ V 0 ** V 1))) && (!!0 (!!1 (V 0 <<= V 1 <-> ??2 (V 0 ++ V 2 === V 1)))) && (!!0 (!!1 (V 0 << V 1 <-> Suc(V 0) <<= V 1)))`;; let [suc_inj; num_cases; add_0; add_suc; mul_0; mul_suc; le_def; lt_def] = CONJUNCTS(REWRITE_RULE[META_AND] (GEN_REWRITE_RULE RAND_CONV [robinson] (MATCH_MP assume (SET_RULE `robinson IN {robinson}`))));; let suc_inj' = prove (`!s t. {robinson} |-- Suc(s) === Suc(t) --> s === t`, REWRITE_TAC[specl_rule [`s:term`; `t:term`] suc_inj]);; let num_cases' = prove (`!t z. ~(z IN FVT t) ==> {robinson} |-- (Not(t === Z) <-> ??z (t === Suc(V z)))`, REPEAT STRIP_TAC THEN MP_TAC(SPEC `t:term` (MATCH_MP spec num_cases)) THEN REWRITE_TAC[formsubst] THEN CONV_TAC(ONCE_DEPTH_CONV TERMSUBST_CONV) THEN REWRITE_TAC[FV; FVT; SET_RULE `({1} UNION {0}) DELETE 0 = {1} DIFF {0}`] THEN REWRITE_TAC[IN_DIFF; IN_SING; UNWIND_THM2; GSYM CONJ_ASSOC; ASSIGN] THEN REWRITE_TAC[ARITH_EQ] THEN LET_TAC THEN MATCH_MP_TAC(REWRITE_RULE[IMP_CONJ_ALT] iff_trans) THEN SUBGOAL_THEN `~(z' IN FVT t)` ASSUME_TAC THENL [EXPAND_TAC "z'" THEN COND_CASES_TAC THEN ASM_SIMP_TAC[SET_RULE `a IN s ==> s UNION {a} = s`; VARIANT_FINITE; FVT_FINITE]; MATCH_MP_TAC imp_antisym THEN ASM_CASES_TAC `z':num = z` THEN ASM_REWRITE_TAC[imp_refl] THEN CONJ_TAC THEN MATCH_MP_TAC ichoose THEN ASM_REWRITE_TAC[FV; IN_DELETE; IN_UNION; IN_SING; FVT] THEN MATCH_MP_TAC gen THEN MATCH_MP_TAC imp_trans THENL [EXISTS_TAC `formsubst (z |=> V z') (t === Suc(V z))`; EXISTS_TAC `formsubst (z' |=> V z) (t === Suc(V z'))`] THEN REWRITE_TAC[iexists] THEN REWRITE_TAC[formsubst] THEN ASM_REWRITE_TAC[termsubst; ASSIGN] THEN MATCH_MP_TAC(MESON[imp_refl] `p = q ==> A |-- p --> q`) THEN AP_THM_TAC THEN AP_TERM_TAC THEN CONV_TAC SYM_CONV THEN MATCH_MP_TAC TERMSUBST_TRIVIAL THEN REWRITE_TAC[ASSIGN] THEN ASM_MESON_TAC[]]);; let add_0' = prove (`!t. {robinson} |-- Z ++ t === t`, REWRITE_TAC[spec_rule `t:term` add_0]);; let add_suc' = prove (`!s t. {robinson} |-- Suc(s) ++ t === Suc(s ++ t)`, REWRITE_TAC[specl_rule [`s:term`; `t:term`] add_suc]);; let mul_0' = prove (`!t. {robinson} |-- Z ** t === Z`, REWRITE_TAC[spec_rule `t:term` mul_0]);; let mul_suc' = prove (`!s t. {robinson} |-- Suc(s) ** t === t ++ s ** t`, REWRITE_TAC[specl_rule [`s:term`; `t:term`] mul_suc]);; let lt_def' = prove (`!s t. {robinson} |-- (s << t <-> Suc(s) <<= t)`, REWRITE_TAC[specl_rule [`s:term`; `t:term`] lt_def]);; let SIGMA1_COMPLETE_ADD = prove (`!m n. {robinson} |-- numeral m ++ numeral n === numeral(m + n)`, INDUCT_TAC THEN REWRITE_TAC[ADD_CLAUSES; numeral] THEN ASM_MESON_TAC[add_0'; add_suc'; axiom_funcong; eq_trans; modusponens]);; let SIGMA1_COMPLETE_MUL = prove (`!m n. {robinson} |-- (numeral m ** numeral n === numeral(m * n))`, INDUCT_TAC THEN REWRITE_TAC[ADD_CLAUSES; MULT_CLAUSES; numeral] THENL [ASM_MESON_TAC[mul_0']; ALL_TAC] THEN GEN_TAC THEN MATCH_MP_TAC eq_trans_rule THEN EXISTS_TAC `numeral(n) ++ numeral(m * n)` THEN CONJ_TAC THENL [ASM_MESON_TAC[mul_suc'; eq_trans_rule; axiom_funcong; imp_trans; modusponens; imp_swap;add_assum; axiom_eqrefl]; ASM_MESON_TAC[SIGMA1_COMPLETE_ADD; ADD_SYM; eq_trans_rule]]);; let SIGMA1_COMPLETE_TERM = prove (`!v t n. FVT t = {} /\ termval v t = n ==> {robinson} |-- (t === numeral n)`, let lemma = prove(`(!n. p /\ (x = n) ==> P n) <=> p ==> P x`,MESON_TAC[]) in GEN_TAC THEN MATCH_MP_TAC term_INDUCT THEN REWRITE_TAC[termval;FVT; NOT_INSERT_EMPTY] THEN CONJ_TAC THENL [GEN_TAC THEN DISCH_THEN(SUBST1_TAC o SYM) THEN REWRITE_TAC[numeral] THEN MESON_TAC[axiom_eqrefl; add_assum]; ALL_TAC] THEN REWRITE_TAC[lemma] THEN REPEAT CONJ_TAC THEN REPEAT GEN_TAC THEN DISCH_THEN(fun th -> REPEAT STRIP_TAC THEN MP_TAC th) THEN RULE_ASSUM_TAC(REWRITE_RULE[EMPTY_UNION]) THEN ASM_REWRITE_TAC[numeral] THEN MESON_TAC[SIGMA1_COMPLETE_ADD; SIGMA1_COMPLETE_MUL; cong_suc; cong_add; cong_mul; eq_trans_rule]);; let canonize_clauses = let lemma0 = MESON[imp_refl; imp_swap; modusponens; axiom_doubleneg] `!A p. A |-- (p --> False) --> False <=> A |-- p` and lemma1 = MESON[iff_imp1; iff_imp2; modusponens; imp_trans] `A |-- p <-> q ==> (A |-- p <=> A |-- q) /\ (A |-- p --> False <=> A |-- q --> False)` in itlist (CONJ o MATCH_MP lemma1 o SPEC_ALL) [axiom_true; axiom_not; axiom_and; axiom_or; iff_def; axiom_exists] lemma0 and false_imp = MESON[imp_truefalse; modusponens] `A |-- p /\ A |-- q --> False ==> A |-- (p --> q) --> False` and true_imp = MESON[axiom_addimp; modusponens; ex_falso; imp_trans] `A |-- p --> False \/ A |-- q ==> A |-- p --> q`;; let CANONIZE_TAC = REWRITE_TAC[canonize_clauses; imp_refl] THEN REPEAT((MATCH_MP_TAC false_imp THEN CONJ_TAC) ORELSE MATCH_MP_TAC true_imp THEN REWRITE_TAC[canonize_clauses; imp_refl]);; let suc_inj_eq = prove (`!s t. {robinson} |-- Suc s === Suc t <-> s === t`, MESON_TAC[suc_inj'; axiom_funcong; imp_antisym]);; let suc_le_eq = prove (`!s t. {robinson} |-- Suc s <<= Suc t <-> s <<= t`, gens_tac [0;1] THEN TRANS_TAC iff_trans `??2 (Suc(V 0) ++ V 2 === Suc(V 1))` THEN REWRITE_TAC[itlist spec_rule [`Suc(V 1)`; `Suc(V 0)`] le_def] THEN TRANS_TAC iff_trans `??2 (V 0 ++ V 2 === V 1)` THEN GEN_REWRITE_TAC RAND_CONV [iff_sym] THEN REWRITE_TAC[itlist spec_rule [`V 1`; `V 0`] le_def] THEN MATCH_MP_TAC exiff THEN TRANS_TAC iff_trans `Suc(V 0 ++ V 2) === Suc(V 1)` THEN REWRITE_TAC[suc_inj_eq] THEN MATCH_MP_TAC cong_eq THEN REWRITE_TAC[axiom_eqrefl; add_suc']);; let le_iff_lt = prove (`!s t. {robinson} |-- s <<= t <-> s << Suc t`, REPEAT GEN_TAC THEN TRANS_TAC iff_trans `Suc s <<= Suc t` THEN ONCE_REWRITE_TAC[iff_sym] THEN REWRITE_TAC[suc_le_eq; lt_def']);; let suc_lt_eq = prove (`!s t. {robinson} |-- Suc s << Suc t <-> s << t`, MESON_TAC[iff_sym; iff_trans; le_iff_lt; lt_def']);; let not_suc_eq_0 = prove (`!t. {robinson} |-- Suc t === Z --> False`, gen_tac 1 THEN SUBGOAL_THEN `{robinson} |-- Not(Suc(V 1) === Z)` MP_TAC THENL [ALL_TAC; REWRITE_TAC[canonize_clauses]] THEN SUBGOAL_THEN `{robinson} |-- ?? 0 (Suc(V 1) === Suc(V 0))` MP_TAC THENL [MATCH_MP_TAC exists_intro THEN EXISTS_TAC `V 1` THEN CONV_TAC(RAND_CONV FORMSUBST_CONV) THEN REWRITE_TAC[axiom_eqrefl]; MESON_TAC[iff_imp2; modusponens; spec_rule `Suc(V 1)` num_cases]]);; let not_suc_le_0 = prove (`!t. {robinson} |-- Suc t <<= Z --> False`, X_GEN_TAC `s:term` THEN SUBGOAL_THEN `{robinson} |-- !!0 (Suc(V 0) <<= Z --> False)` MP_TAC THENL [ALL_TAC; DISCH_THEN(ACCEPT_TAC o spec_rule `s:term`)] THEN MATCH_MP_TAC gen THEN SUBGOAL_THEN `{robinson} |-- ?? 2 (Suc (V 0) ++ V 2 === Z) --> False` MP_TAC THENL [ALL_TAC; MATCH_MP_TAC(REWRITE_RULE[IMP_CONJ] imp_trans) THEN MATCH_MP_TAC iff_imp1 THEN ACCEPT_TAC(itlist spec_rule [`Z`; `Suc(V 0)`] le_def)] THEN MATCH_MP_TAC ichoose THEN REWRITE_TAC[FV; NOT_IN_EMPTY] THEN MATCH_MP_TAC gen THEN TRANS_TAC imp_trans `Suc(V 0 ++ V 2) === Z` THEN REWRITE_TAC[not_suc_eq_0] THEN MATCH_MP_TAC iff_imp1 THEN MATCH_MP_TAC cong_eq THEN REWRITE_TAC[axiom_eqrefl] THEN REWRITE_TAC[add_suc']);; let not_lt_0 = prove (`!t. {robinson} |-- t << Z --> False`, MESON_TAC[not_suc_le_0; lt_def'; imp_trans; iff_imp1]);; let add_0_right = prove (`!n. {robinson} |-- numeral n ++ Z === numeral n`, GEN_TAC THEN MP_TAC(ISPECL [`n:num`; `0`] SIGMA1_COMPLETE_ADD) THEN REWRITE_TAC[numeral; ADD_CLAUSES]);; let ATOM_EQ_FALSE = prove (`!m n. ~(m = n) ==> {robinson} |-- numeral m === numeral n --> False`, ONCE_REWRITE_TAC[SWAP_FORALL_THM] THEN MATCH_MP_TAC WLOG_LT THEN REWRITE_TAC[] THEN CONJ_TAC THENL [MESON_TAC[eq_sym; imp_trans]; ALL_TAC] THEN ONCE_REWRITE_TAC[SWAP_FORALL_THM] THEN INDUCT_TAC THEN REWRITE_TAC[CONJUNCT1 LT] THEN INDUCT_TAC THEN REWRITE_TAC[numeral; not_suc_eq_0; LT_SUC; SUC_INJ] THEN ASM_MESON_TAC[suc_inj_eq; imp_trans; iff_imp1; iff_imp2]);; let ATOM_LE_FALSE = prove (`!m n. n < m ==> {robinson} |-- numeral m <<= numeral n --> False`, INDUCT_TAC THEN REWRITE_TAC[CONJUNCT1 LT] THEN INDUCT_TAC THEN REWRITE_TAC[numeral; not_suc_le_0; LT_SUC] THEN ASM_MESON_TAC[suc_le_eq; imp_trans; iff_imp1; iff_imp2]);; let ATOM_LT_FALSE = prove (`!m n. n <= m ==> {robinson} |-- numeral m << numeral n --> False`, REPEAT GEN_TAC THEN REWRITE_TAC[GSYM LT_SUC_LE] THEN DISCH_THEN(MP_TAC o MATCH_MP ATOM_LE_FALSE) THEN REWRITE_TAC[numeral] THEN ASM_MESON_TAC[lt_def'; imp_trans; iff_imp1; iff_imp2]);; let ATOM_EQ_TRUE = prove (`!m n. m = n ==> {robinson} |-- numeral m === numeral n`, MESON_TAC[axiom_eqrefl]);; let ATOM_LE_TRUE = prove (`!m n. m <= n ==> {robinson} |-- numeral m <<= numeral n`, SUBGOAL_THEN `!m n. {robinson} |-- numeral m <<= numeral(m + n)` MP_TAC THENL [ALL_TAC; MESON_TAC[LE_EXISTS]] THEN REPEAT GEN_TAC THEN MATCH_MP_TAC modusponens THEN EXISTS_TAC `?? 2 (numeral m ++ V 2 === numeral(m + n))` THEN CONJ_TAC THENL [MP_TAC(itlist spec_rule [`numeral(m + n)`; `numeral m`] le_def) THEN MESON_TAC[iff_imp2]; MATCH_MP_TAC exists_intro THEN EXISTS_TAC `numeral n` THEN CONV_TAC(RAND_CONV FORMSUBST_CONV) THEN REWRITE_TAC[SIGMA1_COMPLETE_ADD]]);; let ATOM_LT_TRUE = prove (`!m n. m < n ==> {robinson} |-- numeral m << numeral n`, REPEAT GEN_TAC THEN REWRITE_TAC[GSYM LE_SUC_LT] THEN DISCH_THEN(MP_TAC o MATCH_MP ATOM_LE_TRUE) THEN REWRITE_TAC[numeral] THEN ASM_MESON_TAC[lt_def'; modusponens; iff_imp1; iff_imp2]);; A kind of case analysis rule ; might make it induction in case of PA . let FORMSUBST_FORMSUBST_SAME_NONE = prove (`!s t x p. FVT t = {x} /\ FVT s = {} ==> formsubst (x |=> s) (formsubst (x |=> t) p) = formsubst (x |=> termsubst (x |=> s) t) p`, REWRITE_TAC[RIGHT_FORALL_IMP_THM] THEN REPEAT GEN_TAC THEN STRIP_TAC THEN SUBGOAL_THEN `!y. safe_for y (x |=> termsubst (x |=> s) t)` ASSUME_TAC THENL [GEN_TAC THEN REWRITE_TAC[SAFE_FOR_ASSIGN; TERMSUBST_FVT; ASSIGN] THEN ASM SET_TAC[FVT]; ALL_TAC] THEN MATCH_MP_TAC form_INDUCT THEN ASM_SIMP_TAC[FORMSUBST_SAFE_FOR; SAFE_FOR_ASSIGN; IN_SING; NOT_IN_EMPTY] THEN SIMP_TAC[formsubst] THEN MATCH_MP_TAC(TAUT `(p /\ q /\ r) /\ s ==> p /\ q /\ r /\ s`) THEN CONJ_TAC THENL [REPEAT STRIP_TAC THEN BINOP_TAC THEN REWRITE_TAC[TERMSUBST_TERMSUBST] THEN AP_THM_TAC THEN AP_TERM_TAC THEN REWRITE_TAC[o_DEF; FUN_EQ_THM] THEN X_GEN_TAC `y:num` THEN REWRITE_TAC[ASSIGN] THEN COND_CASES_TAC THEN ASM_REWRITE_TAC[termsubst; ASSIGN]; CONJ_TAC THEN MAP_EVERY X_GEN_TAC [`y:num`; `p:form`] THEN DISCH_TAC THEN (ASM_CASES_TAC `y:num = x` THENL [ASM_REWRITE_TAC[assign; VALMOD_VALMOD_BASIC] THEN SIMP_TAC[VALMOD_TRIVIAL; FORMSUBST_TRIV]; SUBGOAL_THEN `!u. (y |-> V y) (x |=> u) = (x |=> u)` (fun th -> ASM_REWRITE_TAC[th]) THEN GEN_TAC THEN MATCH_MP_TAC VALMOD_TRIVIAL THEN ASM_REWRITE_TAC[ASSIGN]])]);; let num_cases_rule = prove (`!p x. {robinson} |-- formsubst (x |=> Z) p /\ {robinson} |-- formsubst (x |=> Suc(V x)) p ==> {robinson} |-- p`, let lemma = prove (`!A p x t. A |-- formsubst (x |=> t) p ==> A |-- V x === t --> p`, REPEAT GEN_TAC THEN MATCH_MP_TAC(REWRITE_RULE[IMP_CONJ] modusponens) THEN MATCH_MP_TAC imp_swap THEN GEN_REWRITE_TAC (funpow 3 RAND_CONV) [GSYM FORMSUBST_TRIV] THEN CONV_TAC(funpow 3 RAND_CONV(SUBS_CONV[SYM(SPEC `x:num` ASSIGN_TRIV)])) THEN TRANS_TAC imp_trans `t === V x` THEN REWRITE_TAC[isubst; eq_sym]) in REPEAT GEN_TAC THEN GEN_REWRITE_TAC (RAND_CONV o RAND_CONV) [GSYM FORMSUBST_TRIV] THEN CONV_TAC(RAND_CONV(SUBS_CONV[SYM(SPEC `x:num` ASSIGN_TRIV)])) THEN SUBGOAL_THEN `?z. ~(z = x) /\ ~(z IN VARS p)` STRIP_ASSUME_TAC THENL [EXISTS_TAC `VARIANT(x INSERT VARS p)` THEN REWRITE_TAC[GSYM DE_MORGAN_THM; GSYM IN_INSERT] THEN MATCH_MP_TAC NOT_IN_VARIANT THEN SIMP_TAC[VARS_FINITE; FINITE_INSERT; SUBSET_REFL]; ALL_TAC] THEN FIRST_X_ASSUM(fun th -> ONCE_REWRITE_TAC[GSYM(MATCH_MP FORMSUBST_TWICE th)]) THEN SUBGOAL_THEN `~(x IN FV(formsubst (x |=> V z) p))` MP_TAC THENL [REWRITE_TAC[FORMSUBST_FV; IN_ELIM_THM; ASSIGN; NOT_EXISTS_THM] THEN GEN_TAC THEN COND_CASES_TAC THEN ASM_REWRITE_TAC[FVT] THEN ASM SET_TAC[]; ALL_TAC] THEN SPEC_TAC(`formsubst (x |=> V z) p`,`p:form`) THEN REPEAT STRIP_TAC THEN MATCH_MP_TAC spec THEN MATCH_MP_TAC gen THEN FIRST_X_ASSUM(MP_TAC o MATCH_MP lemma) THEN DISCH_THEN(MP_TAC o SPEC `x:num` o MATCH_MP gen) THEN DISCH_THEN(MP_TAC o MATCH_MP (REWRITE_RULE[IMP_CONJ] ichoose)) THEN FIRST_X_ASSUM(MP_TAC o MATCH_MP lemma) THEN ASM_REWRITE_TAC[IMP_IMP] THEN DISCH_THEN(MP_TAC o MATCH_MP ante_disj) THEN MATCH_MP_TAC(REWRITE_RULE[IMP_CONJ_ALT] modusponens) THEN MP_TAC(ISPECL [`V z`; `x:num`] num_cases') THEN ASM_REWRITE_TAC[FVT; IN_SING] THEN DISCH_THEN(MP_TAC o MATCH_MP iff_imp1) THEN REWRITE_TAC[canonize_clauses] THEN MATCH_MP_TAC(REWRITE_RULE[IMP_CONJ_ALT] imp_trans) THEN MESON_TAC[imp_swap; axiom_not; iff_imp1; imp_trans]);; let SIGMAPI1_COMPLETE = prove (`!v p b. sigmapi b 1 p /\ closed p ==> (b /\ holds v p ==> {robinson} |-- p) /\ (~b /\ ~holds v p ==> {robinson} |-- p --> False)`, let lemma1 = prove (`!x n p. (!m. m < n ==> {robinson} |-- formsubst (x |=> numeral m) p) ==> {robinson} |-- !!x (V x << numeral n --> p)`, GEN_TAC THEN INDUCT_TAC THEN X_GEN_TAC `p:form` THEN DISCH_TAC THEN REWRITE_TAC[numeral] THENL [ASM_MESON_TAC[gen; imp_trans; ex_falso; not_lt_0]; ALL_TAC] THEN MATCH_MP_TAC gen THEN MATCH_MP_TAC num_cases_rule THEN EXISTS_TAC `x:num` THEN CONJ_TAC THENL [ONCE_REWRITE_TAC[formsubst] THEN MATCH_MP_TAC add_assum THEN REWRITE_TAC[GSYM numeral] THEN FIRST_X_ASSUM MATCH_MP_TAC THEN ARITH_TAC; ALL_TAC] THEN REWRITE_TAC[formsubst; termsubst; TERMSUBST_NUMERAL; ASSIGN] THEN TRANS_TAC imp_trans `V x << numeral n` THEN CONJ_TAC THENL [MESON_TAC[suc_lt_eq; iff_imp1]; ALL_TAC] THEN MATCH_MP_TAC spec_var THEN EXISTS_TAC `x:num` THEN FIRST_X_ASSUM MATCH_MP_TAC THEN X_GEN_TAC `m:num` THEN DISCH_TAC THEN FIRST_X_ASSUM(MP_TAC o SPEC `SUC m`) THEN ASM_REWRITE_TAC[LT_SUC] THEN MATCH_MP_TAC EQ_IMP THEN AP_TERM_TAC THEN W(MP_TAC o PART_MATCH (lhs o rand) FORMSUBST_FORMSUBST_SAME_NONE o rand o snd) THEN REWRITE_TAC[FVT; FVT_NUMERAL] THEN DISCH_THEN SUBST1_TAC THEN REWRITE_TAC[termsubst; ASSIGN; numeral]) in let lemma2 = prove (`!x n p. (!m. m <= n ==> {robinson} |-- formsubst (x |=> numeral m) p) ==> {robinson} |-- !!x (V x <<= numeral n --> p)`, REPEAT STRIP_TAC THEN MP_TAC(ISPECL [`x:num`; `SUC n`; `p:form`] lemma1) THEN ASM_REWRITE_TAC[LT_SUC_LE] THEN DISCH_TAC THEN MATCH_MP_TAC gen THEN FIRST_ASSUM(MP_TAC o MATCH_MP spec_var) THEN REWRITE_TAC[numeral] THEN MATCH_MP_TAC(REWRITE_RULE[IMP_CONJ] imp_trans) THEN MESON_TAC[iff_imp1; le_iff_lt]) in let lemma3 = prove (`!v x t p. FVT t = {} /\ (!m. m < termval v t ==> {robinson} |-- formsubst (x |=> numeral m) p) ==> {robinson} |-- !!x (V x << t --> p)`, REPEAT STRIP_TAC THEN MATCH_MP_TAC gen THEN FIRST_ASSUM(MP_TAC o MATCH_MP spec_var o MATCH_MP lemma1) THEN MATCH_MP_TAC(REWRITE_RULE[IMP_CONJ] imp_trans) THEN MATCH_MP_TAC iff_imp1 THEN MATCH_MP_TAC cong_lt THEN REWRITE_TAC[axiom_eqrefl] THEN MATCH_MP_TAC SIGMA1_COMPLETE_TERM THEN ASM_MESON_TAC[]) and lemma4 = prove (`!v x t p. FVT t = {} /\ (!m. m <= termval v t ==> {robinson} |-- formsubst (x |=> numeral m) p) ==> {robinson} |-- !!x (V x <<= t --> p)`, REPEAT STRIP_TAC THEN MATCH_MP_TAC gen THEN FIRST_ASSUM(MP_TAC o MATCH_MP spec_var o MATCH_MP lemma2) THEN MATCH_MP_TAC(REWRITE_RULE[IMP_CONJ] imp_trans) THEN MATCH_MP_TAC iff_imp1 THEN MATCH_MP_TAC cong_le THEN REWRITE_TAC[axiom_eqrefl] THEN MATCH_MP_TAC SIGMA1_COMPLETE_TERM THEN ASM_MESON_TAC[]) and lemma5 = prove (`!A x p q. A |-- !!x (p --> Not q) ==> A |-- !!x (Not(p && q))`, REPEAT STRIP_TAC THEN MATCH_MP_TAC gen THEN FIRST_ASSUM(MP_TAC o MATCH_MP spec_var) THEN REWRITE_TAC[canonize_clauses] THEN MESON_TAC[imp_trans; axiom_not; iff_imp1; iff_imp2]) in GEN_TAC THEN GEN_TAC THEN REWRITE_TAC[closed] THEN WF_INDUCT_TAC `complexity p` THEN POP_ASSUM MP_TAC THEN SPEC_TAC(`p:form`,`p:form`) THEN MATCH_MP_TAC form_INDUCT THEN REWRITE_TAC[SIGMAPI_CLAUSES; complexity; ARITH] THEN REWRITE_TAC[MESON[] `(if p then q else F) <=> p /\ q`] THEN ONCE_REWRITE_TAC [TAUT `a /\ b /\ c /\ d /\ e /\ f /\ g /\ h /\ i /\ j /\ k /\ l <=> (a /\ b) /\ (c /\ d /\ e) /\ f /\ (g /\ h /\ i /\ j) /\ (k /\ l)`] THEN CONJ_TAC THENL [CONJ_TAC THEN DISCH_THEN(K ALL_TAC) THEN REWRITE_TAC[holds] THEN MESON_TAC[imp_refl; truth]; ALL_TAC] THEN CONJ_TAC THENL [REPEAT CONJ_TAC THEN MAP_EVERY X_GEN_TAC [`s:term`; `t:term`] THEN DISCH_THEN(K ALL_TAC) THEN X_GEN_TAC `b:bool` THEN REWRITE_TAC[FV; EMPTY_UNION] THEN STRIP_TAC THEN MP_TAC(ISPECL [`v:num->num`; `t:term`; `termval v t`] SIGMA1_COMPLETE_TERM) THEN MP_TAC(ISPECL [`v:num->num`; `s:term`; `termval v s`] SIGMA1_COMPLETE_TERM) THEN ASM_REWRITE_TAC[IMP_IMP] THENL [DISCH_THEN(MP_TAC o MATCH_MP cong_eq); DISCH_THEN(MP_TAC o MATCH_MP cong_lt); DISCH_THEN(MP_TAC o MATCH_MP cong_le)] THEN STRIP_TAC THEN REWRITE_TAC[holds; NOT_LE; NOT_LT] THEN (REPEAT STRIP_TAC THENL [FIRST_X_ASSUM(MATCH_MP_TAC o MATCH_MP(REWRITE_RULE[IMP_CONJ] modusponens) o MATCH_MP iff_imp2); FIRST_X_ASSUM(MATCH_MP_TAC o MATCH_MP(REWRITE_RULE[IMP_CONJ] imp_trans) o MATCH_MP iff_imp1)]) THEN ASM_SIMP_TAC[ATOM_EQ_FALSE; ATOM_EQ_TRUE; ATOM_LT_FALSE; ATOM_LT_TRUE; ATOM_LE_FALSE; ATOM_LE_TRUE]; ALL_TAC] THEN CONJ_TAC THENL [X_GEN_TAC `p:form` THEN DISCH_THEN(K ALL_TAC) THEN DISCH_THEN(MP_TAC o SPEC `p:form`) THEN ANTS_TAC THENL [ARITH_TAC; DISCH_TAC] THEN X_GEN_TAC `b:bool` THEN REWRITE_TAC[FV] THEN STRIP_TAC THEN FIRST_X_ASSUM(MP_TAC o SPEC `~b`) THEN ASM_REWRITE_TAC[holds] THEN BOOL_CASES_TAC `b:bool` THEN CANONIZE_TAC THEN ASM_MESON_TAC[]; ALL_TAC] THEN CONJ_TAC THENL [REPEAT CONJ_TAC THEN MAP_EVERY X_GEN_TAC [`p:form`; `q:form`] THEN DISCH_THEN(K ALL_TAC) THEN DISCH_TAC THEN X_GEN_TAC `b:bool` THEN REWRITE_TAC[FV; EMPTY_UNION] THEN STRIP_TAC THEN FIRST_X_ASSUM(fun th -> MP_TAC(SPEC `p:form` th) THEN MP_TAC(SPEC `q:form` th)) THEN (ANTS_TAC THENL [ARITH_TAC; ALL_TAC]) THEN ONCE_REWRITE_TAC[TAUT `p ==> q ==> r <=> q ==> p ==> r`] THEN (ANTS_TAC THENL [ARITH_TAC; ASM_REWRITE_TAC[IMP_IMP]]) THEN ASM_REWRITE_TAC[holds; canonize_clauses] THENL [DISCH_THEN(CONJUNCTS_THEN(MP_TAC o SPEC `b:bool`)); DISCH_THEN(CONJUNCTS_THEN(MP_TAC o SPEC `b:bool`)); DISCH_THEN(CONJUNCTS_THEN2 (MP_TAC o SPEC `~b`) (MP_TAC o SPEC `b:bool`)); DISCH_THEN(CONJUNCTS_THEN(fun th -> MP_TAC(SPEC `~b` th) THEN MP_TAC(SPEC `b:bool` th)))] THEN ASM_REWRITE_TAC[] THEN BOOL_CASES_TAC `b:bool` THEN ASM_REWRITE_TAC[] THEN REPEAT STRIP_TAC THEN CANONIZE_TAC THEN TRY(FIRST_X_ASSUM(MATCH_MP_TAC o MATCH_MP (TAUT `~(p <=> q) ==> (p /\ ~q ==> r) /\ (~p /\ q ==> s) ==> r \/ s`)) THEN REPEAT STRIP_TAC THEN CANONIZE_TAC) THEN ASM_MESON_TAC[]; ALL_TAC] THEN CONJ_TAC THEN MAP_EVERY X_GEN_TAC [`x:num`; `p:form`] THEN DISCH_THEN(K ALL_TAC) THEN REWRITE_TAC[canonize_clauses; holds] THEN DISCH_TAC THEN X_GEN_TAC `b:bool` THENL [BOOL_CASES_TAC `b:bool` THEN ASM_REWRITE_TAC[] THENL [REWRITE_TAC[IMP_IMP; GSYM CONJ_ASSOC; FV] THEN ONCE_REWRITE_TAC[IMP_CONJ] THEN REWRITE_TAC[LEFT_IMP_EXISTS_THM] THEN MAP_EVERY X_GEN_TAC [`q:form`; `t:term`] THEN DISCH_THEN (CONJUNCTS_THEN2 (DISJ_CASES_THEN SUBST_ALL_TAC) ASSUME_TAC) THEN REWRITE_TAC[SIGMAPI_CLAUSES; FV; holds] THEN (ASM_CASES_TAC `FVT t = {}` THENL [ALL_TAC; ASM SET_TAC[]]) THEN (ASM_CASES_TAC `FV(q) SUBSET {x}` THENL [ALL_TAC; ASM SET_TAC[]]) THEN DISCH_THEN(CONJUNCTS_THEN2 ASSUME_TAC (MP_TAC o CONJUNCT2)) THEN ABBREV_TAC `n = termval v t` THEN ASM_SIMP_TAC[TERMVAL_VALMOD_OTHER; termval; VALMOD] THENL [DISCH_TAC THEN MATCH_MP_TAC lemma3; DISCH_TAC THEN MATCH_MP_TAC lemma4] THEN EXISTS_TAC `v:num->num` THEN ASM_REWRITE_TAC[] THEN X_GEN_TAC `m:num` THEN DISCH_TAC THEN FIRST_X_ASSUM(MP_TAC o SPEC `formsubst (x |=> numeral m) q`) THEN REWRITE_TAC[complexity; COMPLEXITY_FORMSUBST] THEN (ANTS_TAC THENL [ARITH_TAC; DISCH_THEN(MP_TAC o SPEC `T`)]) THEN REWRITE_TAC[IMP_IMP] THEN DISCH_THEN MATCH_MP_TAC THEN ASM_SIMP_TAC[SIGMAPI_FORMSUBST] THEN REWRITE_TAC[FORMSUBST_FV; ASSIGN] THEN REPLICATE_TAC 2 (ONCE_REWRITE_TAC[COND_RAND]) THEN REWRITE_TAC[FVT_NUMERAL; NOT_IN_EMPTY; FVT; IN_SING] THEN (CONJ_TAC THENL [ASM SET_TAC[]; ALL_TAC]) THEN FIRST_X_ASSUM(MP_TAC o SPEC `m:num`) THEN ASM_REWRITE_TAC[] THEN REWRITE_TAC[HOLDS_FORMSUBST] THEN MATCH_MP_TAC EQ_IMP THEN MATCH_MP_TAC HOLDS_VALUATION THEN X_GEN_TAC `y:num` THEN (ASM_CASES_TAC `y:num = x` THENL [ALL_TAC; ASM SET_TAC[]]) THEN ASM_REWRITE_TAC[o_DEF; ASSIGN; VALMOD; TERMVAL_NUMERAL]; STRIP_TAC THEN REWRITE_TAC[NOT_FORALL_THM; LEFT_IMP_EXISTS_THM] THEN X_GEN_TAC `n:num` THEN DISCH_TAC THEN MATCH_MP_TAC imp_trans THEN EXISTS_TAC `formsubst (x |=> numeral n) p` THEN REWRITE_TAC[ispec] THEN FIRST_X_ASSUM(MP_TAC o SPEC `formsubst (x |=> numeral n) p`) THEN REWRITE_TAC[COMPLEXITY_FORMSUBST; ARITH_RULE `n < n + 1`] THEN DISCH_THEN(MP_TAC o SPEC `F`) THEN ASM_SIMP_TAC[SIGMAPI_FORMSUBST; IMP_IMP] THEN DISCH_THEN MATCH_MP_TAC THEN CONJ_TAC THENL [UNDISCH_TAC `FV (!! x p) = {}` THEN REWRITE_TAC[FV; FORMSUBST_FV; SET_RULE `s DELETE a = {} <=> s = {} \/ s = {a}`] THEN STRIP_TAC THEN ASM_REWRITE_TAC[NOT_IN_EMPTY; IN_SING; EMPTY_GSPEC; ASSIGN; UNWIND_THM2; FVT_NUMERAL]; UNDISCH_TAC `~holds((x |-> n) v) p` THEN REWRITE_TAC[HOLDS_FORMSUBST; CONTRAPOS_THM] THEN MATCH_MP_TAC EQ_IMP THEN MATCH_MP_TAC HOLDS_VALUATION THEN RULE_ASSUM_TAC(REWRITE_RULE[FV]) THEN X_GEN_TAC `y:num` THEN ASM_CASES_TAC `y:num = x` THENL [ALL_TAC; ASM SET_TAC[]] THEN ASM_REWRITE_TAC[o_THM; ASSIGN; VALMOD; TERMVAL_NUMERAL]]]; BOOL_CASES_TAC `b:bool` THEN ASM_REWRITE_TAC[] THENL [REWRITE_TAC[FV] THEN STRIP_TAC THEN DISCH_THEN(X_CHOOSE_TAC `n:num`) THEN FIRST_X_ASSUM(MP_TAC o SPEC `formsubst (x |=> numeral n) (Not p)`) THEN REWRITE_TAC[COMPLEXITY_FORMSUBST; complexity] THEN ANTS_TAC THENL [ASM_ARITH_TAC; DISCH_THEN(MP_TAC o SPEC `F`)] THEN ASM_SIMP_TAC[IMP_IMP; SIGMAPI_CLAUSES; SIGMAPI_FORMSUBST] THEN ANTS_TAC THENL [REWRITE_TAC[FORMSUBST_FV; ASSIGN] THEN REPLICATE_TAC 2 (ONCE_REWRITE_TAC[COND_RAND]) THEN REWRITE_TAC[FVT_NUMERAL; NOT_IN_EMPTY; FVT; FV; IN_SING] THEN (CONJ_TAC THENL [ASM SET_TAC[]; ALL_TAC]) THEN UNDISCH_TAC `holds ((x |-> n) v) p` THEN REWRITE_TAC[formsubst; holds; HOLDS_FORMSUBST] THEN MATCH_MP_TAC EQ_IMP THEN MATCH_MP_TAC HOLDS_VALUATION THEN RULE_ASSUM_TAC(REWRITE_RULE[FV]) THEN X_GEN_TAC `y:num` THEN ASM_CASES_TAC `y:num = x` THENL [ALL_TAC; ASM SET_TAC[]] THEN ASM_REWRITE_TAC[o_THM; ASSIGN; VALMOD; TERMVAL_NUMERAL]; MATCH_MP_TAC(REWRITE_RULE[IMP_CONJ] imp_trans) THEN REWRITE_TAC[ispec]]; REWRITE_TAC[IMP_IMP; GSYM CONJ_ASSOC; FV] THEN ONCE_REWRITE_TAC[IMP_CONJ] THEN REWRITE_TAC[LEFT_IMP_EXISTS_THM] THEN MAP_EVERY X_GEN_TAC [`q:form`; `t:term`] THEN DISCH_THEN (CONJUNCTS_THEN2 (DISJ_CASES_THEN SUBST_ALL_TAC) ASSUME_TAC) THEN REWRITE_TAC[SIGMAPI_CLAUSES; FV; holds] THEN (ASM_CASES_TAC `FVT t = {}` THENL [ALL_TAC; ASM SET_TAC[]]) THEN (ASM_CASES_TAC `FV(q) SUBSET {x}` THENL [ALL_TAC; ASM SET_TAC[]]) THEN DISCH_THEN(CONJUNCTS_THEN2 ASSUME_TAC (MP_TAC o CONJUNCT2)) THEN ABBREV_TAC `n = termval v t` THEN ASM_SIMP_TAC[TERMVAL_VALMOD_OTHER; termval; VALMOD] THEN REWRITE_TAC[NOT_EXISTS_THM; TAUT `~(p /\ q) <=> p ==> ~q`] THEN DISCH_TAC THEN MATCH_MP_TAC lemma5 THENL [MATCH_MP_TAC lemma3; MATCH_MP_TAC lemma4] THEN EXISTS_TAC `v:num->num` THEN ASM_REWRITE_TAC[] THEN X_GEN_TAC `m:num` THEN DISCH_TAC THEN FIRST_X_ASSUM(MP_TAC o SPEC `formsubst (x |=> numeral m) (Not q)`) THEN REWRITE_TAC[complexity; COMPLEXITY_FORMSUBST] THEN (ANTS_TAC THENL [ARITH_TAC; DISCH_THEN(MP_TAC o SPEC `T`)]) THEN REWRITE_TAC[IMP_IMP] THEN DISCH_THEN MATCH_MP_TAC THEN ASM_SIMP_TAC[SIGMAPI_FORMSUBST; SIGMAPI_CLAUSES] THEN REWRITE_TAC[FORMSUBST_FV; FV; ASSIGN] THEN REPLICATE_TAC 2 (ONCE_REWRITE_TAC[COND_RAND]) THEN REWRITE_TAC[FVT_NUMERAL; NOT_IN_EMPTY; FVT; IN_SING] THEN (CONJ_TAC THENL [ASM SET_TAC[]; ALL_TAC]) THEN FIRST_X_ASSUM(MP_TAC o SPEC `m:num`) THEN ASM_REWRITE_TAC[] THEN REWRITE_TAC[HOLDS_FORMSUBST; holds; CONTRAPOS_THM] THEN MATCH_MP_TAC EQ_IMP THEN MATCH_MP_TAC HOLDS_VALUATION THEN X_GEN_TAC `y:num` THEN (ASM_CASES_TAC `y:num = x` THENL [ALL_TAC; ASM SET_TAC[]]) THEN ASM_REWRITE_TAC[o_DEF; ASSIGN; VALMOD; TERMVAL_NUMERAL]]]);; Hence a nice alternative form of Goedel 's theorem for any consistent sigma_1 - definable axioms A that extend ( i.e. prove ) the axioms . let G1_ROBINSON = prove (`!A. definable_by (SIGMA 1) (IMAGE gform A) /\ consistent A /\ A |-- robinson ==> ?G. PI 1 G /\ closed G /\ true G /\ ~(A |-- G) /\ (sound_for (SIGMA 1 INTER closed) A ==> ~(A |-- Not G))`, REPEAT STRIP_TAC THEN MATCH_MP_TAC G1_TRAD THEN ASM_REWRITE_TAC[complete_for; INTER; IN_ELIM_THM] THEN X_GEN_TAC `p:form` THEN REWRITE_TAC[IN; true_def] THEN STRIP_TAC THEN MATCH_MP_TAC modusponens THEN EXISTS_TAC `robinson` THEN ASM_REWRITE_TAC[] THEN MATCH_MP_TAC PROVES_MONO THEN EXISTS_TAC `{}:form->bool` THEN REWRITE_TAC[EMPTY_SUBSET] THEN W(MP_TAC o PART_MATCH (lhs o rand) DEDUCTION o snd) THEN MP_TAC(ISPECL [`I:num->num`; `p:form`; `T`] SIGMAPI1_COMPLETE) THEN ASM_REWRITE_TAC[GSYM SIGMA] THEN DISCH_TAC THEN ASM_REWRITE_TAC[] THEN DISCH_THEN MATCH_MP_TAC THEN REWRITE_TAC[robinson; closed; FV; FVT] THEN SET_TAC[]);; let complete = new_definition `complete A <=> !p. closed p ==> A |-- p \/ A |-- Not p`;; let sound = new_definition `sound A <=> !p. A |-- p ==> true p`;; let semcomplete = new_definition `semcomplete A <=> !p. true p ==> A |-- p`;; let generalize = new_definition `generalize vs p = ITLIST (!!) vs p`;; let closure = new_definition `closure p = generalize (list_of_set(FV p)) p`;; let TRUE_GENERALIZE = prove (`!vs p. true(generalize vs p) <=> true p`, REWRITE_TAC[generalize; true_def] THEN LIST_INDUCT_TAC THEN REWRITE_TAC[ITLIST; holds] THEN GEN_TAC THEN FIRST_X_ASSUM(fun th -> GEN_REWRITE_TAC RAND_CONV [GSYM th]) THEN MESON_TAC[VALMOD_REPEAT]);; let PROVABLE_GENERALIZE = prove (`!A p vs. A |-- generalize vs p <=> A |-- p`, GEN_TAC THEN GEN_TAC THEN REWRITE_TAC[generalize] THEN LIST_INDUCT_TAC THEN REWRITE_TAC[ITLIST] THEN FIRST_X_ASSUM(SUBST1_TAC o SYM) THEN MESON_TAC[spec; gen; FORMSUBST_TRIV; ASSIGN_TRIV]);; let FV_GENERALIZE = prove (`!p vs. FV(generalize vs p) = FV(p) DIFF (set_of_list vs)`, GEN_TAC THEN REWRITE_TAC[generalize] THEN LIST_INDUCT_TAC THEN REWRITE_TAC[set_of_list; DIFF_EMPTY; ITLIST] THEN ASM_REWRITE_TAC[FV] THEN SET_TAC[]);; let CLOSED_CLOSURE = prove (`!p. closed(closure p)`, REWRITE_TAC[closed; closure; FV_GENERALIZE] THEN SIMP_TAC[SET_OF_LIST_OF_SET; FV_FINITE; DIFF_EQ_EMPTY]);; let TRUE_CLOSURE = prove (`!p. true(closure p) <=> true p`, REWRITE_TAC[closure; TRUE_GENERALIZE]);; let PROVABLE_CLOSURE = prove (`!A p. A |-- closure p <=> A |-- p`, REWRITE_TAC[closure; PROVABLE_GENERALIZE]);; let DEFINABLE_DEFINABLE_BY = prove (`definable = definable_by (\x. T)`, REWRITE_TAC[FUN_EQ_THM; definable; definable_by]);; let DEFINABLE_ONEVAR = prove (`definable s <=> ?p x. (FV p = {x}) /\ !v. holds v p <=> (v x) IN s`, REWRITE_TAC[definable] THEN EQ_TAC THENL [ALL_TAC; MESON_TAC[]] THEN DISCH_THEN(X_CHOOSE_THEN `p:form` (X_CHOOSE_TAC `x:num`)) THEN EXISTS_TAC `(V x === V x) && formsubst (\y. if y = x then V x else Z) p` THEN EXISTS_TAC `x:num` THEN ASM_REWRITE_TAC[HOLDS_FORMSUBST; FORMSUBST_FV; FV; holds] THEN REWRITE_TAC[COND_RAND; EXTENSION; IN_ELIM_THM; IN_SING; FVT; IN_UNION; COND_EXPAND; NOT_IN_EMPTY; o_THM; termval] THEN MESON_TAC[]);; let CLOSED_TRUE_OR_FALSE = prove (`!p. closed p ==> true p \/ true(Not p)`, REWRITE_TAC[closed; true_def; holds] THEN REPEAT STRIP_TAC THEN ASM_MESON_TAC[HOLDS_VALUATION; NOT_IN_EMPTY]);; let SEMCOMPLETE_IMP_COMPLETE = prove (`!A. semcomplete A ==> complete A`, REWRITE_TAC[semcomplete; complete] THEN MESON_TAC[CLOSED_TRUE_OR_FALSE]);; let SOUND_CLOSED = prove (`sound A <=> !p. closed p /\ A |-- p ==> true p`, REWRITE_TAC[sound] THEN EQ_TAC THENL [MESON_TAC[]; ALL_TAC] THEN MESON_TAC[TRUE_CLOSURE; PROVABLE_CLOSURE; CLOSED_CLOSURE]);; let SOUND_IMP_CONSISTENT = prove (`!A. sound A ==> consistent A`, REWRITE_TAC[sound; consistent; CONSISTENT_ALT] THEN SUBGOAL_THEN `~(true False)` (fun th -> MESON_TAC[th]) THEN REWRITE_TAC[true_def; holds]);; let SEMCOMPLETE_SOUND_EQ_CONSISTENT = prove (`!A. semcomplete A ==> (sound A <=> consistent A)`, REWRITE_TAC[semcomplete] THEN REPEAT STRIP_TAC THEN EQ_TAC THEN REWRITE_TAC[SOUND_IMP_CONSISTENT] THEN REWRITE_TAC[consistent; SOUND_CLOSED] THEN ASM_MESON_TAC[CLOSED_TRUE_OR_FALSE]);;
81b6ea9e3f47f69d848ab680cf9e5cd5798d7ab2b88928d7119f46dcaf8d0cea
haskell-opengl/GLUT
OnYourOwn1.hs
OnYourOwn1.hs ( adapted from OnYourOwn1 which is ( c ) 2004 Astle / Hawkins ) Copyright ( c ) 2018 < > This file is part of HOpenGL and distributed under a BSD - style license See the file libraries / GLUT / LICENSE OnYourOwn1.hs (adapted from OnYourOwn1 which is (c) 2004 Astle/Hawkins) Copyright (c) Sven Panne 2018 <> This file is part of HOpenGL and distributed under a BSD-style license See the file libraries/GLUT/LICENSE -} import Control.Monad ( when, unless ) import Data.Maybe ( isJust ) import Graphics.UI.GLUT hiding ( initialize ) import System.Console.GetOpt import System.Environment ( getProgName ) import System.Exit ( exitWith, ExitCode(..) ) import System.IO ( hPutStr, stderr ) -------------------------------------------------------------------------------- -- Setup GLUT and OpenGL, drop into the event loop. -------------------------------------------------------------------------------- main :: IO () main = do Setup the basic GLUT stuff (_, args) <- getArgsAndInitialize opts <- parseOptions args initialDisplayMode $= [ DoubleBuffered, RGBMode, WithDepthBuffer ] (if useFullscreen opts then fullscreenMode else windowedMode) opts initialize -- Register the event callback functions displayCallback $= do render; swapBuffers reshapeCallback $= Just setupProjection keyboardMouseCallback $= Just keyboardMouseHandler -- No need for an idle callback here, this would just hog the CPU -- without any visible effect At this point , control is relinquished to the GLUT event handler . Control is returned as events occur , via the callback functions . mainLoop fullscreenMode :: Options -> IO () fullscreenMode opts = do let addCapability c = maybe id (\x -> (Where' c IsEqualTo x :)) gameModeCapabilities $= (addCapability GameModeWidth (Just (windowWidth opts)) . addCapability GameModeHeight (Just (windowHeight opts)) . addCapability GameModeBitsPerPlane (bpp opts) . addCapability GameModeRefreshRate (refreshRate opts)) [] _ <- enterGameMode maybeWin <- get currentWindow if isJust maybeWin then cursor $= None else do hPutStr stderr "Could not enter fullscreen mode, using windowed mode\n" windowedMode (opts { useFullscreen = False } ) windowedMode :: Options -> IO () windowedMode opts = do initialWindowSize $= Size (fromIntegral (windowWidth opts)) (fromIntegral (windowHeight opts)) _ <- createWindow "BOGLGP - Chapter 3 - On Your Own 1" return () -------------------------------------------------------------------------------- -- Option handling -------------------------------------------------------------------------------- data Options = Options { useFullscreen :: Bool, windowWidth :: Int, windowHeight :: Int, bpp :: Maybe Int, refreshRate :: Maybe Int } startOpt :: Options startOpt = Options { useFullscreen = False, windowWidth = 800, windowHeight = 600, bpp = Nothing, refreshRate = Nothing } options :: [OptDescr (Options -> IO Options)] options = [ Option ['f'] ["fullscreen"] (NoArg (\opt -> return opt { useFullscreen = True })) "use fullscreen mode if possible", Option ['w'] ["width"] (ReqArg (\arg opt -> do w <- readInt "WIDTH" arg return opt { windowWidth = w }) "WIDTH") "use window width WIDTH", Option ['h'] ["height"] (ReqArg (\arg opt -> do h <- readInt "HEIGHT" arg return opt { windowHeight = h }) "HEIGHT") "use window height HEIGHT", Option ['b'] ["bpp"] (ReqArg (\arg opt -> do b <- readInt "BPP" arg return opt { bpp = Just b }) "BPP") "use BPP bits per plane (ignored in windowed mode)", Option ['r'] ["refresh-rate"] (ReqArg (\arg opt -> do r <- readInt "HZ" arg return opt { refreshRate = Just r }) "HZ") "use refresh rate HZ (ignored in windowed mode)", Option ['?'] ["help"] (NoArg (\_ -> do usage >>= putStr safeExitWith ExitSuccess)) "show help" ] readInt :: String -> String -> IO Int readInt name arg = case reads arg of ((x,[]) : _) -> return x _ -> dieWith ["Can't parse " ++ name ++ " argument '" ++ arg ++ "'\n"] usage :: IO String usage = do progName <- getProgName return $ usageInfo ("Usage: " ++ progName ++ " [OPTION...]") options parseOptions :: [String] -> IO Options parseOptions args = do let (optsActions, nonOptions, errs) = getOpt Permute options args unless (null nonOptions && null errs) (dieWith errs) foldl (>>=) (return startOpt) optsActions dieWith :: [String] -> IO a dieWith errs = do u <- usage mapM_ (hPutStr stderr) (errs ++ [u]) safeExitWith (ExitFailure 1) -------------------------------------------------------------------------------- -- Handle mouse and keyboard events. For this simple demo, just exit when -- ESCAPE is pressed. -------------------------------------------------------------------------------- keyboardMouseHandler :: KeyboardMouseCallback keyboardMouseHandler (Char '\27') Down _ _ = safeExitWith ExitSuccess keyboardMouseHandler _ _ _ _ = return () safeExitWith :: ExitCode -> IO a safeExitWith code = do gma <- get gameModeActive when gma leaveGameMode exitWith code -------------------------------------------------------------------------------- Do one time setup , i.e. set the clear color . -------------------------------------------------------------------------------- initialize :: IO () initialize = do -- clear to black background clearColor $= Color4 0 0 0 0 -------------------------------------------------------------------------------- -- Reset the viewport for window changes. -------------------------------------------------------------------------------- setupProjection :: ReshapeCallback setupProjection (Size width height) = do do n't want a divide by zero let h = max 1 height -- reset the viewport to new dimensions viewport $= (Position 0 0, Size width h) -- set projection matrix as the current matrix matrixMode $= Projection -- reset projection matrix loadIdentity -- calculate aspect ratio of window perspective 52 (fromIntegral width / fromIntegral h) 1 1000 -- set modelview matrix matrixMode $= Modelview 0 -- reset modelview matrix loadIdentity -------------------------------------------------------------------------------- -- Clear and redraw the scene. -------------------------------------------------------------------------------- render :: DisplayCallback render = do -- clear screen and depth buffer clear [ ColorBuffer, DepthBuffer ] loadIdentity lookAt (Vertex3 0 10 0.1) (Vertex3 0 0 0) (Vector3 0 1 0) -- resolve overloading, not needed in "real" programs let color3f = color :: Color3 GLfloat -> IO () color3f (Color3 1 1 1) drawCircleApproximation 2 10 False -- Hello, this is C... :-) for :: [GLint] -> (GLint -> IO ()) -> IO () for = flip mapM_ drawCircleApproximation :: GLfloat -> GLint -> Bool -> IO () drawCircleApproximation radius numberOfSides edgeOnly = -- if edge only, use line strips; otherwise, use polygons renderPrimitive (if edgeOnly then LineStrip else Polygon) $ do -- calculate each vertex on the circle for [ 0 .. numberOfSides - 1 ] $ \v -> do -- calculate the angle of the current vertex let angle = fromIntegral v * 2 * pi / fromIntegral numberOfSides -- draw the current vertex at the correct radius vertex (Vertex3 (cos angle * radius) 0 (sin angle * radius)) if drawing edge only , then need to complete the loop with first vertex when edgeOnly $ vertex (Vertex3 radius 0 0)
null
https://raw.githubusercontent.com/haskell-opengl/GLUT/36207fa51e4c1ea1e5512aeaa373198a4a56cad0/examples/BOGLGP/Chapter03/OnYourOwn1.hs
haskell
------------------------------------------------------------------------------ Setup GLUT and OpenGL, drop into the event loop. ------------------------------------------------------------------------------ Register the event callback functions No need for an idle callback here, this would just hog the CPU without any visible effect ------------------------------------------------------------------------------ Option handling ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ Handle mouse and keyboard events. For this simple demo, just exit when ESCAPE is pressed. ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ clear to black background ------------------------------------------------------------------------------ Reset the viewport for window changes. ------------------------------------------------------------------------------ reset the viewport to new dimensions set projection matrix as the current matrix reset projection matrix calculate aspect ratio of window set modelview matrix reset modelview matrix ------------------------------------------------------------------------------ Clear and redraw the scene. ------------------------------------------------------------------------------ clear screen and depth buffer resolve overloading, not needed in "real" programs Hello, this is C... :-) if edge only, use line strips; otherwise, use polygons calculate each vertex on the circle calculate the angle of the current vertex draw the current vertex at the correct radius
OnYourOwn1.hs ( adapted from OnYourOwn1 which is ( c ) 2004 Astle / Hawkins ) Copyright ( c ) 2018 < > This file is part of HOpenGL and distributed under a BSD - style license See the file libraries / GLUT / LICENSE OnYourOwn1.hs (adapted from OnYourOwn1 which is (c) 2004 Astle/Hawkins) Copyright (c) Sven Panne 2018 <> This file is part of HOpenGL and distributed under a BSD-style license See the file libraries/GLUT/LICENSE -} import Control.Monad ( when, unless ) import Data.Maybe ( isJust ) import Graphics.UI.GLUT hiding ( initialize ) import System.Console.GetOpt import System.Environment ( getProgName ) import System.Exit ( exitWith, ExitCode(..) ) import System.IO ( hPutStr, stderr ) main :: IO () main = do Setup the basic GLUT stuff (_, args) <- getArgsAndInitialize opts <- parseOptions args initialDisplayMode $= [ DoubleBuffered, RGBMode, WithDepthBuffer ] (if useFullscreen opts then fullscreenMode else windowedMode) opts initialize displayCallback $= do render; swapBuffers reshapeCallback $= Just setupProjection keyboardMouseCallback $= Just keyboardMouseHandler At this point , control is relinquished to the GLUT event handler . Control is returned as events occur , via the callback functions . mainLoop fullscreenMode :: Options -> IO () fullscreenMode opts = do let addCapability c = maybe id (\x -> (Where' c IsEqualTo x :)) gameModeCapabilities $= (addCapability GameModeWidth (Just (windowWidth opts)) . addCapability GameModeHeight (Just (windowHeight opts)) . addCapability GameModeBitsPerPlane (bpp opts) . addCapability GameModeRefreshRate (refreshRate opts)) [] _ <- enterGameMode maybeWin <- get currentWindow if isJust maybeWin then cursor $= None else do hPutStr stderr "Could not enter fullscreen mode, using windowed mode\n" windowedMode (opts { useFullscreen = False } ) windowedMode :: Options -> IO () windowedMode opts = do initialWindowSize $= Size (fromIntegral (windowWidth opts)) (fromIntegral (windowHeight opts)) _ <- createWindow "BOGLGP - Chapter 3 - On Your Own 1" return () data Options = Options { useFullscreen :: Bool, windowWidth :: Int, windowHeight :: Int, bpp :: Maybe Int, refreshRate :: Maybe Int } startOpt :: Options startOpt = Options { useFullscreen = False, windowWidth = 800, windowHeight = 600, bpp = Nothing, refreshRate = Nothing } options :: [OptDescr (Options -> IO Options)] options = [ Option ['f'] ["fullscreen"] (NoArg (\opt -> return opt { useFullscreen = True })) "use fullscreen mode if possible", Option ['w'] ["width"] (ReqArg (\arg opt -> do w <- readInt "WIDTH" arg return opt { windowWidth = w }) "WIDTH") "use window width WIDTH", Option ['h'] ["height"] (ReqArg (\arg opt -> do h <- readInt "HEIGHT" arg return opt { windowHeight = h }) "HEIGHT") "use window height HEIGHT", Option ['b'] ["bpp"] (ReqArg (\arg opt -> do b <- readInt "BPP" arg return opt { bpp = Just b }) "BPP") "use BPP bits per plane (ignored in windowed mode)", Option ['r'] ["refresh-rate"] (ReqArg (\arg opt -> do r <- readInt "HZ" arg return opt { refreshRate = Just r }) "HZ") "use refresh rate HZ (ignored in windowed mode)", Option ['?'] ["help"] (NoArg (\_ -> do usage >>= putStr safeExitWith ExitSuccess)) "show help" ] readInt :: String -> String -> IO Int readInt name arg = case reads arg of ((x,[]) : _) -> return x _ -> dieWith ["Can't parse " ++ name ++ " argument '" ++ arg ++ "'\n"] usage :: IO String usage = do progName <- getProgName return $ usageInfo ("Usage: " ++ progName ++ " [OPTION...]") options parseOptions :: [String] -> IO Options parseOptions args = do let (optsActions, nonOptions, errs) = getOpt Permute options args unless (null nonOptions && null errs) (dieWith errs) foldl (>>=) (return startOpt) optsActions dieWith :: [String] -> IO a dieWith errs = do u <- usage mapM_ (hPutStr stderr) (errs ++ [u]) safeExitWith (ExitFailure 1) keyboardMouseHandler :: KeyboardMouseCallback keyboardMouseHandler (Char '\27') Down _ _ = safeExitWith ExitSuccess keyboardMouseHandler _ _ _ _ = return () safeExitWith :: ExitCode -> IO a safeExitWith code = do gma <- get gameModeActive when gma leaveGameMode exitWith code Do one time setup , i.e. set the clear color . initialize :: IO () initialize = do clearColor $= Color4 0 0 0 0 setupProjection :: ReshapeCallback setupProjection (Size width height) = do do n't want a divide by zero let h = max 1 height viewport $= (Position 0 0, Size width h) matrixMode $= Projection loadIdentity perspective 52 (fromIntegral width / fromIntegral h) 1 1000 matrixMode $= Modelview 0 loadIdentity render :: DisplayCallback render = do clear [ ColorBuffer, DepthBuffer ] loadIdentity lookAt (Vertex3 0 10 0.1) (Vertex3 0 0 0) (Vector3 0 1 0) let color3f = color :: Color3 GLfloat -> IO () color3f (Color3 1 1 1) drawCircleApproximation 2 10 False for :: [GLint] -> (GLint -> IO ()) -> IO () for = flip mapM_ drawCircleApproximation :: GLfloat -> GLint -> Bool -> IO () drawCircleApproximation radius numberOfSides edgeOnly = renderPrimitive (if edgeOnly then LineStrip else Polygon) $ do for [ 0 .. numberOfSides - 1 ] $ \v -> do let angle = fromIntegral v * 2 * pi / fromIntegral numberOfSides vertex (Vertex3 (cos angle * radius) 0 (sin angle * radius)) if drawing edge only , then need to complete the loop with first vertex when edgeOnly $ vertex (Vertex3 radius 0 0)
eb07230dcef7c6e40f1f68d79f441c8d0fdcdb440461546824cb47ba653eb6c3
rm-hull/project-euler
euler072.clj
EULER # 072 ;; ========== ;; Consider the fraction, n/d, where n and d are positive integers. If n < d and HCF(n , d)=1 , it is called a reduced proper fraction . ;; If we list the set of reduced proper fractions for d < = 8 in ascending ;; order of size, we get: ;; 1/8 , 1/7 , 1/6 , 1/5 , 1/4 , 2/7 , 1/3 , 3/8 , 2/5 , 3/7 , 1/2 , 4/7 , 3/5 , 5/8 , 2/3 , 5/7 , 3/4 , 4/5 , 5/6 , 6/7 , 7/8 ;; It can be seen that there are 21 elements in this set . ;; ;; How many elements would be contained in the set of reduced proper fractions for d < = 1,000,000 ? ;; (ns euler072 (:use [util.primes])) (defn calc [coll] (reduce + (map phi coll))) (defn solve [n p] (->> (range 1 (inc n)) (partition-all p) (pmap calc) (reduce +))) (time (solve 1000000 100000))
null
https://raw.githubusercontent.com/rm-hull/project-euler/04e689e87a1844cfd83229bb4628051e3ac6a325/src/euler072.clj
clojure
========== Consider the fraction, n/d, where n and d are positive integers. If n < d order of size, we get: How many elements would be contained in the set of reduced proper fractions
EULER # 072 and HCF(n , d)=1 , it is called a reduced proper fraction . If we list the set of reduced proper fractions for d < = 8 in ascending 1/8 , 1/7 , 1/6 , 1/5 , 1/4 , 2/7 , 1/3 , 3/8 , 2/5 , 3/7 , 1/2 , 4/7 , 3/5 , 5/8 , 2/3 , 5/7 , 3/4 , 4/5 , 5/6 , 6/7 , 7/8 It can be seen that there are 21 elements in this set . for d < = 1,000,000 ? (ns euler072 (:use [util.primes])) (defn calc [coll] (reduce + (map phi coll))) (defn solve [n p] (->> (range 1 (inc n)) (partition-all p) (pmap calc) (reduce +))) (time (solve 1000000 100000))
5bc41f74ca924ada06e4c19bf9211da709c896fc82c3e1b731db781ed18db10a
hanshuebner/vlm
traps.lisp
-*- Mode : LISP ; Package : POWERPC - INTERNALS ; Base : 10 ; Syntax : Common - Lisp ; -*- ;;; WARNING ! ! DO NOT MODIFY THIS FILE ! It was automatically generated from vlm : . Any changes made to it will be lost . #+Alpha-AXP-Emulator (in-package "ALPHA-AXP-INTERNALS") #+PowerPC-Emulator (in-package "POWERPC-INTERNALS") (defconstant |trapvector|$k-|stackoverflow| 2627) (defconstant |TrapVectorStackOverflow| 2627) (defconstant |trapvector|$k-|instructionexception| 2048) (defconstant |TrapVectorInstructionException| 2048) (defconstant |trapvector|$k-|arithmeticinstructionexception| 0) (defconstant |TrapVectorArithmeticInstructionException| 0) (defconstant |trapvector|$k-|error| 2624) (defconstant |TrapVectorError| 2624) (defconstant |trapvector|$k-|reset| 2625) (defconstant |TrapVectorReset| 2625) (defconstant |trapvector|$k-|pullapplyargs| 2626) (defconstant |TrapVectorPullApplyArgs| 2626) (defconstant |trapvector|$k-|trace| 2628) (defconstant |TrapVectorTrace| 2628) (defconstant |trapvector|$k-|preemptrequest| 2629) (defconstant |TrapVectorPreemptRequest| 2629) (defconstant |trapvector|$k-|lowprioritysequencebreak| 2632) (defconstant |TrapVectorLowPrioritySequenceBreak| 2632) (defconstant |trapvector|$k-|highprioritysequencebreak| 2633) (defconstant |TrapVectorHighPrioritySequenceBreak| 2633) (defconstant |trapvector|$k-|dbunwindframe| 2646) (defconstant |TrapVectorDBUnwindFrame| 2646) (defconstant |trapvector|$k-|dbunwindcatch| 2647) (defconstant |TrapVectorDBUnwindCatch| 2647) (defconstant |trapvector|$k-|transport| 2630) (defconstant |TrapVectorTransport| 2630) (defconstant |trapvector|$k-|monitor| 2634) (defconstant |TrapVectorMonitor| 2634) (defconstant |trapvector|$k-|pagenotresident| 2640) (defconstant |TrapVectorPageNotResident| 2640) (defconstant |trapvector|$k-|pagefaultrequest| 2641) (defconstant |TrapVectorPageFaultRequest| 2641) (defconstant |trapvector|$k-|pagewritefault| 2642) (defconstant |TrapVectorPageWriteFault| 2642) (defconstant |trapvector|$k-|uncorrectablememoryerror| 2643) (defconstant |TrapVectorUncorrectableMemoryError| 2643) (defconstant |trapvector|$k-|memorybuserror| 2644) (defconstant |TrapVectorMemoryBusError| 2644) (defconstant |trapvector|$k-|dbcachemiss| 2645) (defconstant |TrapVectorDBCacheMiss| 2645) (defconstant |trapmeter|$k-|stackoverflow| 0) (defconstant |TrapMeterStackOverflow| 0) (defconstant |trapmeter|$k-|instructionexception| 1) (defconstant |TrapMeterInstructionException| 1) (defconstant |trapmeter|$k-|arithmeticinstructionexception| 2) (defconstant |TrapMeterArithmeticInstructionException| 2) (defconstant |trapmeter|$k-|error| 3) (defconstant |TrapMeterError| 3) (defconstant |trapmeter|$k-|reset| 4) (defconstant |TrapMeterReset| 4) (defconstant |trapmeter|$k-|pullapplyargs| 5) (defconstant |TrapMeterPullApplyArgs| 5) (defconstant |trapmeter|$k-|trace| 6) (defconstant |TrapMeterTrace| 6) (defconstant |trapmeter|$k-|preemptrequest| 7) (defconstant |TrapMeterPreemptRequest| 7) (defconstant |trapmeter|$k-|lowprioritysequencebreak| 8) (defconstant |TrapMeterLowPrioritySequenceBreak| 8) (defconstant |trapmeter|$k-|highprioritysequencebreak| 9) (defconstant |TrapMeterHighPrioritySequenceBreak| 9) (defconstant |trapmeter|$k-|dbunwindframe| 10) (defconstant |TrapMeterDBUnwindFrame| 10) (defconstant |trapmeter|$k-|dbunwindcatch| 11) (defconstant |TrapMeterDBUnwindCatch| 11) (defconstant |trapmeter|$k-|transport| 12) (defconstant |TrapMeterTransport| 12) (defconstant |trapmeter|$k-|monitor| 13) (defconstant |TrapMeterMonitor| 13) (defconstant |trapmeter|$k-|pagenotresident| 14) (defconstant |TrapMeterPageNotResident| 14) (defconstant |trapmeter|$k-|pagefaultrequest| 15) (defconstant |TrapMeterPageFaultRequest| 15) (defconstant |trapmeter|$k-|pagewritefault| 16) (defconstant |TrapMeterPageWriteFault| 16) (defconstant |trapmeter|$k-|uncorrectablememoryerror| 17) (defconstant |TrapMeterUncorrectableMemoryError| 17) (defconstant |trapmeter|$k-|memorybuserror| 18) (defconstant |TrapMeterMemoryBusError| 18) (defconstant |trapmeter|$k-|dbcachemiss| 19) (defconstant |TrapMeterDBCacheMiss| 19) (defconstant |trapmeter|$k-|nentries| 20) (defconstant |TrapMeterNEntries| 20)
null
https://raw.githubusercontent.com/hanshuebner/vlm/20510ddc98b52252a406012a50a4d3bbd1b75dd0/emulator/traps.lisp
lisp
Package : POWERPC - INTERNALS ; Base : 10 ; Syntax : Common - Lisp ; -*-
WARNING ! ! DO NOT MODIFY THIS FILE ! It was automatically generated from vlm : . Any changes made to it will be lost . #+Alpha-AXP-Emulator (in-package "ALPHA-AXP-INTERNALS") #+PowerPC-Emulator (in-package "POWERPC-INTERNALS") (defconstant |trapvector|$k-|stackoverflow| 2627) (defconstant |TrapVectorStackOverflow| 2627) (defconstant |trapvector|$k-|instructionexception| 2048) (defconstant |TrapVectorInstructionException| 2048) (defconstant |trapvector|$k-|arithmeticinstructionexception| 0) (defconstant |TrapVectorArithmeticInstructionException| 0) (defconstant |trapvector|$k-|error| 2624) (defconstant |TrapVectorError| 2624) (defconstant |trapvector|$k-|reset| 2625) (defconstant |TrapVectorReset| 2625) (defconstant |trapvector|$k-|pullapplyargs| 2626) (defconstant |TrapVectorPullApplyArgs| 2626) (defconstant |trapvector|$k-|trace| 2628) (defconstant |TrapVectorTrace| 2628) (defconstant |trapvector|$k-|preemptrequest| 2629) (defconstant |TrapVectorPreemptRequest| 2629) (defconstant |trapvector|$k-|lowprioritysequencebreak| 2632) (defconstant |TrapVectorLowPrioritySequenceBreak| 2632) (defconstant |trapvector|$k-|highprioritysequencebreak| 2633) (defconstant |TrapVectorHighPrioritySequenceBreak| 2633) (defconstant |trapvector|$k-|dbunwindframe| 2646) (defconstant |TrapVectorDBUnwindFrame| 2646) (defconstant |trapvector|$k-|dbunwindcatch| 2647) (defconstant |TrapVectorDBUnwindCatch| 2647) (defconstant |trapvector|$k-|transport| 2630) (defconstant |TrapVectorTransport| 2630) (defconstant |trapvector|$k-|monitor| 2634) (defconstant |TrapVectorMonitor| 2634) (defconstant |trapvector|$k-|pagenotresident| 2640) (defconstant |TrapVectorPageNotResident| 2640) (defconstant |trapvector|$k-|pagefaultrequest| 2641) (defconstant |TrapVectorPageFaultRequest| 2641) (defconstant |trapvector|$k-|pagewritefault| 2642) (defconstant |TrapVectorPageWriteFault| 2642) (defconstant |trapvector|$k-|uncorrectablememoryerror| 2643) (defconstant |TrapVectorUncorrectableMemoryError| 2643) (defconstant |trapvector|$k-|memorybuserror| 2644) (defconstant |TrapVectorMemoryBusError| 2644) (defconstant |trapvector|$k-|dbcachemiss| 2645) (defconstant |TrapVectorDBCacheMiss| 2645) (defconstant |trapmeter|$k-|stackoverflow| 0) (defconstant |TrapMeterStackOverflow| 0) (defconstant |trapmeter|$k-|instructionexception| 1) (defconstant |TrapMeterInstructionException| 1) (defconstant |trapmeter|$k-|arithmeticinstructionexception| 2) (defconstant |TrapMeterArithmeticInstructionException| 2) (defconstant |trapmeter|$k-|error| 3) (defconstant |TrapMeterError| 3) (defconstant |trapmeter|$k-|reset| 4) (defconstant |TrapMeterReset| 4) (defconstant |trapmeter|$k-|pullapplyargs| 5) (defconstant |TrapMeterPullApplyArgs| 5) (defconstant |trapmeter|$k-|trace| 6) (defconstant |TrapMeterTrace| 6) (defconstant |trapmeter|$k-|preemptrequest| 7) (defconstant |TrapMeterPreemptRequest| 7) (defconstant |trapmeter|$k-|lowprioritysequencebreak| 8) (defconstant |TrapMeterLowPrioritySequenceBreak| 8) (defconstant |trapmeter|$k-|highprioritysequencebreak| 9) (defconstant |TrapMeterHighPrioritySequenceBreak| 9) (defconstant |trapmeter|$k-|dbunwindframe| 10) (defconstant |TrapMeterDBUnwindFrame| 10) (defconstant |trapmeter|$k-|dbunwindcatch| 11) (defconstant |TrapMeterDBUnwindCatch| 11) (defconstant |trapmeter|$k-|transport| 12) (defconstant |TrapMeterTransport| 12) (defconstant |trapmeter|$k-|monitor| 13) (defconstant |TrapMeterMonitor| 13) (defconstant |trapmeter|$k-|pagenotresident| 14) (defconstant |TrapMeterPageNotResident| 14) (defconstant |trapmeter|$k-|pagefaultrequest| 15) (defconstant |TrapMeterPageFaultRequest| 15) (defconstant |trapmeter|$k-|pagewritefault| 16) (defconstant |TrapMeterPageWriteFault| 16) (defconstant |trapmeter|$k-|uncorrectablememoryerror| 17) (defconstant |TrapMeterUncorrectableMemoryError| 17) (defconstant |trapmeter|$k-|memorybuserror| 18) (defconstant |TrapMeterMemoryBusError| 18) (defconstant |trapmeter|$k-|dbcachemiss| 19) (defconstant |TrapMeterDBCacheMiss| 19) (defconstant |trapmeter|$k-|nentries| 20) (defconstant |TrapMeterNEntries| 20)
fd377becd661ab5999caa3b700426b04420b36052217d6a8aef2d78b99c5fa00
devaspot/games
tavla_scoring.erl
%% Author: serge Created : Jan 24 , 2013 %% Description: -module(tavla_scoring). -include_lib("eunit/include/eunit.hrl"). %% %% Exported Functions %% -export([ init/3, last_round_result/1, round_finished/2 ]). -define(MODE_STANDARD, standard). -define(MODE_PAIRED, paired). -define(ACH_WIN_NORMAL, 1). -define(ACH_WIN_MARS, 2). -define(ACH_OPP_SURRENDER_NORMAL, 3). -define(ACH_OPP_SURRENDER_MARS, 4). -record(state, {mode :: standard, seats_num :: integer(), rounds_num :: undefined | pos_integer(), last_round_num :: integer(), [ { SeatNum , DeltaPoints } ] [ { SeatNum , [ { AchId , Points } ] } ] [ { SeatNum , Points } ] FinishInfo }). %% %% API Functions %% @spec init(Mode , SeatsInfo , RoundsNum ) - > ScoringState %% @doc Initialises scoring state. %% @end %% Types: %% Mode = standard | paired SeatsInfo = [ { SeatNum , Points } ] %% SeatNum = integer() %% Points = integer() RoundsNum = undefined | ( ) init(Mode, SeatsInfo, RoundsNum) -> gas:info(?MODULE,"TAVLA_NG_SCORING init Mode: ~p SeatsInfo = ~p RoundsNum = ~p", [Mode, SeatsInfo, RoundsNum]), true = lists:member(Mode, [?MODE_STANDARD, ?MODE_PAIRED]), true = is_integer(RoundsNum) orelse RoundsNum == undefined, SeatsNum = length(SeatsInfo), true = lists:seq(1, SeatsNum) == lists:sort([SeatNum || {SeatNum, _} <- SeatsInfo]), #state{mode = Mode, seats_num = SeatsNum, rounds_num = RoundsNum, last_round_num = 0, round_score = undefined, finish_info = undefined, round_achs = undefined, total_score = SeatsInfo }. ) - > { FinishInfo , RoundScore , AchsPoints , TotalScore } | %% no_rounds_played %% @end %% Types: %% FinishInfo = timeout | set_timeout | %% {win, WinnerSeatNum, Condition} %% Condition = normal | mars RoundScore = [ { SeatNum , DeltaPoints } ] AchsPoints = [ { SeatNum , [ { AchId , Points } ] } ] TotalScore = [ { SeatNum , Points } ] last_round_result(#state{last_round_num = 0}) -> no_rounds_played; last_round_result(#state{round_score = RoundScore, round_achs = RoundAchs, total_score = TotalScore, finish_info = FinishInfo }) -> {FinishInfo, RoundScore, RoundAchs, TotalScore}. @spec round_finished(ScoringState , FinishReason ) - > %% {NewScoringState, GameIsOver} %% @end %% Types: %% FinishReason = timeout | set_timeout | { win , SeatNum , Condition } | { surrender , SeatNum , Condition } %% Condition = normal | mars %% GameisOver = boolean() round_finished(#state{mode = GameMode, seats_num = SeatsNum, last_round_num = LastRoundNum, total_score = TotalScore} = State, FinishReason) -> ScoringMode = get_scoring_mode(GameMode), PointingRules = get_pointing_rules(ScoringMode), Seats = lists:seq(1, SeatsNum), FinishInfo = finish_info(GameMode, FinishReason), PlayersAchs = players_achivements(GameMode, Seats, FinishInfo), RoundAchs = [{SeatNum, get_achivements_points(PointingRules, Achivements)} || {SeatNum, Achivements} <- PlayersAchs], RoundScore = [{SeatNum, sum_achivements_points(AchPoints)} || {SeatNum, AchPoints} <- RoundAchs], RoundNum = LastRoundNum + 1, NewTotalScore = add_delta(TotalScore, RoundScore), NewState = State#state{last_round_num = RoundNum, round_score = RoundScore, total_score = NewTotalScore, round_achs = RoundAchs, finish_info = FinishInfo}, {NewState, detect_game_finish(NewState)}. %% %% Local Functions %% detect_game_finish(#state{last_round_num = RoundNum, finish_info = FinishInfo, rounds_num = MaxRoundNum}) -> if FinishInfo == set_timeout -> true; true -> RoundNum == MaxRoundNum end. players_achivements(Mode, Seats, FinishInfo) -> case FinishInfo of timeout -> [{SeatNum, player_achivements_no_winner(Mode, SeatNum)} || SeatNum <- Seats]; set_timeout -> [{SeatNum, player_achivements_no_winner(Mode, SeatNum)} || SeatNum <- Seats]; {win, Winner, Condition} -> [{SeatNum, player_achivements_win(Mode, SeatNum, Winner, Condition)} || SeatNum <- Seats]; {surrender, Surrender, Condition} -> [{SeatNum, player_achivements_surrender(Mode, SeatNum, Surrender, Condition)} || SeatNum <- Seats] end. %% finish_info(GameMode, FinishReason) -> %% timeout | %% set_timeout | { win , Winner , Condition } | %% {surrender, Surrender, Condition} finish_info(_GameMode, FinishReason) -> FinishReason. , Achivements ) - > AchsPoints %% @end get_achivements_points(PointingRules, Achivements) -> [{Ach, lists:nth(Ach, PointingRules)} || Ach <- Achivements]. ) - > integer ( ) %% @end sum_achivements_points(AchPoints) -> lists:foldl(fun({_, P}, Acc)-> Acc + P end, 0, AchPoints). , RoundScores ) - > NewTotalScore %% @end add_delta(TotalScore, RoundScores) -> [{SeatNum, proplists:get_value(SeatNum, TotalScore) + Delta} || {SeatNum, Delta} <- RoundScores]. player_achivements_no_winner(Mode, SeatNum) -> player_achivements(Mode, SeatNum, no_winner, undefined, undefined). player_achivements_win(Mode, SeatNum, Winner, Condition) -> player_achivements(Mode, SeatNum, win, Winner, Condition). player_achivements_surrender(Mode, SeatNum, Surrender, Condition) -> player_achivements(Mode, SeatNum, surrender, Surrender, Condition). player_achivements(Mode , SeatNum , FinishType , Subject , Condition ) - > [ { AchId } ] player_achivements(_Mode, SeatNum, FinishType, Subject, Condition) -> 1 {?ACH_WIN_NORMAL, FinishType == win andalso SeatNum == Subject andalso Condition == normal}, 2 {?ACH_WIN_MARS, FinishType == win andalso SeatNum == Subject andalso Condition == mars}, 3 {?ACH_OPP_SURRENDER_NORMAL, FinishType == surrender andalso SeatNum =/= Subject andalso Condition == normal}, 4 {?ACH_OPP_SURRENDER_MARS, FinishType == surrender andalso SeatNum =/= Subject andalso Condition == mars} ], [Ach || {Ach, true} <- L]. get_pointing_rules(ScoringMode) -> {_, Rules} = lists:keyfind(ScoringMode, 1, points_matrix()), Rules. points_matrix() -> 1 2 3 4 < --- achievement number {standard, [1, 2, 1, 2]} ]. %%=================================================================== ) - > ScoringMode %% @end get_scoring_mode(?MODE_STANDARD) -> standard; get_scoring_mode(?MODE_PAIRED) -> standard.
null
https://raw.githubusercontent.com/devaspot/games/a1f7c3169c53d31e56049e90e0094a3f309603ae/apps/server/src/tavla/tavla_scoring.erl
erlang
Author: serge Description: Exported Functions API Functions @doc Initialises scoring state. @end Types: Mode = standard | paired SeatNum = integer() Points = integer() no_rounds_played @end Types: FinishInfo = timeout | set_timeout | {win, WinnerSeatNum, Condition} Condition = normal | mars {NewScoringState, GameIsOver} @end Types: FinishReason = timeout | set_timeout | Condition = normal | mars GameisOver = boolean() Local Functions finish_info(GameMode, FinishReason) -> timeout | set_timeout | {surrender, Surrender, Condition} @end @end @end =================================================================== @end
Created : Jan 24 , 2013 -module(tavla_scoring). -include_lib("eunit/include/eunit.hrl"). -export([ init/3, last_round_result/1, round_finished/2 ]). -define(MODE_STANDARD, standard). -define(MODE_PAIRED, paired). -define(ACH_WIN_NORMAL, 1). -define(ACH_WIN_MARS, 2). -define(ACH_OPP_SURRENDER_NORMAL, 3). -define(ACH_OPP_SURRENDER_MARS, 4). -record(state, {mode :: standard, seats_num :: integer(), rounds_num :: undefined | pos_integer(), last_round_num :: integer(), [ { SeatNum , DeltaPoints } ] [ { SeatNum , [ { AchId , Points } ] } ] [ { SeatNum , Points } ] FinishInfo }). @spec init(Mode , SeatsInfo , RoundsNum ) - > ScoringState SeatsInfo = [ { SeatNum , Points } ] RoundsNum = undefined | ( ) init(Mode, SeatsInfo, RoundsNum) -> gas:info(?MODULE,"TAVLA_NG_SCORING init Mode: ~p SeatsInfo = ~p RoundsNum = ~p", [Mode, SeatsInfo, RoundsNum]), true = lists:member(Mode, [?MODE_STANDARD, ?MODE_PAIRED]), true = is_integer(RoundsNum) orelse RoundsNum == undefined, SeatsNum = length(SeatsInfo), true = lists:seq(1, SeatsNum) == lists:sort([SeatNum || {SeatNum, _} <- SeatsInfo]), #state{mode = Mode, seats_num = SeatsNum, rounds_num = RoundsNum, last_round_num = 0, round_score = undefined, finish_info = undefined, round_achs = undefined, total_score = SeatsInfo }. ) - > { FinishInfo , RoundScore , AchsPoints , TotalScore } | RoundScore = [ { SeatNum , DeltaPoints } ] AchsPoints = [ { SeatNum , [ { AchId , Points } ] } ] TotalScore = [ { SeatNum , Points } ] last_round_result(#state{last_round_num = 0}) -> no_rounds_played; last_round_result(#state{round_score = RoundScore, round_achs = RoundAchs, total_score = TotalScore, finish_info = FinishInfo }) -> {FinishInfo, RoundScore, RoundAchs, TotalScore}. @spec round_finished(ScoringState , FinishReason ) - > { win , SeatNum , Condition } | { surrender , SeatNum , Condition } round_finished(#state{mode = GameMode, seats_num = SeatsNum, last_round_num = LastRoundNum, total_score = TotalScore} = State, FinishReason) -> ScoringMode = get_scoring_mode(GameMode), PointingRules = get_pointing_rules(ScoringMode), Seats = lists:seq(1, SeatsNum), FinishInfo = finish_info(GameMode, FinishReason), PlayersAchs = players_achivements(GameMode, Seats, FinishInfo), RoundAchs = [{SeatNum, get_achivements_points(PointingRules, Achivements)} || {SeatNum, Achivements} <- PlayersAchs], RoundScore = [{SeatNum, sum_achivements_points(AchPoints)} || {SeatNum, AchPoints} <- RoundAchs], RoundNum = LastRoundNum + 1, NewTotalScore = add_delta(TotalScore, RoundScore), NewState = State#state{last_round_num = RoundNum, round_score = RoundScore, total_score = NewTotalScore, round_achs = RoundAchs, finish_info = FinishInfo}, {NewState, detect_game_finish(NewState)}. detect_game_finish(#state{last_round_num = RoundNum, finish_info = FinishInfo, rounds_num = MaxRoundNum}) -> if FinishInfo == set_timeout -> true; true -> RoundNum == MaxRoundNum end. players_achivements(Mode, Seats, FinishInfo) -> case FinishInfo of timeout -> [{SeatNum, player_achivements_no_winner(Mode, SeatNum)} || SeatNum <- Seats]; set_timeout -> [{SeatNum, player_achivements_no_winner(Mode, SeatNum)} || SeatNum <- Seats]; {win, Winner, Condition} -> [{SeatNum, player_achivements_win(Mode, SeatNum, Winner, Condition)} || SeatNum <- Seats]; {surrender, Surrender, Condition} -> [{SeatNum, player_achivements_surrender(Mode, SeatNum, Surrender, Condition)} || SeatNum <- Seats] end. { win , Winner , Condition } | finish_info(_GameMode, FinishReason) -> FinishReason. , Achivements ) - > AchsPoints get_achivements_points(PointingRules, Achivements) -> [{Ach, lists:nth(Ach, PointingRules)} || Ach <- Achivements]. ) - > integer ( ) sum_achivements_points(AchPoints) -> lists:foldl(fun({_, P}, Acc)-> Acc + P end, 0, AchPoints). , RoundScores ) - > NewTotalScore add_delta(TotalScore, RoundScores) -> [{SeatNum, proplists:get_value(SeatNum, TotalScore) + Delta} || {SeatNum, Delta} <- RoundScores]. player_achivements_no_winner(Mode, SeatNum) -> player_achivements(Mode, SeatNum, no_winner, undefined, undefined). player_achivements_win(Mode, SeatNum, Winner, Condition) -> player_achivements(Mode, SeatNum, win, Winner, Condition). player_achivements_surrender(Mode, SeatNum, Surrender, Condition) -> player_achivements(Mode, SeatNum, surrender, Surrender, Condition). player_achivements(Mode , SeatNum , FinishType , Subject , Condition ) - > [ { AchId } ] player_achivements(_Mode, SeatNum, FinishType, Subject, Condition) -> 1 {?ACH_WIN_NORMAL, FinishType == win andalso SeatNum == Subject andalso Condition == normal}, 2 {?ACH_WIN_MARS, FinishType == win andalso SeatNum == Subject andalso Condition == mars}, 3 {?ACH_OPP_SURRENDER_NORMAL, FinishType == surrender andalso SeatNum =/= Subject andalso Condition == normal}, 4 {?ACH_OPP_SURRENDER_MARS, FinishType == surrender andalso SeatNum =/= Subject andalso Condition == mars} ], [Ach || {Ach, true} <- L]. get_pointing_rules(ScoringMode) -> {_, Rules} = lists:keyfind(ScoringMode, 1, points_matrix()), Rules. points_matrix() -> 1 2 3 4 < --- achievement number {standard, [1, 2, 1, 2]} ]. ) - > ScoringMode get_scoring_mode(?MODE_STANDARD) -> standard; get_scoring_mode(?MODE_PAIRED) -> standard.
0ba63738fc48bab4b1ef4936777aeae34d5152cd0716f7c60a2b340ffa68c4c5
input-output-hk/qeditas
script.ml
Copyright ( c ) 2015 The Qeditas developers Distributed under the MIT software license , see the accompanying file COPYING or -license.php . file COPYING or -license.php. *) open Big_int open Ser open Sha256 open Ripemd160 open Hash open Secp256k1 open Cryptocurr open Signat exception Invalid exception OP_ELSE of int list * int list list * int list list exception OP_ENDIF of int list * int list list * int list list let print_bytelist bl = List.iter (fun b -> Printf.printf " %d" b) bl let print_stack stk = List.iter (fun bl -> Printf.printf "*"; print_bytelist bl; Printf.printf "\n") stk let hashval_bytelist h = let (h4,h3,h2,h1,h0) = h in let bl = ref [] in bl := Int32.to_int (Int32.logand h0 255l)::!bl; bl := Int32.to_int (Int32.logand (Int32.shift_right_logical h0 8) 255l)::!bl; bl := Int32.to_int (Int32.logand (Int32.shift_right_logical h0 16) 255l)::!bl; bl := Int32.to_int (Int32.shift_right_logical h0 24)::!bl; bl := Int32.to_int (Int32.logand h1 255l)::!bl; bl := Int32.to_int (Int32.logand (Int32.shift_right_logical h1 8) 255l)::!bl; bl := Int32.to_int (Int32.logand (Int32.shift_right_logical h1 16) 255l)::!bl; bl := Int32.to_int (Int32.shift_right_logical h1 24)::!bl; bl := Int32.to_int (Int32.logand h2 255l)::!bl; bl := Int32.to_int (Int32.logand (Int32.shift_right_logical h2 8) 255l)::!bl; bl := Int32.to_int (Int32.logand (Int32.shift_right_logical h2 16) 255l)::!bl; bl := Int32.to_int (Int32.shift_right_logical h2 24)::!bl; bl := Int32.to_int (Int32.logand h3 255l)::!bl; bl := Int32.to_int (Int32.logand (Int32.shift_right_logical h3 8) 255l)::!bl; bl := Int32.to_int (Int32.logand (Int32.shift_right_logical h3 16) 255l)::!bl; bl := Int32.to_int (Int32.shift_right_logical h3 24)::!bl; bl := Int32.to_int (Int32.logand h4 255l)::!bl; bl := Int32.to_int (Int32.logand (Int32.shift_right_logical h4 8) 255l)::!bl; bl := Int32.to_int (Int32.logand (Int32.shift_right_logical h4 16) 255l)::!bl; bl := Int32.to_int (Int32.shift_right_logical h4 24)::!bl; !bl let md256_bytelist h = let (h7,h6,h5,h4,h3,h2,h1,h0) = h in let bl = ref [] in bl := Int32.to_int (Int32.logand h0 255l)::!bl; bl := Int32.to_int (Int32.logand (Int32.shift_right_logical h0 8) 255l)::!bl; bl := Int32.to_int (Int32.logand (Int32.shift_right_logical h0 16) 255l)::!bl; bl := Int32.to_int (Int32.shift_right_logical h0 24)::!bl; bl := Int32.to_int (Int32.logand h1 255l)::!bl; bl := Int32.to_int (Int32.logand (Int32.shift_right_logical h1 8) 255l)::!bl; bl := Int32.to_int (Int32.logand (Int32.shift_right_logical h1 16) 255l)::!bl; bl := Int32.to_int (Int32.shift_right_logical h1 24)::!bl; bl := Int32.to_int (Int32.logand h2 255l)::!bl; bl := Int32.to_int (Int32.logand (Int32.shift_right_logical h2 8) 255l)::!bl; bl := Int32.to_int (Int32.logand (Int32.shift_right_logical h2 16) 255l)::!bl; bl := Int32.to_int (Int32.shift_right_logical h2 24)::!bl; bl := Int32.to_int (Int32.logand h3 255l)::!bl; bl := Int32.to_int (Int32.logand (Int32.shift_right_logical h3 8) 255l)::!bl; bl := Int32.to_int (Int32.logand (Int32.shift_right_logical h3 16) 255l)::!bl; bl := Int32.to_int (Int32.shift_right_logical h3 24)::!bl; bl := Int32.to_int (Int32.logand h4 255l)::!bl; bl := Int32.to_int (Int32.logand (Int32.shift_right_logical h4 8) 255l)::!bl; bl := Int32.to_int (Int32.logand (Int32.shift_right_logical h4 16) 255l)::!bl; bl := Int32.to_int (Int32.shift_right_logical h4 24)::!bl; bl := Int32.to_int (Int32.logand h4 255l)::!bl; bl := Int32.to_int (Int32.logand (Int32.shift_right_logical h4 8) 255l)::!bl; bl := Int32.to_int (Int32.logand (Int32.shift_right_logical h4 16) 255l)::!bl; bl := Int32.to_int (Int32.shift_right_logical h4 24)::!bl; bl := Int32.to_int (Int32.logand h5 255l)::!bl; bl := Int32.to_int (Int32.logand (Int32.shift_right_logical h5 8) 255l)::!bl; bl := Int32.to_int (Int32.logand (Int32.shift_right_logical h5 16) 255l)::!bl; bl := Int32.to_int (Int32.shift_right_logical h5 24)::!bl; bl := Int32.to_int (Int32.logand h6 255l)::!bl; bl := Int32.to_int (Int32.logand (Int32.shift_right_logical h6 8) 255l)::!bl; bl := Int32.to_int (Int32.logand (Int32.shift_right_logical h6 16) 255l)::!bl; bl := Int32.to_int (Int32.shift_right_logical h6 24)::!bl; bl := Int32.to_int (Int32.logand h7 255l)::!bl; bl := Int32.to_int (Int32.logand (Int32.shift_right_logical h7 8) 255l)::!bl; bl := Int32.to_int (Int32.logand (Int32.shift_right_logical h7 16) 255l)::!bl; bl := Int32.to_int (Int32.shift_right_logical h7 24)::!bl; !bl let hash160_bytelist l = let b = Buffer.create 100 in List.iter (fun x -> Buffer.add_char b (Char.chr x)) l; hash160 (Buffer.contents b) let sha256_bytelist l = let b = Buffer.create 100 in List.iter (fun x -> Buffer.add_char b (Char.chr x)) l; sha256str (Buffer.contents b) let hash256_bytelist l = let b = Buffer.create 100 in List.iter (fun x -> Buffer.add_char b (Char.chr x)) l; sha256dstr (Buffer.contents b) let rec next_bytes i bl = if i > 0 then begin match bl with | [] -> raise (Failure("missing bytes")) | (b::br) -> let (byl,bs) = next_bytes (i-1) br in (b::byl,bs) end else ([],bl) let rec remove_nth n l = match l with | (x::r) -> if n = 0 then r else x::remove_nth (n-1) r | [] -> raise (Failure("remove_nth called with too big an n or too short a list")) (*** inum_le and blnum_le are little endian; inum_be and blnum_be are big endian ***) let rec inumr_le x r s = match x with | [] -> r | (y::z) -> inumr_le z (add_big_int r (shift_left_big_int (big_int_of_int y) s)) (s + 8) let inum_le x = inumr_le x zero_big_int 0 let rec inumr_be x r = match x with | [] -> r | (y::z) -> inumr_be z (or_big_int (big_int_of_int y) (shift_left_big_int r 8)) let inum_be x = inumr_be x zero_big_int let next_inum_le i bl = let (bs,br) = next_bytes i bl in (inum_le bs,br) let next_inum_be i bl = let (bs,br) = next_bytes i bl in (inum_be bs,br) let rec blnum_le x i = if i > 0 then (int_of_big_int (and_big_int x (big_int_of_int 255)))::(blnum_le (shift_right_towards_zero_big_int x 8) (i-1)) else [] let rec blnum_be x i = if i > 0 then (int_of_big_int (and_big_int (shift_right_towards_zero_big_int x ((i-1)*8)) (big_int_of_int 255)))::(blnum_be x (i-1)) else [] let num32 x = let (x0,x1,x2,x3) = match x with | [x0;x1;x2;x3] -> (x0,x1,x2,x3) | [x0;x1;x2] -> (x0,x1,x2,0) | [x0;x1] -> (x0,x1,0,0) | [x0] -> (x0,0,0,0) | [] -> (0,0,0,0) | _ -> raise (Failure "not a 32-bit integer") in Int32.logor (Int32.of_int x0) (Int32.logor (Int32.shift_left (Int32.of_int x1) 8) (Int32.logor (Int32.shift_left (Int32.of_int x2) 16) (Int32.shift_left (Int32.of_int x2) 24))) let blnum32 x = [Int32.to_int (Int32.logand x 255l); Int32.to_int (Int32.logand (Int32.shift_right_logical x 8) 255l); Int32.to_int (Int32.logand (Int32.shift_right_logical x 16) 255l); Int32.to_int (Int32.logand (Int32.shift_right_logical x 24) 255l)] * * format : 02 x , 03 x or 04 x y , * * format: 02 x, 03 x or 04 x y, ***) let bytelist_to_pt bl = match bl with | (z::xl) when z = 2 -> let x = inum_be xl in Some(x,curve_y true x) | (z::xl) when z = 3 -> let x = inum_be xl in Some(x,curve_y false x) | (z::br) when z = 4 -> let (xl,yl) = next_bytes 32 br in let x = inum_be xl in let y = inum_be yl in Printf.printf "x: %s\ny: %s\n" (string_of_big_int x) (string_of_big_int y); Some(x,y) | _ -> None let rec data_from_stack n stk = if n > 0 then begin match stk with | (d::stk2) -> let (data,stkr) = data_from_stack (n-1) stk2 in (d::data,stkr) | [] -> raise (Failure("Unexpected case in data_from_stack, not enough items on the stack")) end else ([],stk) let num_data_from_stack stk = match stk with | (x::stk) -> let n = int_of_big_int (inum_le x) in if n >= 0 then data_from_stack n stk else raise (Failure("Neg number in num_data_from_stack")) | _ -> raise (Failure("Empty stack in num_data_from_stack")) let inside_ifs = ref 0;; let rec skip_statements bl stp = match bl with | [] -> raise (Failure("Ran out of commands before IF block ended")) | (b::br) when List.mem b stp -> (b,br) | (b::br) when b > 0 && b < 76 -> let (byl,bs) = next_bytes b br in skip_statements bs stp | (76::b::br) -> let (byl,bs) = next_bytes b br in skip_statements bs stp | (77::b0::b1::br) -> let (byl,bs) = next_bytes (b0+256*b1) br in skip_statements bs stp | (78::b0::b1::b2::b3::br) -> let (byl,bs) = next_bytes (b0+256*b1+65536*b2+16777216*b3) br in skip_statements bs stp | (b::br) when b = 99 || b = 100 -> let (_,bs) = skip_statements br [104] in skip_statements bs stp | (b::br) -> skip_statements br stp let rec eval_script (tosign:big_int) bl stk altstk = match bl with | [] -> (stk,altstk) | (0::br) -> eval_script tosign br ([]::stk) altstk | (b::br) when b < 76 -> let (byl,bs) = next_bytes b br in eval_script tosign bs (byl::stk) altstk | (76::b::br) -> let (byl,bs) = next_bytes b br in eval_script tosign bs (byl::stk) altstk | (77::b0::b1::br) -> let (byl,bs) = next_bytes (b0+256*b1) br in eval_script tosign bs (byl::stk) altstk | (78::b0::b1::b2::b3::br) -> let (byl,bs) = next_bytes (b0+256*b1+65536*b2+16777216*b3) br in eval_script tosign bs (byl::stk) altstk | (79::br) -> eval_script tosign br ([129]::stk) altstk | (81::br) -> eval_script tosign br ([1]::stk) altstk | (b::br) when b >= 82 && b <= 96 -> eval_script tosign br ([b-80]::stk) altstk | (97::br) -> eval_script tosign br stk altstk | (99::br) -> begin match stk with | x::stkr -> let n = inum_le x in if sign_big_int n = 0 then let (b,bl2) = skip_statements br [103;104] in if b = 103 then eval_script_if tosign bl2 stkr altstk else if b = 104 then eval_script tosign bl2 stkr altstk else begin Printf.printf "IF block ended with %d\n" b; raise (Failure("IF block ended improperly")) end else eval_script_if tosign br stkr altstk | [] -> raise (Failure("Nothing on stack for OP_IF")) end | (100::br) -> begin match stk with | x::stkr -> let n = inum_le x in if sign_big_int n = 0 then eval_script_if tosign br stkr altstk else let (b,bl2) = skip_statements br [103;104] in if b = 103 then eval_script_if tosign bl2 stkr altstk else if b = 104 then eval_script tosign bl2 stkr altstk else begin Printf.printf "IF block ended with %d\n" b; raise (Failure("IF block ended improperly")) end | [] -> raise (Failure("Nothing on stack for OP_NOTIF")) end | (103::br) -> raise (OP_ELSE(br,stk,altstk)) | (104::br) -> raise (OP_ENDIF(br,stk,altstk)) | (105::br) -> begin match stk with | ([1]::stkr) -> eval_script tosign br stk altstk | _ -> raise Invalid end | (106::br) -> raise Invalid | (107::br) -> begin match stk with | (x::stkr) -> eval_script tosign br stkr (x::altstk) | _ -> raise (Failure("not enough inputs to OP_TOALTSTACK")) end | (108::br) -> begin match altstk with | (x::altstkr) -> eval_script tosign br (x::stk) altstkr | _ -> raise (Failure("alt stack empty when OP_FROMALTSTACK occurred")) end | (109::br) -> begin match stk with | (_::_::stkr) -> eval_script tosign br stkr altstk | _ -> raise (Failure("not enough inputs to OP_2DROP")) end | (110::br) -> begin match stk with | (x2::x1::stkr) -> eval_script tosign br (x2::x1::stkr) altstk | _ -> raise (Failure("not enough inputs to OP_2DUP")) end | (111::br) -> begin match stk with | (x3::x2::x1::stkr) -> eval_script tosign br (x3::x2::x1::x3::x2::x1::stkr) altstk | _ -> raise (Failure("not enough inputs to OP_3DUP")) end | (112::br) -> begin match stk with | (x4::x3::x2::x1::stkr) -> eval_script tosign br (x2::x1::x4::x3::x2::x1::stkr) altstk | _ -> raise (Failure("not enough inputs to OP_2OVER")) end | (113::br) -> begin match stk with | (x6::x5::x4::x3::x2::x1::stkr) -> eval_script tosign br (x2::x1::x6::x5::x4::x3::stkr) altstk | _ -> raise (Failure("not enough inputs to OP_2ROT")) end | (114::br) -> begin match stk with | (x4::x3::x2::x1::stkr) -> eval_script tosign br (x2::x1::x4::x3::stkr) altstk | _ -> raise (Failure("not enough inputs to OP_2SWAP")) end | (115::br) -> begin match stk with | ([]::stkr) -> eval_script tosign br stk altstk | (x::stkr) -> eval_script tosign br (x::x::stkr) altstk | _ -> raise (Failure("not enough inputs to OP_IFDUP")) end | (116::br) -> let l = Int32.of_int (List.length stk) in eval_script tosign br (blnum32 l::stk) altstk | (117::br) -> begin match stk with | (_::stkr) -> eval_script tosign br stkr altstk | _ -> raise (Failure("not enough inputs to OP_DROP")) end | (118::br) -> begin match stk with | (x::stkr) -> eval_script tosign br (x::stk) altstk | _ -> raise (Failure("not enough inputs to OP_DUP")) end | (119::br) -> begin match stk with | (x2::x1::stkr) -> eval_script tosign br (x2::stkr) altstk | _ -> raise (Failure("not enough inputs to OP_NIP")) end | (120::br) -> begin match stk with | (x2::x1::stkr) -> eval_script tosign br (x1::x2::x1::stkr) altstk | _ -> raise (Failure("not enough inputs to OP_OVER")) end | (121::br) -> begin match stk with | (x::stkr) -> let n = inum_le x in if lt_big_int n zero_big_int then raise (Failure("neg number given in OP_PICK")) else let n = int_of_big_int n in begin try let xn = List.nth stkr n in eval_script tosign br (xn::stkr) altstk with Failure(z) -> if z = "nth" then raise (Failure("Not enough on stack for OP_PICK")) else raise (Failure(z)) end | _ -> raise (Failure("not enough inputs for OP_PICK")) end | (122::br) -> begin match stk with | (x::stkr) -> let n = inum_le x in if lt_big_int n zero_big_int then raise (Failure("neg number given in OP_ROLL")) else let n = int_of_big_int n in begin try let xn = List.nth stkr n in eval_script tosign br (xn::remove_nth n stkr) altstk with Failure(z) -> if z = "nth" then raise (Failure("Not enough on stack for OP_ROLL")) else raise (Failure(z)) end | _ -> raise (Failure("not enough inputs for OP_ROLL")) end | (123::br) -> begin match stk with | (x3::x2::x1::stkr) -> eval_script tosign br (x1::x3::x2::stkr) altstk | _ -> raise (Failure("not enough inputs to OP_ROT")) end | (124::br) -> begin match stk with | (x2::x1::stkr) -> eval_script tosign br (x1::x2::stkr) altstk | _ -> raise (Failure("not enough inputs to OP_SWAP")) end | (125::br) -> begin match stk with | (x2::x1::stkr) -> eval_script tosign br (x2::x1::x2::stkr) altstk | _ -> raise (Failure("not enough inputs to OP_TUCK")) end | (130::br) -> begin match stk with | (x::stkr) -> let n = List.length x in eval_script tosign br (blnum32 (Int32.of_int n)::stk) altstk | _ -> raise (Failure("not enough inputs to OP_SIZE")) end | (135::br) -> begin match stk with | (x::y::stkr) -> * * Handling this the same way as OP_NUMEQUAL since there are examples where [ ] is considered equal to [ 0 ] . * * eval_script tosign br ([1]::stkr) altstk else eval_script tosign br ([]::stkr) altstk | _ -> raise (Failure ("not enough inputs for OP_EQUAL")) end | (136::br) -> begin match stk with | (x::y::stkr) -> * * Handling this the same way as OP_NUMEQUAL since there are examples where [ ] is considered equal to [ 0 ] . * * eval_script tosign br stkr altstk else raise Invalid | _ -> raise (Failure ("not enough inputs for OP_EQUAL")) end | (139::br) -> begin match stk with | (x::stkr) -> let n = num32 x in eval_script tosign br (blnum32 (Int32.add n 1l)::stkr) altstk | _ -> raise (Failure("not enough inputs to OP_1ADD")) end | (140::br) -> begin match stk with | (x::stkr) -> let n = num32 x in eval_script tosign br (blnum32 (Int32.sub n 1l)::stkr) altstk | _ -> raise (Failure("not enough inputs to OP_1SUB")) end | (143::br) -> begin match stk with | (x::stkr) -> let n = num32 x in eval_script tosign br (blnum32 (Int32.neg n)::stk) altstk | _ -> raise (Failure("not enough inputs to OP_NEGATE")) end | (144::br) -> begin match stk with | (x::stkr) -> let n = num32 x in eval_script tosign br (blnum32 (Int32.abs n)::stk) altstk | _ -> raise (Failure("not enough inputs to OP_ABS")) end | (145::br) -> begin match stk with | (x::stkr) -> let n = inum_le x in if sign_big_int n = 0 then eval_script tosign br ([1]::stkr) altstk else eval_script tosign br ([]::stkr) altstk | _ -> raise (Failure ("not enough inputs for OP_NOT")) end | (146::br) -> begin match stk with | (x::stkr) -> let n = inum_le x in if sign_big_int n = 0 then eval_script tosign br ([]::stkr) altstk else eval_script tosign br ([1]::stkr) altstk | _ -> raise (Failure ("not enough inputs for OP_0NOTEQUAL")) end | (147::br) -> begin match stk with | (y::x::stkr) -> let z = Int32.add (num32 x) (num32 y) in eval_script tosign br (blnum32 z::stkr) altstk | _ -> raise (Failure ("not enough inputs for OP_ADD")) end | (148::br) -> begin match stk with | (y::x::stkr) -> let z = Int32.sub (num32 x) (num32 y) in eval_script tosign br (blnum32 z::stkr) altstk | _ -> raise (Failure ("not enough inputs for OP_SUB")) end | (154::br) -> begin match stk with | (y::x::stkr) -> if sign_big_int (inum_le x) = 0 || sign_big_int (inum_le y) = 0 then eval_script tosign br ([]::stkr) altstk else eval_script tosign br ([1]::stkr) altstk | _ -> raise (Failure ("not enough inputs for OP_BOOLAND")) end | (155::br) -> begin match stk with | (y::x::stkr) -> if sign_big_int (inum_le x) = 0 && sign_big_int (inum_le y) = 0 then eval_script tosign br ([]::stkr) altstk else eval_script tosign br ([1]::stkr) altstk | _ -> raise (Failure ("not enough inputs for OP_BOOLOR")) end | (156::br) -> begin match stk with | (y::x::stkr) -> if eq_big_int (inum_le x) (inum_le y) then eval_script tosign br ([1]::stkr) altstk else eval_script tosign br ([]::stkr) altstk | _ -> raise (Failure ("not enough inputs for OP_NUMEQUAL")) end | (157::br) -> begin match stk with | (y::x::stkr) -> if eq_big_int (inum_le x) (inum_le y) then eval_script tosign br stkr altstk else raise Invalid | _ -> raise (Failure ("not enough inputs for OP_NUMEQUALVERIFY")) end | (158::br) -> begin match stk with | (y::x::stkr) -> if eq_big_int (inum_le x) (inum_le y) then eval_script tosign br ([]::stkr) altstk else eval_script tosign br ([1]::stkr) altstk | _ -> raise (Failure ("not enough inputs for OP_NUMNOTEQUAL")) end | (159::br) -> begin match stk with | (y::x::stkr) -> if lt_big_int (inum_le x) (inum_le y) then eval_script tosign br ([1]::stkr) altstk else eval_script tosign br ([]::stkr) altstk | _ -> raise (Failure ("not enough inputs for OP_LESSTHAN")) end | (160::br) -> begin match stk with | (y::x::stkr) -> if gt_big_int (inum_le x) (inum_le y) then eval_script tosign br ([1]::stkr) altstk else eval_script tosign br ([]::stkr) altstk | _ -> raise (Failure ("not enough inputs for OP_GREATERTHAN")) end | (161::br) -> begin match stk with | (y::x::stkr) -> if le_big_int (inum_le x) (inum_le y) then eval_script tosign br ([1]::stkr) altstk else eval_script tosign br ([]::stkr) altstk | _ -> raise (Failure ("not enough inputs for OP_LESSTHANOREQUAL")) end | (162::br) -> begin match stk with | (y::x::stkr) -> if ge_big_int (inum_le x) (inum_le y) then eval_script tosign br ([1]::stkr) altstk else eval_script tosign br ([]::stkr) altstk | _ -> raise (Failure ("not enough inputs for OP_GREATERTHANOREQUAL")) end | (163::br) -> let min32 x y = if x > y then y else x in begin match stk with | (y::x::stkr) -> let z = min32 (num32 x) (num32 y) in eval_script tosign br (blnum32 z::stkr) altstk | _ -> raise (Failure ("not enough inputs for OP_MIN")) end | (164::br) -> let max32 x y = if x < y then y else x in begin match stk with | (y::x::stkr) -> let z = max32 (num32 x) (num32 y) in eval_script tosign br (blnum32 z::stkr) altstk | _ -> raise (Failure ("not enough inputs for OP_MAX")) end | (165::br) -> begin match stk with | (mx::mn::x::stkr) -> let xx = num32 x in if num32 mn <= xx && xx < (num32 mx) then eval_script tosign br ([1]::stkr) altstk else eval_script tosign br ([]::stkr) altstk | _ -> raise (Failure ("not enough inputs for OP_WITHIN")) end | (168::br) -> begin match stk with | (l::stkr) -> eval_script tosign br ((md256_bytelist (sha256_bytelist l))::stkr) altstk | _ -> raise (Failure ("not enough inputs for SHA256")) end | (169::br) -> begin match stk with | (l::stkr) -> eval_script tosign br ((hashval_bytelist (hash160_bytelist l))::stkr) altstk | _ -> raise (Failure ("not enough inputs for HASH160")) end | (170::br) -> begin match stk with | (l::stkr) -> eval_script tosign br ((md256_bytelist (hash256_bytelist l))::stkr) altstk | _ -> raise (Failure ("not enough inputs for HASH256")) end * OP_CHECKSIG , this differs from Bitcoin ; the ( r , s ) are given as 2 32 - byte big endian integers and are not DER encoded * begin match stk with | (pubkey::gsg::stkr) -> eval_script tosign br (if checksig tosign gsg pubkey then ([1]::stkr) else ([]::stkr)) altstk | _ -> raise (Failure ("not enough inputs for OP_CHECKSIG")) end * , this differs from Bitcoin ; the ( r , s ) are given as 2 32 - byte big endian integers and are not DER encoded * begin match stk with | (pubkey::gsg::stkr) -> if checksig tosign gsg pubkey then eval_script tosign br stkr altstk else raise Invalid | _ -> raise (Failure ("not enough inputs for OP_CHECKSIGVERIFY")) end * OP_CHECK_MULTISIG , this differs from Bitcoin ; it does n't take an extra unused argument ; also the ( r , s ) are given as 2 32 - byte big endian integers and are not DER encoded * let (pubkeys,stk2) = num_data_from_stack stk in let (gsgs,stk3) = num_data_from_stack stk2 in eval_script tosign br (if checkmultisig tosign gsgs pubkeys then ([1]::stk3) else ([]::stk3)) altstk * OP_CHECK_MULTISIG_VERIFY , this differs from Bitcoin ; it does n't take an extra unused argument ; also the ( r , s ) are given as 2 32 - byte big endian integers and are not DER encoded * let (pubkeys,stk2) = num_data_from_stack stk in let (gsgs,stk3) = num_data_from_stack stk2 in if checkmultisig tosign gsgs pubkeys then eval_script tosign br stk3 altstk else raise Invalid | (171::br) -> eval_script tosign br stk altstk (** treat OP_CODESEPARATOR as a no op **) | (b::br) when b = 97 || b >= 176 && b <= 185 -> eval_script tosign br stk altstk (** no ops **) | (80::br) -> if !inside_ifs > 0 then eval_script tosign br stk altstk else raise Invalid | _ -> print_bytelist bl; raise (Failure ("Unhandled case")) and eval_script_if tosign bl stk allstk = try incr inside_ifs; eval_script tosign bl stk allstk with | OP_ELSE(br,stk2,allstk2) -> let (b,br2) = skip_statements br [103;104] in if b = 103 then eval_script_if tosign br2 stk2 allstk2 else if b = 104 then begin decr inside_ifs; eval_script tosign br2 stk2 allstk2 end else begin Printf.printf "IF block ended with %d\n" b; raise (Failure("IF block ended improperly")) end | OP_ENDIF(br,stk2,allstk2) -> decr inside_ifs; eval_script tosign br stk2 allstk2 * * eval_script is mutually recursive with checksig and since endorsements require scripts to be evaluated to check the signatures of endorsees * * and checksig tosign gsg pubkey = try let q = bytelist_to_pt pubkey in match gsg with * * ordinary signature : 0 < r[32 bytes ] > < s[32 bytes ] > * * let (r,sbl) = next_inum_be 32 rsl in let s = inum_be sbl in verify_signed_big_int tosign q (r,s) * * signature via endorsement of a p2pkh to p2pkh : 1 < r[32 bytes ] > < s[32 bytes ] > < r2[32 bytes ] > < s2[32 bytes ] > < compr_or_uncompr_byte > < pubkey2 > * * let (r,esg) = next_inum_be 32 esg in let (s,esg) = next_inum_be 32 esg in let (r2,esg) = next_inum_be 32 esg in let (s2,esg) = next_inum_be 32 esg in begin match esg with | (c::esg) -> let q2 = bytelist_to_pt (c::esg) in begin match q2 with | Some(x2,y2) -> let x2m = big_int_md256 x2 in let beta = if c = 4 then let y2m = big_int_md256 y2 in hashpubkey x2m y2m else hashpubkeyc c x2m in (*** alpha signs that beta can sign ***) let ee = md256_big_int (md256_of_bitcoin_message ("endorse " ^ (addr_qedaddrstr (hashval_p2pkh_addr beta)))) in verify_signed_big_int ee q (r,s) && verify_signed_big_int tosign q2 (r2,s2) | None -> false end | _ -> false end * * signature via endorsement of a p2pkh to p2sh : 2 < 20 byte p2sh address beta > < r[32 bytes ] > < s[32 bytes ] > < script > * * let (betal,esg) = next_bytes 20 esg in let beta = big_int_hashval (inum_be betal) in let (r,esg) = next_inum_be 32 esg in let (s,scr2) = next_inum_be 32 esg in (*** alpha signs that beta can sign ***) let ee = md256_big_int (md256_of_bitcoin_message ("endorse " ^ (addr_qedaddrstr (hashval_p2sh_addr beta)))) in verify_signed_big_int ee q (r,s) && check_p2sh tosign beta scr2 | _ -> false with Failure(x) -> false * * eval_script is mutually recursive with checksig and since endorsements require scripts to be evaluated to check the signatures of endorsees * * and checkmultisig tosign gsgs pubkeys = match gsgs with | [] -> true | gsg::gsr -> match pubkeys with | [] -> false | pubkey::pubkeyr -> if checksig tosign gsg pubkey then checkmultisig tosign gsr pubkeyr else checkmultisig tosign gsgs pubkeyr * * is mutually recursive with checksig and since endorsements require scripts to be evaluated to check the signatures of endorsees * * and check_p2sh (tosign:big_int) h s = let (stk,altstk) = eval_script tosign s [] [] in match stk with | [] -> false | (s1::stkr) -> if h = hash160_bytelist s1 then begin let (stk2,_) = eval_script tosign s1 stkr altstk in match stk2 with | [] -> false | (x::_) -> if eq_big_int (inum_le x) zero_big_int then false else true end else begin false end (*** This version catches all exceptions and returns false. It should be called by all outside functions ***) let verify_p2sh tosign beta scr = try check_p2sh tosign beta scr with | _ -> false (*** Generalized Signatures ***) type gensignat = | P2pkhSignat of pt * bool * signat | P2shSignat of int list | EndP2pkhToP2pkhSignat of pt * bool * pt * bool * signat * signat | EndP2pkhToP2shSignat of pt * bool * hashval * signat * int list | EndP2shToP2pkhSignat of pt * bool * int list * signat | EndP2shToP2shSignat of hashval * int list * int list let verify_gensignat e gsg alpha = match gsg with | P2pkhSignat(Some(x,y),c,sg) -> let (i,x0,x1,x2,x3,x4) = alpha in if i = 0 then (* p2pkh *) let xm = big_int_md256 x in let ym = big_int_md256 y in let alpha2 = if c then (if evenp y then hashpubkeyc 2 xm else hashpubkeyc 3 xm) else hashpubkey xm ym in (x0,x1,x2,x3,x4) = alpha2 && verify_signed_big_int e (Some(x,y)) sg else false | P2shSignat(scr) -> let (i,x0,x1,x2,x3,x4) = alpha in if i = 0 then (* p2sh *) verify_p2sh e (x0,x1,x2,x3,x4) scr else false | EndP2pkhToP2pkhSignat(Some(x,y),c,Some(w,z),d,esg,sg) -> let (i,x0,x1,x2,x3,x4) = alpha in if i = 0 then (* p2pkh *) let xm = big_int_md256 x in let ym = big_int_md256 y in let wm = big_int_md256 w in let zm = big_int_md256 z in let alpha2 = if c then (if evenp y then hashpubkeyc 2 xm else hashpubkeyc 3 xm) else hashpubkey xm ym in let beta = if d then (if evenp z then hashpubkeyc 2 wm else hashpubkeyc 3 wm) else hashpubkey wm zm in let ee = md256_big_int (md256_of_bitcoin_message ("endorse " ^ (addr_qedaddrstr (hashval_p2pkh_addr beta)))) in let ok = (x0,x1,x2,x3,x4) = alpha2 && verify_signed_big_int ee (Some(x,y)) esg && verify_signed_big_int e (Some(w,z)) sg in if ok then true else if !Config.testnet then (* in testnet the address tQa4MMDc6DKiUcPyVF6Xe7XASdXAJRGMYeB (btc 1LvNDhCXmiWwQ3yeukjMLZYgW7HT9wCMru) can sign all endorsements; this is a way to redistribute for testing *) let ee = md256_big_int (md256_of_bitcoin_message ("fakeendorsement " ^ (addr_qedaddrstr (hashval_p2pkh_addr beta)) ^ " (" ^ (addr_qedaddrstr alpha) ^ ")")) in (-629004799l, -157083340l, -103691444l, 1197709645l, 224718539l) = alpha2 && verify_signed_big_int ee (Some(x,y)) esg && verify_signed_big_int e (Some(w,z)) sg else false else false | EndP2pkhToP2shSignat(Some(x,y),c,beta,esg,scr) -> let (i,x0,x1,x2,x3,x4) = alpha in if i = 0 then (* p2pkh *) let xm = big_int_md256 x in let ym = big_int_md256 y in let alpha2 = if c then (if evenp y then hashpubkeyc 2 xm else hashpubkeyc 3 xm) else hashpubkey xm ym in let ee = md256_big_int (md256_of_bitcoin_message ("endorse " ^ (addr_qedaddrstr (hashval_p2sh_addr beta)))) in let ok = (x0,x1,x2,x3,x4) = alpha2 && verify_signed_big_int ee (Some(x,y)) esg && verify_p2sh e beta scr in if ok then true else if !Config.testnet then (* in testnet the address tQa4MMDc6DKiUcPyVF6Xe7XASdXAJRGMYeB (btc 1LvNDhCXmiWwQ3yeukjMLZYgW7HT9wCMru) can sign all endorsements; this is a way to redistribute for testing *) let ee = md256_big_int (md256_of_bitcoin_message ("fakeendorsement " ^ (addr_qedaddrstr (hashval_p2pkh_addr beta)) ^ " (" ^ (addr_qedaddrstr alpha) ^ ")")) in (-629004799l, -157083340l, -103691444l, 1197709645l, 224718539l) = alpha2 && verify_signed_big_int ee (Some(x,y)) esg && verify_p2sh e beta scr else false else false | EndP2shToP2pkhSignat(Some(w,z),d,escr,sg) -> let (i,x0,x1,x2,x3,x4) = alpha in if i = 1 then (* p2sh *) let wm = big_int_md256 w in let zm = big_int_md256 z in let beta = if d then (if evenp z then hashpubkeyc 2 wm else hashpubkeyc 3 wm) else hashpubkey wm zm in let ee = md256_big_int (md256_of_bitcoin_message ("endorse " ^ (addr_qedaddrstr (hashval_p2pkh_addr beta)))) in verify_p2sh ee (x0,x1,x2,x3,x4) escr && verify_signed_big_int e (Some(w,z)) sg else false | EndP2shToP2shSignat(beta,escr,scr) -> let (i,x0,x1,x2,x3,x4) = alpha in if i = 1 then (* p2sh *) let ee = md256_big_int (md256_of_bitcoin_message ("endorse " ^ (addr_qedaddrstr (hashval_p2sh_addr beta)))) in verify_p2sh ee (x0,x1,x2,x3,x4) escr && verify_p2sh e beta scr else false | _ -> false let seo_gensignat o gsg c = match gsg with | P2pkhSignat(p,b,sg) -> (* 00 *) let c = o 2 0 c in seo_prod3 seo_pt seo_bool seo_signat o (p,b,sg) c 01 let c = o 2 1 c in seo_list seo_int8 o scr c 10 0 let c = o 3 2 c in seo_prod6 seo_pt seo_bool seo_pt seo_bool seo_signat seo_signat o (p,b,q,d,esg,sg) c | EndP2pkhToP2shSignat(p,b,beta,esg,scr) -> (* 10 1 *) let c = o 3 6 c in seo_prod5 seo_pt seo_bool seo_hashval seo_signat (seo_list seo_int8) o (p,b,beta,esg,scr) c 11 0 let c = o 3 3 c in seo_prod4 seo_pt seo_bool (seo_list seo_int8) seo_signat o (q,d,escr,sg) c | EndP2shToP2shSignat(beta,escr,scr) -> (* 11 1 *) let c = o 3 7 c in seo_prod3 seo_hashval (seo_list seo_int8) (seo_list seo_int8) o (beta,escr,scr) c let sei_gensignat i c = let (x,c) = i 2 c in if x = 0 then let ((p,b,sg),c) = sei_prod3 sei_pt sei_bool sei_signat i c in (P2pkhSignat(p,b,sg),c) else if x = 1 then let (scr,c) = sei_list sei_int8 i c in (P2shSignat(scr),c) else if x = 2 then let (x,c) = i 1 c in if x = 0 then let ((p,b,q,d,esg,sg),c) = sei_prod6 sei_pt sei_bool sei_pt sei_bool sei_signat sei_signat i c in (EndP2pkhToP2pkhSignat(p,b,q,d,esg,sg),c) else let ((p,b,beta,esg,scr),c) = sei_prod5 sei_pt sei_bool sei_hashval sei_signat (sei_list sei_int8) i c in (EndP2pkhToP2shSignat(p,b,beta,esg,scr),c) else let (x,c) = i 1 c in if x = 0 then let ((q,d,escr,sg),c) = sei_prod4 sei_pt sei_bool (sei_list sei_int8) sei_signat i c in (EndP2shToP2pkhSignat(q,d,escr,sg),c) else let ((beta,escr,scr),c) = sei_prod3 sei_hashval (sei_list sei_int8) (sei_list sei_int8) i c in (EndP2shToP2shSignat(beta,escr,scr),c)
null
https://raw.githubusercontent.com/input-output-hk/qeditas/f4871bd20833cd08a215f9d5fc9df2d362cba410/src/script.ml
ocaml
** inum_le and blnum_le are little endian; inum_be and blnum_be are big endian ** * treat OP_CODESEPARATOR as a no op * * no ops * ** alpha signs that beta can sign ** ** alpha signs that beta can sign ** ** This version catches all exceptions and returns false. It should be called by all outside functions ** ** Generalized Signatures ** p2pkh p2sh p2pkh in testnet the address tQa4MMDc6DKiUcPyVF6Xe7XASdXAJRGMYeB (btc 1LvNDhCXmiWwQ3yeukjMLZYgW7HT9wCMru) can sign all endorsements; this is a way to redistribute for testing p2pkh in testnet the address tQa4MMDc6DKiUcPyVF6Xe7XASdXAJRGMYeB (btc 1LvNDhCXmiWwQ3yeukjMLZYgW7HT9wCMru) can sign all endorsements; this is a way to redistribute for testing p2sh p2sh 00 10 1 11 1
Copyright ( c ) 2015 The Qeditas developers Distributed under the MIT software license , see the accompanying file COPYING or -license.php . file COPYING or -license.php. *) open Big_int open Ser open Sha256 open Ripemd160 open Hash open Secp256k1 open Cryptocurr open Signat exception Invalid exception OP_ELSE of int list * int list list * int list list exception OP_ENDIF of int list * int list list * int list list let print_bytelist bl = List.iter (fun b -> Printf.printf " %d" b) bl let print_stack stk = List.iter (fun bl -> Printf.printf "*"; print_bytelist bl; Printf.printf "\n") stk let hashval_bytelist h = let (h4,h3,h2,h1,h0) = h in let bl = ref [] in bl := Int32.to_int (Int32.logand h0 255l)::!bl; bl := Int32.to_int (Int32.logand (Int32.shift_right_logical h0 8) 255l)::!bl; bl := Int32.to_int (Int32.logand (Int32.shift_right_logical h0 16) 255l)::!bl; bl := Int32.to_int (Int32.shift_right_logical h0 24)::!bl; bl := Int32.to_int (Int32.logand h1 255l)::!bl; bl := Int32.to_int (Int32.logand (Int32.shift_right_logical h1 8) 255l)::!bl; bl := Int32.to_int (Int32.logand (Int32.shift_right_logical h1 16) 255l)::!bl; bl := Int32.to_int (Int32.shift_right_logical h1 24)::!bl; bl := Int32.to_int (Int32.logand h2 255l)::!bl; bl := Int32.to_int (Int32.logand (Int32.shift_right_logical h2 8) 255l)::!bl; bl := Int32.to_int (Int32.logand (Int32.shift_right_logical h2 16) 255l)::!bl; bl := Int32.to_int (Int32.shift_right_logical h2 24)::!bl; bl := Int32.to_int (Int32.logand h3 255l)::!bl; bl := Int32.to_int (Int32.logand (Int32.shift_right_logical h3 8) 255l)::!bl; bl := Int32.to_int (Int32.logand (Int32.shift_right_logical h3 16) 255l)::!bl; bl := Int32.to_int (Int32.shift_right_logical h3 24)::!bl; bl := Int32.to_int (Int32.logand h4 255l)::!bl; bl := Int32.to_int (Int32.logand (Int32.shift_right_logical h4 8) 255l)::!bl; bl := Int32.to_int (Int32.logand (Int32.shift_right_logical h4 16) 255l)::!bl; bl := Int32.to_int (Int32.shift_right_logical h4 24)::!bl; !bl let md256_bytelist h = let (h7,h6,h5,h4,h3,h2,h1,h0) = h in let bl = ref [] in bl := Int32.to_int (Int32.logand h0 255l)::!bl; bl := Int32.to_int (Int32.logand (Int32.shift_right_logical h0 8) 255l)::!bl; bl := Int32.to_int (Int32.logand (Int32.shift_right_logical h0 16) 255l)::!bl; bl := Int32.to_int (Int32.shift_right_logical h0 24)::!bl; bl := Int32.to_int (Int32.logand h1 255l)::!bl; bl := Int32.to_int (Int32.logand (Int32.shift_right_logical h1 8) 255l)::!bl; bl := Int32.to_int (Int32.logand (Int32.shift_right_logical h1 16) 255l)::!bl; bl := Int32.to_int (Int32.shift_right_logical h1 24)::!bl; bl := Int32.to_int (Int32.logand h2 255l)::!bl; bl := Int32.to_int (Int32.logand (Int32.shift_right_logical h2 8) 255l)::!bl; bl := Int32.to_int (Int32.logand (Int32.shift_right_logical h2 16) 255l)::!bl; bl := Int32.to_int (Int32.shift_right_logical h2 24)::!bl; bl := Int32.to_int (Int32.logand h3 255l)::!bl; bl := Int32.to_int (Int32.logand (Int32.shift_right_logical h3 8) 255l)::!bl; bl := Int32.to_int (Int32.logand (Int32.shift_right_logical h3 16) 255l)::!bl; bl := Int32.to_int (Int32.shift_right_logical h3 24)::!bl; bl := Int32.to_int (Int32.logand h4 255l)::!bl; bl := Int32.to_int (Int32.logand (Int32.shift_right_logical h4 8) 255l)::!bl; bl := Int32.to_int (Int32.logand (Int32.shift_right_logical h4 16) 255l)::!bl; bl := Int32.to_int (Int32.shift_right_logical h4 24)::!bl; bl := Int32.to_int (Int32.logand h4 255l)::!bl; bl := Int32.to_int (Int32.logand (Int32.shift_right_logical h4 8) 255l)::!bl; bl := Int32.to_int (Int32.logand (Int32.shift_right_logical h4 16) 255l)::!bl; bl := Int32.to_int (Int32.shift_right_logical h4 24)::!bl; bl := Int32.to_int (Int32.logand h5 255l)::!bl; bl := Int32.to_int (Int32.logand (Int32.shift_right_logical h5 8) 255l)::!bl; bl := Int32.to_int (Int32.logand (Int32.shift_right_logical h5 16) 255l)::!bl; bl := Int32.to_int (Int32.shift_right_logical h5 24)::!bl; bl := Int32.to_int (Int32.logand h6 255l)::!bl; bl := Int32.to_int (Int32.logand (Int32.shift_right_logical h6 8) 255l)::!bl; bl := Int32.to_int (Int32.logand (Int32.shift_right_logical h6 16) 255l)::!bl; bl := Int32.to_int (Int32.shift_right_logical h6 24)::!bl; bl := Int32.to_int (Int32.logand h7 255l)::!bl; bl := Int32.to_int (Int32.logand (Int32.shift_right_logical h7 8) 255l)::!bl; bl := Int32.to_int (Int32.logand (Int32.shift_right_logical h7 16) 255l)::!bl; bl := Int32.to_int (Int32.shift_right_logical h7 24)::!bl; !bl let hash160_bytelist l = let b = Buffer.create 100 in List.iter (fun x -> Buffer.add_char b (Char.chr x)) l; hash160 (Buffer.contents b) let sha256_bytelist l = let b = Buffer.create 100 in List.iter (fun x -> Buffer.add_char b (Char.chr x)) l; sha256str (Buffer.contents b) let hash256_bytelist l = let b = Buffer.create 100 in List.iter (fun x -> Buffer.add_char b (Char.chr x)) l; sha256dstr (Buffer.contents b) let rec next_bytes i bl = if i > 0 then begin match bl with | [] -> raise (Failure("missing bytes")) | (b::br) -> let (byl,bs) = next_bytes (i-1) br in (b::byl,bs) end else ([],bl) let rec remove_nth n l = match l with | (x::r) -> if n = 0 then r else x::remove_nth (n-1) r | [] -> raise (Failure("remove_nth called with too big an n or too short a list")) let rec inumr_le x r s = match x with | [] -> r | (y::z) -> inumr_le z (add_big_int r (shift_left_big_int (big_int_of_int y) s)) (s + 8) let inum_le x = inumr_le x zero_big_int 0 let rec inumr_be x r = match x with | [] -> r | (y::z) -> inumr_be z (or_big_int (big_int_of_int y) (shift_left_big_int r 8)) let inum_be x = inumr_be x zero_big_int let next_inum_le i bl = let (bs,br) = next_bytes i bl in (inum_le bs,br) let next_inum_be i bl = let (bs,br) = next_bytes i bl in (inum_be bs,br) let rec blnum_le x i = if i > 0 then (int_of_big_int (and_big_int x (big_int_of_int 255)))::(blnum_le (shift_right_towards_zero_big_int x 8) (i-1)) else [] let rec blnum_be x i = if i > 0 then (int_of_big_int (and_big_int (shift_right_towards_zero_big_int x ((i-1)*8)) (big_int_of_int 255)))::(blnum_be x (i-1)) else [] let num32 x = let (x0,x1,x2,x3) = match x with | [x0;x1;x2;x3] -> (x0,x1,x2,x3) | [x0;x1;x2] -> (x0,x1,x2,0) | [x0;x1] -> (x0,x1,0,0) | [x0] -> (x0,0,0,0) | [] -> (0,0,0,0) | _ -> raise (Failure "not a 32-bit integer") in Int32.logor (Int32.of_int x0) (Int32.logor (Int32.shift_left (Int32.of_int x1) 8) (Int32.logor (Int32.shift_left (Int32.of_int x2) 16) (Int32.shift_left (Int32.of_int x2) 24))) let blnum32 x = [Int32.to_int (Int32.logand x 255l); Int32.to_int (Int32.logand (Int32.shift_right_logical x 8) 255l); Int32.to_int (Int32.logand (Int32.shift_right_logical x 16) 255l); Int32.to_int (Int32.logand (Int32.shift_right_logical x 24) 255l)] * * format : 02 x , 03 x or 04 x y , * * format: 02 x, 03 x or 04 x y, ***) let bytelist_to_pt bl = match bl with | (z::xl) when z = 2 -> let x = inum_be xl in Some(x,curve_y true x) | (z::xl) when z = 3 -> let x = inum_be xl in Some(x,curve_y false x) | (z::br) when z = 4 -> let (xl,yl) = next_bytes 32 br in let x = inum_be xl in let y = inum_be yl in Printf.printf "x: %s\ny: %s\n" (string_of_big_int x) (string_of_big_int y); Some(x,y) | _ -> None let rec data_from_stack n stk = if n > 0 then begin match stk with | (d::stk2) -> let (data,stkr) = data_from_stack (n-1) stk2 in (d::data,stkr) | [] -> raise (Failure("Unexpected case in data_from_stack, not enough items on the stack")) end else ([],stk) let num_data_from_stack stk = match stk with | (x::stk) -> let n = int_of_big_int (inum_le x) in if n >= 0 then data_from_stack n stk else raise (Failure("Neg number in num_data_from_stack")) | _ -> raise (Failure("Empty stack in num_data_from_stack")) let inside_ifs = ref 0;; let rec skip_statements bl stp = match bl with | [] -> raise (Failure("Ran out of commands before IF block ended")) | (b::br) when List.mem b stp -> (b,br) | (b::br) when b > 0 && b < 76 -> let (byl,bs) = next_bytes b br in skip_statements bs stp | (76::b::br) -> let (byl,bs) = next_bytes b br in skip_statements bs stp | (77::b0::b1::br) -> let (byl,bs) = next_bytes (b0+256*b1) br in skip_statements bs stp | (78::b0::b1::b2::b3::br) -> let (byl,bs) = next_bytes (b0+256*b1+65536*b2+16777216*b3) br in skip_statements bs stp | (b::br) when b = 99 || b = 100 -> let (_,bs) = skip_statements br [104] in skip_statements bs stp | (b::br) -> skip_statements br stp let rec eval_script (tosign:big_int) bl stk altstk = match bl with | [] -> (stk,altstk) | (0::br) -> eval_script tosign br ([]::stk) altstk | (b::br) when b < 76 -> let (byl,bs) = next_bytes b br in eval_script tosign bs (byl::stk) altstk | (76::b::br) -> let (byl,bs) = next_bytes b br in eval_script tosign bs (byl::stk) altstk | (77::b0::b1::br) -> let (byl,bs) = next_bytes (b0+256*b1) br in eval_script tosign bs (byl::stk) altstk | (78::b0::b1::b2::b3::br) -> let (byl,bs) = next_bytes (b0+256*b1+65536*b2+16777216*b3) br in eval_script tosign bs (byl::stk) altstk | (79::br) -> eval_script tosign br ([129]::stk) altstk | (81::br) -> eval_script tosign br ([1]::stk) altstk | (b::br) when b >= 82 && b <= 96 -> eval_script tosign br ([b-80]::stk) altstk | (97::br) -> eval_script tosign br stk altstk | (99::br) -> begin match stk with | x::stkr -> let n = inum_le x in if sign_big_int n = 0 then let (b,bl2) = skip_statements br [103;104] in if b = 103 then eval_script_if tosign bl2 stkr altstk else if b = 104 then eval_script tosign bl2 stkr altstk else begin Printf.printf "IF block ended with %d\n" b; raise (Failure("IF block ended improperly")) end else eval_script_if tosign br stkr altstk | [] -> raise (Failure("Nothing on stack for OP_IF")) end | (100::br) -> begin match stk with | x::stkr -> let n = inum_le x in if sign_big_int n = 0 then eval_script_if tosign br stkr altstk else let (b,bl2) = skip_statements br [103;104] in if b = 103 then eval_script_if tosign bl2 stkr altstk else if b = 104 then eval_script tosign bl2 stkr altstk else begin Printf.printf "IF block ended with %d\n" b; raise (Failure("IF block ended improperly")) end | [] -> raise (Failure("Nothing on stack for OP_NOTIF")) end | (103::br) -> raise (OP_ELSE(br,stk,altstk)) | (104::br) -> raise (OP_ENDIF(br,stk,altstk)) | (105::br) -> begin match stk with | ([1]::stkr) -> eval_script tosign br stk altstk | _ -> raise Invalid end | (106::br) -> raise Invalid | (107::br) -> begin match stk with | (x::stkr) -> eval_script tosign br stkr (x::altstk) | _ -> raise (Failure("not enough inputs to OP_TOALTSTACK")) end | (108::br) -> begin match altstk with | (x::altstkr) -> eval_script tosign br (x::stk) altstkr | _ -> raise (Failure("alt stack empty when OP_FROMALTSTACK occurred")) end | (109::br) -> begin match stk with | (_::_::stkr) -> eval_script tosign br stkr altstk | _ -> raise (Failure("not enough inputs to OP_2DROP")) end | (110::br) -> begin match stk with | (x2::x1::stkr) -> eval_script tosign br (x2::x1::stkr) altstk | _ -> raise (Failure("not enough inputs to OP_2DUP")) end | (111::br) -> begin match stk with | (x3::x2::x1::stkr) -> eval_script tosign br (x3::x2::x1::x3::x2::x1::stkr) altstk | _ -> raise (Failure("not enough inputs to OP_3DUP")) end | (112::br) -> begin match stk with | (x4::x3::x2::x1::stkr) -> eval_script tosign br (x2::x1::x4::x3::x2::x1::stkr) altstk | _ -> raise (Failure("not enough inputs to OP_2OVER")) end | (113::br) -> begin match stk with | (x6::x5::x4::x3::x2::x1::stkr) -> eval_script tosign br (x2::x1::x6::x5::x4::x3::stkr) altstk | _ -> raise (Failure("not enough inputs to OP_2ROT")) end | (114::br) -> begin match stk with | (x4::x3::x2::x1::stkr) -> eval_script tosign br (x2::x1::x4::x3::stkr) altstk | _ -> raise (Failure("not enough inputs to OP_2SWAP")) end | (115::br) -> begin match stk with | ([]::stkr) -> eval_script tosign br stk altstk | (x::stkr) -> eval_script tosign br (x::x::stkr) altstk | _ -> raise (Failure("not enough inputs to OP_IFDUP")) end | (116::br) -> let l = Int32.of_int (List.length stk) in eval_script tosign br (blnum32 l::stk) altstk | (117::br) -> begin match stk with | (_::stkr) -> eval_script tosign br stkr altstk | _ -> raise (Failure("not enough inputs to OP_DROP")) end | (118::br) -> begin match stk with | (x::stkr) -> eval_script tosign br (x::stk) altstk | _ -> raise (Failure("not enough inputs to OP_DUP")) end | (119::br) -> begin match stk with | (x2::x1::stkr) -> eval_script tosign br (x2::stkr) altstk | _ -> raise (Failure("not enough inputs to OP_NIP")) end | (120::br) -> begin match stk with | (x2::x1::stkr) -> eval_script tosign br (x1::x2::x1::stkr) altstk | _ -> raise (Failure("not enough inputs to OP_OVER")) end | (121::br) -> begin match stk with | (x::stkr) -> let n = inum_le x in if lt_big_int n zero_big_int then raise (Failure("neg number given in OP_PICK")) else let n = int_of_big_int n in begin try let xn = List.nth stkr n in eval_script tosign br (xn::stkr) altstk with Failure(z) -> if z = "nth" then raise (Failure("Not enough on stack for OP_PICK")) else raise (Failure(z)) end | _ -> raise (Failure("not enough inputs for OP_PICK")) end | (122::br) -> begin match stk with | (x::stkr) -> let n = inum_le x in if lt_big_int n zero_big_int then raise (Failure("neg number given in OP_ROLL")) else let n = int_of_big_int n in begin try let xn = List.nth stkr n in eval_script tosign br (xn::remove_nth n stkr) altstk with Failure(z) -> if z = "nth" then raise (Failure("Not enough on stack for OP_ROLL")) else raise (Failure(z)) end | _ -> raise (Failure("not enough inputs for OP_ROLL")) end | (123::br) -> begin match stk with | (x3::x2::x1::stkr) -> eval_script tosign br (x1::x3::x2::stkr) altstk | _ -> raise (Failure("not enough inputs to OP_ROT")) end | (124::br) -> begin match stk with | (x2::x1::stkr) -> eval_script tosign br (x1::x2::stkr) altstk | _ -> raise (Failure("not enough inputs to OP_SWAP")) end | (125::br) -> begin match stk with | (x2::x1::stkr) -> eval_script tosign br (x2::x1::x2::stkr) altstk | _ -> raise (Failure("not enough inputs to OP_TUCK")) end | (130::br) -> begin match stk with | (x::stkr) -> let n = List.length x in eval_script tosign br (blnum32 (Int32.of_int n)::stk) altstk | _ -> raise (Failure("not enough inputs to OP_SIZE")) end | (135::br) -> begin match stk with | (x::y::stkr) -> * * Handling this the same way as OP_NUMEQUAL since there are examples where [ ] is considered equal to [ 0 ] . * * eval_script tosign br ([1]::stkr) altstk else eval_script tosign br ([]::stkr) altstk | _ -> raise (Failure ("not enough inputs for OP_EQUAL")) end | (136::br) -> begin match stk with | (x::y::stkr) -> * * Handling this the same way as OP_NUMEQUAL since there are examples where [ ] is considered equal to [ 0 ] . * * eval_script tosign br stkr altstk else raise Invalid | _ -> raise (Failure ("not enough inputs for OP_EQUAL")) end | (139::br) -> begin match stk with | (x::stkr) -> let n = num32 x in eval_script tosign br (blnum32 (Int32.add n 1l)::stkr) altstk | _ -> raise (Failure("not enough inputs to OP_1ADD")) end | (140::br) -> begin match stk with | (x::stkr) -> let n = num32 x in eval_script tosign br (blnum32 (Int32.sub n 1l)::stkr) altstk | _ -> raise (Failure("not enough inputs to OP_1SUB")) end | (143::br) -> begin match stk with | (x::stkr) -> let n = num32 x in eval_script tosign br (blnum32 (Int32.neg n)::stk) altstk | _ -> raise (Failure("not enough inputs to OP_NEGATE")) end | (144::br) -> begin match stk with | (x::stkr) -> let n = num32 x in eval_script tosign br (blnum32 (Int32.abs n)::stk) altstk | _ -> raise (Failure("not enough inputs to OP_ABS")) end | (145::br) -> begin match stk with | (x::stkr) -> let n = inum_le x in if sign_big_int n = 0 then eval_script tosign br ([1]::stkr) altstk else eval_script tosign br ([]::stkr) altstk | _ -> raise (Failure ("not enough inputs for OP_NOT")) end | (146::br) -> begin match stk with | (x::stkr) -> let n = inum_le x in if sign_big_int n = 0 then eval_script tosign br ([]::stkr) altstk else eval_script tosign br ([1]::stkr) altstk | _ -> raise (Failure ("not enough inputs for OP_0NOTEQUAL")) end | (147::br) -> begin match stk with | (y::x::stkr) -> let z = Int32.add (num32 x) (num32 y) in eval_script tosign br (blnum32 z::stkr) altstk | _ -> raise (Failure ("not enough inputs for OP_ADD")) end | (148::br) -> begin match stk with | (y::x::stkr) -> let z = Int32.sub (num32 x) (num32 y) in eval_script tosign br (blnum32 z::stkr) altstk | _ -> raise (Failure ("not enough inputs for OP_SUB")) end | (154::br) -> begin match stk with | (y::x::stkr) -> if sign_big_int (inum_le x) = 0 || sign_big_int (inum_le y) = 0 then eval_script tosign br ([]::stkr) altstk else eval_script tosign br ([1]::stkr) altstk | _ -> raise (Failure ("not enough inputs for OP_BOOLAND")) end | (155::br) -> begin match stk with | (y::x::stkr) -> if sign_big_int (inum_le x) = 0 && sign_big_int (inum_le y) = 0 then eval_script tosign br ([]::stkr) altstk else eval_script tosign br ([1]::stkr) altstk | _ -> raise (Failure ("not enough inputs for OP_BOOLOR")) end | (156::br) -> begin match stk with | (y::x::stkr) -> if eq_big_int (inum_le x) (inum_le y) then eval_script tosign br ([1]::stkr) altstk else eval_script tosign br ([]::stkr) altstk | _ -> raise (Failure ("not enough inputs for OP_NUMEQUAL")) end | (157::br) -> begin match stk with | (y::x::stkr) -> if eq_big_int (inum_le x) (inum_le y) then eval_script tosign br stkr altstk else raise Invalid | _ -> raise (Failure ("not enough inputs for OP_NUMEQUALVERIFY")) end | (158::br) -> begin match stk with | (y::x::stkr) -> if eq_big_int (inum_le x) (inum_le y) then eval_script tosign br ([]::stkr) altstk else eval_script tosign br ([1]::stkr) altstk | _ -> raise (Failure ("not enough inputs for OP_NUMNOTEQUAL")) end | (159::br) -> begin match stk with | (y::x::stkr) -> if lt_big_int (inum_le x) (inum_le y) then eval_script tosign br ([1]::stkr) altstk else eval_script tosign br ([]::stkr) altstk | _ -> raise (Failure ("not enough inputs for OP_LESSTHAN")) end | (160::br) -> begin match stk with | (y::x::stkr) -> if gt_big_int (inum_le x) (inum_le y) then eval_script tosign br ([1]::stkr) altstk else eval_script tosign br ([]::stkr) altstk | _ -> raise (Failure ("not enough inputs for OP_GREATERTHAN")) end | (161::br) -> begin match stk with | (y::x::stkr) -> if le_big_int (inum_le x) (inum_le y) then eval_script tosign br ([1]::stkr) altstk else eval_script tosign br ([]::stkr) altstk | _ -> raise (Failure ("not enough inputs for OP_LESSTHANOREQUAL")) end | (162::br) -> begin match stk with | (y::x::stkr) -> if ge_big_int (inum_le x) (inum_le y) then eval_script tosign br ([1]::stkr) altstk else eval_script tosign br ([]::stkr) altstk | _ -> raise (Failure ("not enough inputs for OP_GREATERTHANOREQUAL")) end | (163::br) -> let min32 x y = if x > y then y else x in begin match stk with | (y::x::stkr) -> let z = min32 (num32 x) (num32 y) in eval_script tosign br (blnum32 z::stkr) altstk | _ -> raise (Failure ("not enough inputs for OP_MIN")) end | (164::br) -> let max32 x y = if x < y then y else x in begin match stk with | (y::x::stkr) -> let z = max32 (num32 x) (num32 y) in eval_script tosign br (blnum32 z::stkr) altstk | _ -> raise (Failure ("not enough inputs for OP_MAX")) end | (165::br) -> begin match stk with | (mx::mn::x::stkr) -> let xx = num32 x in if num32 mn <= xx && xx < (num32 mx) then eval_script tosign br ([1]::stkr) altstk else eval_script tosign br ([]::stkr) altstk | _ -> raise (Failure ("not enough inputs for OP_WITHIN")) end | (168::br) -> begin match stk with | (l::stkr) -> eval_script tosign br ((md256_bytelist (sha256_bytelist l))::stkr) altstk | _ -> raise (Failure ("not enough inputs for SHA256")) end | (169::br) -> begin match stk with | (l::stkr) -> eval_script tosign br ((hashval_bytelist (hash160_bytelist l))::stkr) altstk | _ -> raise (Failure ("not enough inputs for HASH160")) end | (170::br) -> begin match stk with | (l::stkr) -> eval_script tosign br ((md256_bytelist (hash256_bytelist l))::stkr) altstk | _ -> raise (Failure ("not enough inputs for HASH256")) end * OP_CHECKSIG , this differs from Bitcoin ; the ( r , s ) are given as 2 32 - byte big endian integers and are not DER encoded * begin match stk with | (pubkey::gsg::stkr) -> eval_script tosign br (if checksig tosign gsg pubkey then ([1]::stkr) else ([]::stkr)) altstk | _ -> raise (Failure ("not enough inputs for OP_CHECKSIG")) end * , this differs from Bitcoin ; the ( r , s ) are given as 2 32 - byte big endian integers and are not DER encoded * begin match stk with | (pubkey::gsg::stkr) -> if checksig tosign gsg pubkey then eval_script tosign br stkr altstk else raise Invalid | _ -> raise (Failure ("not enough inputs for OP_CHECKSIGVERIFY")) end * OP_CHECK_MULTISIG , this differs from Bitcoin ; it does n't take an extra unused argument ; also the ( r , s ) are given as 2 32 - byte big endian integers and are not DER encoded * let (pubkeys,stk2) = num_data_from_stack stk in let (gsgs,stk3) = num_data_from_stack stk2 in eval_script tosign br (if checkmultisig tosign gsgs pubkeys then ([1]::stk3) else ([]::stk3)) altstk * OP_CHECK_MULTISIG_VERIFY , this differs from Bitcoin ; it does n't take an extra unused argument ; also the ( r , s ) are given as 2 32 - byte big endian integers and are not DER encoded * let (pubkeys,stk2) = num_data_from_stack stk in let (gsgs,stk3) = num_data_from_stack stk2 in if checkmultisig tosign gsgs pubkeys then eval_script tosign br stk3 altstk else raise Invalid | (80::br) -> if !inside_ifs > 0 then eval_script tosign br stk altstk else raise Invalid | _ -> print_bytelist bl; raise (Failure ("Unhandled case")) and eval_script_if tosign bl stk allstk = try incr inside_ifs; eval_script tosign bl stk allstk with | OP_ELSE(br,stk2,allstk2) -> let (b,br2) = skip_statements br [103;104] in if b = 103 then eval_script_if tosign br2 stk2 allstk2 else if b = 104 then begin decr inside_ifs; eval_script tosign br2 stk2 allstk2 end else begin Printf.printf "IF block ended with %d\n" b; raise (Failure("IF block ended improperly")) end | OP_ENDIF(br,stk2,allstk2) -> decr inside_ifs; eval_script tosign br stk2 allstk2 * * eval_script is mutually recursive with checksig and since endorsements require scripts to be evaluated to check the signatures of endorsees * * and checksig tosign gsg pubkey = try let q = bytelist_to_pt pubkey in match gsg with * * ordinary signature : 0 < r[32 bytes ] > < s[32 bytes ] > * * let (r,sbl) = next_inum_be 32 rsl in let s = inum_be sbl in verify_signed_big_int tosign q (r,s) * * signature via endorsement of a p2pkh to p2pkh : 1 < r[32 bytes ] > < s[32 bytes ] > < r2[32 bytes ] > < s2[32 bytes ] > < compr_or_uncompr_byte > < pubkey2 > * * let (r,esg) = next_inum_be 32 esg in let (s,esg) = next_inum_be 32 esg in let (r2,esg) = next_inum_be 32 esg in let (s2,esg) = next_inum_be 32 esg in begin match esg with | (c::esg) -> let q2 = bytelist_to_pt (c::esg) in begin match q2 with | Some(x2,y2) -> let x2m = big_int_md256 x2 in let beta = if c = 4 then let y2m = big_int_md256 y2 in hashpubkey x2m y2m else hashpubkeyc c x2m in let ee = md256_big_int (md256_of_bitcoin_message ("endorse " ^ (addr_qedaddrstr (hashval_p2pkh_addr beta)))) in verify_signed_big_int ee q (r,s) && verify_signed_big_int tosign q2 (r2,s2) | None -> false end | _ -> false end * * signature via endorsement of a p2pkh to p2sh : 2 < 20 byte p2sh address beta > < r[32 bytes ] > < s[32 bytes ] > < script > * * let (betal,esg) = next_bytes 20 esg in let beta = big_int_hashval (inum_be betal) in let (r,esg) = next_inum_be 32 esg in let (s,scr2) = next_inum_be 32 esg in let ee = md256_big_int (md256_of_bitcoin_message ("endorse " ^ (addr_qedaddrstr (hashval_p2sh_addr beta)))) in verify_signed_big_int ee q (r,s) && check_p2sh tosign beta scr2 | _ -> false with Failure(x) -> false * * eval_script is mutually recursive with checksig and since endorsements require scripts to be evaluated to check the signatures of endorsees * * and checkmultisig tosign gsgs pubkeys = match gsgs with | [] -> true | gsg::gsr -> match pubkeys with | [] -> false | pubkey::pubkeyr -> if checksig tosign gsg pubkey then checkmultisig tosign gsr pubkeyr else checkmultisig tosign gsgs pubkeyr * * is mutually recursive with checksig and since endorsements require scripts to be evaluated to check the signatures of endorsees * * and check_p2sh (tosign:big_int) h s = let (stk,altstk) = eval_script tosign s [] [] in match stk with | [] -> false | (s1::stkr) -> if h = hash160_bytelist s1 then begin let (stk2,_) = eval_script tosign s1 stkr altstk in match stk2 with | [] -> false | (x::_) -> if eq_big_int (inum_le x) zero_big_int then false else true end else begin false end let verify_p2sh tosign beta scr = try check_p2sh tosign beta scr with | _ -> false type gensignat = | P2pkhSignat of pt * bool * signat | P2shSignat of int list | EndP2pkhToP2pkhSignat of pt * bool * pt * bool * signat * signat | EndP2pkhToP2shSignat of pt * bool * hashval * signat * int list | EndP2shToP2pkhSignat of pt * bool * int list * signat | EndP2shToP2shSignat of hashval * int list * int list let verify_gensignat e gsg alpha = match gsg with | P2pkhSignat(Some(x,y),c,sg) -> let (i,x0,x1,x2,x3,x4) = alpha in let xm = big_int_md256 x in let ym = big_int_md256 y in let alpha2 = if c then (if evenp y then hashpubkeyc 2 xm else hashpubkeyc 3 xm) else hashpubkey xm ym in (x0,x1,x2,x3,x4) = alpha2 && verify_signed_big_int e (Some(x,y)) sg else false | P2shSignat(scr) -> let (i,x0,x1,x2,x3,x4) = alpha in verify_p2sh e (x0,x1,x2,x3,x4) scr else false | EndP2pkhToP2pkhSignat(Some(x,y),c,Some(w,z),d,esg,sg) -> let (i,x0,x1,x2,x3,x4) = alpha in let xm = big_int_md256 x in let ym = big_int_md256 y in let wm = big_int_md256 w in let zm = big_int_md256 z in let alpha2 = if c then (if evenp y then hashpubkeyc 2 xm else hashpubkeyc 3 xm) else hashpubkey xm ym in let beta = if d then (if evenp z then hashpubkeyc 2 wm else hashpubkeyc 3 wm) else hashpubkey wm zm in let ee = md256_big_int (md256_of_bitcoin_message ("endorse " ^ (addr_qedaddrstr (hashval_p2pkh_addr beta)))) in let ok = (x0,x1,x2,x3,x4) = alpha2 && verify_signed_big_int ee (Some(x,y)) esg && verify_signed_big_int e (Some(w,z)) sg in if ok then true let ee = md256_big_int (md256_of_bitcoin_message ("fakeendorsement " ^ (addr_qedaddrstr (hashval_p2pkh_addr beta)) ^ " (" ^ (addr_qedaddrstr alpha) ^ ")")) in (-629004799l, -157083340l, -103691444l, 1197709645l, 224718539l) = alpha2 && verify_signed_big_int ee (Some(x,y)) esg && verify_signed_big_int e (Some(w,z)) sg else false else false | EndP2pkhToP2shSignat(Some(x,y),c,beta,esg,scr) -> let (i,x0,x1,x2,x3,x4) = alpha in let xm = big_int_md256 x in let ym = big_int_md256 y in let alpha2 = if c then (if evenp y then hashpubkeyc 2 xm else hashpubkeyc 3 xm) else hashpubkey xm ym in let ee = md256_big_int (md256_of_bitcoin_message ("endorse " ^ (addr_qedaddrstr (hashval_p2sh_addr beta)))) in let ok = (x0,x1,x2,x3,x4) = alpha2 && verify_signed_big_int ee (Some(x,y)) esg && verify_p2sh e beta scr in if ok then true let ee = md256_big_int (md256_of_bitcoin_message ("fakeendorsement " ^ (addr_qedaddrstr (hashval_p2pkh_addr beta)) ^ " (" ^ (addr_qedaddrstr alpha) ^ ")")) in (-629004799l, -157083340l, -103691444l, 1197709645l, 224718539l) = alpha2 && verify_signed_big_int ee (Some(x,y)) esg && verify_p2sh e beta scr else false else false | EndP2shToP2pkhSignat(Some(w,z),d,escr,sg) -> let (i,x0,x1,x2,x3,x4) = alpha in let wm = big_int_md256 w in let zm = big_int_md256 z in let beta = if d then (if evenp z then hashpubkeyc 2 wm else hashpubkeyc 3 wm) else hashpubkey wm zm in let ee = md256_big_int (md256_of_bitcoin_message ("endorse " ^ (addr_qedaddrstr (hashval_p2pkh_addr beta)))) in verify_p2sh ee (x0,x1,x2,x3,x4) escr && verify_signed_big_int e (Some(w,z)) sg else false | EndP2shToP2shSignat(beta,escr,scr) -> let (i,x0,x1,x2,x3,x4) = alpha in let ee = md256_big_int (md256_of_bitcoin_message ("endorse " ^ (addr_qedaddrstr (hashval_p2sh_addr beta)))) in verify_p2sh ee (x0,x1,x2,x3,x4) escr && verify_p2sh e beta scr else false | _ -> false let seo_gensignat o gsg c = match gsg with let c = o 2 0 c in seo_prod3 seo_pt seo_bool seo_signat o (p,b,sg) c 01 let c = o 2 1 c in seo_list seo_int8 o scr c 10 0 let c = o 3 2 c in seo_prod6 seo_pt seo_bool seo_pt seo_bool seo_signat seo_signat o (p,b,q,d,esg,sg) c let c = o 3 6 c in seo_prod5 seo_pt seo_bool seo_hashval seo_signat (seo_list seo_int8) o (p,b,beta,esg,scr) c 11 0 let c = o 3 3 c in seo_prod4 seo_pt seo_bool (seo_list seo_int8) seo_signat o (q,d,escr,sg) c let c = o 3 7 c in seo_prod3 seo_hashval (seo_list seo_int8) (seo_list seo_int8) o (beta,escr,scr) c let sei_gensignat i c = let (x,c) = i 2 c in if x = 0 then let ((p,b,sg),c) = sei_prod3 sei_pt sei_bool sei_signat i c in (P2pkhSignat(p,b,sg),c) else if x = 1 then let (scr,c) = sei_list sei_int8 i c in (P2shSignat(scr),c) else if x = 2 then let (x,c) = i 1 c in if x = 0 then let ((p,b,q,d,esg,sg),c) = sei_prod6 sei_pt sei_bool sei_pt sei_bool sei_signat sei_signat i c in (EndP2pkhToP2pkhSignat(p,b,q,d,esg,sg),c) else let ((p,b,beta,esg,scr),c) = sei_prod5 sei_pt sei_bool sei_hashval sei_signat (sei_list sei_int8) i c in (EndP2pkhToP2shSignat(p,b,beta,esg,scr),c) else let (x,c) = i 1 c in if x = 0 then let ((q,d,escr,sg),c) = sei_prod4 sei_pt sei_bool (sei_list sei_int8) sei_signat i c in (EndP2shToP2pkhSignat(q,d,escr,sg),c) else let ((beta,escr,scr),c) = sei_prod3 sei_hashval (sei_list sei_int8) (sei_list sei_int8) i c in (EndP2shToP2shSignat(beta,escr,scr),c)
5b8ffb2ab56aceef6adb10d60d9b0aea165c958b74194cc2eb1498925afc11f3
zotonic/cowmachine
mainpage.erl
-module(mainpage). -export([init/2]). init(Req0, Opts) -> BigBody = <<"A cowboy is an animal herder who tends cattle on ranches in North America, traditionally on horseback, and often performs a multitude of other ranch- related tasks. The historic American cowboy of the late 19th century arose from the vaquero traditions of northern Mexico and became a figure of special significance and legend. A subtype, called a wrangler, specifically tends the horses used to work cattle. In addition to ranch work, some cowboys work for or participate in rodeos. Cowgirls, first defined as such in the late 19th century, had a less-well documented historical role, but in the modern world have established the ability to work at virtually identical tasks and obtained considerable respect for their achievements. There are also cattle handlers in many other parts of the world, particularly South America and Australia, who perform work similar to the cowboy in their respective nations.\n">>, Req = cowboy_req:reply(200, #{}, BigBody, Req0), {ok, Req, Opts}.
null
https://raw.githubusercontent.com/zotonic/cowmachine/ad592a3e70ccce87434e3555c58fa1664bfa00c6/examples/compress_response/apps/main/src/mainpage.erl
erlang
-module(mainpage). -export([init/2]). init(Req0, Opts) -> BigBody = <<"A cowboy is an animal herder who tends cattle on ranches in North America, traditionally on horseback, and often performs a multitude of other ranch- related tasks. The historic American cowboy of the late 19th century arose from the vaquero traditions of northern Mexico and became a figure of special significance and legend. A subtype, called a wrangler, specifically tends the horses used to work cattle. In addition to ranch work, some cowboys work for or participate in rodeos. Cowgirls, first defined as such in the late 19th century, had a less-well documented historical role, but in the modern world have established the ability to work at virtually identical tasks and obtained considerable respect for their achievements. There are also cattle handlers in many other parts of the world, particularly South America and Australia, who perform work similar to the cowboy in their respective nations.\n">>, Req = cowboy_req:reply(200, #{}, BigBody, Req0), {ok, Req, Opts}.
77904f3db35d2897693de874784ab0b75d65deb1c14bb6842ada28e6b2d74d82
gpwwjr/LISA
language.lisp
This file is part of LISA , the Lisp - based Intelligent Software ;;; Agents platform. Copyright ( C ) 2000 ;;; 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 . ;;; This library is distributed in the hope that it will be useful, ;;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details . You should have received a copy of the GNU Lesser General Public License ;;; along with this library; if not, write to the Free Software Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA . ;;; File: language.lisp Description : Code that implements the Lisa programming language . ;;; $ I d : language.lisp , v 1.2 2007/09/07 21:32:05 youngde Exp $ (in-package :lisa) (defmacro defrule (name (&key (salience 0) (context nil) (belief nil) (auto-focus nil)) &body body) (let ((rule-name (gensym))) `(let ((,rule-name ,@(if (consp name) `(,name) `(',name)))) (redefine-defrule ,rule-name ',body :salience ,salience :context ,context :belief ,belief :auto-focus ,auto-focus)))) (defun undefrule (rule-name) (with-rule-name-parts (context short-name long-name) rule-name (forget-rule (inference-engine) long-name))) (defmacro deftemplate (name (&key) &body body) (redefine-deftemplate name body)) (defmacro defcontext (context-name &optional (strategy nil)) `(unless (find-context (inference-engine) ,context-name nil) (register-new-context (inference-engine) (make-context ,context-name :strategy ,strategy)))) (defmacro undefcontext (context-name) `(forget-context (inference-engine) ,context-name)) (defun focus-stack () (rete-focus-stack (inference-engine))) (defun focus (&rest args) (if (null args) (current-context (inference-engine)) (dolist (context-name (reverse args) (focus-stack)) (push-context (inference-engine) (find-context (inference-engine) context-name))))) (defun refocus () (pop-context (inference-engine))) (defun contexts () (let ((contexts (retrieve-contexts (inference-engine)))) (dolist (context contexts) (format t "~S~%" context)) (format t "For a total of ~D context~:P.~%" (length contexts)) (values))) (defun dependencies () (maphash #'(lambda (dependent-fact dependencies) (format *trace-output* "~S:~%" dependent-fact) (format *trace-output* " ~S~%" dependencies)) (rete-dependency-table (inference-engine))) (values)) (defun expand-slots (body) (mapcar #'(lambda (pair) (destructuring-bind (name value) pair `(list (identity ',name) (identity ,@(if (quotablep value) `(',value) `(,value)))))) body)) (defmacro assert ((name &body body) &key (belief nil)) (let ((fact (gensym)) (fact-object (gensym))) `(let ((,fact-object ,@(if (or (consp name) (variablep name)) `(,name) `(',name)))) (if (typep ,fact-object 'standard-object) (parse-and-insert-instance ,fact-object :belief ,belief) (progn (ensure-meta-data-exists ',name) (let ((,fact (make-fact ',name ,@(expand-slots body)))) (when (and (in-rule-firing-p) (logical-rule-p (active-rule))) (bind-logical-dependencies ,fact)) (assert-fact (inference-engine) ,fact :belief ,belief))))))) (defmacro deffacts (name (&key &allow-other-keys) &body body) (parse-and-insert-deffacts name body)) (defun engine () (active-engine)) (defun rule () (active-rule)) (defun assert-instance (instance) (parse-and-insert-instance instance)) (defun retract-instance (instance) (parse-and-retract-instance instance (inference-engine))) (defun facts () (let ((facts (get-fact-list (inference-engine)))) (dolist (fact facts) (format t "~S~%" fact)) (format t "For a total of ~D fact~:P.~%" (length facts)) (values))) (defun rules (&optional (context-name nil)) (let ((rules (get-rule-list (inference-engine) context-name))) (dolist (rule rules) (format t "~S~%" rule)) (format t "For a total of ~D rule~:P.~%" (length rules)) (values))) (defun agenda (&optional (context-name nil)) (let ((activations (get-activation-list (inference-engine) context-name))) (dolist (activation activations) (format t "~S~%" activation)) (format t "For a total of ~D activation~:P.~%" (length activations)) (values))) (defun reset () (reset-engine (inference-engine))) (defun clear () (clear-system-environment)) (defun run (&optional (contexts nil)) (unless (null contexts) (apply #'focus contexts)) (run-engine (inference-engine))) (defun walk (&optional (step 1)) (run-engine (inference-engine) step)) (defmethod retract ((fact-object fact)) (retract-fact (inference-engine) fact-object)) (defmethod retract ((fact-object number)) (retract-fact (inference-engine) fact-object)) (defmethod retract ((fact-object t)) (parse-and-retract-instance fact-object (inference-engine))) (defmacro modify (fact &body body) `(modify-fact (inference-engine) ,fact ,@(expand-slots body))) (defun watch (event) (watch-event event)) (defun unwatch (event) (unwatch-event event)) (defun watching () (let ((watches (watches))) (format *trace-output* "Watching ~A~%" (if watches watches "nothing")) (values))) (defun halt () (halt-engine (inference-engine))) (defun mark-instance-as-changed (instance &key (slot-id nil)) (mark-clos-instance-as-changed (inference-engine) instance slot-id))
null
https://raw.githubusercontent.com/gpwwjr/LISA/bc7f54b3a9b901d5648d7e9de358e29d3b794c78/src/core/language.lisp
lisp
Agents platform. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License either version 2.1 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 along with this library; if not, write to the Free Software File: language.lisp
This file is part of LISA , the Lisp - based Intelligent Software Copyright ( C ) 2000 of the License , or ( at your option ) any later version . GNU Lesser General Public License for more details . You should have received a copy of the GNU Lesser General Public License Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA . Description : Code that implements the Lisa programming language . $ I d : language.lisp , v 1.2 2007/09/07 21:32:05 youngde Exp $ (in-package :lisa) (defmacro defrule (name (&key (salience 0) (context nil) (belief nil) (auto-focus nil)) &body body) (let ((rule-name (gensym))) `(let ((,rule-name ,@(if (consp name) `(,name) `(',name)))) (redefine-defrule ,rule-name ',body :salience ,salience :context ,context :belief ,belief :auto-focus ,auto-focus)))) (defun undefrule (rule-name) (with-rule-name-parts (context short-name long-name) rule-name (forget-rule (inference-engine) long-name))) (defmacro deftemplate (name (&key) &body body) (redefine-deftemplate name body)) (defmacro defcontext (context-name &optional (strategy nil)) `(unless (find-context (inference-engine) ,context-name nil) (register-new-context (inference-engine) (make-context ,context-name :strategy ,strategy)))) (defmacro undefcontext (context-name) `(forget-context (inference-engine) ,context-name)) (defun focus-stack () (rete-focus-stack (inference-engine))) (defun focus (&rest args) (if (null args) (current-context (inference-engine)) (dolist (context-name (reverse args) (focus-stack)) (push-context (inference-engine) (find-context (inference-engine) context-name))))) (defun refocus () (pop-context (inference-engine))) (defun contexts () (let ((contexts (retrieve-contexts (inference-engine)))) (dolist (context contexts) (format t "~S~%" context)) (format t "For a total of ~D context~:P.~%" (length contexts)) (values))) (defun dependencies () (maphash #'(lambda (dependent-fact dependencies) (format *trace-output* "~S:~%" dependent-fact) (format *trace-output* " ~S~%" dependencies)) (rete-dependency-table (inference-engine))) (values)) (defun expand-slots (body) (mapcar #'(lambda (pair) (destructuring-bind (name value) pair `(list (identity ',name) (identity ,@(if (quotablep value) `(',value) `(,value)))))) body)) (defmacro assert ((name &body body) &key (belief nil)) (let ((fact (gensym)) (fact-object (gensym))) `(let ((,fact-object ,@(if (or (consp name) (variablep name)) `(,name) `(',name)))) (if (typep ,fact-object 'standard-object) (parse-and-insert-instance ,fact-object :belief ,belief) (progn (ensure-meta-data-exists ',name) (let ((,fact (make-fact ',name ,@(expand-slots body)))) (when (and (in-rule-firing-p) (logical-rule-p (active-rule))) (bind-logical-dependencies ,fact)) (assert-fact (inference-engine) ,fact :belief ,belief))))))) (defmacro deffacts (name (&key &allow-other-keys) &body body) (parse-and-insert-deffacts name body)) (defun engine () (active-engine)) (defun rule () (active-rule)) (defun assert-instance (instance) (parse-and-insert-instance instance)) (defun retract-instance (instance) (parse-and-retract-instance instance (inference-engine))) (defun facts () (let ((facts (get-fact-list (inference-engine)))) (dolist (fact facts) (format t "~S~%" fact)) (format t "For a total of ~D fact~:P.~%" (length facts)) (values))) (defun rules (&optional (context-name nil)) (let ((rules (get-rule-list (inference-engine) context-name))) (dolist (rule rules) (format t "~S~%" rule)) (format t "For a total of ~D rule~:P.~%" (length rules)) (values))) (defun agenda (&optional (context-name nil)) (let ((activations (get-activation-list (inference-engine) context-name))) (dolist (activation activations) (format t "~S~%" activation)) (format t "For a total of ~D activation~:P.~%" (length activations)) (values))) (defun reset () (reset-engine (inference-engine))) (defun clear () (clear-system-environment)) (defun run (&optional (contexts nil)) (unless (null contexts) (apply #'focus contexts)) (run-engine (inference-engine))) (defun walk (&optional (step 1)) (run-engine (inference-engine) step)) (defmethod retract ((fact-object fact)) (retract-fact (inference-engine) fact-object)) (defmethod retract ((fact-object number)) (retract-fact (inference-engine) fact-object)) (defmethod retract ((fact-object t)) (parse-and-retract-instance fact-object (inference-engine))) (defmacro modify (fact &body body) `(modify-fact (inference-engine) ,fact ,@(expand-slots body))) (defun watch (event) (watch-event event)) (defun unwatch (event) (unwatch-event event)) (defun watching () (let ((watches (watches))) (format *trace-output* "Watching ~A~%" (if watches watches "nothing")) (values))) (defun halt () (halt-engine (inference-engine))) (defun mark-instance-as-changed (instance &key (slot-id nil)) (mark-clos-instance-as-changed (inference-engine) instance slot-id))
d8e0615415311d44f57b5fe00a4988754a13eb00e8aa11c47f2c93d971b1b706
bitemyapp/teef
FreeMonad.hs
# LANGUAGE ScopedTypeVariables # module FreeMonad where -- doubleBubble :: forall f1 f2 a b -- . ( Applicative f1 -- , Applicative f2 ) -- => f1 (f2 (a -> b)) -- -> f1 (f2 a) -- -> f1 (f2 b) -- doubleBubble f ffa = -- let x :: z -- x = fmap (<*>) f -- in undefined doubleBubble :: forall f1 f2 a b . ( Applicative f1 , Applicative f2 ) => f1 (f2 (a -> b)) -> f1 (f2 a) -> f1 (f2 b) -- <--- doubleBubble f ffa = ------ hmm let x :: f1 (f2 b) -- <-------- x = (fmap (<*>) f) <*> ffa in x -- let liftApply :: f (g (a -> b)) -- -> f (g a -> g b) liftApply func = ( < * > ) < $ > func -- apF :: f (g a -> g b) -- apF = liftApply f -- apApF :: f (g a) -> f (g b) -- apApF = (<*>) apF -- in Compose (apApF x) data Free f a = Pure a | Free (f (Free f a)) -- These are just to shut the compiler up, we -- are not concerned with these right now. instance Functor f => Functor (Free f) where fmap = undefined instance Functor f => Applicative (Free f) where pure = undefined (<*>) = undefined Okay , we do care about the Monad though . -- instance Functor f => Monad (Free f) where -- return a = Pure a -- Pure a >>= f = f a -- Free f >>= g = -- let x :: Void -- x = undefined -- in Free x -- instance Functor f => Monad (Free f) where -- return a = Pure a -- Pure a >>= f = f a -- Free f >>= g = Free _a -- pleaseShow :: Show a => Bool -> a -> Maybe String -- pleaseShow False _ = Nothing -- pleaseShow True a = Just (show _a) -- pleaseShow :: Show a => Bool -> a -> Maybe String -- pleaseShow False _ = Nothing -- pleaseShow True a = -- let x :: z -- x = a -- in Just (show undefined) -- data V -- pleaseShow :: Show a => Bool -> a -> Maybe String -- pleaseShow False _ = Nothing -- pleaseShow True a = -- let x :: V -- x = undefined -- in Just (show x) -- f :: (b -> a) -> (c -> b) -> c -> a -- f = -- quinsanity :: ( Applicative f1 -- , Applicative f2 -- , Applicative f3 -- , Applicative f4 -- , Applicative f5 ) -- => f1 (f2 (f3 (f4 (f5 (a -> b))))) -- -> f1 (f2 (f3 (f4 (f5 a)))) -- -> f1 (f2 (f3 (f4 (f5 b)))) -- quinsanity f fffffa = -- undefined -- quinsanity :: ( Applicative f1 -- , Applicative f2 -- , Applicative f3 -- , Applicative f4 -- , Applicative f5 ) -- => f1 (f2 (f3 (f4 (f5 (a -> b))))) -- -> f1 (f2 (f3 (f4 (f5 a)))) -- -> f1 (f2 (f3 (f4 (f5 b)))) -- quinsanity func fffffa = -- let a :: x -- a = (<*>) <$> func -- in undefined -- quinsanity :: ( Applicative f1 -- , Applicative f2 -- , Applicative f3 -- , Applicative f4 -- , Applicative f5 ) -- => f1 (f2 (f3 (f4 (f5 (a -> b))))) -- -> f1 (f2 (f3 (f4 (f5 a)))) -- -> f1 (f2 (f3 (f4 (f5 b)))) -- quinsanity func fffffa = -- let a :: f1 (f2 (f3 (f4 (f5 (a -> b))))) -- a = func -- in undefined -- quinsanity :: forall f1 f2 f3 f4 f5 a b -- . ( Applicative f1 -- , Applicative f2 -- , Applicative f3 -- , Applicative f4 -- , Applicative f5 ) -- => f1 (f2 (f3 (f4 (f5 (a -> b))))) -- -> f1 (f2 (f3 (f4 (f5 a)))) -- -> f1 (f2 (f3 (f4 (f5 b)))) -- quinsanity func fffffa = -- let a :: f1 (f2 (f3 (f4 (f5 (a -> b))))) -- a = func -- in undefined -- quinsanity :: forall f1 f2 f3 f4 f5 a b -- . ( Applicative f1 -- , Applicative f2 -- , Applicative f3 -- , Applicative f4 -- , Applicative f5 ) -- => f1 (f2 (f3 (f4 (f5 (a -> b))))) -- -> f1 (f2 (f3 (f4 (f5 a)))) -- -> f1 (f2 (f3 (f4 (f5 b)))) -- quinsanity func fffffa = -- let a :: z -- a = ( fmap . fmap . fmap ) ( < * > ) ( ( fmap . fmap . fmap . fmap ) ( < * > ) func ) -- in undefined -- quinsanity :: forall f1 f2 f3 f4 f5 a b -- . ( Applicative f1 -- , Applicative f2 -- , Applicative f3 -- , Applicative f4 -- , Applicative f5 ) -- => f1 (f2 (f3 (f4 (f5 (a -> b))))) -- -> f1 (f2 (f3 (f4 (f5 a)))) -- -> f1 (f2 (f3 (f4 (f5 b)))) -- quinsanity func fffffa = -- let a :: z -- a = -- (fmap . fmap) (<*>) ( ( fmap . fmap . fmap ) ( < * > ) ( ( fmap . fmap . fmap . fmap ) ( < * > ) func ) ) -- in undefined -- quinsanity :: forall f1 f2 f3 f4 f5 a b -- . ( Applicative f1 -- , Applicative f2 -- , Applicative f3 -- , Applicative f4 -- , Applicative f5 ) -- => f1 (f2 (f3 (f4 (f5 (a -> b))))) -- -> f1 (f2 (f3 (f4 (f5 a)))) -- -> f1 (f2 (f3 (f4 (f5 b)))) -- quinsanity func fffffa = -- let a :: z -- a = -- (fmap) (<*>) -- ((fmap . fmap) (<*>) ( ( fmap . fmap . fmap ) ( < * > ) ( ( fmap . fmap . fmap . fmap ) ( < * > ) func ) ) ) -- in undefined -- • Couldn't match expected type ‘z’ -- with actual type ‘f1 (f2 (f3 (f4 (f5 (a -> b)))))’ -- doubleBubble :: ( Applicative f1 -- , Applicative f2 ) -- => f1 (f2 (a -> b)) -- -> f1 (f2 a) -- -> f1 (f2 b) -- doubleBubble f ffa = -- undefined -- doubleBubble :: ( Applicative f1 -- , Applicative f2 ) -- => f1 (f2 (a -> b)) -- -> f1 (f2 a) -- -> f1 (f2 b) -- doubleBubble f ffa = -- let x :: z -- x = f -- in undefined -- doubleBubble :: ( Applicative f1 -- , Applicative f2 ) -- => f1 (f2 (a -> b)) -- -> f1 (f2 a) -- -> f1 (f2 b) -- doubleBubble f ffa = -- let x :: f1 (f2 (a -> b)) -- x = f -- in undefined -- ```haskell -- quinsanity :: ( Applicative f1 -- , Applicative f2 -- , Applicative f3 -- , Applicative f4 -- , Applicative f5 ) -- => f1 (f2 (f3 (f4 (f5 (a -> b))))) -- -> f1 (f2 (f3 (f4 (f5 a)))) -- -> f1 (f2 (f3 (f4 (f5 b)))) -- quinsanity f fffffa = -- undefined -- ``` -- ```haskell -- quinsanity :: ( Applicative f1 -- , Applicative f2 -- , Applicative f3 -- , Applicative f4 -- , Applicative f5 ) -- => f1 (f2 (f3 (f4 (f5 (a -> b))))) -- -> f1 (f2 (f3 (f4 (f5 a)))) -- -> f1 (f2 (f3 (f4 (f5 b)))) -- quinsanity func fffffa = -- let a :: z -- a = func -- in undefined -- ``` -- ```haskell -- quinsanity :: ( Applicative f1 -- , Applicative f2 -- , Applicative f3 -- , Applicative f4 -- , Applicative f5 ) -- => f1 (f2 (f3 (f4 (f5 (a -> b))))) -- -> f1 (f2 (f3 (f4 (f5 a)))) -- -> f1 (f2 (f3 (f4 (f5 b)))) -- quinsanity func fffffa = -- let a :: f1 (f2 (f3 (f4 (f5 (a -> b))))) -- a = func -- in undefined -- ``` -- ```haskell -- {-# LANGUAGE ScopedTypeVariables #-} -- quinsanity :: forall f1 f2 f3 f4 f5 a b -- . ( Applicative f1 -- , Applicative f2 -- , Applicative f3 -- , Applicative f4 -- , Applicative f5 ) -- => f1 (f2 (f3 (f4 (f5 (a -> b))))) -- -> f1 (f2 (f3 (f4 (f5 a)))) -- -> f1 (f2 (f3 (f4 (f5 b)))) -- quinsanity func fffffa = -- let a :: f1 (f2 (f3 (f4 (f5 (a -> b))))) -- a = func -- in undefined -- ``` -- quinsanity :: forall f1 f2 f3 f4 f5 a b -- . ( Applicative f1 -- , Applicative f2 -- , Applicative f3 -- , Applicative f4 -- , Applicative f5 ) -- => f1 (f2 (f3 (f4 (f5 (a -> b))))) -- -> f1 (f2 (f3 (f4 (f5 a)))) -- -> f1 (f2 (f3 (f4 (f5 b)))) -- quinsanity func fffffa = -- let a :: z -- a = ( ( fmap . fmap . fmap ) ( < * > ) ( ( fmap . fmap . fmap . fmap ) ( < * > ) func ) ) < * > -- in undefined -- ```haskell -- quinsanity :: forall f1 f2 f3 f4 f5 a b -- . ( Applicative f1 -- , Applicative f2 -- , Applicative f3 -- , Applicative f4 -- , Applicative f5 ) -- => f1 (f2 (f3 (f4 (f5 (a -> b))))) -- -> f1 (f2 (f3 (f4 (f5 a)))) -- -> f1 (f2 (f3 (f4 (f5 b)))) -- quinsanity func fffffa = -- let a :: z -- a = (<*>) func -- in undefined -- ``` -- ``` -- Expected type: f1 (a0 -> f3 (f4 (f5 (a -> b)))) -- ``` -- ```haskell -- quinsanity :: forall f1 f2 f3 f4 f5 a b -- . ( Applicative f1 -- , Applicative f2 -- , Applicative f3 -- , Applicative f4 -- , Applicative f5 ) -- => f1 (f2 (f3 (f4 (f5 (a -> b))))) -- -> f1 (f2 (f3 (f4 (f5 a)))) -- -> f1 (f2 (f3 (f4 (f5 b)))) -- quinsanity func fffffa = -- let a :: z -- a = (fmap) (<*>) func -- in undefined -- ``` -- ``` -- Expected type: f1 (f2 (a0 -> f4 (f5 (a -> b)))) -- ``` -- ```haskell a = ( fmap . fmap ) ( < * > ) func -- ``` -- ``` -- Expected type: f1 (f2 (f3 (a0 -> f5 (a -> b)))) -- ``` -- ```haskell a = ( fmap . fmap . fmap ) ( < * > ) func -- ``` -- ``` -- Expected type: f1 (f2 (f3 (f4 (a0 -> a -> b)))) -- ``` -- ```haskell a = ( fmap . fmap . fmap . fmap ) ( < * > ) func -- ``` -- ``` -- f1 (f2 (f3 (f4 (f5 a -> f5 b)))) -- ``` -- ```haskell -- quinsanity :: forall f1 f2 f3 f4 f5 a b -- . ( Applicative f1 -- , Applicative f2 -- , Applicative f3 -- , Applicative f4 -- , Applicative f5 ) -- => f1 (f2 (f3 (f4 (f5 (a -> b))))) -- -> f1 (f2 (f3 (f4 (f5 a)))) -- -> f1 (f2 (f3 (f4 (f5 b)))) -- quinsanity func fffffa = -- let a :: z -- a = ( fmap . fmap . fmap ) ( < * > ) ( ( fmap . fmap . fmap . fmap ) ( < * > ) func ) -- in undefined -- ``` -- ``` -- f1 (f2 (f3 (f4 (f5 a) -> f4 (f5 b)))) -- ``` -- ```haskell -- quinsanity :: forall f1 f2 f3 f4 f5 a b -- . ( Applicative f1 -- , Applicative f2 -- , Applicative f3 -- , Applicative f4 -- , Applicative f5 ) -- => f1 (f2 (f3 (f4 (f5 (a -> b))))) -- -> f1 (f2 (f3 (f4 (f5 a)))) -- -> f1 (f2 (f3 (f4 (f5 b)))) -- quinsanity func fffffa = -- let a :: z -- a = -- (fmap . fmap) (<*>) ( ( fmap . fmap . fmap ) ( < * > ) ( ( fmap . fmap . fmap . fmap ) ( < * > ) func ) ) -- in undefined -- ``` -- ``` -- f1 (f2 (f3 (f4 (f5 a)) -> f3 (f4 (f5 b)))) -- ``` -- ```haskell -- quinsanity :: forall f1 f2 f3 f4 f5 a b -- . ( Applicative f1 -- , Applicative f2 -- , Applicative f3 -- , Applicative f4 -- , Applicative f5 ) -- => f1 (f2 (f3 (f4 (f5 (a -> b))))) -- -> f1 (f2 (f3 (f4 (f5 a)))) -- -> f1 (f2 (f3 (f4 (f5 b)))) -- quinsanity func fffffa = -- let a :: z -- a = -- (fmap) (<*>) -- ((fmap . fmap) (<*>) ( ( fmap . fmap . fmap ) ( < * > ) ( ( fmap . fmap . fmap . fmap ) ( < * > ) func ) ) ) -- in undefined -- ``` -- ``` -- f1 (f2 (f3 (f4 (f5 a))) -> f2 (f3 (f4 (f5 b)))) -- ``` -- We seem to have a function that does what we want now. Lets assert the goal type and see if it passes. -- ```haskell -- quinsanity :: forall f1 f2 f3 f4 f5 a b -- . ( Applicative f1 -- , Applicative f2 -- , Applicative f3 -- , Applicative f4 -- , Applicative f5 ) -- => f1 (f2 (f3 (f4 (f5 (a -> b))))) -- -> f1 (f2 (f3 (f4 (f5 a)))) -- -> f1 (f2 (f3 (f4 (f5 b)))) -- quinsanity func fffffa = -- let a :: f1 (f2 (f3 (f4 (f5 a)))) -- -> f1 (f2 (f3 (f4 (f5 b)))) -- a = -- (fmap) (<*>) -- ((fmap . fmap) (<*>) ( ( fmap . fmap . fmap ) ( < * > ) ( ( fmap . fmap . fmap . fmap ) ( < * > ) func ) ) ) -- in undefined -- ``` -- quinsanity :: forall f1 f2 f3 f4 f5 a b -- . ( Applicative f1 -- , Applicative f2 -- , Applicative f3 -- , Applicative f4 -- , Applicative f5 ) -- => f1 (f2 (f3 (f4 (f5 (a -> b))))) -- -> f1 (f2 (f3 (f4 (f5 a)))) -- -> f1 (f2 (f3 (f4 (f5 b)))) -- quinsanity func fffffa = -- let a :: z -- a = -- (fmap (<*>) -- ((fmap . fmap) (<*>) ( ( fmap . fmap . fmap ) ( < * > ) ( ( fmap . fmap . fmap . fmap ) ( < * > ) func ) ) ) ) < * > -- in undefined -- Expected type: f1 (a0 -> f3 (f4 (f5 (a -> b)))) -- Actual type: f1 (f2 (f3 (f4 (f5 (a -> b))))) -- • Couldn't match expected type ‘z’ -- with actual type ‘f1 a0 -> f1 (f3 (f4 (f5 (a -> b))))’ -- Expected type: f1 (f2 (a0 -> f4 (f5 (a -> b)))) -- Actual type: f1 (f2 (f3 (f4 (f5 (a -> b))))) -- quinsanity :: ( Applicative f1 -- , Applicative f2 -- , Applicative f3 -- , Applicative f4 -- , Applicative f5 ) -- => f1 (f2 (f3 (f4 (f5 (a -> b))))) -- -> f1 (f2 (f3 (f4 (f5 a)))) -- -> f1 (f2 (f3 (f4 (f5 b)))) -- quinsanity func fffffa = -- let a :: z -- a = ((<*>) <$> -- ((fmap . fmap) (<*>) ( ( fmap . fmap . fmap ) ( < * > ) ( ( fmap . fmap . fmap . fmap ) ( < * > ) func ) ) ) ) -- in undefined
null
https://raw.githubusercontent.com/bitemyapp/teef/9144263b65e20e4013442bfc038053a08bfbccf0/code/FreeMonad.hs
haskell
doubleBubble :: forall f1 f2 a b . ( Applicative f1 , Applicative f2 ) => f1 (f2 (a -> b)) -> f1 (f2 a) -> f1 (f2 b) doubleBubble f ffa = let x :: z x = fmap (<*>) f in undefined <--- ---- hmm <-------- let liftApply :: f (g (a -> b)) -> f (g a -> g b) apF :: f (g a -> g b) apF = liftApply f apApF :: f (g a) -> f (g b) apApF = (<*>) apF in Compose (apApF x) These are just to shut the compiler up, we are not concerned with these right now. instance Functor f => Monad (Free f) where return a = Pure a Pure a >>= f = f a Free f >>= g = let x :: Void x = undefined in Free x instance Functor f => Monad (Free f) where return a = Pure a Pure a >>= f = f a Free f >>= g = Free _a pleaseShow :: Show a => Bool -> a -> Maybe String pleaseShow False _ = Nothing pleaseShow True a = Just (show _a) pleaseShow :: Show a => Bool -> a -> Maybe String pleaseShow False _ = Nothing pleaseShow True a = let x :: z x = a in Just (show undefined) data V pleaseShow :: Show a => Bool -> a -> Maybe String pleaseShow False _ = Nothing pleaseShow True a = let x :: V x = undefined in Just (show x) f :: (b -> a) -> (c -> b) -> c -> a f = quinsanity :: ( Applicative f1 , Applicative f2 , Applicative f3 , Applicative f4 , Applicative f5 ) => f1 (f2 (f3 (f4 (f5 (a -> b))))) -> f1 (f2 (f3 (f4 (f5 a)))) -> f1 (f2 (f3 (f4 (f5 b)))) quinsanity f fffffa = undefined quinsanity :: ( Applicative f1 , Applicative f2 , Applicative f3 , Applicative f4 , Applicative f5 ) => f1 (f2 (f3 (f4 (f5 (a -> b))))) -> f1 (f2 (f3 (f4 (f5 a)))) -> f1 (f2 (f3 (f4 (f5 b)))) quinsanity func fffffa = let a :: x a = (<*>) <$> func in undefined quinsanity :: ( Applicative f1 , Applicative f2 , Applicative f3 , Applicative f4 , Applicative f5 ) => f1 (f2 (f3 (f4 (f5 (a -> b))))) -> f1 (f2 (f3 (f4 (f5 a)))) -> f1 (f2 (f3 (f4 (f5 b)))) quinsanity func fffffa = let a :: f1 (f2 (f3 (f4 (f5 (a -> b))))) a = func in undefined quinsanity :: forall f1 f2 f3 f4 f5 a b . ( Applicative f1 , Applicative f2 , Applicative f3 , Applicative f4 , Applicative f5 ) => f1 (f2 (f3 (f4 (f5 (a -> b))))) -> f1 (f2 (f3 (f4 (f5 a)))) -> f1 (f2 (f3 (f4 (f5 b)))) quinsanity func fffffa = let a :: f1 (f2 (f3 (f4 (f5 (a -> b))))) a = func in undefined quinsanity :: forall f1 f2 f3 f4 f5 a b . ( Applicative f1 , Applicative f2 , Applicative f3 , Applicative f4 , Applicative f5 ) => f1 (f2 (f3 (f4 (f5 (a -> b))))) -> f1 (f2 (f3 (f4 (f5 a)))) -> f1 (f2 (f3 (f4 (f5 b)))) quinsanity func fffffa = let a :: z a = in undefined quinsanity :: forall f1 f2 f3 f4 f5 a b . ( Applicative f1 , Applicative f2 , Applicative f3 , Applicative f4 , Applicative f5 ) => f1 (f2 (f3 (f4 (f5 (a -> b))))) -> f1 (f2 (f3 (f4 (f5 a)))) -> f1 (f2 (f3 (f4 (f5 b)))) quinsanity func fffffa = let a :: z a = (fmap . fmap) (<*>) in undefined quinsanity :: forall f1 f2 f3 f4 f5 a b . ( Applicative f1 , Applicative f2 , Applicative f3 , Applicative f4 , Applicative f5 ) => f1 (f2 (f3 (f4 (f5 (a -> b))))) -> f1 (f2 (f3 (f4 (f5 a)))) -> f1 (f2 (f3 (f4 (f5 b)))) quinsanity func fffffa = let a :: z a = (fmap) (<*>) ((fmap . fmap) (<*>) in undefined • Couldn't match expected type ‘z’ with actual type ‘f1 (f2 (f3 (f4 (f5 (a -> b)))))’ doubleBubble :: ( Applicative f1 , Applicative f2 ) => f1 (f2 (a -> b)) -> f1 (f2 a) -> f1 (f2 b) doubleBubble f ffa = undefined doubleBubble :: ( Applicative f1 , Applicative f2 ) => f1 (f2 (a -> b)) -> f1 (f2 a) -> f1 (f2 b) doubleBubble f ffa = let x :: z x = f in undefined doubleBubble :: ( Applicative f1 , Applicative f2 ) => f1 (f2 (a -> b)) -> f1 (f2 a) -> f1 (f2 b) doubleBubble f ffa = let x :: f1 (f2 (a -> b)) x = f in undefined ```haskell quinsanity :: ( Applicative f1 , Applicative f2 , Applicative f3 , Applicative f4 , Applicative f5 ) => f1 (f2 (f3 (f4 (f5 (a -> b))))) -> f1 (f2 (f3 (f4 (f5 a)))) -> f1 (f2 (f3 (f4 (f5 b)))) quinsanity f fffffa = undefined ``` ```haskell quinsanity :: ( Applicative f1 , Applicative f2 , Applicative f3 , Applicative f4 , Applicative f5 ) => f1 (f2 (f3 (f4 (f5 (a -> b))))) -> f1 (f2 (f3 (f4 (f5 a)))) -> f1 (f2 (f3 (f4 (f5 b)))) quinsanity func fffffa = let a :: z a = func in undefined ``` ```haskell quinsanity :: ( Applicative f1 , Applicative f2 , Applicative f3 , Applicative f4 , Applicative f5 ) => f1 (f2 (f3 (f4 (f5 (a -> b))))) -> f1 (f2 (f3 (f4 (f5 a)))) -> f1 (f2 (f3 (f4 (f5 b)))) quinsanity func fffffa = let a :: f1 (f2 (f3 (f4 (f5 (a -> b))))) a = func in undefined ``` ```haskell {-# LANGUAGE ScopedTypeVariables #-} quinsanity :: forall f1 f2 f3 f4 f5 a b . ( Applicative f1 , Applicative f2 , Applicative f3 , Applicative f4 , Applicative f5 ) => f1 (f2 (f3 (f4 (f5 (a -> b))))) -> f1 (f2 (f3 (f4 (f5 a)))) -> f1 (f2 (f3 (f4 (f5 b)))) quinsanity func fffffa = let a :: f1 (f2 (f3 (f4 (f5 (a -> b))))) a = func in undefined ``` quinsanity :: forall f1 f2 f3 f4 f5 a b . ( Applicative f1 , Applicative f2 , Applicative f3 , Applicative f4 , Applicative f5 ) => f1 (f2 (f3 (f4 (f5 (a -> b))))) -> f1 (f2 (f3 (f4 (f5 a)))) -> f1 (f2 (f3 (f4 (f5 b)))) quinsanity func fffffa = let a :: z a = in undefined ```haskell quinsanity :: forall f1 f2 f3 f4 f5 a b . ( Applicative f1 , Applicative f2 , Applicative f3 , Applicative f4 , Applicative f5 ) => f1 (f2 (f3 (f4 (f5 (a -> b))))) -> f1 (f2 (f3 (f4 (f5 a)))) -> f1 (f2 (f3 (f4 (f5 b)))) quinsanity func fffffa = let a :: z a = (<*>) func in undefined ``` ``` Expected type: f1 (a0 -> f3 (f4 (f5 (a -> b)))) ``` ```haskell quinsanity :: forall f1 f2 f3 f4 f5 a b . ( Applicative f1 , Applicative f2 , Applicative f3 , Applicative f4 , Applicative f5 ) => f1 (f2 (f3 (f4 (f5 (a -> b))))) -> f1 (f2 (f3 (f4 (f5 a)))) -> f1 (f2 (f3 (f4 (f5 b)))) quinsanity func fffffa = let a :: z a = (fmap) (<*>) func in undefined ``` ``` Expected type: f1 (f2 (a0 -> f4 (f5 (a -> b)))) ``` ```haskell ``` ``` Expected type: f1 (f2 (f3 (a0 -> f5 (a -> b)))) ``` ```haskell ``` ``` Expected type: f1 (f2 (f3 (f4 (a0 -> a -> b)))) ``` ```haskell ``` ``` f1 (f2 (f3 (f4 (f5 a -> f5 b)))) ``` ```haskell quinsanity :: forall f1 f2 f3 f4 f5 a b . ( Applicative f1 , Applicative f2 , Applicative f3 , Applicative f4 , Applicative f5 ) => f1 (f2 (f3 (f4 (f5 (a -> b))))) -> f1 (f2 (f3 (f4 (f5 a)))) -> f1 (f2 (f3 (f4 (f5 b)))) quinsanity func fffffa = let a :: z a = in undefined ``` ``` f1 (f2 (f3 (f4 (f5 a) -> f4 (f5 b)))) ``` ```haskell quinsanity :: forall f1 f2 f3 f4 f5 a b . ( Applicative f1 , Applicative f2 , Applicative f3 , Applicative f4 , Applicative f5 ) => f1 (f2 (f3 (f4 (f5 (a -> b))))) -> f1 (f2 (f3 (f4 (f5 a)))) -> f1 (f2 (f3 (f4 (f5 b)))) quinsanity func fffffa = let a :: z a = (fmap . fmap) (<*>) in undefined ``` ``` f1 (f2 (f3 (f4 (f5 a)) -> f3 (f4 (f5 b)))) ``` ```haskell quinsanity :: forall f1 f2 f3 f4 f5 a b . ( Applicative f1 , Applicative f2 , Applicative f3 , Applicative f4 , Applicative f5 ) => f1 (f2 (f3 (f4 (f5 (a -> b))))) -> f1 (f2 (f3 (f4 (f5 a)))) -> f1 (f2 (f3 (f4 (f5 b)))) quinsanity func fffffa = let a :: z a = (fmap) (<*>) ((fmap . fmap) (<*>) in undefined ``` ``` f1 (f2 (f3 (f4 (f5 a))) -> f2 (f3 (f4 (f5 b)))) ``` We seem to have a function that does what we want now. Lets assert the goal type and see if it passes. ```haskell quinsanity :: forall f1 f2 f3 f4 f5 a b . ( Applicative f1 , Applicative f2 , Applicative f3 , Applicative f4 , Applicative f5 ) => f1 (f2 (f3 (f4 (f5 (a -> b))))) -> f1 (f2 (f3 (f4 (f5 a)))) -> f1 (f2 (f3 (f4 (f5 b)))) quinsanity func fffffa = let a :: f1 (f2 (f3 (f4 (f5 a)))) -> f1 (f2 (f3 (f4 (f5 b)))) a = (fmap) (<*>) ((fmap . fmap) (<*>) in undefined ``` quinsanity :: forall f1 f2 f3 f4 f5 a b . ( Applicative f1 , Applicative f2 , Applicative f3 , Applicative f4 , Applicative f5 ) => f1 (f2 (f3 (f4 (f5 (a -> b))))) -> f1 (f2 (f3 (f4 (f5 a)))) -> f1 (f2 (f3 (f4 (f5 b)))) quinsanity func fffffa = let a :: z a = (fmap (<*>) ((fmap . fmap) (<*>) in undefined Expected type: f1 (a0 -> f3 (f4 (f5 (a -> b)))) Actual type: f1 (f2 (f3 (f4 (f5 (a -> b))))) • Couldn't match expected type ‘z’ with actual type ‘f1 a0 -> f1 (f3 (f4 (f5 (a -> b))))’ Expected type: f1 (f2 (a0 -> f4 (f5 (a -> b)))) Actual type: f1 (f2 (f3 (f4 (f5 (a -> b))))) quinsanity :: ( Applicative f1 , Applicative f2 , Applicative f3 , Applicative f4 , Applicative f5 ) => f1 (f2 (f3 (f4 (f5 (a -> b))))) -> f1 (f2 (f3 (f4 (f5 a)))) -> f1 (f2 (f3 (f4 (f5 b)))) quinsanity func fffffa = let a :: z a = ((<*>) <$> ((fmap . fmap) (<*>) in undefined
# LANGUAGE ScopedTypeVariables # module FreeMonad where doubleBubble :: forall f1 f2 a b . ( Applicative f1 , Applicative f2 ) => f1 (f2 (a -> b)) -> f1 (f2 a) x = (fmap (<*>) f) <*> ffa in x liftApply func = ( < * > ) < $ > func data Free f a = Pure a | Free (f (Free f a)) instance Functor f => Functor (Free f) where fmap = undefined instance Functor f => Applicative (Free f) where pure = undefined (<*>) = undefined Okay , we do care about the Monad though . ( fmap . fmap . fmap ) ( < * > ) ( ( fmap . fmap . fmap . fmap ) ( < * > ) func ) ( ( fmap . fmap . fmap ) ( < * > ) ( ( fmap . fmap . fmap . fmap ) ( < * > ) func ) ) ( ( fmap . fmap . fmap ) ( < * > ) ( ( fmap . fmap . fmap . fmap ) ( < * > ) func ) ) ) ( ( fmap . fmap . fmap ) ( < * > ) ( ( fmap . fmap . fmap . fmap ) ( < * > ) func ) ) < * > a = ( fmap . fmap ) ( < * > ) func a = ( fmap . fmap . fmap ) ( < * > ) func a = ( fmap . fmap . fmap . fmap ) ( < * > ) func ( fmap . fmap . fmap ) ( < * > ) ( ( fmap . fmap . fmap . fmap ) ( < * > ) func ) ( ( fmap . fmap . fmap ) ( < * > ) ( ( fmap . fmap . fmap . fmap ) ( < * > ) func ) ) ( ( fmap . fmap . fmap ) ( < * > ) ( ( fmap . fmap . fmap . fmap ) ( < * > ) func ) ) ) ( ( fmap . fmap . fmap ) ( < * > ) ( ( fmap . fmap . fmap . fmap ) ( < * > ) func ) ) ) ( ( fmap . fmap . fmap ) ( < * > ) ( ( fmap . fmap . fmap . fmap ) ( < * > ) func ) ) ) ) < * > ( ( fmap . fmap . fmap ) ( < * > ) ( ( fmap . fmap . fmap . fmap ) ( < * > ) func ) ) ) )
3978bc4c77d9777fefb29bf27d164799005724c0ce380bc7d69d9b819a8a005c
baconpaul/composition-kit
meddley.clj
(ns composition-kit.compositions.nerdbait.meddley (:require [composition-kit.music-lib.midi-util :as midi]) (:require [composition-kit.music-lib.tempo :as tempo]) (:require [composition-kit.music-lib.logical-sequence :as ls]) (:require [composition-kit.music-lib.logical-item :as i]) (:use composition-kit.core)) ;; F D- F D- Bes C F C F Bes C D- Bes C A D- Bes F Bes F bes C F TODOS Fade out strings in chorus 2 Articulation V3P1 ; Harmony more open also . (def instruments (-> (midi/midi-instrument-map) (midi/add-midi-instrument :vln-1-db-leg (midi/midi-port 0)) (midi/add-midi-instrument :vln-1-ub-leg (midi/midi-port 1)) (midi/add-midi-instrument :vln-1-marc-long (midi/midi-port 2)) (midi/add-midi-instrument :vln-1-marc-short (midi/midi-port 3)) (midi/add-midi-instrument :vln-2-db-leg (midi/midi-port 4)) (midi/add-midi-instrument :vln-2-ub-leg (midi/midi-port 5)) (midi/add-midi-instrument :vln-2-marc-long (midi/midi-port 6)) (midi/add-midi-instrument :vln-2-marc-short (midi/midi-port 7)) (midi/add-midi-instrument :cl-db-leg (midi/midi-port 8)) (midi/add-midi-instrument :cl-ub-leg (midi/midi-port 9)) (midi/add-midi-instrument :cl-marc-long (midi/midi-port 10)) (midi/add-midi-instrument :cl-marc-short (midi/midi-port 11)) (midi/add-midi-instrument :vla-db-leg (midi/midi-port 12)) (midi/add-midi-instrument :vla-ub-leg (midi/midi-port 13)) (midi/add-midi-instrument :vla-marc-long (midi/midi-port 14)) (midi/add-midi-instrument :vla-marc-short (midi/midi-port 15)) (midi/add-midi-instrument :bass-marc-long (midi/midi-port "Bus 2" 0)) (midi/add-midi-instrument :flute-sus-acc (midi/midi-port "Bus 3" 0)) (midi/add-midi-instrument :flute-short (midi/midi-port "Bus 3" 1)) (midi/add-midi-instrument :flute-sus-vib (midi/midi-port "Bus 3" 2)) (midi/add-midi-instrument :oboe-stac (midi/midi-port "Bus 3" 3)) (midi/add-midi-instrument :oboe-sus-vib (midi/midi-port "Bus 3" 4)) (midi/add-midi-instrument :ehorn-stac (midi/midi-port "Bus 3" 6)) (midi/add-midi-instrument :ehorn-sus-vib (midi/midi-port "Bus 3" 5)) (midi/add-midi-instrument :bsn-stac (midi/midi-port "Bus 3" 8)) (midi/add-midi-instrument :bsn-sus-vib (midi/midi-port "Bus 3" 7)) (midi/add-midi-instrument :fh-leg (midi/midi-port "Bus 4" 0)) (midi/add-midi-instrument :tp-leg (midi/midi-port "Bus 4" 1)) (midi/add-midi-instrument :tp-sta (midi/midi-port "Bus 4" 2)) (midi/add-midi-instrument :tbn-leg (midi/midi-port "Bus 4" 3)) (midi/add-midi-instrument :solov-leg-exp (midi/midi-port "Bus 5" 0)) (midi/add-midi-instrument :solov-leg-lyr (midi/midi-port "Bus 5" 1)) (midi/add-midi-instrument :solov-marc (midi/midi-port "Bus 5" 2)) (midi/add-midi-instrument :solov-stac (midi/midi-port "Bus 5" 3)) (midi/add-midi-instrument :soloc-leg-exp (midi/midi-port "Bus 5" 4)) (midi/add-midi-instrument :soloc-leg-lyr (midi/midi-port "Bus 5" 5)) (midi/add-midi-instrument :soloc-marc (midi/midi-port "Bus 5" 6)) )) (def tdelay 150) (def clock (tempo/constant-tempo 3 8 77)) (defn try-out [s] (midi-play (-> s (ls/with-clock clock)) :beat-clock clock)) (defn make-alias [s k1 k2] (assoc s k1 (k2 s))) (def accent-pattern-dynamics (fn [i] (fn [w] (let [b (i/item-beat w) b3 (mod b 3/2) ] (cond (= b3 0) (+ 80 (/ b 10)) :else (- 87 (* 3 b3)))) ))) (defn control-surge [ctrl p1 p2 beat-len] (let [diff (- p2 p1) ct (max diff (- diff)) dt (/ beat-len (dec ct)) ] (map (fn [i] (i/control-event ctrl (+ p1 (* diff (/ i ct))) (* dt i))) (range ct)) ) ) (defn control-reset [ctrl inst] (-> [ (i/control-event ctrl 80 0) ] (ls/on-instrument inst))) (def verse-2-violin-1 (let [alias-instr (-> instruments (make-alias :db :vln-1-db-leg) (make-alias :ub :vln-1-ub-leg) (make-alias :ml :vln-1-marc-long) (make-alias :ms :vln-1-marc-short) ) ] (>>> (<*> (-> (lily " ^hold=0.97 ^i=db c2. ^u=ub d4. d4. ^i=db c2. ^i=ub d4. d4. ^i=db d2. ^i=ub e2. ^i=db f2. ^i=ms e16 f e8 ^i=ml d8 ^i=ub c4. " :relative :c5 :instruments alias-instr) (ls/line-segment-dynamics 0 15 (* 8 3) 72) ) (-> (>>> (control-surge 11 30 40 3) (rest-for 3) (control-surge 11 40 80 3) (rest-for 3) (control-surge 11 80 95 3) (rest-for 3) ) (ls/on-instrument (:db alias-instr)) ) (-> (>>> (rest-for 3) (control-surge 11 30 40 3) (rest-for 3) (control-surge 11 40 80 3) (rest-for 3) (control-surge 11 80 95 3) ) (ls/on-instrument (:ub alias-instr)) ) ) (-> (lily " ^i=ms ^hold=0.86 c8 c c c c c d d d e e e f f f f f f f f f g g g g g g g g g a a a a a g ^hold=0.97 ^i=db f2. d2. " :relative :c5 :instruments alias-instr) (ls/transform :dynamics accent-pattern-dynamics) (ls/amplify 0.8) ) (<*> (lily "^i=ub ^hold=0.97 c4.*50 ^i=db d2." :relative :c5 :instruments alias-instr) (-> (>>> (control-surge 11 90 80 3/2) (rest-for 3) (control-surge 11 80 0 3/2) ) (ls/on-instrument (:ub alias-instr))) (-> (>>> (control-surge 11 90 80 3/2) (rest-for 3) (control-surge 11 80 0 3/2) ) (ls/on-instrument (:db alias-instr))) ) ( rest - for ( * 2 3/2 ) ) ))) ( try - out verse-2 - violin-1 ) ; ; TODO next make this more expressive by using the mod wheel ( cc 1 ) ;; So the function I need is " Control - Curve c # curve - fn len " ;; then that takes up 0 -> len and you can chain them with >>> ;; then delegate everything to 'curve' library ;; For ths instruments I'm using in legato section Because these instruments are smaller , CC 1 ( the Mod Wheel ) controls the cross - fade of both vibrato and dynamics at the same time . CC 11 ( Expression ) performs global volume control . What is different about the “ Niente ” versions is that CC 1 can bring the volume all the way to zero ;; in addition to cross-fading dynamics and vibrato. (def verse-2-violin-2 (let [alias-instr (-> instruments (make-alias :db :vln-2-db-leg) (make-alias :ub :vln-2-ub-leg) (make-alias :ml :vln-2-marc-long) (make-alias :ms :vln-2-marc-short) ) ] (>>> (<*> (-> (lily " ^hold=0.97 ^i=db a2. ^u=ub a4. a4. ^i=db a2. ^i=ub a4. a4. ^i=db bes2. ^i=ub c2. ^i=db c2. ^i=ms c16 d ^i=ml c4 ^i=ub g4. " :relative :c5 :instruments alias-instr) (ls/line-segment-dynamics 0 15 (* 8 3) 72)) (-> (>>> (control-surge 11 30 40 3) (rest-for 3) (control-surge 11 40 80 3) (rest-for 3) (control-surge 11 80 95 3) (rest-for 3) ) (ls/on-instrument (:db alias-instr)) ) (-> (>>> (rest-for 3) (control-surge 11 30 40 3) (rest-for 3) (control-surge 11 40 80 3) (rest-for 3) (control-surge 11 80 95 3) ) (ls/on-instrument (:ub alias-instr)) )) (-> (lily " ^i=ms ^hold=0.86 f8 f f f f f f f f g g g a a a a a a bes bes bes bes bes bes c c c c c c cis cis cis cis cis cis ^hold=0.97 ^i=db a2. f2. " :relative :c4 :instruments alias-instr) (ls/transform :dynamics accent-pattern-dynamics) (ls/amplify 0.8)) (lily "^i=ub ^hold=0.97 bes1.*50 ^i=db c1." :relative :c5 :instruments alias-instr) ))) (def verse-2-viola (let [alias-instr (-> instruments (make-alias :db :vla-db-leg) (make-alias :ub :vla-ub-leg) (make-alias :ml :vla-marc-long) (make-alias :ms :vla-marc-short) ) ] (>>> (<*> (-> (lily " ^hold=0.97 ^i=db f2 ^i=ub e4 ^i=db d2 ^i=ub e4 ^i=db f2 ^i=ub e4 ^i=db d4. ^i=ub f4. ^i=db f2. ^i=ub g2. ^i=db a2. ^i=ms g16 a ^i=ml g4 ^i=ub g4. " :relative :c4 :instruments alias-instr) (ls/line-segment-dynamics 0 15 (* 8 3) 72)) (-> (>>> (control-surge 11 30 40 3) (rest-for 3) (control-surge 11 40 80 3) (rest-for 3) (control-surge 11 80 95 3) (rest-for 3) ) (ls/on-instrument (:db alias-instr)) ) (-> (>>> (rest-for 3) (control-surge 11 30 40 3) (rest-for 3) (control-surge 11 40 80 3) (rest-for 3) (control-surge 11 80 95 3) ) (ls/on-instrument (:ub alias-instr)) )) (-> (lily " ^i=ms ^hold=0.86 f8 f f f f f bes bes bes g g g a g f f g a bes bes bes bes c d c c c c d c cis cis cis cis cis a ^hold=0.97 ^i=db a2. d2. " :relative :c3 :instruments alias-instr) (ls/transform :dynamics accent-pattern-dynamics) (ls/amplify 0.8) ) ))) (def verse-2-cello (let [alias-instr (-> instruments (make-alias :db :cl-db-leg) (make-alias :ub :cl-ub-leg) (make-alias :ml :cl-marc-long) (make-alias :ms :cl-marc-short) )] (>>> (<*> (-> (lily "^hold=0.97 ^inst=ml f2 f'8 e d2 d8 e f8 c d f, g bes a bes a g f e bes4. f8 bes4 c8 d e c' d e f16 g f8 c f,16 g f8 c e16 d c4 c16 d e4" :relative :c2 :instruments alias-instr)) (-> (>>> (control-surge 11 30 40 3) (rest-for 3) (control-surge 11 40 80 3) (rest-for 3) (control-surge 11 80 95 3) (rest-for 3) ) (ls/on-instrument (:db alias-instr)) ) (-> (>>> (rest-for 3) (control-surge 11 30 40 3) (rest-for 3) (control-surge 11 40 80 3) (rest-for 3) (control-surge 11 80 95 3) ) (ls/on-instrument (:ub alias-instr)) )) (-> (lily "^hold=0.4 ^inst=ms f,8 g a a bes c d e f g e c d e f f d a bes c d d e f c, d e f g b a cis e cis b a ^hold=0.97 ^inst=ml d2. c2. " :relative :c3 :instruments alias-instr) (ls/transform :dynamics accent-pattern-dynamics) (ls/amplify 1.03) ) (-> (lily "^hold=0.97 ^inst=ub bes1.*97 ^inst=db f1." :instruments alias-instr :relative :c4)) ) ) ) (def verse-2-bass (>>> (rest-for (* 16 3/2)) (-> (lily "^hold=0.97 f4. f4. bes,4. c4. d4. d4 c8 bes4. bes4. c4. c4. cis4 b8 a4. d4. d4." :relative :c2) (ls/line-segment-dynamics 0 80 (* 13 3/2) 104 (* 16 3/2) 80) (ls/on-instrument (:bass-marc-long instruments)) ) )) ;;(try-out verse-2-bass) These all start at the bes->c 4 . transition before the f starts again (def verse-3-violin-1 (let [alias-instr (-> instruments (make-alias :db :vln-1-db-leg) (make-alias :ub :vln-1-ub-leg) (make-alias :ml :vln-1-marc-long) (make-alias :ms :vln-1-marc-short) ) ] (>>> (-> (lily "^hold=0.8 ^inst=ms d16 e f e f a g a bes c f e " :relative :c4 :instruments alias-instr) (ls/line-segment-dynamics 0 20 3 70)) (-> (<*> (control-reset 11 (:db alias-instr)) (control-reset 11 (:ub alias-instr)) (lily "^hold=0.97 ^inst=db f2. ^inst=ub d2. ^inst=db c2. ^inst=ub d2. ^inst=db d2. ^inst=ub e2. ^inst=db f2. ^inst=ms e16 f e8 d ^inst=ml c4." :relative :c5 :instruments alias-instr))) (-> (lily " ^i=ms ^hold=0.86 c8 c c c c c d d d e e e f f f f f f f f f g g g g g g g g g a a a a a g ^hold=0.97 ^i=db f2. d2. " :relative :c5 :instruments alias-instr) (ls/transform :dynamics accent-pattern-dynamics) (ls/amplify 0.8) )) ) ) (def verse-3-violin-2 (let [alias-instr (-> instruments (make-alias :db :vln-2-db-leg) (make-alias :ub :vln-2-ub-leg) (make-alias :ml :vln-2-marc-long) (make-alias :ms :vln-2-marc-short) ) ] (>>> (-> (lily "^hold=0.8 ^inst=ms bes16 c d c d f e f g g c bes " :relative :c4 :instruments alias-instr) (ls/line-segment-dynamics 0 20 3 70)) (<*> (control-reset 11 (:ub alias-instr)) (control-reset 11 (:db alias-instr)) (-> (lily "^hold=0.97 ^inst=db a2. ^inst=ub a2. ^inst=db a2. ^inst=ub a2. ^inst=db bes2. ^inst=ub c2. ^inst=db c2. ^inst=ms c16 d c8 c8 ^inst=ml g4. " :relative :c5 :instruments alias-instr))) (-> (lily " ^i=ms ^hold=0.86 f8 f f f f f f f f g g g a a a a a a bes bes bes bes bes bes c c c c c c cis cis cis cis cis cis ^hold=0.97 ^i=db a2. f2. " :relative :c4 :instruments alias-instr) (ls/transform :dynamics accent-pattern-dynamics) (ls/amplify 0.8)) ) ) ) (def verse-3-viola (let [alias-instr (-> instruments (make-alias :db :vla-db-leg) (make-alias :ub :vla-ub-leg) (make-alias :ml :vla-marc-long) (make-alias :ms :vla-marc-short) ) ] (>>> (<*> (control-reset 11 (:ub alias-instr)) (control-reset 11 (:db alias-instr)) (-> (lily "^hold=0.8 ^inst=db d4 ^inst=ub f8 ^inst=db e4 ^inst=ub g8 ^inst=db c2. a2. c2. a2. f2. g2. a2. ^inst=ms c16 d e8 f ^inst=ml e4. " :relative :c3 :instruments alias-instr) (ls/line-segment-dynamics 0 30 3 70))) (-> (lily " ^i=ms ^hold=0.86 f8 f f f f f bes bes bes g g g a g f f g a bes bes bes bes c d c c c c d c cis cis cis cis cis a ^hold=0.97 ^i=db a2. d2. " :relative :c3 :instruments alias-instr) (ls/transform :dynamics accent-pattern-dynamics) (ls/amplify 0.8) ) ) ) ) (def verse-3-cello (let [alias-instr (-> instruments (make-alias :db :cl-db-leg) (make-alias :ub :cl-ub-leg) (make-alias :ml :cl-marc-long) (make-alias :ms :cl-marc-short) ) ] (>>> (<*> (control-reset 11 (:ub alias-instr)) (control-reset 11 (:db alias-instr)) (-> (lily "^hold=0.8 ^inst=db bes4 ^inst=ub bes8 ^inst=db c4 ^inst=ub e8 ^inst=db f2. d2. f2. d2. d2. e2. f2. ^inst=ml c8. g16 c'8 c,4. " :relative :c3 :instruments alias-instr) (ls/line-segment-dynamics 0 30 3 70))) (-> (lily "^hold=0.4 ^inst=ms f,8 g a a bes c d e f g e c d e f f d a bes c d d e f c, d e f g b a cis e cis b a ^hold=0.97 ^inst=ml d2. c2. " :relative :c3 :instruments alias-instr) (ls/transform :dynamics accent-pattern-dynamics) (ls/amplify 1.03) ) ) ) ) (def verse-3-bass (>>> (rest-for 3) (-> (lily "^hold=1.01 f2. d2. f2. d2. bes2. c2. f2. c2. f,2. bes4. c4. d2. bes2. c2. a2. d2. c2." :relative :c2) (ls/on-instrument (:bass-marc-long instruments)) (ls/line-segment-dynamics 0 65 24 74 45 108 52 70) ))) (def verse-3-flute (let [ai (-> instruments (make-alias :sv :flute-sus-vib) (make-alias :sa :flute-sus-acc) (make-alias :st :flute-short) )] (>>> (rest-for 3) (-> (lily "^hold=0.97 ^inst=sv c4. c8 ^inst=st c16 d f e ^inst=sv f4. d4. ^inst=sv c4. c8 ^inst=st c16 d f e ^inst=sv f4. a4. ^inst=st bes16*120 a g f e d c d e f g c d c bes a g f e f g a bes g ^inst=sv a2. bes4. c4. ^inst=sa f,2 ^inst=st a8 a bes16 g f d bes8 ^inst=sv c4. ^inst=st d16 e f g bes g ^inst=sa a4. bes4. ^inst=st c16 g f d c bes a32 bes d bes ^inst=sv c4 c'4. ^inst=sa cis2. ^inst=sv d2. c2. " :relative :c5 :instruments ai)) ))) #_(try-out verse-3-flute) (def verse-3-oboe (let [ai (-> instruments (make-alias :ot :oboe-stac) (make-alias :ov :oboe-sus-vib) )] (>>> (rest-for 3) (-> (lily "^hold=0.97 r2. r2. r2. r2. ^inst=ov f4.*104 ^hold=0.7 ^inst=ot e16 f g a bes e d c bes a g f e f g a bes g ^hold=0.97 ^inst=ov f2. d4. e4. ^inst=ov a'2 ^inst=ot c8 c d16 bes a f d8 ^inst=ov e4. ^inst=ot f16 g f e d c ^inst=ov c4. f4. ^inst=ot e16 c bes f e d e32 g e f ^inst=ov e4 e'4. ^inst=ov e2. ^inst=ov f2. e2. " :relative :c4 :instruments ai)) ))) (def verse-3-ehorn (let [ai (-> instruments (make-alias :et :ehorn-stac) (make-alias :ev :ehorn-sus-vib) )] (>>> (rest-for 3) (-> (lily "^hold=0.97 r2. r2. r2. r2. ^inst=ev d4.*104 ^hold=0.7 ^inst=et c8 e8 f16 g bes a f e d c bes d e f f8 ^hold=0.97 ^inst=ev c2. bes4. c4. ^inst=ev f2 ^inst=et f8 e ^inst=ev d4. c4. ^inst=et d8 f a ^inst=ev d4. bes4 f,8 g'4. c2. e2. d2. c2. " :relative :c4 :instruments ai)) ))) (def verse-3-bassoon (let [ai (-> instruments (make-alias :bt :bsn-stac) (make-alias :bv :bsn-sus-vib) )] (>>> (rest-for 3) (-> (lily "^hold=0.97 r2. r2. r2. r2. ^inst=bv bes4.*104 c4. ^hold=0.7 ^inst=bt bes8 f' bes, c g' c ^hold=0.97 ^inst=bv c2. bes4. g4. f2 a4 bes8 d bes c4. d2 f4 bes,4. c8 c, g' c2 c,4 a'2 cis4 d2. c2. " :relative :c3 :instruments ai)) )) ) (def fh-swells (<*> (-> (lily "^hold=0.96 a2. bes4. c4. d2. bes2. c2. cis2. d2. c2." :relative :c4) (ls/on-instrument (:fh-leg instruments)) ) (-> (lily "^hold=0.96 f2. d4. e4. f2. f2. g2. a2. a2. a2." :relative :c4) (ls/on-instrument (:fh-leg instruments)) ) (-> (>>> (<*> (control-surge 1 30 100 3) (control-surge 11 70 100 3) ) (control-surge 1 40 97 3/2) (control-surge 1 60 104 3/2) (control-surge 1 70 104 3) (control-surge 1 80 104 3) (control-surge 1 80 104 3) (control-surge 1 97 110 3);; the CIS (control-surge 1 70 84 3) (control-surge 1 50 72 3) ) (ls/on-instrument (:fh-leg instruments)) ) )) (def tp-swells (-> (<*> (lily "^hold=0.96 c2. f4. g4. a2. f2. e2. e2. d2. c2." :relative :c4 ) (lily "^hold=0.96 f2. bes4. c4. d2. d2. g2. a2. f2. f2." :relative :c4 ) (>>> (<*> (control-surge 1 30 100 3) (control-surge 11 70 100 3) ) (control-surge 1 40 97 3/2) (control-surge 1 60 104 3/2) (control-surge 1 70 104 3) (control-surge 1 80 104 3) (control-surge 1 80 104 3) (control-surge 1 97 110 3);; the CIS (control-surge 1 70 84 3) (control-surge 1 50 72 3) ) ) (ls/on-instrument (:tp-leg instruments)) )) (def tbn-swells (-> (<*> (lily "^hold=0.96 f2. bes4. c4. d2. bes2. c4. e,4. cis'4. a4. d2. c2." :relative :c3 ) (>>> (<*> (control-surge 1 30 100 3) (control-surge 11 70 100 3) ) (control-surge 1 40 97 3/2) (control-surge 1 60 104 3/2) (control-surge 1 70 104 3) (control-surge 1 80 104 3) (control-surge 1 80 104 3) (control-surge 1 97 110 3);; the CIS (control-surge 1 70 84 3) (control-surge 1 50 72 3) ) ) (ls/on-instrument (:tbn-leg instruments)) )) (def solo-violin (let [ai (-> instruments (make-alias :exp :solov-leg-exp ) (make-alias :lyr :solov-leg-lyr ) (make-alias :marc :solov-marc ) (make-alias :stac :solov-stac ) ) ] (>>> (<*> (lily "^hold=0.97 ^i=exp f2.*120 bes2.*120 a2. c2." :relative :c5 :instruments ai) (-> (>>> (control-surge 11 90 102 3) (control-surge 11 94 112 3) (control-surge 11 94 112 3) (control-surge 11 94 112 3) ) (ls/on-instrument (:solov-leg-exp instruments)) ) ) (<*> (lily "^hold=0.97 ^i=lyr d4. ^hold=0.8 ^i=stac d8*60 d e f*84 e d ^hold=0.97 ^i=lyr d4.*97 ^i=stac ^hold=0.8 c16 f a8 a g16 a f c f e d c bes a g c bes a g f e f " :relative :c5 :instruments ai) (-> (>>> (control-surge 11 90 102 3/2) (rest-for 3) (control-surge 11 88 76 3/2) ) (ls/on-instrument (:solov-leg-lyr instruments)) ) (-> (>>> (rest-for 3/2) (control-surge 11 60 82 3/2) (control-surge 11 82 64 3/2) (control-surge 11 72 84 2) (control-surge 11 84 17 2) (control-surge 11 84 17 2) ) (ls/on-instrument (:solov-stac instruments)) ) ) (<*> (lily "^hold=0.97 ^i=exp f2*120 a4 bes2.*120 a2. c2. d2. f1." :relative :c4 :instruments ai) (-> (>>> (control-surge 11 90 102 3) (control-surge 11 94 112 3) (control-surge 11 94 112 3) (control-surge 11 94 112 3) ) (ls/on-instrument (:solov-leg-exp instruments)) ) ) ) )) ;;(try-out solo-violin) (def solo-cello (let [ai (-> instruments (make-alias :exp :soloc-leg-exp ) (make-alias :lyr :soloc-leg-lyr ) (make-alias :marc :soloc-marc ) ) ] (>>> (<*> (lily "^hold=0.97 ^inst=marc f16*120 g a bes c8 e ^inst=lyr f4 ^inst=exp d4. bes4. c4. ^inst=marc c16*77 d c*80 bes*84 a d*78 ^inst=lyr c2. bes4. f4 g8 f2. a4 c8 f4. c2. ^i=exp bes2 c4 d2. c2. f2. f2. f4. a4. " :relative :c3 :instruments ai) (-> (>>>) (ls/on-instrument (:marc ai)) ) (-> (>>> (rest-for 3/2) (control-surge 11 70 80 2) (rest-for 6) (control-surge 11 72 102 15) ) (ls/on-instrument (:lyr ai)) ) (-> (>>> (rest-for 24) (control-surge 11 70 90 3) (control-surge 11 82 94 3) (control-surge 11 90 106 3) (control-surge 11 82 97 3) (control-surge 11 77 92 3) (control-surge 11 70 86 3) ) (ls/on-instrument (:exp ai)) ) )) ) ) ;;(try-out (<*> solo-cello solo-violin)) (map ls/beat-length (list verse-2-violin-1 verse-2-violin-2 verse-2-viola verse-2-cello verse-2-bass )) (def final-song (-> (>>> (rest-for tdelay) (rest-for 6) (<*> verse-2-violin-1 verse-2-violin-2 verse-2-viola verse-2-cello verse-2-bass ) (rest-for (* 10 3/2)) (<*> (<*> verse-3-violin-1 verse-3-violin-2 verse-3-viola verse-3-cello verse-3-bass) (<*> verse-3-flute verse-3-oboe verse-3-ehorn verse-3-bassoon ) 8 measures plus that extra we get for the intro (<*> fh-swells tp-swells tbn-swells)) ) (<*> solo-violin solo-cello ) (rest-for 180) ) (ls/with-clock clock) ) ) (def play-meddley true) (def ag (when play-meddley (midi-play final-song : samples [ { : file " /Users / paul / Desktop / MM / Bouncedown.wav " : zero - point ( * ( tempo / beats - to - time clock -3 ) 1000000 ) } ] :beat-clock clock tdelay ; ; ( + 50 tdelay ) )) ) ;;(midi/all-notes-off)
null
https://raw.githubusercontent.com/baconpaul/composition-kit/fce0addb74a9c30ba06e051d3bca51c5a2b0ce6f/src/composition_kit/compositions/nerdbait/meddley.clj
clojure
F D- F D- Bes C F C Harmony more open also . ; TODO next make this more expressive by using the mod wheel ( cc 1 ) So the function I need is then that takes up 0 -> len and you can chain them with >>> then delegate everything to 'curve' library For ths instruments I'm using in legato section in addition to cross-fading dynamics and vibrato. (try-out verse-2-bass) the CIS the CIS the CIS (try-out solo-violin) (try-out (<*> solo-cello solo-violin)) ; ( + 50 tdelay ) (midi/all-notes-off)
(ns composition-kit.compositions.nerdbait.meddley (:require [composition-kit.music-lib.midi-util :as midi]) (:require [composition-kit.music-lib.tempo :as tempo]) (:require [composition-kit.music-lib.logical-sequence :as ls]) (:require [composition-kit.music-lib.logical-item :as i]) (:use composition-kit.core)) F Bes C D- Bes C A D- Bes F Bes F bes C F TODOS Fade out strings in chorus 2 (def instruments (-> (midi/midi-instrument-map) (midi/add-midi-instrument :vln-1-db-leg (midi/midi-port 0)) (midi/add-midi-instrument :vln-1-ub-leg (midi/midi-port 1)) (midi/add-midi-instrument :vln-1-marc-long (midi/midi-port 2)) (midi/add-midi-instrument :vln-1-marc-short (midi/midi-port 3)) (midi/add-midi-instrument :vln-2-db-leg (midi/midi-port 4)) (midi/add-midi-instrument :vln-2-ub-leg (midi/midi-port 5)) (midi/add-midi-instrument :vln-2-marc-long (midi/midi-port 6)) (midi/add-midi-instrument :vln-2-marc-short (midi/midi-port 7)) (midi/add-midi-instrument :cl-db-leg (midi/midi-port 8)) (midi/add-midi-instrument :cl-ub-leg (midi/midi-port 9)) (midi/add-midi-instrument :cl-marc-long (midi/midi-port 10)) (midi/add-midi-instrument :cl-marc-short (midi/midi-port 11)) (midi/add-midi-instrument :vla-db-leg (midi/midi-port 12)) (midi/add-midi-instrument :vla-ub-leg (midi/midi-port 13)) (midi/add-midi-instrument :vla-marc-long (midi/midi-port 14)) (midi/add-midi-instrument :vla-marc-short (midi/midi-port 15)) (midi/add-midi-instrument :bass-marc-long (midi/midi-port "Bus 2" 0)) (midi/add-midi-instrument :flute-sus-acc (midi/midi-port "Bus 3" 0)) (midi/add-midi-instrument :flute-short (midi/midi-port "Bus 3" 1)) (midi/add-midi-instrument :flute-sus-vib (midi/midi-port "Bus 3" 2)) (midi/add-midi-instrument :oboe-stac (midi/midi-port "Bus 3" 3)) (midi/add-midi-instrument :oboe-sus-vib (midi/midi-port "Bus 3" 4)) (midi/add-midi-instrument :ehorn-stac (midi/midi-port "Bus 3" 6)) (midi/add-midi-instrument :ehorn-sus-vib (midi/midi-port "Bus 3" 5)) (midi/add-midi-instrument :bsn-stac (midi/midi-port "Bus 3" 8)) (midi/add-midi-instrument :bsn-sus-vib (midi/midi-port "Bus 3" 7)) (midi/add-midi-instrument :fh-leg (midi/midi-port "Bus 4" 0)) (midi/add-midi-instrument :tp-leg (midi/midi-port "Bus 4" 1)) (midi/add-midi-instrument :tp-sta (midi/midi-port "Bus 4" 2)) (midi/add-midi-instrument :tbn-leg (midi/midi-port "Bus 4" 3)) (midi/add-midi-instrument :solov-leg-exp (midi/midi-port "Bus 5" 0)) (midi/add-midi-instrument :solov-leg-lyr (midi/midi-port "Bus 5" 1)) (midi/add-midi-instrument :solov-marc (midi/midi-port "Bus 5" 2)) (midi/add-midi-instrument :solov-stac (midi/midi-port "Bus 5" 3)) (midi/add-midi-instrument :soloc-leg-exp (midi/midi-port "Bus 5" 4)) (midi/add-midi-instrument :soloc-leg-lyr (midi/midi-port "Bus 5" 5)) (midi/add-midi-instrument :soloc-marc (midi/midi-port "Bus 5" 6)) )) (def tdelay 150) (def clock (tempo/constant-tempo 3 8 77)) (defn try-out [s] (midi-play (-> s (ls/with-clock clock)) :beat-clock clock)) (defn make-alias [s k1 k2] (assoc s k1 (k2 s))) (def accent-pattern-dynamics (fn [i] (fn [w] (let [b (i/item-beat w) b3 (mod b 3/2) ] (cond (= b3 0) (+ 80 (/ b 10)) :else (- 87 (* 3 b3)))) ))) (defn control-surge [ctrl p1 p2 beat-len] (let [diff (- p2 p1) ct (max diff (- diff)) dt (/ beat-len (dec ct)) ] (map (fn [i] (i/control-event ctrl (+ p1 (* diff (/ i ct))) (* dt i))) (range ct)) ) ) (defn control-reset [ctrl inst] (-> [ (i/control-event ctrl 80 0) ] (ls/on-instrument inst))) (def verse-2-violin-1 (let [alias-instr (-> instruments (make-alias :db :vln-1-db-leg) (make-alias :ub :vln-1-ub-leg) (make-alias :ml :vln-1-marc-long) (make-alias :ms :vln-1-marc-short) ) ] (>>> (<*> (-> (lily " ^hold=0.97 ^i=db c2. ^u=ub d4. d4. ^i=db c2. ^i=ub d4. d4. ^i=db d2. ^i=ub e2. ^i=db f2. ^i=ms e16 f e8 ^i=ml d8 ^i=ub c4. " :relative :c5 :instruments alias-instr) (ls/line-segment-dynamics 0 15 (* 8 3) 72) ) (-> (>>> (control-surge 11 30 40 3) (rest-for 3) (control-surge 11 40 80 3) (rest-for 3) (control-surge 11 80 95 3) (rest-for 3) ) (ls/on-instrument (:db alias-instr)) ) (-> (>>> (rest-for 3) (control-surge 11 30 40 3) (rest-for 3) (control-surge 11 40 80 3) (rest-for 3) (control-surge 11 80 95 3) ) (ls/on-instrument (:ub alias-instr)) ) ) (-> (lily " ^i=ms ^hold=0.86 c8 c c c c c d d d e e e f f f f f f f f f g g g g g g g g g a a a a a g ^hold=0.97 ^i=db f2. d2. " :relative :c5 :instruments alias-instr) (ls/transform :dynamics accent-pattern-dynamics) (ls/amplify 0.8) ) (<*> (lily "^i=ub ^hold=0.97 c4.*50 ^i=db d2." :relative :c5 :instruments alias-instr) (-> (>>> (control-surge 11 90 80 3/2) (rest-for 3) (control-surge 11 80 0 3/2) ) (ls/on-instrument (:ub alias-instr))) (-> (>>> (control-surge 11 90 80 3/2) (rest-for 3) (control-surge 11 80 0 3/2) ) (ls/on-instrument (:db alias-instr))) ) ( rest - for ( * 2 3/2 ) ) ))) " Control - Curve c # curve - fn len " Because these instruments are smaller , CC 1 ( the Mod Wheel ) controls the cross - fade of both vibrato and dynamics at the same time . CC 11 ( Expression ) performs global volume control . What is different about the “ Niente ” versions is that CC 1 can bring the volume all the way to zero (def verse-2-violin-2 (let [alias-instr (-> instruments (make-alias :db :vln-2-db-leg) (make-alias :ub :vln-2-ub-leg) (make-alias :ml :vln-2-marc-long) (make-alias :ms :vln-2-marc-short) ) ] (>>> (<*> (-> (lily " ^hold=0.97 ^i=db a2. ^u=ub a4. a4. ^i=db a2. ^i=ub a4. a4. ^i=db bes2. ^i=ub c2. ^i=db c2. ^i=ms c16 d ^i=ml c4 ^i=ub g4. " :relative :c5 :instruments alias-instr) (ls/line-segment-dynamics 0 15 (* 8 3) 72)) (-> (>>> (control-surge 11 30 40 3) (rest-for 3) (control-surge 11 40 80 3) (rest-for 3) (control-surge 11 80 95 3) (rest-for 3) ) (ls/on-instrument (:db alias-instr)) ) (-> (>>> (rest-for 3) (control-surge 11 30 40 3) (rest-for 3) (control-surge 11 40 80 3) (rest-for 3) (control-surge 11 80 95 3) ) (ls/on-instrument (:ub alias-instr)) )) (-> (lily " ^i=ms ^hold=0.86 f8 f f f f f f f f g g g a a a a a a bes bes bes bes bes bes c c c c c c cis cis cis cis cis cis ^hold=0.97 ^i=db a2. f2. " :relative :c4 :instruments alias-instr) (ls/transform :dynamics accent-pattern-dynamics) (ls/amplify 0.8)) (lily "^i=ub ^hold=0.97 bes1.*50 ^i=db c1." :relative :c5 :instruments alias-instr) ))) (def verse-2-viola (let [alias-instr (-> instruments (make-alias :db :vla-db-leg) (make-alias :ub :vla-ub-leg) (make-alias :ml :vla-marc-long) (make-alias :ms :vla-marc-short) ) ] (>>> (<*> (-> (lily " ^hold=0.97 ^i=db f2 ^i=ub e4 ^i=db d2 ^i=ub e4 ^i=db f2 ^i=ub e4 ^i=db d4. ^i=ub f4. ^i=db f2. ^i=ub g2. ^i=db a2. ^i=ms g16 a ^i=ml g4 ^i=ub g4. " :relative :c4 :instruments alias-instr) (ls/line-segment-dynamics 0 15 (* 8 3) 72)) (-> (>>> (control-surge 11 30 40 3) (rest-for 3) (control-surge 11 40 80 3) (rest-for 3) (control-surge 11 80 95 3) (rest-for 3) ) (ls/on-instrument (:db alias-instr)) ) (-> (>>> (rest-for 3) (control-surge 11 30 40 3) (rest-for 3) (control-surge 11 40 80 3) (rest-for 3) (control-surge 11 80 95 3) ) (ls/on-instrument (:ub alias-instr)) )) (-> (lily " ^i=ms ^hold=0.86 f8 f f f f f bes bes bes g g g a g f f g a bes bes bes bes c d c c c c d c cis cis cis cis cis a ^hold=0.97 ^i=db a2. d2. " :relative :c3 :instruments alias-instr) (ls/transform :dynamics accent-pattern-dynamics) (ls/amplify 0.8) ) ))) (def verse-2-cello (let [alias-instr (-> instruments (make-alias :db :cl-db-leg) (make-alias :ub :cl-ub-leg) (make-alias :ml :cl-marc-long) (make-alias :ms :cl-marc-short) )] (>>> (<*> (-> (lily "^hold=0.97 ^inst=ml f2 f'8 e d2 d8 e f8 c d f, g bes a bes a g f e bes4. f8 bes4 c8 d e c' d e f16 g f8 c f,16 g f8 c e16 d c4 c16 d e4" :relative :c2 :instruments alias-instr)) (-> (>>> (control-surge 11 30 40 3) (rest-for 3) (control-surge 11 40 80 3) (rest-for 3) (control-surge 11 80 95 3) (rest-for 3) ) (ls/on-instrument (:db alias-instr)) ) (-> (>>> (rest-for 3) (control-surge 11 30 40 3) (rest-for 3) (control-surge 11 40 80 3) (rest-for 3) (control-surge 11 80 95 3) ) (ls/on-instrument (:ub alias-instr)) )) (-> (lily "^hold=0.4 ^inst=ms f,8 g a a bes c d e f g e c d e f f d a bes c d d e f c, d e f g b a cis e cis b a ^hold=0.97 ^inst=ml d2. c2. " :relative :c3 :instruments alias-instr) (ls/transform :dynamics accent-pattern-dynamics) (ls/amplify 1.03) ) (-> (lily "^hold=0.97 ^inst=ub bes1.*97 ^inst=db f1." :instruments alias-instr :relative :c4)) ) ) ) (def verse-2-bass (>>> (rest-for (* 16 3/2)) (-> (lily "^hold=0.97 f4. f4. bes,4. c4. d4. d4 c8 bes4. bes4. c4. c4. cis4 b8 a4. d4. d4." :relative :c2) (ls/line-segment-dynamics 0 80 (* 13 3/2) 104 (* 16 3/2) 80) (ls/on-instrument (:bass-marc-long instruments)) ) )) These all start at the bes->c 4 . transition before the f starts again (def verse-3-violin-1 (let [alias-instr (-> instruments (make-alias :db :vln-1-db-leg) (make-alias :ub :vln-1-ub-leg) (make-alias :ml :vln-1-marc-long) (make-alias :ms :vln-1-marc-short) ) ] (>>> (-> (lily "^hold=0.8 ^inst=ms d16 e f e f a g a bes c f e " :relative :c4 :instruments alias-instr) (ls/line-segment-dynamics 0 20 3 70)) (-> (<*> (control-reset 11 (:db alias-instr)) (control-reset 11 (:ub alias-instr)) (lily "^hold=0.97 ^inst=db f2. ^inst=ub d2. ^inst=db c2. ^inst=ub d2. ^inst=db d2. ^inst=ub e2. ^inst=db f2. ^inst=ms e16 f e8 d ^inst=ml c4." :relative :c5 :instruments alias-instr))) (-> (lily " ^i=ms ^hold=0.86 c8 c c c c c d d d e e e f f f f f f f f f g g g g g g g g g a a a a a g ^hold=0.97 ^i=db f2. d2. " :relative :c5 :instruments alias-instr) (ls/transform :dynamics accent-pattern-dynamics) (ls/amplify 0.8) )) ) ) (def verse-3-violin-2 (let [alias-instr (-> instruments (make-alias :db :vln-2-db-leg) (make-alias :ub :vln-2-ub-leg) (make-alias :ml :vln-2-marc-long) (make-alias :ms :vln-2-marc-short) ) ] (>>> (-> (lily "^hold=0.8 ^inst=ms bes16 c d c d f e f g g c bes " :relative :c4 :instruments alias-instr) (ls/line-segment-dynamics 0 20 3 70)) (<*> (control-reset 11 (:ub alias-instr)) (control-reset 11 (:db alias-instr)) (-> (lily "^hold=0.97 ^inst=db a2. ^inst=ub a2. ^inst=db a2. ^inst=ub a2. ^inst=db bes2. ^inst=ub c2. ^inst=db c2. ^inst=ms c16 d c8 c8 ^inst=ml g4. " :relative :c5 :instruments alias-instr))) (-> (lily " ^i=ms ^hold=0.86 f8 f f f f f f f f g g g a a a a a a bes bes bes bes bes bes c c c c c c cis cis cis cis cis cis ^hold=0.97 ^i=db a2. f2. " :relative :c4 :instruments alias-instr) (ls/transform :dynamics accent-pattern-dynamics) (ls/amplify 0.8)) ) ) ) (def verse-3-viola (let [alias-instr (-> instruments (make-alias :db :vla-db-leg) (make-alias :ub :vla-ub-leg) (make-alias :ml :vla-marc-long) (make-alias :ms :vla-marc-short) ) ] (>>> (<*> (control-reset 11 (:ub alias-instr)) (control-reset 11 (:db alias-instr)) (-> (lily "^hold=0.8 ^inst=db d4 ^inst=ub f8 ^inst=db e4 ^inst=ub g8 ^inst=db c2. a2. c2. a2. f2. g2. a2. ^inst=ms c16 d e8 f ^inst=ml e4. " :relative :c3 :instruments alias-instr) (ls/line-segment-dynamics 0 30 3 70))) (-> (lily " ^i=ms ^hold=0.86 f8 f f f f f bes bes bes g g g a g f f g a bes bes bes bes c d c c c c d c cis cis cis cis cis a ^hold=0.97 ^i=db a2. d2. " :relative :c3 :instruments alias-instr) (ls/transform :dynamics accent-pattern-dynamics) (ls/amplify 0.8) ) ) ) ) (def verse-3-cello (let [alias-instr (-> instruments (make-alias :db :cl-db-leg) (make-alias :ub :cl-ub-leg) (make-alias :ml :cl-marc-long) (make-alias :ms :cl-marc-short) ) ] (>>> (<*> (control-reset 11 (:ub alias-instr)) (control-reset 11 (:db alias-instr)) (-> (lily "^hold=0.8 ^inst=db bes4 ^inst=ub bes8 ^inst=db c4 ^inst=ub e8 ^inst=db f2. d2. f2. d2. d2. e2. f2. ^inst=ml c8. g16 c'8 c,4. " :relative :c3 :instruments alias-instr) (ls/line-segment-dynamics 0 30 3 70))) (-> (lily "^hold=0.4 ^inst=ms f,8 g a a bes c d e f g e c d e f f d a bes c d d e f c, d e f g b a cis e cis b a ^hold=0.97 ^inst=ml d2. c2. " :relative :c3 :instruments alias-instr) (ls/transform :dynamics accent-pattern-dynamics) (ls/amplify 1.03) ) ) ) ) (def verse-3-bass (>>> (rest-for 3) (-> (lily "^hold=1.01 f2. d2. f2. d2. bes2. c2. f2. c2. f,2. bes4. c4. d2. bes2. c2. a2. d2. c2." :relative :c2) (ls/on-instrument (:bass-marc-long instruments)) (ls/line-segment-dynamics 0 65 24 74 45 108 52 70) ))) (def verse-3-flute (let [ai (-> instruments (make-alias :sv :flute-sus-vib) (make-alias :sa :flute-sus-acc) (make-alias :st :flute-short) )] (>>> (rest-for 3) (-> (lily "^hold=0.97 ^inst=sv c4. c8 ^inst=st c16 d f e ^inst=sv f4. d4. ^inst=sv c4. c8 ^inst=st c16 d f e ^inst=sv f4. a4. ^inst=st bes16*120 a g f e d c d e f g c d c bes a g f e f g a bes g ^inst=sv a2. bes4. c4. ^inst=sa f,2 ^inst=st a8 a bes16 g f d bes8 ^inst=sv c4. ^inst=st d16 e f g bes g ^inst=sa a4. bes4. ^inst=st c16 g f d c bes a32 bes d bes ^inst=sv c4 c'4. ^inst=sa cis2. ^inst=sv d2. c2. " :relative :c5 :instruments ai)) ))) #_(try-out verse-3-flute) (def verse-3-oboe (let [ai (-> instruments (make-alias :ot :oboe-stac) (make-alias :ov :oboe-sus-vib) )] (>>> (rest-for 3) (-> (lily "^hold=0.97 r2. r2. r2. r2. ^inst=ov f4.*104 ^hold=0.7 ^inst=ot e16 f g a bes e d c bes a g f e f g a bes g ^hold=0.97 ^inst=ov f2. d4. e4. ^inst=ov a'2 ^inst=ot c8 c d16 bes a f d8 ^inst=ov e4. ^inst=ot f16 g f e d c ^inst=ov c4. f4. ^inst=ot e16 c bes f e d e32 g e f ^inst=ov e4 e'4. ^inst=ov e2. ^inst=ov f2. e2. " :relative :c4 :instruments ai)) ))) (def verse-3-ehorn (let [ai (-> instruments (make-alias :et :ehorn-stac) (make-alias :ev :ehorn-sus-vib) )] (>>> (rest-for 3) (-> (lily "^hold=0.97 r2. r2. r2. r2. ^inst=ev d4.*104 ^hold=0.7 ^inst=et c8 e8 f16 g bes a f e d c bes d e f f8 ^hold=0.97 ^inst=ev c2. bes4. c4. ^inst=ev f2 ^inst=et f8 e ^inst=ev d4. c4. ^inst=et d8 f a ^inst=ev d4. bes4 f,8 g'4. c2. e2. d2. c2. " :relative :c4 :instruments ai)) ))) (def verse-3-bassoon (let [ai (-> instruments (make-alias :bt :bsn-stac) (make-alias :bv :bsn-sus-vib) )] (>>> (rest-for 3) (-> (lily "^hold=0.97 r2. r2. r2. r2. ^inst=bv bes4.*104 c4. ^hold=0.7 ^inst=bt bes8 f' bes, c g' c ^hold=0.97 ^inst=bv c2. bes4. g4. f2 a4 bes8 d bes c4. d2 f4 bes,4. c8 c, g' c2 c,4 a'2 cis4 d2. c2. " :relative :c3 :instruments ai)) )) ) (def fh-swells (<*> (-> (lily "^hold=0.96 a2. bes4. c4. d2. bes2. c2. cis2. d2. c2." :relative :c4) (ls/on-instrument (:fh-leg instruments)) ) (-> (lily "^hold=0.96 f2. d4. e4. f2. f2. g2. a2. a2. a2." :relative :c4) (ls/on-instrument (:fh-leg instruments)) ) (-> (>>> (<*> (control-surge 1 30 100 3) (control-surge 11 70 100 3) ) (control-surge 1 40 97 3/2) (control-surge 1 60 104 3/2) (control-surge 1 70 104 3) (control-surge 1 80 104 3) (control-surge 1 80 104 3) (control-surge 1 70 84 3) (control-surge 1 50 72 3) ) (ls/on-instrument (:fh-leg instruments)) ) )) (def tp-swells (-> (<*> (lily "^hold=0.96 c2. f4. g4. a2. f2. e2. e2. d2. c2." :relative :c4 ) (lily "^hold=0.96 f2. bes4. c4. d2. d2. g2. a2. f2. f2." :relative :c4 ) (>>> (<*> (control-surge 1 30 100 3) (control-surge 11 70 100 3) ) (control-surge 1 40 97 3/2) (control-surge 1 60 104 3/2) (control-surge 1 70 104 3) (control-surge 1 80 104 3) (control-surge 1 80 104 3) (control-surge 1 70 84 3) (control-surge 1 50 72 3) ) ) (ls/on-instrument (:tp-leg instruments)) )) (def tbn-swells (-> (<*> (lily "^hold=0.96 f2. bes4. c4. d2. bes2. c4. e,4. cis'4. a4. d2. c2." :relative :c3 ) (>>> (<*> (control-surge 1 30 100 3) (control-surge 11 70 100 3) ) (control-surge 1 40 97 3/2) (control-surge 1 60 104 3/2) (control-surge 1 70 104 3) (control-surge 1 80 104 3) (control-surge 1 80 104 3) (control-surge 1 70 84 3) (control-surge 1 50 72 3) ) ) (ls/on-instrument (:tbn-leg instruments)) )) (def solo-violin (let [ai (-> instruments (make-alias :exp :solov-leg-exp ) (make-alias :lyr :solov-leg-lyr ) (make-alias :marc :solov-marc ) (make-alias :stac :solov-stac ) ) ] (>>> (<*> (lily "^hold=0.97 ^i=exp f2.*120 bes2.*120 a2. c2." :relative :c5 :instruments ai) (-> (>>> (control-surge 11 90 102 3) (control-surge 11 94 112 3) (control-surge 11 94 112 3) (control-surge 11 94 112 3) ) (ls/on-instrument (:solov-leg-exp instruments)) ) ) (<*> (lily "^hold=0.97 ^i=lyr d4. ^hold=0.8 ^i=stac d8*60 d e f*84 e d ^hold=0.97 ^i=lyr d4.*97 ^i=stac ^hold=0.8 c16 f a8 a g16 a f c f e d c bes a g c bes a g f e f " :relative :c5 :instruments ai) (-> (>>> (control-surge 11 90 102 3/2) (rest-for 3) (control-surge 11 88 76 3/2) ) (ls/on-instrument (:solov-leg-lyr instruments)) ) (-> (>>> (rest-for 3/2) (control-surge 11 60 82 3/2) (control-surge 11 82 64 3/2) (control-surge 11 72 84 2) (control-surge 11 84 17 2) (control-surge 11 84 17 2) ) (ls/on-instrument (:solov-stac instruments)) ) ) (<*> (lily "^hold=0.97 ^i=exp f2*120 a4 bes2.*120 a2. c2. d2. f1." :relative :c4 :instruments ai) (-> (>>> (control-surge 11 90 102 3) (control-surge 11 94 112 3) (control-surge 11 94 112 3) (control-surge 11 94 112 3) ) (ls/on-instrument (:solov-leg-exp instruments)) ) ) ) )) (def solo-cello (let [ai (-> instruments (make-alias :exp :soloc-leg-exp ) (make-alias :lyr :soloc-leg-lyr ) (make-alias :marc :soloc-marc ) ) ] (>>> (<*> (lily "^hold=0.97 ^inst=marc f16*120 g a bes c8 e ^inst=lyr f4 ^inst=exp d4. bes4. c4. ^inst=marc c16*77 d c*80 bes*84 a d*78 ^inst=lyr c2. bes4. f4 g8 f2. a4 c8 f4. c2. ^i=exp bes2 c4 d2. c2. f2. f2. f4. a4. " :relative :c3 :instruments ai) (-> (>>>) (ls/on-instrument (:marc ai)) ) (-> (>>> (rest-for 3/2) (control-surge 11 70 80 2) (rest-for 6) (control-surge 11 72 102 15) ) (ls/on-instrument (:lyr ai)) ) (-> (>>> (rest-for 24) (control-surge 11 70 90 3) (control-surge 11 82 94 3) (control-surge 11 90 106 3) (control-surge 11 82 97 3) (control-surge 11 77 92 3) (control-surge 11 70 86 3) ) (ls/on-instrument (:exp ai)) ) )) ) ) (map ls/beat-length (list verse-2-violin-1 verse-2-violin-2 verse-2-viola verse-2-cello verse-2-bass )) (def final-song (-> (>>> (rest-for tdelay) (rest-for 6) (<*> verse-2-violin-1 verse-2-violin-2 verse-2-viola verse-2-cello verse-2-bass ) (rest-for (* 10 3/2)) (<*> (<*> verse-3-violin-1 verse-3-violin-2 verse-3-viola verse-3-cello verse-3-bass) (<*> verse-3-flute verse-3-oboe verse-3-ehorn verse-3-bassoon ) 8 measures plus that extra we get for the intro (<*> fh-swells tp-swells tbn-swells)) ) (<*> solo-violin solo-cello ) (rest-for 180) ) (ls/with-clock clock) ) ) (def play-meddley true) (def ag (when play-meddley (midi-play final-song : samples [ { : file " /Users / paul / Desktop / MM / Bouncedown.wav " : zero - point ( * ( tempo / beats - to - time clock -3 ) 1000000 ) } ] :beat-clock clock )) )
75491675f2d041d03bedca2a87974e5fc53e0bb29f79b0eae29bfcbbbe37e424
zenspider/schemers
exercise.4.25.scm
#!/usr/bin/env csi -s (require rackunit) Exercise 4.25 ;; Suppose that (in ordinary applicative-order ;; Scheme) we define `unless' as shown above and then define ;; `factorial' in terms of `unless' as ;; ;; (define (factorial n) ;; (unless (= n 1) ;; (* n (factorial (- n 1))) 1 ) ) ;; What happens if we attempt to evaluate ` ( factorial 5 ) ' ? Will our ;; definitions work in a normal-order language? ;; (define (unless. t a b) ;; (if (not t) a b)) ;; ;; (define (factorial n) ;; (unless. (= n 1) ;; (* n (factorial (- n 1))) ;; 1)) ;; ( factorial 5 ) ... infinite loop ... but we knew that from chapter 1 . what 's the point ?
null
https://raw.githubusercontent.com/zenspider/schemers/2939ca553ac79013a4c3aaaec812c1bad3933b16/sicp/ch_4/exercise.4.25.scm
scheme
Suppose that (in ordinary applicative-order Scheme) we define `unless' as shown above and then define `factorial' in terms of `unless' as (define (factorial n) (unless (= n 1) (* n (factorial (- n 1))) definitions work in a normal-order language? (define (unless. t a b) (if (not t) a b)) (define (factorial n) (unless. (= n 1) (* n (factorial (- n 1))) 1))
#!/usr/bin/env csi -s (require rackunit) Exercise 4.25 1 ) ) What happens if we attempt to evaluate ` ( factorial 5 ) ' ? Will our ( factorial 5 ) ... infinite loop ... but we knew that from chapter 1 . what 's the point ?
c093b3b92fcf1f76a42c6b74423d8d8db4b4668128f361a06904a387f3bb2c3e
alesaccoia/festival_flinger
ogi_span_mx_syl.scm
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;<--CSLU-->;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; Center for Spoken Language Understanding ; ; Oregon Graduate Institute of Science & Technology ; ; Portland , OR USA ; ; Copyright ( c ) 1999 ; ; ;; ;; This module is not part of the CSTR / University of Edinburgh ; ; ;; release of the Festival TTS system. ;; ;; ;; ;; In addition to any conditions disclaimers below, please see the file ;; " license_cslu_tts.txt " distributed with this software for information ; ; ;; on usage and redistribution, and for a DISCLAIMER OF ALL WARRANTIES. ;; ;; ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;<--CSLU-->;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Syllabification and accent prediction module for Mexican Spanish ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (set! A_Z '(a a1 e e1 i i1 o o1 u u1 b tS dZ d f g h j k l L m n N ny p q r rr s t w x ) ) (set! CONS '( b tS dZ d f g h j k l L m n N ny p q r rr s t w x ) ) (set! SET1 '( i u o b tS dZ d f g h j k l L m n N ny p q r rr s t w x ) ) (set! SET2 '( i u o b tS dZ d f g h j k l L m n N ny p q r rr s t w x ) ) (set! SET3 '( i u a b tS dZ d f g h j k l L m n N ny p q r rr s t w x ) ) (set! A_Z3 '(b tS dZ d f g h j k l L m n N ny p q r rr s t x ) ) (set! VOWELS '(a e i o u a1 e1 i1 o1 u1 w) ) (set! VOWELS1 '(a e i o u w) ) (set! STVOWELS '(a1 e1 i1 o1 u1) ) (define(next_syl l lset) (set! tail l ) (cond (( equal? l nil) nil) ((not (member (car l) lset )) nil) ((member (car l) '(w)) (append (cons (car l) nil) (next_syl (cdr l) A_Z3))) ((member (car l) '(i u)) (append (cons (car l) nil) (next_syl (cdr l) A_Z))) ((member (car l) '(a a1)) (append (cons (car l) nil) (next_syl (cdr l) SET1))) ((member (car l) '(e e1)) (append (cons (car l) nil) (next_syl (cdr l) SET2))) ((member (car l) '(o o1)) (append (cons (car l) nil) (next_syl (cdr l) SET3))) ((member (car l) '(i1 u1)) (append (cons (car l) nil) (next_syl (cdr l) CONS))) ((member (car l) STVOWELS) (append (cons (car l) nil) (next_syl (cdr l) A_Z))) ((member (car l) VOWELS1) (append (cons (car l) nil) (next_syl (cdr l) A_Z1))) ((member (car l) '(c) ) (append (cons (car l) nil) (next_syl (cdr l) '()))) ((member (car l) '(l) ) (append (cons (car l) nil) (next_syl (cdr l) '(b d f g k l p t)))) ((member (car l) '(m) ) (append (cons (car l) nil) (next_syl (cdr l) '(m)))) ((member (car l) '(n) ) (append (cons (car l) nil) (next_syl (cdr l) '(n)))) ((member (car l) '(r) ) (append (cons (car l) nil) (next_syl (cdr l) '(b d f g k p r t)))) ((and (member (car l) '(s) ) (equal? syl_last 's)) (append (cons (car l) nil) (next_syl (cdr l) '(b d k n s)))) ((member (car l) '(s) ) (append (cons (car l) nil) (next_syl (cdr l) '(s)))) ((member (car l) '(t) ) (append (cons (car l) nil) (next_syl (cdr l) '(t)))) ((member (car l) '(z) ) (append (cons (car l) nil) (next_syl (cdr l) '(z)))) ((member (car l) '(b tS d f g j k J p q x ) ) (append (cons (car l) nil) (next_syl (cdr l) '(b tS d f g j k J p q x )))) (t (append (cons (car l) nil) (next_syl (cdr l) (cons (car l) nil) ))) ) ) (define(syl l ) (set! syl_last (car l)) (if (equal? l nil) nil (append (cons (next_syl l (cons (car l ))) nil) (syl tail) ) )) (define (solve_CV l ) (cond (( equal? l nil) nil) ((not (member (caar l) VOWELS )) ( cons ( reverse(append ( car l ) ( cadr l ) ) ) ( solve_CV ( cddr l ) ) ) ) (cons (append (car l) (cadr l)) (solve_CV (cddr l)) )) (t ;; (cons (reverse (car l)) (solve_CV (cdr l)) )) (cons (car l) (solve_CV (cdr l)) )) ) ) (define (is_accented_syl s) (cond ((equal? s nil) nil) ((member (car s) '(a1 e1 i1 o1 u1)) t) (t (is_accented_syl (cdr s))) ) ) (define (is_accented l) (cond ((equal? l nil) nil) ((is_accented_syl (car l)) t) (t (is_accented (cdr l))) ) ) (define (normal s) (cond ((equal? s nil) nil) ((equal? 'a1 (car s)) (append '(a) (normal (cdr s)))) ((equal? (car s) 'e1) (cons 'e (normal (cdr s)))) ((equal? (car s) 'i1) (cons 'i (normal (cdr s)))) ((equal? (car s) 'o1) (cons 'o (normal (cdr s)))) ((equal? (car s) 'u1) (cons 'u (normal (cdr s)))) (t (cons (car s) (normal (cdr s))) ) ) ) (define (build_accented l) (cond ((equal? l nil) nil) ((is_accented_syl (car l)) (cons (list (reverse (normal (car l))) 1) (build_accented (cdr l)) ) ) (t (cons (list (reverse (car l)) 0) (build_accented (cdr l)) ) ) ) ) (define (set_stress l pos cp) (cond ((equal? l nil) nil) ((equal? pos cp) (cons (list (reverse (car l)) 1) (set_stress (cdr l) pos (+ cp 1)) ) ) (t (cons (list (reverse (car l)) 0) (set_stress (cdr l) pos (+ cp 1)) ) ) ) ) (define (solve_stress l ) (cond ((is_accented l) (build_accented l)) (set_stress l 1 1)) (set_stress l 2 1)) (t ) ) (define (mex.syllabify.phstress word) (set! drow (reverse word)) (set! bob (reverse(solve_stress (solve_CV (syl drow ))))) ;; (print bob) bob ) (provide 'span_mx_syl)
null
https://raw.githubusercontent.com/alesaccoia/festival_flinger/87345aad3a3230751a8ff479f74ba1676217accd/lib/ogi/ogi_spanish/ogi_span_mx_syl.scm
scheme
<--CSLU-->;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ; ; ; ; ;; ; release of the Festival TTS system. ;; ;; In addition to any conditions disclaimers below, please see the file ;; ; on usage and redistribution, and for a DISCLAIMER OF ALL WARRANTIES. ;; ;; <--CSLU-->;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (cons (reverse (car l)) (solve_CV (cdr l)) )) (print bob)
Syllabification and accent prediction module for Mexican Spanish (set! A_Z '(a a1 e e1 i i1 o o1 u u1 b tS dZ d f g h j k l L m n N ny p q r rr s t w x ) ) (set! CONS '( b tS dZ d f g h j k l L m n N ny p q r rr s t w x ) ) (set! SET1 '( i u o b tS dZ d f g h j k l L m n N ny p q r rr s t w x ) ) (set! SET2 '( i u o b tS dZ d f g h j k l L m n N ny p q r rr s t w x ) ) (set! SET3 '( i u a b tS dZ d f g h j k l L m n N ny p q r rr s t w x ) ) (set! A_Z3 '(b tS dZ d f g h j k l L m n N ny p q r rr s t x ) ) (set! VOWELS '(a e i o u a1 e1 i1 o1 u1 w) ) (set! VOWELS1 '(a e i o u w) ) (set! STVOWELS '(a1 e1 i1 o1 u1) ) (define(next_syl l lset) (set! tail l ) (cond (( equal? l nil) nil) ((not (member (car l) lset )) nil) ((member (car l) '(w)) (append (cons (car l) nil) (next_syl (cdr l) A_Z3))) ((member (car l) '(i u)) (append (cons (car l) nil) (next_syl (cdr l) A_Z))) ((member (car l) '(a a1)) (append (cons (car l) nil) (next_syl (cdr l) SET1))) ((member (car l) '(e e1)) (append (cons (car l) nil) (next_syl (cdr l) SET2))) ((member (car l) '(o o1)) (append (cons (car l) nil) (next_syl (cdr l) SET3))) ((member (car l) '(i1 u1)) (append (cons (car l) nil) (next_syl (cdr l) CONS))) ((member (car l) STVOWELS) (append (cons (car l) nil) (next_syl (cdr l) A_Z))) ((member (car l) VOWELS1) (append (cons (car l) nil) (next_syl (cdr l) A_Z1))) ((member (car l) '(c) ) (append (cons (car l) nil) (next_syl (cdr l) '()))) ((member (car l) '(l) ) (append (cons (car l) nil) (next_syl (cdr l) '(b d f g k l p t)))) ((member (car l) '(m) ) (append (cons (car l) nil) (next_syl (cdr l) '(m)))) ((member (car l) '(n) ) (append (cons (car l) nil) (next_syl (cdr l) '(n)))) ((member (car l) '(r) ) (append (cons (car l) nil) (next_syl (cdr l) '(b d f g k p r t)))) ((and (member (car l) '(s) ) (equal? syl_last 's)) (append (cons (car l) nil) (next_syl (cdr l) '(b d k n s)))) ((member (car l) '(s) ) (append (cons (car l) nil) (next_syl (cdr l) '(s)))) ((member (car l) '(t) ) (append (cons (car l) nil) (next_syl (cdr l) '(t)))) ((member (car l) '(z) ) (append (cons (car l) nil) (next_syl (cdr l) '(z)))) ((member (car l) '(b tS d f g j k J p q x ) ) (append (cons (car l) nil) (next_syl (cdr l) '(b tS d f g j k J p q x )))) (t (append (cons (car l) nil) (next_syl (cdr l) (cons (car l) nil) ))) ) ) (define(syl l ) (set! syl_last (car l)) (if (equal? l nil) nil (append (cons (next_syl l (cons (car l ))) nil) (syl tail) ) )) (define (solve_CV l ) (cond (( equal? l nil) nil) ((not (member (caar l) VOWELS )) ( cons ( reverse(append ( car l ) ( cadr l ) ) ) ( solve_CV ( cddr l ) ) ) ) (cons (append (car l) (cadr l)) (solve_CV (cddr l)) )) (t (cons (car l) (solve_CV (cdr l)) )) ) ) (define (is_accented_syl s) (cond ((equal? s nil) nil) ((member (car s) '(a1 e1 i1 o1 u1)) t) (t (is_accented_syl (cdr s))) ) ) (define (is_accented l) (cond ((equal? l nil) nil) ((is_accented_syl (car l)) t) (t (is_accented (cdr l))) ) ) (define (normal s) (cond ((equal? s nil) nil) ((equal? 'a1 (car s)) (append '(a) (normal (cdr s)))) ((equal? (car s) 'e1) (cons 'e (normal (cdr s)))) ((equal? (car s) 'i1) (cons 'i (normal (cdr s)))) ((equal? (car s) 'o1) (cons 'o (normal (cdr s)))) ((equal? (car s) 'u1) (cons 'u (normal (cdr s)))) (t (cons (car s) (normal (cdr s))) ) ) ) (define (build_accented l) (cond ((equal? l nil) nil) ((is_accented_syl (car l)) (cons (list (reverse (normal (car l))) 1) (build_accented (cdr l)) ) ) (t (cons (list (reverse (car l)) 0) (build_accented (cdr l)) ) ) ) ) (define (set_stress l pos cp) (cond ((equal? l nil) nil) ((equal? pos cp) (cons (list (reverse (car l)) 1) (set_stress (cdr l) pos (+ cp 1)) ) ) (t (cons (list (reverse (car l)) 0) (set_stress (cdr l) pos (+ cp 1)) ) ) ) ) (define (solve_stress l ) (cond ((is_accented l) (build_accented l)) (set_stress l 1 1)) (set_stress l 2 1)) (t ) ) (define (mex.syllabify.phstress word) (set! drow (reverse word)) (set! bob (reverse(solve_stress (solve_CV (syl drow ))))) bob ) (provide 'span_mx_syl)
38e424e821270099fd715270ab1de29bcbb5cdafa4419cd75f25ecec8aa066a3
votinginfoproject/data-processor
ordered_contest_test.clj
(ns vip.data-processor.validation.v5.ordered-contest-test (:require [vip.data-processor.validation.v5.ordered-contest :as v5.ordered-contest] [clojure.test :refer :all] [vip.data-processor.test-helpers :refer :all] [vip.data-processor.db.postgres :as psql] [vip.data-processor.validation.xml :as xml] [clojure.core.async :as a])) (use-fixtures :once setup-postgres) (deftest ^:postgres validate-no-missing-contest-ids-test (let [errors-chan (a/chan 100) ctx {:xml-source-file-path (xml-input "v5-ordered-contests.xml") :errors-chan errors-chan} out-ctx (-> ctx psql/start-run xml/load-xml-ltree v5.ordered-contest/validate-no-missing-contest-ids) errors (all-errors errors-chan)] (testing "contest-id missing is an error" (is (contains-error? errors {:severity :errors :scope :ordered-contest :identifier "VipObject.0.OrderedContest.0.ContestId" :error-type :missing}))) (testing "contest-id present is OK" (assert-no-problems errors {:severity :errors :scope :ordered-contest :identifier "VipObject.0.OrderedContest.1.ContestId" :error-type :missing}))))
null
https://raw.githubusercontent.com/votinginfoproject/data-processor/b4baf334b3a6219d12125af8e8c1e3de93ba1dc9/test/vip/data_processor/validation/v5/ordered_contest_test.clj
clojure
(ns vip.data-processor.validation.v5.ordered-contest-test (:require [vip.data-processor.validation.v5.ordered-contest :as v5.ordered-contest] [clojure.test :refer :all] [vip.data-processor.test-helpers :refer :all] [vip.data-processor.db.postgres :as psql] [vip.data-processor.validation.xml :as xml] [clojure.core.async :as a])) (use-fixtures :once setup-postgres) (deftest ^:postgres validate-no-missing-contest-ids-test (let [errors-chan (a/chan 100) ctx {:xml-source-file-path (xml-input "v5-ordered-contests.xml") :errors-chan errors-chan} out-ctx (-> ctx psql/start-run xml/load-xml-ltree v5.ordered-contest/validate-no-missing-contest-ids) errors (all-errors errors-chan)] (testing "contest-id missing is an error" (is (contains-error? errors {:severity :errors :scope :ordered-contest :identifier "VipObject.0.OrderedContest.0.ContestId" :error-type :missing}))) (testing "contest-id present is OK" (assert-no-problems errors {:severity :errors :scope :ordered-contest :identifier "VipObject.0.OrderedContest.1.ContestId" :error-type :missing}))))
4f060e810ffc6c7a290c4c83210cc7b8b6a32679f6ee371eb45d712bcbf40e9f
erlang/otp
diameter_config_SUITE.erl
%% %% %CopyrightBegin% %% Copyright Ericsson AB 2013 - 2022 . 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% %% %% %% Test service and transport config. In particular, of the detection %% of config errors. %% -module(diameter_config_SUITE). %% testscases, no common_test dependency -export([run/0, run/1]). %% common_test wrapping -export([suite/0, all/0, start_service/1, add_transport/1]). -define(util, diameter_util). %% Lists of {Key, GoodConfigList, BadConfigList} with which to %% configure. -define(SERVICE_CONFIG, [{application, [[[{dictionary, diameter_gen_base_rfc6733}, {module, ?MODULE}]] | [[[{dictionary, D}, {module, M}, {alias, A}, {state, S}, {answer_errors, AE}, {request_errors, RE}, {call_mutates_state, C}]] || D <- [diameter_gen_base_rfc3588, diameter_gen_base_rfc6733], M <- [?MODULE, [?MODULE, diameter_lib:now()]], A <- [0, common, make_ref()], S <- [[], make_ref()], AE <- [report, callback, discard], RE <- [answer_3xxx, answer, callback], C <- [true, false]]], [[x], [[]], [[{dictionary, diameter_gen_base_rfc3588}]], [[{module, ?MODULE}]] | [[[{dictionary, diameter_gen_base_rfc6733}, {module, ?MODULE}, {K,x}]] || K <- [answer_errors, request_errors, call_mutates_state]]]}, {restrict_connections, [[false], [node], [nodes], [[node(), node()]]], []}, {sequence, [[{0,32}], [{1,31}]], [[{2,31}]]}, {share_peers, [[true], [false], [[node()]]], [[x]]}, {use_shared_peers, [[true], [false], [[node(), node()]]], [[x]]}, {string_decode, [[true], [false]], [[0], [x]]}, {incoming_maxlen, [[0], [65536], [16#FFFFFF]], [[-1], [1 bsl 24], [infinity], [false]]}, {spawn_opt, [[[]], [[monitor, link]]], [[false]]}, {invalid_option, %% invalid service options are rejected [], [[x], [x,x]]}]). -define(TRANSPORT_CONFIG, [{transport_module, [[?MODULE]], [[[?MODULE]]]}, {transport_config, [[{}, 3000], [{}, infinity]], [[{}, x]]}, {applications, [[[1, a, [x]]]], [[x]]}, {capabilities, [[[{'Origin-Host', "diameter.erlang.org"}]], [[{'Origin-Realm', "erlang.org"}]]] ++ [[[{'Host-IP-Address', L}]] || L <- [[{127,0,0,1}], ["127.0.0.1"], ["127.0.0.1", "FFFF::1", "::1", {1,2,3,4,5,6,7,8}]]] ++ [[[{'Product-Name', N}]] || N <- [["Product", $-, ["Name"]], "Norðurálfa", "ᚠᚢᚦᚨᚱᚲ"]] ++ [[[{K,V}]] || K <- ['Vendor-Id', 'Origin-State-Id', 'Firmware-Revision'], V <- [0, 256, 16#FFFF]] ++ [[[{K,V}]] || K <- ['Supported-Vendor-Id', 'Auth-Application-Id', 'Acct-Application-Id', 'Inband-Security-Id'], V <- [[17], [0, 256, 16#FFFF]]] ++ [[[{'Vendor-Specific-Application-Id', [[{'Vendor-Id', V}, {'Auth-Application-Id', [0]}, {'Acct-Application-Id', [4]}]]}]] || V <- [1, [1]]], [[x], [[{'Origin-Host', "ᚠᚢᚦᚨᚱᚲ"}]]] ++ [[[{'Host-IP-Address', A}]] || A <- [{127,0,0,1}]] ++ [[[{'Product-Name', N}]] || N <- [x, 1]] ++ [[[{K,V}]] || K <- ['Vendor-Id', 'Origin-State-Id', 'Firmware-Revision'], V <- [x, [0], -1, 1 bsl 32]] ++ [[[{K,V}]] || K <- ['Supported-Vendor-Id', 'Auth-Application-Id', 'Acct-Application-Id', 'Inband-Security-Id'], V <- [x, 17, [-1], [1 bsl 32]]] ++ [[[{'Vendor-Specific-Application-Id', V}]] || V <- [x, [[{'Vendor-Id', 1 bsl 32}]], [[{'Auth-Application-Id', 1}]]]]}, {capabilities_cb, [[x]], []}, {capx_timeout, [[3000]], [[{?MODULE, tmo, []}]]}, {disconnect_cb, [[x]], []}, {length_errors, [[exit], [handle], [discard]], [[x]]}, {dpr_timeout, [[0], [3000], [16#FFFFFFFF]], [[infinity], [-1], [1 bsl 32], [x]]}, {dpa_timeout, [[0], [3000], [16#FFFFFFFF]], [[infinity], [-1], [1 bsl 32], [x]]}, {connect_timer, [[3000]], [[infinity]]}, {watchdog_timer, [[3000], [{?MODULE, tmo, []}]], [[infinity], [-1]]}, {watchdog_config, [[[{okay, 0}, {suspect, 0}]], [[{okay, 1}]], [[{suspect, 2}]]], [[x], [[{open, 0}]]]}, {pool_size, [[1], [100]], [[0], [infinity], [-1], [x]]}, {private, [[x]], []}, {spawn_opt, [[[]], [[monitor, link]]], [[false]]}, {invalid_option, %% invalid transport options are silently ignored [[x], [x,x]], []}]). %% =========================================================================== suite() -> [{timetrap, {seconds, 15}}]. all() -> [start_service, add_transport]. start_service(_Config) -> run([start_service]). add_transport(_Config) -> run([add_transport]). %% =========================================================================== run() -> run(all()). run(List) when is_list(List) -> try ?util:run([[[fun run/1, {F, 5000}] || F <- List]]) after dbg:stop_clear(), diameter:stop() end; run({F, Tmo}) -> ok = diameter:start(), try ?util:run([{[fun run/1, F], Tmo}]) after ok = diameter:stop() end; run(start_service) -> ?util:run([[fun start/1, T] || T <- [lists:keyfind(capabilities, 1, ?TRANSPORT_CONFIG) | ?SERVICE_CONFIG]]); run(add_transport) -> ?util:run([[fun add/1, T] || T <- ?TRANSPORT_CONFIG]). start(T) -> do(fun start/3, T). add(T) -> do(fun add/3, T). %% =========================================================================== do/2 do(F, {Key, Good, Bad}) -> F(Key, Good, Bad). %% add/3 add(Key, Good, Bad) -> {[],[]} = {[{Vs,T} || Vs <- Good, T <- [add(Key, Vs)], [T] /= [T || {ok,_} <- [T]]], [{Vs,T} || Vs <- Bad, T <- [add(Key, Vs)], [T] /= [T || {error,_} <- [T]]]}. add(Key, Vs) -> T = list_to_tuple([Key | Vs]), diameter:add_transport(make_ref(), {connect, [T]}). %% start/3 start(Key, Good, Bad) -> {[],[]} = {[{Vs,T} || Vs <- Good, T <- [start(Key, Vs)], T /= ok], [{Vs,T} || Vs <- Bad, T <- [start(Key, Vs)], [T] /= [T || {error,_} <- [T]]]}. start(capabilities = K, [Vs]) -> if is_list(Vs) -> start(make_ref(), Vs ++ apps(K)); true -> {error, Vs} end; start(Key, Vs) when is_atom(Key) -> start(make_ref(), [list_to_tuple([Key | Vs]) | apps(Key)]); start(SvcName, Opts) -> try diameter:start_service(SvcName, Opts) after diameter:stop_service(SvcName) end. apps(application) -> []; apps(_) -> [{application, [{dictionary, diameter_gen_base_rfc6733}, {module, ?MODULE}]}].
null
https://raw.githubusercontent.com/erlang/otp/66dd3c397b5dd68cb087a1a830f25c62c5d1d2ad/lib/diameter/test/diameter_config_SUITE.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% Test service and transport config. In particular, of the detection of config errors. testscases, no common_test dependency common_test wrapping Lists of {Key, GoodConfigList, BadConfigList} with which to configure. invalid service options are rejected invalid transport options are silently ignored =========================================================================== =========================================================================== =========================================================================== add/3 start/3
Copyright Ericsson AB 2013 - 2022 . 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(diameter_config_SUITE). -export([run/0, run/1]). -export([suite/0, all/0, start_service/1, add_transport/1]). -define(util, diameter_util). -define(SERVICE_CONFIG, [{application, [[[{dictionary, diameter_gen_base_rfc6733}, {module, ?MODULE}]] | [[[{dictionary, D}, {module, M}, {alias, A}, {state, S}, {answer_errors, AE}, {request_errors, RE}, {call_mutates_state, C}]] || D <- [diameter_gen_base_rfc3588, diameter_gen_base_rfc6733], M <- [?MODULE, [?MODULE, diameter_lib:now()]], A <- [0, common, make_ref()], S <- [[], make_ref()], AE <- [report, callback, discard], RE <- [answer_3xxx, answer, callback], C <- [true, false]]], [[x], [[]], [[{dictionary, diameter_gen_base_rfc3588}]], [[{module, ?MODULE}]] | [[[{dictionary, diameter_gen_base_rfc6733}, {module, ?MODULE}, {K,x}]] || K <- [answer_errors, request_errors, call_mutates_state]]]}, {restrict_connections, [[false], [node], [nodes], [[node(), node()]]], []}, {sequence, [[{0,32}], [{1,31}]], [[{2,31}]]}, {share_peers, [[true], [false], [[node()]]], [[x]]}, {use_shared_peers, [[true], [false], [[node(), node()]]], [[x]]}, {string_decode, [[true], [false]], [[0], [x]]}, {incoming_maxlen, [[0], [65536], [16#FFFFFF]], [[-1], [1 bsl 24], [infinity], [false]]}, {spawn_opt, [[[]], [[monitor, link]]], [[false]]}, [], [[x], [x,x]]}]). -define(TRANSPORT_CONFIG, [{transport_module, [[?MODULE]], [[[?MODULE]]]}, {transport_config, [[{}, 3000], [{}, infinity]], [[{}, x]]}, {applications, [[[1, a, [x]]]], [[x]]}, {capabilities, [[[{'Origin-Host', "diameter.erlang.org"}]], [[{'Origin-Realm', "erlang.org"}]]] ++ [[[{'Host-IP-Address', L}]] || L <- [[{127,0,0,1}], ["127.0.0.1"], ["127.0.0.1", "FFFF::1", "::1", {1,2,3,4,5,6,7,8}]]] ++ [[[{'Product-Name', N}]] || N <- [["Product", $-, ["Name"]], "Norðurálfa", "ᚠᚢᚦᚨᚱᚲ"]] ++ [[[{K,V}]] || K <- ['Vendor-Id', 'Origin-State-Id', 'Firmware-Revision'], V <- [0, 256, 16#FFFF]] ++ [[[{K,V}]] || K <- ['Supported-Vendor-Id', 'Auth-Application-Id', 'Acct-Application-Id', 'Inband-Security-Id'], V <- [[17], [0, 256, 16#FFFF]]] ++ [[[{'Vendor-Specific-Application-Id', [[{'Vendor-Id', V}, {'Auth-Application-Id', [0]}, {'Acct-Application-Id', [4]}]]}]] || V <- [1, [1]]], [[x], [[{'Origin-Host', "ᚠᚢᚦᚨᚱᚲ"}]]] ++ [[[{'Host-IP-Address', A}]] || A <- [{127,0,0,1}]] ++ [[[{'Product-Name', N}]] || N <- [x, 1]] ++ [[[{K,V}]] || K <- ['Vendor-Id', 'Origin-State-Id', 'Firmware-Revision'], V <- [x, [0], -1, 1 bsl 32]] ++ [[[{K,V}]] || K <- ['Supported-Vendor-Id', 'Auth-Application-Id', 'Acct-Application-Id', 'Inband-Security-Id'], V <- [x, 17, [-1], [1 bsl 32]]] ++ [[[{'Vendor-Specific-Application-Id', V}]] || V <- [x, [[{'Vendor-Id', 1 bsl 32}]], [[{'Auth-Application-Id', 1}]]]]}, {capabilities_cb, [[x]], []}, {capx_timeout, [[3000]], [[{?MODULE, tmo, []}]]}, {disconnect_cb, [[x]], []}, {length_errors, [[exit], [handle], [discard]], [[x]]}, {dpr_timeout, [[0], [3000], [16#FFFFFFFF]], [[infinity], [-1], [1 bsl 32], [x]]}, {dpa_timeout, [[0], [3000], [16#FFFFFFFF]], [[infinity], [-1], [1 bsl 32], [x]]}, {connect_timer, [[3000]], [[infinity]]}, {watchdog_timer, [[3000], [{?MODULE, tmo, []}]], [[infinity], [-1]]}, {watchdog_config, [[[{okay, 0}, {suspect, 0}]], [[{okay, 1}]], [[{suspect, 2}]]], [[x], [[{open, 0}]]]}, {pool_size, [[1], [100]], [[0], [infinity], [-1], [x]]}, {private, [[x]], []}, {spawn_opt, [[[]], [[monitor, link]]], [[false]]}, [[x], [x,x]], []}]). suite() -> [{timetrap, {seconds, 15}}]. all() -> [start_service, add_transport]. start_service(_Config) -> run([start_service]). add_transport(_Config) -> run([add_transport]). run() -> run(all()). run(List) when is_list(List) -> try ?util:run([[[fun run/1, {F, 5000}] || F <- List]]) after dbg:stop_clear(), diameter:stop() end; run({F, Tmo}) -> ok = diameter:start(), try ?util:run([{[fun run/1, F], Tmo}]) after ok = diameter:stop() end; run(start_service) -> ?util:run([[fun start/1, T] || T <- [lists:keyfind(capabilities, 1, ?TRANSPORT_CONFIG) | ?SERVICE_CONFIG]]); run(add_transport) -> ?util:run([[fun add/1, T] || T <- ?TRANSPORT_CONFIG]). start(T) -> do(fun start/3, T). add(T) -> do(fun add/3, T). do/2 do(F, {Key, Good, Bad}) -> F(Key, Good, Bad). add(Key, Good, Bad) -> {[],[]} = {[{Vs,T} || Vs <- Good, T <- [add(Key, Vs)], [T] /= [T || {ok,_} <- [T]]], [{Vs,T} || Vs <- Bad, T <- [add(Key, Vs)], [T] /= [T || {error,_} <- [T]]]}. add(Key, Vs) -> T = list_to_tuple([Key | Vs]), diameter:add_transport(make_ref(), {connect, [T]}). start(Key, Good, Bad) -> {[],[]} = {[{Vs,T} || Vs <- Good, T <- [start(Key, Vs)], T /= ok], [{Vs,T} || Vs <- Bad, T <- [start(Key, Vs)], [T] /= [T || {error,_} <- [T]]]}. start(capabilities = K, [Vs]) -> if is_list(Vs) -> start(make_ref(), Vs ++ apps(K)); true -> {error, Vs} end; start(Key, Vs) when is_atom(Key) -> start(make_ref(), [list_to_tuple([Key | Vs]) | apps(Key)]); start(SvcName, Opts) -> try diameter:start_service(SvcName, Opts) after diameter:stop_service(SvcName) end. apps(application) -> []; apps(_) -> [{application, [{dictionary, diameter_gen_base_rfc6733}, {module, ?MODULE}]}].
ce11c1ca7dac87d6ed8258c2a2cf931f266af86508b7670e59c4c8d8e9a3c7db
mtt-lang/mtt-lang
Util.ml
open Base open Result.Let_syntax open ParserInterface (* Parsing with error handling utilities *) let parse_from_e : type a. a ast_kind -> input_kind -> (a, error) Result.t = fun ast_kind source -> parse_from ast_kind source |> Result.map_error ~f:(fun parse_error -> [%string "Parse error: $parse_error"]) (* Parsing and typechecking with error handling utilities *) let parse_and_typecheck source typ_str = let%bind ast = parse_from_e Term source in let%bind typ = parse_from_e Type (String typ_str) in Typechecker.check ast typ |> Result.map_error ~f:(fun infer_err -> [%string "Typechecking error: $(MttError.located_to_string infer_err)"]) (* Parsing and type inference with error handling utilities *) let parse_and_typeinfer source = let%bind ast = parse_from_e Term source in Typechecker.infer ast |> Result.map_error ~f:(fun infer_err -> [%string "Type inference error: $(MttError.located_to_string infer_err)"]) (* Parsing and evaluation with error handling utilities *) let parse_and_eval source = let%bind ast = parse_from_e Term source in Evaluator.eval ast |> Result.map_error ~f:(fun eval_err -> [%string "Evaluation error: $(MttError.to_string eval_err)"])
null
https://raw.githubusercontent.com/mtt-lang/mtt-lang/2d330efccd154e1c158dc673ca3ec4f64b9dd09e/core/Util.ml
ocaml
Parsing with error handling utilities Parsing and typechecking with error handling utilities Parsing and type inference with error handling utilities Parsing and evaluation with error handling utilities
open Base open Result.Let_syntax open ParserInterface let parse_from_e : type a. a ast_kind -> input_kind -> (a, error) Result.t = fun ast_kind source -> parse_from ast_kind source |> Result.map_error ~f:(fun parse_error -> [%string "Parse error: $parse_error"]) let parse_and_typecheck source typ_str = let%bind ast = parse_from_e Term source in let%bind typ = parse_from_e Type (String typ_str) in Typechecker.check ast typ |> Result.map_error ~f:(fun infer_err -> [%string "Typechecking error: $(MttError.located_to_string infer_err)"]) let parse_and_typeinfer source = let%bind ast = parse_from_e Term source in Typechecker.infer ast |> Result.map_error ~f:(fun infer_err -> [%string "Type inference error: $(MttError.located_to_string infer_err)"]) let parse_and_eval source = let%bind ast = parse_from_e Term source in Evaluator.eval ast |> Result.map_error ~f:(fun eval_err -> [%string "Evaluation error: $(MttError.to_string eval_err)"])
144403ea16d986f8cbdede287d6cb566751aa8f4267cc6bf8b294686375b7a89
penpot/penpot
hsva.cljs
This Source Code Form is subject to the terms of the Mozilla Public License , v. 2.0 . If a copy of the MPL was not distributed with this file , You can obtain one at /. ;; ;; Copyright (c) KALEIDOS INC (ns app.main.ui.workspace.colorpicker.hsva (:require [app.main.ui.workspace.colorpicker.slider-selector :refer [slider-selector]] [app.util.color :as uc] [rumext.v2 :as mf])) (mf/defc hsva-selector [{:keys [color disable-opacity on-change on-start-drag on-finish-drag]}] (let [{hue :h saturation :s value :v alpha :alpha} color handle-change-slider (fn [key] (fn [new-value] (let [change (hash-map key new-value) {:keys [h s v]} (merge color change) hex (uc/hsv->hex [h s v]) [r g b] (uc/hex->rgb hex)] (on-change (merge change {:hex hex :r r :g g :b b}))))) on-change-opacity (fn [new-alpha] (on-change {:alpha new-alpha}))] [:div.hsva-selector [:span.hsva-selector-label "H"] [:& slider-selector {:class "hue" :max-value 360 :value hue :on-change (handle-change-slider :h) :on-start-drag on-start-drag :on-finish-drag on-finish-drag}] [:span.hsva-selector-label "S"] [:& slider-selector {:class "saturation" :max-value 1 :value saturation :on-change (handle-change-slider :s) :on-start-drag on-start-drag :on-finish-drag on-finish-drag}] [:span.hsva-selector-label "V"] [:& slider-selector {:class "value" :reverse? true :max-value 255 :value value :on-change (handle-change-slider :v) :on-start-drag on-start-drag :on-finish-drag on-finish-drag}] (when (not disable-opacity) [:* [:span.hsva-selector-label "A"] [:& slider-selector {:class "opacity" :max-value 1 :value alpha :on-change on-change-opacity :on-start-drag on-start-drag :on-finish-drag on-finish-drag}]])]))
null
https://raw.githubusercontent.com/penpot/penpot/7303d311d5f23d515fa3fcdc6cd13cf7f429d1fe/frontend/src/app/main/ui/workspace/colorpicker/hsva.cljs
clojure
Copyright (c) KALEIDOS INC
This Source Code Form is subject to the terms of the Mozilla Public License , v. 2.0 . If a copy of the MPL was not distributed with this file , You can obtain one at /. (ns app.main.ui.workspace.colorpicker.hsva (:require [app.main.ui.workspace.colorpicker.slider-selector :refer [slider-selector]] [app.util.color :as uc] [rumext.v2 :as mf])) (mf/defc hsva-selector [{:keys [color disable-opacity on-change on-start-drag on-finish-drag]}] (let [{hue :h saturation :s value :v alpha :alpha} color handle-change-slider (fn [key] (fn [new-value] (let [change (hash-map key new-value) {:keys [h s v]} (merge color change) hex (uc/hsv->hex [h s v]) [r g b] (uc/hex->rgb hex)] (on-change (merge change {:hex hex :r r :g g :b b}))))) on-change-opacity (fn [new-alpha] (on-change {:alpha new-alpha}))] [:div.hsva-selector [:span.hsva-selector-label "H"] [:& slider-selector {:class "hue" :max-value 360 :value hue :on-change (handle-change-slider :h) :on-start-drag on-start-drag :on-finish-drag on-finish-drag}] [:span.hsva-selector-label "S"] [:& slider-selector {:class "saturation" :max-value 1 :value saturation :on-change (handle-change-slider :s) :on-start-drag on-start-drag :on-finish-drag on-finish-drag}] [:span.hsva-selector-label "V"] [:& slider-selector {:class "value" :reverse? true :max-value 255 :value value :on-change (handle-change-slider :v) :on-start-drag on-start-drag :on-finish-drag on-finish-drag}] (when (not disable-opacity) [:* [:span.hsva-selector-label "A"] [:& slider-selector {:class "opacity" :max-value 1 :value alpha :on-change on-change-opacity :on-start-drag on-start-drag :on-finish-drag on-finish-drag}]])]))
96c4bfa2362018aacfa72ce16c639f0242c2626b64405522f973001f9f1177d7
nick8325/equinox
Form.hs
module Form where -- HOF data Expr = Expr :@ Expr | Lambda Symbol Expr | Symbol Symbol | Expr := Expr | Expr :& Expr | Neg Expr | Truth deriving ( Eq, Ord ) data Symbol = Name ::: Type deriving ( Eq, Ord ) forAll :: Symbol -> Expr -> Expr forAll x p = Lambda x p := Lambda x Truth (/\) :: Expr -> Expr -> Expr p /\ q = conj :@ p :@ q type Name = String data Type = Base Name -- more info here | Type :-> Type deriving ( Eq, Ord ) ind, bool :: Type ind = Base "$i" bool = Base "$o" FOF data Form = Term :=: Term | Not Form | Form :&: Form | Form :|: Form | ForAll Symbol Form | Exists Symbol Form | Bool Bool data Term = Fun Symbol [Term] | Var Symbol
null
https://raw.githubusercontent.com/nick8325/equinox/67351fbc4358fdea931b4c1dfb659f5527b40917/Haskell/NewStuff/Form.hs
haskell
HOF more info here
module Form where data Expr = Expr :@ Expr | Lambda Symbol Expr | Symbol Symbol | Expr := Expr | Expr :& Expr | Neg Expr | Truth deriving ( Eq, Ord ) data Symbol = Name ::: Type deriving ( Eq, Ord ) forAll :: Symbol -> Expr -> Expr forAll x p = Lambda x p := Lambda x Truth (/\) :: Expr -> Expr -> Expr p /\ q = conj :@ p :@ q type Name = String data Type | Type :-> Type deriving ( Eq, Ord ) ind, bool :: Type ind = Base "$i" bool = Base "$o" FOF data Form = Term :=: Term | Not Form | Form :&: Form | Form :|: Form | ForAll Symbol Form | Exists Symbol Form | Bool Bool data Term = Fun Symbol [Term] | Var Symbol
569018acccba33de77e4fbb4e23b0cae3faa21ba8fa345b4923704fde16ec7f6
juxt/vext
flowable.clj
Copyright © 2020 , JUXT LTD . Clojure shim upon io.reactivex . Flowable (ns juxt.vext.flowable (:refer-clojure :exclude [map count merge-with repeat reduce]) (:import (io.reactivex.functions Function))) (defn do-on-complete [f flowable] (.doOnComplete flowable (reify io.reactivex.functions.Action (run [_] (f))))) (defn do-on-terminate [f flowable] (.doOnTerminate flowable (reify io.reactivex.functions.Action (run [_] (f))))) (defn map [f flowable] (.flatMap flowable (reify Function (apply [_ item] (f item))))) (defn subscribe ([flowable] (.subscribe flowable)) ([subscriber flowable] (.subscribe flowable subscriber))) (defn ignore-elements [flowable] (.ignoreElements flowable)) (defn count [flowable] (.count flowable)) (defn publish [flowable] (.publish flowable)) (defn merge-with [other flowable] (.mergeWith flowable other)) (defn repeat [n flowable] (.repeat flowable n)) (defn as-consumer [f] (reify io.reactivex.functions.Consumer (accept [_ t] (f t)))) (defn reduce [seed bifn f] (.reduce f seed (reify io.reactivex.functions.BiFunction (apply [_ acc i] (bifn acc i)))))
null
https://raw.githubusercontent.com/juxt/vext/9e109bb43b0cb2c31ec439e7438c7bfb298ff16d/src/juxt/vext/flowable.clj
clojure
Copyright © 2020 , JUXT LTD . Clojure shim upon io.reactivex . Flowable (ns juxt.vext.flowable (:refer-clojure :exclude [map count merge-with repeat reduce]) (:import (io.reactivex.functions Function))) (defn do-on-complete [f flowable] (.doOnComplete flowable (reify io.reactivex.functions.Action (run [_] (f))))) (defn do-on-terminate [f flowable] (.doOnTerminate flowable (reify io.reactivex.functions.Action (run [_] (f))))) (defn map [f flowable] (.flatMap flowable (reify Function (apply [_ item] (f item))))) (defn subscribe ([flowable] (.subscribe flowable)) ([subscriber flowable] (.subscribe flowable subscriber))) (defn ignore-elements [flowable] (.ignoreElements flowable)) (defn count [flowable] (.count flowable)) (defn publish [flowable] (.publish flowable)) (defn merge-with [other flowable] (.mergeWith flowable other)) (defn repeat [n flowable] (.repeat flowable n)) (defn as-consumer [f] (reify io.reactivex.functions.Consumer (accept [_ t] (f t)))) (defn reduce [seed bifn f] (.reduce f seed (reify io.reactivex.functions.BiFunction (apply [_ acc i] (bifn acc i)))))
85f869740e0c7fdc65cb0034750591f8c3a66ec4c3b35043382d3c8c815a52f8
parenthesin/microservice-boilerplate-malli
utils.clj
(ns parenthesin.utils (:require [malli.dev.pretty :as pretty] [malli.instrument :as mi])) (defn with-malli-intrumentation "Wraps f ensuring there has malli collect and instrument started before running it" [f] (mi/collect! {:ns (all-ns)}) (mi/instrument! {:report (pretty/reporter)}) (f) (mi/unstrument!))
null
https://raw.githubusercontent.com/parenthesin/microservice-boilerplate-malli/efd1e64b5755afdae608554daa22564fd078e0a1/src/parenthesin/utils.clj
clojure
(ns parenthesin.utils (:require [malli.dev.pretty :as pretty] [malli.instrument :as mi])) (defn with-malli-intrumentation "Wraps f ensuring there has malli collect and instrument started before running it" [f] (mi/collect! {:ns (all-ns)}) (mi/instrument! {:report (pretty/reporter)}) (f) (mi/unstrument!))
ac64206bc6310d8d5720d09cfee7767f5c0dec529e76da34e8073f90196301e3
luminus-framework/examples
handler.clj
(ns guestbook-datomic.handler (:require [guestbook-datomic.layout :refer [error-page]] [guestbook-datomic.routes.home :refer [home-routes]] [compojure.core :refer [routes wrap-routes]] [compojure.route :as route] [guestbook-datomic.env :refer [defaults]] [mount.core :as mount] [guestbook-datomic.middleware :as middleware])) (mount/defstate init-app :start ((or (:init defaults) identity)) :stop ((or (:stop defaults) identity))) (mount/defstate app :start (middleware/wrap-base (routes (-> #'home-routes (wrap-routes middleware/wrap-csrf) (wrap-routes middleware/wrap-formats)) (route/not-found (:body (error-page {:status 404 :title "page not found"}))))))
null
https://raw.githubusercontent.com/luminus-framework/examples/cbeee2fef8f457a6a6bac2cae0b640370ae2499b/guestbook-datomic/src/clj/guestbook_datomic/handler.clj
clojure
(ns guestbook-datomic.handler (:require [guestbook-datomic.layout :refer [error-page]] [guestbook-datomic.routes.home :refer [home-routes]] [compojure.core :refer [routes wrap-routes]] [compojure.route :as route] [guestbook-datomic.env :refer [defaults]] [mount.core :as mount] [guestbook-datomic.middleware :as middleware])) (mount/defstate init-app :start ((or (:init defaults) identity)) :stop ((or (:stop defaults) identity))) (mount/defstate app :start (middleware/wrap-base (routes (-> #'home-routes (wrap-routes middleware/wrap-csrf) (wrap-routes middleware/wrap-formats)) (route/not-found (:body (error-page {:status 404 :title "page not found"}))))))
fb7b50e122b405d446d7bf33625404eef56e5a858d4baf2fb23e98f2396d7824
mvaldesdeleon/haskell-book
difflist.hs
module Main where import Criterion.Main newtype DList a = DL { unDL :: [a] -> [a] } {-# INLINE empty #-} empty :: DList a empty = DL $ const [] # INLINE singleton # singleton :: a -> DList a singleton x = DL $ const [x] # INLINE toList # toList :: DList a -> [a] toList xs = unDL xs [] infixr `cons` # INLINE cons # cons :: a -> DList a -> DList a cons x xs = DL ((x :) . unDL xs) infixl `snoc` # INLINE snoc # snoc :: DList a -> a -> DList a snoc xs x = DL (unDL xs . (x :)) # INLINE append # append :: DList a -> DList a -> DList a append xs ys = DL (unDL xs . unDL ys) schlemiel :: Int -> [Int] schlemiel i = go i [] where go 0 xs = xs go n xs = go (n - 1) ([n] ++ xs) constructDlist :: Int -> [Int] constructDlist i = toList $ go i empty where go 0 xs = xs go n xs = go (n - 1) (singleton n `append` xs) main :: IO () main = defaultMain [ bench "concat list" $ whnf schlemiel 123456 , bench "concat dlist" $ whnf constructDlist 123456 ]
null
https://raw.githubusercontent.com/mvaldesdeleon/haskell-book/ee4a70708041686abe2f1d951185786119470eb4/ch28/difflist.hs
haskell
# INLINE empty #
module Main where import Criterion.Main newtype DList a = DL { unDL :: [a] -> [a] } empty :: DList a empty = DL $ const [] # INLINE singleton # singleton :: a -> DList a singleton x = DL $ const [x] # INLINE toList # toList :: DList a -> [a] toList xs = unDL xs [] infixr `cons` # INLINE cons # cons :: a -> DList a -> DList a cons x xs = DL ((x :) . unDL xs) infixl `snoc` # INLINE snoc # snoc :: DList a -> a -> DList a snoc xs x = DL (unDL xs . (x :)) # INLINE append # append :: DList a -> DList a -> DList a append xs ys = DL (unDL xs . unDL ys) schlemiel :: Int -> [Int] schlemiel i = go i [] where go 0 xs = xs go n xs = go (n - 1) ([n] ++ xs) constructDlist :: Int -> [Int] constructDlist i = toList $ go i empty where go 0 xs = xs go n xs = go (n - 1) (singleton n `append` xs) main :: IO () main = defaultMain [ bench "concat list" $ whnf schlemiel 123456 , bench "concat dlist" $ whnf constructDlist 123456 ]
af833c9ce08f482fc036684b9c4d5a70c17749b990bae8caf0bf4ce370bcf377
basho/riak_cs
upgrade_downgrade_test.erl
%% --------------------------------------------------------------------- %% Copyright ( c ) 2007 - 2014 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(upgrade_downgrade_test). -export([confirm/0]). -include_lib("eunit/include/eunit.hrl"). -include_lib("erlcloud/include/erlcloud_aws.hrl"). -define(TEST_BUCKET, "riak-test-bucket-foobar"). -define(KEY_SINGLE_BLOCK, "riak_test_key1"). -define(KEY_MULTIPLE_BLOCK, "riak_test_key2"). confirm() -> PrevConfig = rtcs_config:previous_configs(), {UserConfig, {RiakNodes, _CSNodes, _Stanchion}} = rtcs:setup(2, PrevConfig, previous), lager:info("nodes> ~p", [rt_config:get(rt_nodes)]), lager:info("versions> ~p", [rt_config:get(rt_versions)]), {ok, Data} = prepare_all_data(UserConfig), ok = verify_all_data(UserConfig, Data), AdminCreds = {UserConfig#aws_config.access_key_id, UserConfig#aws_config.secret_access_key}, {_, RiakCurrentVsn} = rtcs_dev:riak_root_and_vsn(current, rt_config:get(build_type, oss)), %% Upgrade!!! [begin N = rtcs_dev:node_id(RiakNode), lager:debug("upgrading ~p", [N]), rtcs_exec:stop_cs(N, previous), ok = rt:upgrade(RiakNode, RiakCurrentVsn), rt:wait_for_service(RiakNode, riak_kv), ok = rtcs_config:upgrade_cs(N, AdminCreds), rtcs:set_advanced_conf({cs, current, N}, [{riak_cs, [{riak_host, {"127.0.0.1", rtcs_config:pb_port(1)}}]}]), rtcs_exec:start_cs(N, current) end || RiakNode <- RiakNodes], rt:wait_until_ring_converged(RiakNodes), rtcs_exec:stop_stanchion(previous), rtcs_config:migrate_stanchion(previous, current, AdminCreds), rtcs_exec:start_stanchion(current), ok = verify_all_data(UserConfig, Data), ok = cleanup_all_data(UserConfig), lager:info("Upgrading to current successfully done"), {ok, Data2} = prepare_all_data(UserConfig), {_, RiakPrevVsn} = rtcs_dev:riak_root_and_vsn(previous, rt_config:get(build_type, oss)), %% Downgrade!! rtcs_exec:stop_stanchion(current), rtcs_config:migrate_stanchion(current, previous, AdminCreds), rtcs_exec:start_stanchion(previous), [begin N = rtcs_dev:node_id(RiakNode), lager:debug("downgrading ~p", [N]), rtcs_exec:stop_cs(N, current), rt:stop(RiakNode), rt:wait_until_unpingable(RiakNode), %% get the bitcask directory BitcaskDataDir = filename:join([rtcs_dev:node_path(RiakNode), "data", "bitcask"]), lager:info("downgrading Bitcask datadir ~s...", [BitcaskDataDir]), %% and run the downgrade script: %% Downgrading from 2.0 does not work... %% And here's the downgrade script, which is downloaded at `make compile-riak-test`. %% Result = downgrade_bitcask:main([BitcaskDataDir]), lager:info("downgrade script done: ~p", [Result]), ok = rt:upgrade(RiakNode, RiakPrevVsn), rt:wait_for_service(RiakNode, riak_kv), ok = rtcs_config:migrate_cs(current, previous, N, AdminCreds), rtcs_exec:start_cs(N, previous) end || RiakNode <- RiakNodes], rt:wait_until_ring_converged(RiakNodes), ok = verify_all_data(UserConfig, Data2), lager:info("Downgrading to previous successfully done"), rtcs:pass(). %% TODO: add more data and test cases prepare_all_data(UserConfig) -> lager:info("User is valid on the cluster, and has no buckets"), ?assertEqual([{buckets, []}], erlcloud_s3:list_buckets(UserConfig)), lager:info("creating bucket ~p", [?TEST_BUCKET]), ?assertEqual(ok, erlcloud_s3:create_bucket(?TEST_BUCKET, UserConfig)), ?assertMatch([{buckets, [[{name, ?TEST_BUCKET}, _]]}], erlcloud_s3:list_buckets(UserConfig)), %% setup objects SingleBlock = crypto:rand_bytes(400), erlcloud_s3:put_object(?TEST_BUCKET, ?KEY_SINGLE_BLOCK, SingleBlock, UserConfig), MultipleBlock = crypto:rand_bytes(4000000), % not aligned to block boundary erlcloud_s3:put_object(?TEST_BUCKET, ?KEY_MULTIPLE_BLOCK, MultipleBlock, UserConfig), {ok, [{single_block, SingleBlock}, {multiple_block, MultipleBlock}]}. %% TODO: add more data and test cases verify_all_data(UserConfig, Data) -> SingleBlock = proplists:get_value(single_block, Data), MultipleBlock = proplists:get_value(multiple_block, Data), %% basic GET test cases basic_get_test_case(?TEST_BUCKET, ?KEY_SINGLE_BLOCK, SingleBlock, UserConfig), basic_get_test_case(?TEST_BUCKET, ?KEY_MULTIPLE_BLOCK, MultipleBlock, UserConfig), ok. cleanup_all_data(UserConfig) -> erlcloud_s3:delete_object(?TEST_BUCKET, ?KEY_SINGLE_BLOCK, UserConfig), erlcloud_s3:delete_object(?TEST_BUCKET, ?KEY_MULTIPLE_BLOCK, UserConfig), erlcloud_s3:delete_bucket(?TEST_BUCKET, UserConfig), ok. basic_get_test_case(Bucket, Key, ExpectedContent, Config) -> Obj = erlcloud_s3:get_object(Bucket, Key, Config), assert_whole_content(ExpectedContent, Obj). assert_whole_content(ExpectedContent, ResultObj) -> Content = proplists:get_value(content, ResultObj), ContentLength = proplists:get_value(content_length, ResultObj), ?assertEqual(byte_size(ExpectedContent), list_to_integer(ContentLength)), ?assertEqual(byte_size(ExpectedContent), byte_size(Content)), ?assertEqual(ExpectedContent, Content).
null
https://raw.githubusercontent.com/basho/riak_cs/c0c1012d1c9c691c74c8c5d9f69d388f5047bcd2/riak_test/tests/upgrade_downgrade_test.erl
erlang
--------------------------------------------------------------------- Version 2.0 (the "License"); you may not use this file a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --------------------------------------------------------------------- Upgrade!!! Downgrade!! get the bitcask directory and run the downgrade script: Downgrading from 2.0 does not work... And here's the downgrade script, which is downloaded at `make compile-riak-test`. TODO: add more data and test cases setup objects not aligned to block boundary TODO: add more data and test cases basic GET test cases
Copyright ( c ) 2007 - 2014 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(upgrade_downgrade_test). -export([confirm/0]). -include_lib("eunit/include/eunit.hrl"). -include_lib("erlcloud/include/erlcloud_aws.hrl"). -define(TEST_BUCKET, "riak-test-bucket-foobar"). -define(KEY_SINGLE_BLOCK, "riak_test_key1"). -define(KEY_MULTIPLE_BLOCK, "riak_test_key2"). confirm() -> PrevConfig = rtcs_config:previous_configs(), {UserConfig, {RiakNodes, _CSNodes, _Stanchion}} = rtcs:setup(2, PrevConfig, previous), lager:info("nodes> ~p", [rt_config:get(rt_nodes)]), lager:info("versions> ~p", [rt_config:get(rt_versions)]), {ok, Data} = prepare_all_data(UserConfig), ok = verify_all_data(UserConfig, Data), AdminCreds = {UserConfig#aws_config.access_key_id, UserConfig#aws_config.secret_access_key}, {_, RiakCurrentVsn} = rtcs_dev:riak_root_and_vsn(current, rt_config:get(build_type, oss)), [begin N = rtcs_dev:node_id(RiakNode), lager:debug("upgrading ~p", [N]), rtcs_exec:stop_cs(N, previous), ok = rt:upgrade(RiakNode, RiakCurrentVsn), rt:wait_for_service(RiakNode, riak_kv), ok = rtcs_config:upgrade_cs(N, AdminCreds), rtcs:set_advanced_conf({cs, current, N}, [{riak_cs, [{riak_host, {"127.0.0.1", rtcs_config:pb_port(1)}}]}]), rtcs_exec:start_cs(N, current) end || RiakNode <- RiakNodes], rt:wait_until_ring_converged(RiakNodes), rtcs_exec:stop_stanchion(previous), rtcs_config:migrate_stanchion(previous, current, AdminCreds), rtcs_exec:start_stanchion(current), ok = verify_all_data(UserConfig, Data), ok = cleanup_all_data(UserConfig), lager:info("Upgrading to current successfully done"), {ok, Data2} = prepare_all_data(UserConfig), {_, RiakPrevVsn} = rtcs_dev:riak_root_and_vsn(previous, rt_config:get(build_type, oss)), rtcs_exec:stop_stanchion(current), rtcs_config:migrate_stanchion(current, previous, AdminCreds), rtcs_exec:start_stanchion(previous), [begin N = rtcs_dev:node_id(RiakNode), lager:debug("downgrading ~p", [N]), rtcs_exec:stop_cs(N, current), rt:stop(RiakNode), rt:wait_until_unpingable(RiakNode), BitcaskDataDir = filename:join([rtcs_dev:node_path(RiakNode), "data", "bitcask"]), lager:info("downgrading Bitcask datadir ~s...", [BitcaskDataDir]), Result = downgrade_bitcask:main([BitcaskDataDir]), lager:info("downgrade script done: ~p", [Result]), ok = rt:upgrade(RiakNode, RiakPrevVsn), rt:wait_for_service(RiakNode, riak_kv), ok = rtcs_config:migrate_cs(current, previous, N, AdminCreds), rtcs_exec:start_cs(N, previous) end || RiakNode <- RiakNodes], rt:wait_until_ring_converged(RiakNodes), ok = verify_all_data(UserConfig, Data2), lager:info("Downgrading to previous successfully done"), rtcs:pass(). prepare_all_data(UserConfig) -> lager:info("User is valid on the cluster, and has no buckets"), ?assertEqual([{buckets, []}], erlcloud_s3:list_buckets(UserConfig)), lager:info("creating bucket ~p", [?TEST_BUCKET]), ?assertEqual(ok, erlcloud_s3:create_bucket(?TEST_BUCKET, UserConfig)), ?assertMatch([{buckets, [[{name, ?TEST_BUCKET}, _]]}], erlcloud_s3:list_buckets(UserConfig)), SingleBlock = crypto:rand_bytes(400), erlcloud_s3:put_object(?TEST_BUCKET, ?KEY_SINGLE_BLOCK, SingleBlock, UserConfig), erlcloud_s3:put_object(?TEST_BUCKET, ?KEY_MULTIPLE_BLOCK, MultipleBlock, UserConfig), {ok, [{single_block, SingleBlock}, {multiple_block, MultipleBlock}]}. verify_all_data(UserConfig, Data) -> SingleBlock = proplists:get_value(single_block, Data), MultipleBlock = proplists:get_value(multiple_block, Data), basic_get_test_case(?TEST_BUCKET, ?KEY_SINGLE_BLOCK, SingleBlock, UserConfig), basic_get_test_case(?TEST_BUCKET, ?KEY_MULTIPLE_BLOCK, MultipleBlock, UserConfig), ok. cleanup_all_data(UserConfig) -> erlcloud_s3:delete_object(?TEST_BUCKET, ?KEY_SINGLE_BLOCK, UserConfig), erlcloud_s3:delete_object(?TEST_BUCKET, ?KEY_MULTIPLE_BLOCK, UserConfig), erlcloud_s3:delete_bucket(?TEST_BUCKET, UserConfig), ok. basic_get_test_case(Bucket, Key, ExpectedContent, Config) -> Obj = erlcloud_s3:get_object(Bucket, Key, Config), assert_whole_content(ExpectedContent, Obj). assert_whole_content(ExpectedContent, ResultObj) -> Content = proplists:get_value(content, ResultObj), ContentLength = proplists:get_value(content_length, ResultObj), ?assertEqual(byte_size(ExpectedContent), list_to_integer(ContentLength)), ?assertEqual(byte_size(ExpectedContent), byte_size(Content)), ?assertEqual(ExpectedContent, Content).
1037e9481a49969850b8a8ef3565028d2d38d2a7e59ee09df9f1cb7cc5680df5
Bogdanp/racksnaps
http.rkt
#lang racket/base (require net/http-client racket/format racket/match racket/port racket/string) (provide get) (define conn (http-conn-open "pkgs.racket-lang.org" #:ssl? #t #:port 443 #:auto-reconnect? #t)) (define (get . path) (define-values (status _headers in) (http-conn-sendrecv! conn (~a "/" (string-join path "/")))) (match status [(regexp #rx"HTTP.... 200 ") (read in)] [(regexp #rx"HTTP.... [345].. ") (error 'get "failed to get path:~n path: ~a~n response: ~a" path (port->bytes in))]))
null
https://raw.githubusercontent.com/Bogdanp/racksnaps/86116e12b5e6f1537d313323fd7a33e81413452b/http.rkt
racket
#lang racket/base (require net/http-client racket/format racket/match racket/port racket/string) (provide get) (define conn (http-conn-open "pkgs.racket-lang.org" #:ssl? #t #:port 443 #:auto-reconnect? #t)) (define (get . path) (define-values (status _headers in) (http-conn-sendrecv! conn (~a "/" (string-join path "/")))) (match status [(regexp #rx"HTTP.... 200 ") (read in)] [(regexp #rx"HTTP.... [345].. ") (error 'get "failed to get path:~n path: ~a~n response: ~a" path (port->bytes in))]))
3406beb25f8184c5cb0afae5f7c915df0ee161116248a22f4a035daa9b07aa1b
naoiwata/sicp
q-1.09.scm
; ; -> @author naoiwata - > SICP Chapter1 ; -> q-1.9 ; (define (inc n) (+ n 1)) (define (dec n) (- n 1)) ;(A) (define (pulsA a b) (if (= a 0) b (inc (+ (dec a) b)))) (pulsA 4 5) - > ( inc ( + ( dec 4 ) 5 ) ) - > ( inc ( inc ( + ( dec 3 ) 5 ) ) ) - > ( inc ( inc ( inc ( + ( dec 2 ) 5 ) ) ) ) - > ( inc ( inc ( inc ( inc ( + ( dec 1 ) 5 ) ) ) ) ) - > ( inc ( inc ( inc ( inc ( inc ( + 0 ) 5 ) ) ) ) ) ; -> (inc (inc (inc (inc 5)))) ; -> (inc (inc (inc 6))) ; -> (inc (inc 7)) ; -> (inc 8) - > 9 ; -> ; recursive process ;(B) (define (pulsB a b) (if (= a 0) b (+ (dec a) (inc b)))) (pulsB 4 5) - > ( + ( dec 4 ) ( inc 5 ) ) - > ( + ( dec 3 ) ( inc 6 ) ) - > ( + ( dec 2 ) ( inc 7 ) ) - > ( + ( dec 1 ) ( inc 8) ) - > 9 ; -> ; iterative process
null
https://raw.githubusercontent.com/naoiwata/sicp/7314136c5892de402015acfe4b9148a3558b1211/chapter1/q-1.09.scm
scheme
-> @author naoiwata -> q-1.9 (A) -> (inc (inc (inc (inc 5)))) -> (inc (inc (inc 6))) -> (inc (inc 7)) -> (inc 8) -> recursive process (B) -> iterative process
- > SICP Chapter1 (define (inc n) (+ n 1)) (define (dec n) (- n 1)) (define (pulsA a b) (if (= a 0) b (inc (+ (dec a) b)))) (pulsA 4 5) - > ( inc ( + ( dec 4 ) 5 ) ) - > ( inc ( inc ( + ( dec 3 ) 5 ) ) ) - > ( inc ( inc ( inc ( + ( dec 2 ) 5 ) ) ) ) - > ( inc ( inc ( inc ( inc ( + ( dec 1 ) 5 ) ) ) ) ) - > ( inc ( inc ( inc ( inc ( inc ( + 0 ) 5 ) ) ) ) ) - > 9 (define (pulsB a b) (if (= a 0) b (+ (dec a) (inc b)))) (pulsB 4 5) - > ( + ( dec 4 ) ( inc 5 ) ) - > ( + ( dec 3 ) ( inc 6 ) ) - > ( + ( dec 2 ) ( inc 7 ) ) - > ( + ( dec 1 ) ( inc 8) ) - > 9
48db596edd82ce1ebeb632de48d5e273f1196a020e9b83f80f3953c21fba46e9
NorfairKing/cursor
Base.hs
# LANGUAGE RecordWildCards # # LANGUAGE ScopedTypeVariables # # LANGUAGE TypeFamilies # module Cursor.Tree.Base ( singletonTreeCursor, makeTreeCursor, makeNodeTreeCursor, makeTreeCursorWithSelection, rebuildTreeCursor, mapTreeCursor, currentTree, makeTreeCursorWithAbove, traverseTreeCursor, foldTreeCursor, ) where import Control.Monad import Cursor.Tree.Types singletonTreeCursor :: a -> TreeCursor a b singletonTreeCursor v = TreeCursor {treeAbove = Nothing, treeCurrent = v, treeBelow = emptyCForest} makeTreeCursor :: (b -> a) -> CTree b -> TreeCursor a b makeTreeCursor g (CNode v fs) = TreeCursor {treeAbove = Nothing, treeCurrent = g v, treeBelow = fs} makeNodeTreeCursor :: a -> CForest b -> TreeCursor a b makeNodeTreeCursor v fs = TreeCursor {treeAbove = Nothing, treeCurrent = v, treeBelow = fs} makeTreeCursorWithSelection :: (a -> b) -> (b -> a) -> TreeCursorSelection -> CTree b -> Maybe (TreeCursor a b) makeTreeCursorWithSelection f g sel = walkDown sel . makeTreeCursor g where walkDown SelectNode tc = pure tc walkDown (SelectChild i s) TreeCursor {..} = (walkDown s =<<) $ case splitAt i $ unpackCForest treeBelow of (_, []) -> Nothing (lefts, current : rights) -> Just $ makeTreeCursorWithAbove g current $ Just $ TreeAbove { treeAboveLefts = reverse lefts, treeAboveAbove = treeAbove, treeAboveNode = f treeCurrent, treeAboveRights = rights } rebuildTreeCursor :: (a -> b) -> TreeCursor a b -> CTree b rebuildTreeCursor f TreeCursor {..} = wrapAbove treeAbove $ CNode (f treeCurrent) treeBelow where wrapAbove Nothing t = t wrapAbove (Just TreeAbove {..}) t = wrapAbove treeAboveAbove $ CNode treeAboveNode $ openForest $ concat [reverse treeAboveLefts, [t], treeAboveRights] mapTreeCursor :: (a -> c) -> (b -> d) -> TreeCursor a b -> TreeCursor c d mapTreeCursor f g TreeCursor {..} = TreeCursor { treeAbove = fmap g <$> treeAbove, treeCurrent = f treeCurrent, treeBelow = fmap g treeBelow } currentTree :: (a -> b) -> TreeCursor a b -> CTree b currentTree f TreeCursor {..} = CNode (f treeCurrent) treeBelow makeTreeCursorWithAbove :: (b -> a) -> CTree b -> Maybe (TreeAbove b) -> TreeCursor a b makeTreeCursorWithAbove g (CNode a forest) mta = TreeCursor {treeAbove = mta, treeCurrent = g a, treeBelow = forest} traverseTreeCursor :: forall a b m c. Monad m => ([CTree b] -> b -> [CTree b] -> c -> m c) -> (a -> CForest b -> m c) -> TreeCursor a b -> m c traverseTreeCursor wrapFunc currentFunc TreeCursor {..} = currentFunc treeCurrent treeBelow >>= wrapAbove treeAbove where wrapAbove :: Maybe (TreeAbove b) -> c -> m c wrapAbove Nothing = pure wrapAbove (Just ta) = goAbove ta goAbove :: TreeAbove b -> c -> m c goAbove TreeAbove {..} = wrapFunc (reverse treeAboveLefts) treeAboveNode treeAboveRights >=> wrapAbove treeAboveAbove foldTreeCursor :: forall a b c. ([CTree b] -> b -> [CTree b] -> c -> c) -> (a -> CForest b -> c) -> TreeCursor a b -> c foldTreeCursor wrapFunc currentFunc TreeCursor {..} = wrapAbove treeAbove $ currentFunc treeCurrent treeBelow where wrapAbove :: Maybe (TreeAbove b) -> c -> c wrapAbove Nothing = id wrapAbove (Just ta) = goAbove ta goAbove :: TreeAbove b -> c -> c goAbove TreeAbove {..} = wrapAbove treeAboveAbove . wrapFunc (reverse treeAboveLefts) treeAboveNode treeAboveRights
null
https://raw.githubusercontent.com/NorfairKing/cursor/ff27e78281430c298a25a7805c9c61ca1e69f4c5/cursor/src/Cursor/Tree/Base.hs
haskell
# LANGUAGE RecordWildCards # # LANGUAGE ScopedTypeVariables # # LANGUAGE TypeFamilies # module Cursor.Tree.Base ( singletonTreeCursor, makeTreeCursor, makeNodeTreeCursor, makeTreeCursorWithSelection, rebuildTreeCursor, mapTreeCursor, currentTree, makeTreeCursorWithAbove, traverseTreeCursor, foldTreeCursor, ) where import Control.Monad import Cursor.Tree.Types singletonTreeCursor :: a -> TreeCursor a b singletonTreeCursor v = TreeCursor {treeAbove = Nothing, treeCurrent = v, treeBelow = emptyCForest} makeTreeCursor :: (b -> a) -> CTree b -> TreeCursor a b makeTreeCursor g (CNode v fs) = TreeCursor {treeAbove = Nothing, treeCurrent = g v, treeBelow = fs} makeNodeTreeCursor :: a -> CForest b -> TreeCursor a b makeNodeTreeCursor v fs = TreeCursor {treeAbove = Nothing, treeCurrent = v, treeBelow = fs} makeTreeCursorWithSelection :: (a -> b) -> (b -> a) -> TreeCursorSelection -> CTree b -> Maybe (TreeCursor a b) makeTreeCursorWithSelection f g sel = walkDown sel . makeTreeCursor g where walkDown SelectNode tc = pure tc walkDown (SelectChild i s) TreeCursor {..} = (walkDown s =<<) $ case splitAt i $ unpackCForest treeBelow of (_, []) -> Nothing (lefts, current : rights) -> Just $ makeTreeCursorWithAbove g current $ Just $ TreeAbove { treeAboveLefts = reverse lefts, treeAboveAbove = treeAbove, treeAboveNode = f treeCurrent, treeAboveRights = rights } rebuildTreeCursor :: (a -> b) -> TreeCursor a b -> CTree b rebuildTreeCursor f TreeCursor {..} = wrapAbove treeAbove $ CNode (f treeCurrent) treeBelow where wrapAbove Nothing t = t wrapAbove (Just TreeAbove {..}) t = wrapAbove treeAboveAbove $ CNode treeAboveNode $ openForest $ concat [reverse treeAboveLefts, [t], treeAboveRights] mapTreeCursor :: (a -> c) -> (b -> d) -> TreeCursor a b -> TreeCursor c d mapTreeCursor f g TreeCursor {..} = TreeCursor { treeAbove = fmap g <$> treeAbove, treeCurrent = f treeCurrent, treeBelow = fmap g treeBelow } currentTree :: (a -> b) -> TreeCursor a b -> CTree b currentTree f TreeCursor {..} = CNode (f treeCurrent) treeBelow makeTreeCursorWithAbove :: (b -> a) -> CTree b -> Maybe (TreeAbove b) -> TreeCursor a b makeTreeCursorWithAbove g (CNode a forest) mta = TreeCursor {treeAbove = mta, treeCurrent = g a, treeBelow = forest} traverseTreeCursor :: forall a b m c. Monad m => ([CTree b] -> b -> [CTree b] -> c -> m c) -> (a -> CForest b -> m c) -> TreeCursor a b -> m c traverseTreeCursor wrapFunc currentFunc TreeCursor {..} = currentFunc treeCurrent treeBelow >>= wrapAbove treeAbove where wrapAbove :: Maybe (TreeAbove b) -> c -> m c wrapAbove Nothing = pure wrapAbove (Just ta) = goAbove ta goAbove :: TreeAbove b -> c -> m c goAbove TreeAbove {..} = wrapFunc (reverse treeAboveLefts) treeAboveNode treeAboveRights >=> wrapAbove treeAboveAbove foldTreeCursor :: forall a b c. ([CTree b] -> b -> [CTree b] -> c -> c) -> (a -> CForest b -> c) -> TreeCursor a b -> c foldTreeCursor wrapFunc currentFunc TreeCursor {..} = wrapAbove treeAbove $ currentFunc treeCurrent treeBelow where wrapAbove :: Maybe (TreeAbove b) -> c -> c wrapAbove Nothing = id wrapAbove (Just ta) = goAbove ta goAbove :: TreeAbove b -> c -> c goAbove TreeAbove {..} = wrapAbove treeAboveAbove . wrapFunc (reverse treeAboveLefts) treeAboveNode treeAboveRights
67040fafcd33e876ef5b905e2b170a042b52433985990732fd599fd7f9774620
S8A/htdp-exercises
ex189.rkt
The first three lines of this file were inserted by . They record metadata ;; about the language level of this file in a form that our tools can easily process. #reader(lib "htdp-beginner-abbr-reader.ss" "lang")((modname ex189) (read-case-sensitive #t) (teachpacks ((lib "image.rkt" "teachpack" "2htdp") (lib "universe.rkt" "teachpack" "2htdp") (lib "batch-io.rkt" "teachpack" "2htdp"))) (htdp-settings #(#t constructor repeating-decimal #f #t none #f ((lib "image.rkt" "teachpack" "2htdp") (lib "universe.rkt" "teachpack" "2htdp") (lib "batch-io.rkt" "teachpack" "2htdp")) #f))) ; Number List-of-numbers -> Boolean ; determines whether n occurs in a list of numbers (define (search n alon) (cond [(empty? alon) #false] [else (or (= (first alon) n) (search n (rest alon)))])) (check-expect (search 5 '()) #false) (check-expect (search 10 (list 5 14 10 4 3)) #true) (check-expect (search 3 (list 4 5 7 2 6)) #false) ; Number List-of-numbers -> Boolean ; determines whether n occurs in a sorted list of numbers (define (search-sorted n sln) (cond [(empty? sln) #false] [else (cond [(= n (first sln)) #true] [(> n (first sln)) #false] [else (search n (rest sln))])])) (check-expect (search-sorted 3 '()) #false) (check-expect (search-sorted 10 (list 14 10 5 4 3)) #true) (check-expect (search-sorted 5 (list 7 6 4 3 2)) #false)
null
https://raw.githubusercontent.com/S8A/htdp-exercises/578e49834a9513f29ef81b7589b28081c5e0b69f/ex189.rkt
racket
about the language level of this file in a form that our tools can easily process. Number List-of-numbers -> Boolean determines whether n occurs in a list of numbers Number List-of-numbers -> Boolean determines whether n occurs in a sorted list of numbers
The first three lines of this file were inserted by . They record metadata #reader(lib "htdp-beginner-abbr-reader.ss" "lang")((modname ex189) (read-case-sensitive #t) (teachpacks ((lib "image.rkt" "teachpack" "2htdp") (lib "universe.rkt" "teachpack" "2htdp") (lib "batch-io.rkt" "teachpack" "2htdp"))) (htdp-settings #(#t constructor repeating-decimal #f #t none #f ((lib "image.rkt" "teachpack" "2htdp") (lib "universe.rkt" "teachpack" "2htdp") (lib "batch-io.rkt" "teachpack" "2htdp")) #f))) (define (search n alon) (cond [(empty? alon) #false] [else (or (= (first alon) n) (search n (rest alon)))])) (check-expect (search 5 '()) #false) (check-expect (search 10 (list 5 14 10 4 3)) #true) (check-expect (search 3 (list 4 5 7 2 6)) #false) (define (search-sorted n sln) (cond [(empty? sln) #false] [else (cond [(= n (first sln)) #true] [(> n (first sln)) #false] [else (search n (rest sln))])])) (check-expect (search-sorted 3 '()) #false) (check-expect (search-sorted 10 (list 14 10 5 4 3)) #true) (check-expect (search-sorted 5 (list 7 6 4 3 2)) #false)
514f5e3453739f37e298fabc856f511a4817f7634c479d94fdbefc502bba9147
PuercoPop/Movitz
arrays.lisp
;;;;------------------------------------------------------------------ ;;;; Copyright ( C ) 2001 - 2005 , Department of Computer Science , University of Tromso , Norway . ;;;; ;;;; For distribution policy, see the accompanying file COPYING. ;;;; ;;;; Filename: arrays.lisp ;;;; Description: Author : < > Created at : Sun Feb 11 23:14:04 2001 ;;;; $ I d : arrays.lisp , v 1.68 2008 - 04 - 21 19:30:40 Exp $ ;;;; ;;;;------------------------------------------------------------------ (require :muerte/basic-macros) (require :muerte/typep) (require :muerte/memref) (provide :muerte/arrays) (in-package muerte) (defconstant array-total-size-limit most-positive-fixnum) (defconstant array-dimension-limit most-positive-fixnum) (defconstant array-rank-limit 1024) (defmacro/cross-compilation vector-double-dispatch ((s1 s2) &rest clauses) (flet ((make-double-dispatch-value (et1 et2) (+ (* #x100 (binary-types:enum-value 'movitz::movitz-vector-element-type et1)) (binary-types:enum-value 'movitz::movitz-vector-element-type et2)))) `(case (+ (ash (vector-element-type-code ,s1) 8) (vector-element-type-code ,s2)) ,@(mapcar (lambda (clause) (destructuring-bind (keys . forms) clause (if (atom keys) (cons keys forms) (cons (make-double-dispatch-value (first keys) (second keys)) forms)))) clauses)))) (defmacro with-indirect-vector ((var form &key (check-type t)) &body body) `(let ((,var ,form)) ,(when check-type `(check-type ,var indirect-vector)) (macrolet ((,var (slot) (let ((index (position slot '(displaced-to displaced-offset fill-pointer length)))) (assert index () "Unknown indirect-vector slot ~S." slot) `(memref ,',var (movitz-type-slot-offset 'movitz-basic-vector 'data) :index ,index)))) ,@body))) (define-compiler-macro vector-element-type-code (object) `(let ((x (memref ,object (movitz-type-slot-offset 'movitz-basic-vector 'element-type) :type :unsigned-byte8))) (if (/= x ,(binary-types:enum-value 'movitz::movitz-vector-element-type :indirects)) x (memref ,object (movitz-type-slot-offset 'movitz-basic-vector 'fill-pointer) :index 1 :type :unsigned-byte8)))) (defun vector-element-type-code (object) (vector-element-type-code object)) (defun (setf vector-element-type-code) (numeric-element-type vector) (check-type vector vector) (setf (memref vector (movitz-type-slot-offset 'movitz-basic-vector 'element-type) :type :unsigned-byte8) numeric-element-type)) (defun array-element-type (array) (ecase (vector-element-type-code array) (#.(binary-types:enum-value 'movitz::movitz-vector-element-type :any-t) t) (#.(binary-types:enum-value 'movitz::movitz-vector-element-type :character) 'character) (#.(binary-types:enum-value 'movitz::movitz-vector-element-type :u8) '(unsigned-byte 8)) (#.(binary-types:enum-value 'movitz::movitz-vector-element-type :u16) '(unsigned-byte 16)) (#.(binary-types:enum-value 'movitz::movitz-vector-element-type :u32) '(unsigned-byte 32)) (#.(binary-types:enum-value 'movitz::movitz-vector-element-type :bit) 'bit) (#.(binary-types:enum-value 'movitz::movitz-vector-element-type :code) 'code))) (defun upgraded-array-element-type (type-specifier &optional environment) "=> upgraded-type-specifier" We 're in dire need of subtypep .. (cond ((symbolp type-specifier) (case type-specifier ((nil character base-char standard-char) 'character) ((code) 'code) (t (let ((deriver (gethash type-specifier *derived-typespecs*))) (if (not deriver) t (upgraded-array-element-type (funcall deriver))))))) ((null type-specifier) t) ((consp type-specifier) (case (car type-specifier) ((integer) (let* ((q (cdr type-specifier)) (min (if q (pop q) '*)) (max (if q (pop q) '*))) (let ((min (if (consp min) (1+ (car min)) min)) (max (if (consp max) (1- (car max)) max))) (cond ((or (eq min '*) (eq max '*)) t) ((<= 0 min max 1) 'bit) ((<= 0 min max #xff) '(unsigned-byte 8)) ((<= 0 min max #xffff) '(unsigned-byte 16)) ((<= 0 min max #xffffffff) '(unsigned-byte 32)))))) (t (let ((deriver (gethash (car type-specifier) *derived-typespecs*))) (if (not deriver) t (upgraded-array-element-type (apply deriver (cdr type-specifier)) environment)))))) (t t))) (defun array-dimension (array axis-number) (etypecase array (indirect-vector (assert (eq 0 axis-number)) (with-indirect-vector (indirect array :check-type nil) (indirect length))) ((simple-array * 1) (assert (eq 0 axis-number)) (memref array (movitz-type-slot-offset 'movitz-basic-vector 'num-elements))))) (defun array-dimensions (array) (let (r) (dotimes (d (array-rank array)) (push (array-dimension array d) r)) (nreverse r))) (defun array-rank (array) (etypecase array (indirect-vector 1) ((simple-array * 1) 1))) (defun shrink-vector (vector new-size) (check-type vector vector) (setf (memref vector (movitz-type-slot-offset 'movitz-basic-vector 'num-elements)) new-size)) (define-compiler-macro %basic-vector-has-fill-pointer-p (vector) "Does the basic-vector have a fill-pointer?" `(with-inline-assembly (:returns :boolean-zf=1) (:compile-form (:result-mode :eax) ,vector) (:testl ,(logxor #xffffffff (* movitz:+movitz-fixnum-factor+ (1- (expt 2 14)))) (:eax ,(binary-types:slot-offset 'movitz:movitz-basic-vector 'movitz::num-elements))))) (define-compiler-macro %basic-vector-fill-pointer (vector) "Return the basic-vector's fill-pointer. The result is only valid if %basic-vector-has-fill-pointer-p is true." `(with-inline-assembly (:returns :register) (:compile-form (:result-mode :register) ,vector) (:movzxw ((:result-register) ,(binary-types:slot-offset 'movitz:movitz-basic-vector 'movitz::fill-pointer)) (:result-register)))) (defun array-has-fill-pointer-p (array) (etypecase array (indirect-vector t) ((simple-array * 1) (%basic-vector-has-fill-pointer-p array)) (array nil))) (defun fill-pointer (vector) (etypecase vector (indirect-vector (memref vector (movitz-type-slot-offset 'movitz-basic-vector 'data) :index 2)) ((simple-array * 1) (assert (%basic-vector-has-fill-pointer-p vector) (vector) "Vector has no fill-pointer.") (%basic-vector-fill-pointer vector)))) (defun shallow-copy-vector (vector) (check-type vector (simple-array * 1)) (let ((length (the fixnum (memref vector (movitz-type-slot-offset 'movitz-basic-vector 'num-elements))))) (ecase (memref vector (movitz-type-slot-offset 'movitz-basic-vector 'element-type) :type :unsigned-byte8) ((#.(binary-types:enum-value 'movitz::movitz-vector-element-type :any-t) #.(binary-types:enum-value 'movitz::movitz-vector-element-type :indirects)) (%shallow-copy-object vector (+ 2 length))) ((#.(binary-types:enum-value 'movitz::movitz-vector-element-type :u32) #.(binary-types:enum-value 'movitz::movitz-vector-element-type :stack)) (%shallow-copy-non-pointer-object vector (+ 2 length))) ((#.(binary-types:enum-value 'movitz::movitz-vector-element-type :character) #.(binary-types:enum-value 'movitz::movitz-vector-element-type :u8) #.(binary-types:enum-value 'movitz::movitz-vector-element-type :code)) (%shallow-copy-non-pointer-object vector (+ 2 (truncate (+ 3 length) 4)))) ((#.(binary-types:enum-value 'movitz::movitz-vector-element-type :u16)) (%shallow-copy-non-pointer-object vector (+ 2 (truncate (+ 1 length) 2)))) ((#.(binary-types:enum-value 'movitz::movitz-vector-element-type :bit)) (%shallow-copy-non-pointer-object vector (+ 2 (truncate (+ 31 length) 32))))))) (defun (setf fill-pointer) (new-fill-pointer vector) (etypecase vector (indirect-vector (macrolet ((do-it () `(with-inline-assembly (:returns :eax) (:compile-two-forms (:eax :ebx) new-fill-pointer vector) (:testb ,movitz:+movitz-fixnum-zmask+ :al) (:jnz 'illegal-fill-pointer) (:movl (:ebx (:offset movitz-basic-vector data) 12) :ecx) (:cmpl :ebx :ecx) (:jg '(:sub-program (illegal-fill-pointer) (:compile-form (:result-mode :ignore) (error "Illegal fill-pointer: ~W." new-fill-pointer)))) (:movl :eax (:ebx (:offset movitz-basic-vector data) 8))))) (do-it))) ((simple-array * 1) (macrolet ((do-it () `(with-inline-assembly (:returns :eax) (:compile-two-forms (:eax :ebx) new-fill-pointer vector) (:testb ,movitz:+movitz-fixnum-zmask+ :al) (:jnz 'illegal-fill-pointer) (:movl (:ebx (:offset movitz-basic-vector num-elements)) :ecx) (:testl ,(logxor #xffffffff (* movitz:+movitz-fixnum-factor+ (1- (expt 2 14)))) :ecx) (:jnz '(:sub-program () (:compile-form (:result-mode :ignore) (error "Vector has no fill-pointer.")))) (:cmpl :eax :ecx) (:jc '(:sub-program (illegal-fill-pointer) (:compile-form (:result-mode :ignore) (error "Illegal fill-pointer: ~W." new-fill-pointer)))) (:movw :ax (:ebx (:offset movitz-basic-vector fill-pointer)))))) (do-it))))) (defun vector-aref%unsafe (vector index) "No type-checking of <vector> or <index>." (with-inline-assembly (:returns :eax) (:compile-form (:result-mode :eax) vector) (:compile-form (:result-mode :ebx) index) (:movzxb (:eax -1) :ecx) (:testl :ecx :ecx) ; element-type 0? (:jnz 'not-any-t) #.(cl:if (cl:plusp (cl:- movitz::+movitz-fixnum-shift+ 2)) `(:sarl ,(cl:- movitz::+movitz-fixnum-shift+ 2) :ebx) :nop) (:movl (:eax :ebx 2) :eax) (:jmp 'done) not-any-t (:shrl #.movitz::+movitz-fixnum-shift+ :ebx) element - type 1 ? (:jnz 'not-character) (:movb (:eax :ebx 2) :bl) (:xorl :eax :eax) (:movb :bl :ah) (:movb #.(movitz::tag :character) :al) (:jmp 'done) not-character (:decl :ecx) (:jnz '(:sub-program (not-u8) (:int 62) (:jmp (:pc+ -4)))) (:movzxb (:eax :ebx 2) :eax) (:shll #.movitz::+movitz-fixnum-shift+ :eax) done)) (defun (setf vector-aref%unsafe) (value vector index) (with-inline-assembly (:returns :ebx) (:compile-form (:result-mode :ebx) value) (:compile-form (:result-mode :eax) vector) (:compile-form (:result-mode :ecx) index) (:movzxb (:eax -1) :edx) (:testl :edx :edx) ; element-type 0? (:jnz 'not-any-t) #.(cl:if (cl:plusp (cl:- movitz::+movitz-fixnum-shift+ 2)) `(:sarl ,(cl:- movitz::+movitz-fixnum-shift+ 2) :ebx) :nop) (:movl :ebx (:eax :ecx 2)) (:jmp 'done) not-any-t (:shrl #.movitz::+movitz-fixnum-shift+ :ecx) element - type 1 ? (:jnz 'not-character) (:movb :bh (:eax :ecx 2)) (:jmp 'done) not-character (:decl :edx) (:jnz '(:sub-program (not-u8) (:int 62) (:jmp (:pc+ -4)))) (:shll #.(cl:- 8 movitz::+movitz-fixnum-shift+) :ebx) (:movb :bh (:eax :ecx 2)) (:shrl #.(cl:- 8 movitz::+movitz-fixnum-shift+) :ebx) done)) (defun aref (array &rest subscripts) (numargs-case (2 (array index) (etypecase array (indirect-vector (with-indirect-vector (indirect array :check-type nil) (aref (indirect displaced-to) (+ index (indirect displaced-offset))))) (vector (macrolet ((do-it () `(with-inline-assembly (:returns :eax) (:declare-label-set basic-vector-dispatcher ,(loop with x = (make-list 9 :initial-element 'unknown) for et in '(:any-t :character :u8 :u32 :stack :code :bit) do (setf (elt x (binary-types:enum-value 'movitz::movitz-vector-element-type et)) et) finally (return x))) (:compile-two-forms (:eax :ebx) array index) (:movl (:eax ,movitz:+other-type-offset+) :ecx) (:testb ,movitz:+movitz-fixnum-zmask+ :bl) (:jnz '(:sub-program (illegal-index) (:compile-form (:result-mode :ignore) (error "Illegal index: ~S." index)))) (:shrl 8 :ecx) (:andl 7 :ecx) (:cmpl :ebx (:eax ,(binary-types:slot-offset 'movitz:movitz-basic-vector 'movitz::num-elements))) (:jbe '(:sub-program (out-of-bounds) (:compile-form (:result-mode :ignore) (error "Index ~D is beyond vector length ~D." index (memref array (movitz-type-slot-offset 'movitz-basic-vector 'num-elements)))))) (:jmp (:esi (:ecx 4) 'basic-vector-dispatcher ,(binary-types:slot-offset 'movitz:movitz-funobj 'movitz::constant0))) (:jnever '(:sub-program (unknown) (:int 100))) :u32 :stack (:movl (:eax :ebx ,(binary-types:slot-offset 'movitz:movitz-basic-vector 'movitz::data)) :ecx) (:call-local-pf box-u32-ecx) (:jmp 'return) :u8 :code (:movl :ebx :ecx) (:shrl ,movitz:+movitz-fixnum-shift+ :ecx) (:movzxb (:eax :ecx ,(binary-types:slot-offset 'movitz:movitz-basic-vector 'movitz::data)) :ecx) (:leal ((:ecx ,movitz:+movitz-fixnum-factor+)) :eax) (:jmp 'return) :character (:movl :ebx :ecx) (:movl :eax :ebx) (:shrl ,movitz:+movitz-fixnum-shift+ :ecx) (:movl ,(movitz:tag :character) :eax) (:movb (:ebx :ecx ,(binary-types:slot-offset 'movitz:movitz-basic-vector 'movitz::data)) :ah) (:jmp 'return) :bit (:movl :ebx :ecx) (:movl :eax :ebx) (:shrl ,movitz:+movitz-fixnum-shift+ :ecx) (:xorl :eax :eax) (:btl :ecx (:ebx ,(binary-types:slot-offset 'movitz:movitz-basic-vector 'movitz::data))) (:jnc 'return) (:addl ,movitz:+movitz-fixnum-factor+ :eax) (:jmp 'return) :any-t (,movitz:*compiler-nonlocal-lispval-read-segment-prefix* :movl (:eax :ebx ,(binary-types:slot-offset 'movitz:movitz-basic-vector 'movitz::data)) :eax) return))) (do-it))))) (t (vector &rest subscripts) (declare (ignore vector subscripts)) (error "Multi-dimensional arrays not implemented.")))) (defun (setf aref) (value vector &rest subscripts) (numargs-case (3 (value vector index) (etypecase vector (indirect-vector (with-indirect-vector (indirect vector :check-type nil) (setf (aref (indirect displaced-to) (+ index (indirect displaced-offset))) value))) (vector (macrolet ((do-it () `(with-inline-assembly (:returns :eax) (:compile-two-forms (:eax :ebx) value vector) (:leal (:ebx ,(- (movitz:tag :other))) :ecx) (:compile-form (:result-mode :edx) index) (:testb 7 :cl) (:jnz '(:sub-program (not-a-vector) (:movl :ebx :eax) (:load-constant vector :edx) (:int 59))) (:movl (:ebx ,movitz:+other-type-offset+) :ecx) (:andl #xffff :ecx) (:testb ,movitz:+movitz-fixnum-zmask+ :dl) (:jnz '(:sub-program (not-an-index) (:movl :edx :eax) (:load-constant index :edx) (:int 59))) (:cmpl (:ebx ,(binary-types:slot-offset 'movitz:movitz-basic-vector 'movitz::num-elements)) :edx) (:jnc '(:sub-program (illegal-index) (:compile-form (:result-mode :ignore) (error "Index ~S out of range." index)))) ;; t? (:cmpl ,(movitz:basic-vector-type-tag :any-t) :ecx) (:jne 'not-any-t-vector) (,movitz:*compiler-nonlocal-lispval-write-segment-prefix* :movl :eax (:ebx :edx ,(binary-types:slot-offset 'movitz:movitz-basic-vector 'movitz::data))) (:jmp 'return) not-any-t-vector ;; Character? (:cmpl ,(movitz:basic-vector-type-tag :character) :ecx) (:jne 'not-character-vector) (:cmpb ,(movitz:tag :character) :al) (:jne '(:sub-program (not-a-character) (:load-constant character :edx) (:int 59))) (:movl :edx :ecx) (:shrl ,movitz:+movitz-fixnum-shift+ :ecx) (:movb :ah (:ebx :ecx ,(binary-types:slot-offset 'movitz:movitz-basic-vector 'movitz::data))) (:jmp 'return) not-character-vector ;; u8? (:cmpl ,(movitz:basic-vector-type-tag :u8) :ecx) (:jne 'not-u8-vector) code-vector (:testl ,(logxor #xffffffff (* #xff movitz:+movitz-fixnum-factor+)) :eax) (:jne '(:sub-program (not-an-u8) (:compile-form (:result-mode :ignore) (error "Not an (unsigned-byte 8): ~S" value)))) (:shll ,(- 8 movitz:+movitz-fixnum-shift+) :eax) (:movl :edx :ecx) (:shrl ,movitz:+movitz-fixnum-shift+ :ecx) (:movb :ah (:ebx :ecx ,(binary-types:slot-offset 'movitz:movitz-basic-vector 'movitz::data))) (:shrl ,(- 8 movitz:+movitz-fixnum-shift+) :eax) (:jmp 'return) not-u8-vector ;; Code? (:cmpl ,(movitz:basic-vector-type-tag :code) :ecx) (:je 'code-vector) ;; u32? (:cmpl ,(movitz:basic-vector-type-tag :u32) :ecx) (:jne 'not-u32-vector) (:call-local-pf unbox-u32) (:movl :ecx (:ebx :edx ,(binary-types:slot-offset 'movitz:movitz-basic-vector 'movitz::data))) (:jmp 'return) not-u32-vector ;; bit? (:cmpl ,(movitz:basic-vector-type-tag :bit) :ecx) (:jne 'not-bit-vector) (:testl ,(logxor #xffffffff (* #x1 movitz:+movitz-fixnum-factor+)) :eax) (:jne '(:sub-program (not-a-bit) (:compile-form (:result-mode :ignore) (error "Not a bit: ~S" value)))) (:movl :edx :ecx) (:shrl ,movitz:+movitz-fixnum-shift+ :ecx) (:testl :eax :eax) (:jnz 'set-one-bit) (:btrl :ecx (:ebx ,(binary-types:slot-offset 'movitz:movitz-basic-vector 'movitz::data))) (:jmp 'return) set-one-bit (:btsl :ecx (:ebx ,(binary-types:slot-offset 'movitz:movitz-basic-vector 'movitz::data))) (:jmp 'return) not-bit-vector (:compile-form (:result-mode :ignore) (error "Not a vector: ~S" vector)) return) )) (do-it))))) (t (value vector &rest subscripts) (declare (ignore value vector subscripts)) (error "Multi-dimensional arrays not implemented.")))) ;;; simple-vector accessors (define-compiler-macro svref%unsafe (simple-vector index) `(memref ,simple-vector (movitz-type-slot-offset 'movitz-basic-vector 'data) :index ,index)) (define-compiler-macro (setf svref%unsafe) (value simple-vector index) `(setf (memref ,simple-vector (movitz-type-slot-offset 'movitz-basic-vector 'data) :index ,index) ,value)) (defun svref%unsafe (simple-vector index) ;; (compiler-macro-call svref%unsafe simple-vector index)) (with-inline-assembly (:returns :eax) (:compile-two-forms (:eax :ebx) simple-vector index) (:movl (:eax :ebx #.(binary-types:slot-offset 'movitz:movitz-basic-vector 'movitz::data)) :eax))) (defun (setf svref%unsafe) (value simple-vector index) (setf (svref%unsafe simple-vector index) value)) (defun svref (simple-vector index) (macrolet ((do-it () `(with-inline-assembly (:returns :eax) (:compile-two-forms (:eax :ebx) simple-vector index) (:leal (:eax ,(- (movitz::tag :other))) :ecx) (:testb 7 :cl) (:jne '(:sub-program (not-basic-simple-vector) (:compile-form (:result-mode :ignore) (error "Not a simple-vector: ~S." simple-vector)))) (:movl (:eax ,movitz:+other-type-offset+) :ecx) (:testb ,movitz:+movitz-fixnum-zmask+ :bl) (:jnz '(:sub-program (illegal-index) (:compile-form (:result-mode :ignore) (error "Illegal index: ~S." index)))) (:cmpw ,(movitz:basic-vector-type-tag :any-t) :cx) (:jne 'not-basic-simple-vector) (:cmpl :ebx (:eax (:offset movitz-basic-vector num-elements))) (:jbe 'illegal-index) (:movl (:eax :ebx (:offset movitz-basic-vector data)) :eax) ))) (do-it))) (defun (setf svref) (value simple-vector index) (macrolet ((do-it () `(with-inline-assembly (:returns :eax) (:compile-two-forms (:ebx :edx) simple-vector index) (:leal (:ebx ,(- (movitz::tag :other))) :ecx) (:testb 7 :cl) (:jne '(:sub-program (not-basic-simple-vector) (:compile-form (:result-mode :ignore) (error "Not a simple-vector: ~S." simple-vector)))) (:movl (:ebx ,movitz:+other-type-offset+) :ecx) (:testb ,movitz:+movitz-fixnum-zmask+ :dl) (:jnz '(:sub-program (illegal-index) (:compile-form (:result-mode :ignore) (error "Illegal index: ~S." index)))) (:compile-form (:result-mode :eax) value) (:cmpw ,(movitz:basic-vector-type-tag :any-t) :cx) (:jne 'not-basic-simple-vector) (:cmpl :edx (:ebx (:offset movitz-basic-vector num-elements))) (:jbe 'illegal-index) (:movl :eax (:ebx :edx (:offset movitz-basic-vector data)))))) (do-it))) ;;; string accessors (defun char (string index) (assert (below index (array-dimension string 0))) (etypecase string (simple-string (memref string (movitz-type-slot-offset 'movitz-basic-vector 'data) :index index :type :character)) (string (with-indirect-vector (indirect string) (char (indirect displaced-to) (+ index (indirect displaced-offset))))))) (defun (setf char) (value string index) (assert (below index (array-dimension string 0))) (etypecase string (simple-string (check-type value character) (setf (memref string (movitz-type-slot-offset 'movitz-basic-vector 'data) :index index :type :character) value)) (string (with-indirect-vector (indirect string) (setf (char (indirect displaced-to) (+ index (indirect displaced-offset))) value))))) (defun schar (string index) (check-type string simple-string) (assert (below index (length string))) (memref string (movitz-type-slot-offset 'movitz-basic-vector 'data) :index index :type :character)) (defun (setf schar) (value string index) (check-type string simple-string) (check-type value character) (assert (below index (length string))) (setf (memref string (movitz-type-slot-offset 'movitz-basic-vector 'data) :index index :type :character) value)) (define-compiler-macro char%unsafe (string index) `(memref ,string (movitz-type-slot-offset 'movitz-basic-vector 'data) :index ,index :type :character)) (defun char%unsafe (string index) (char%unsafe string index)) (define-compiler-macro (setf char%unsafe) (value string index) `(setf (memref ,string (movitz-type-slot-offset 'movitz-basic-vector 'data) :index ,index :type :character) ,value)) (defun (setf char%unsafe) (value string index) (setf (char%unsafe string index) value)) ;;; bit accessors (defun bit (array &rest subscripts) (numargs-case (2 (array index) (etypecase array (indirect-vector (with-indirect-vector (indirect array :check-type nil) (aref (indirect displaced-to) (+ index (indirect displaced-offset))))) (simple-bit-vector (macrolet ((do-it () `(with-inline-assembly (:returns :eax) (:compile-two-forms (:eax :ebx) array index) (:testb ,movitz:+movitz-fixnum-zmask+ :bl) (:jnz '(:sub-program (illegal-index) (:compile-form (:result-mode :ignore) (error "Illegal index: ~S." index)))) (:cmpl :ebx (:eax ,(binary-types:slot-offset 'movitz:movitz-basic-vector 'movitz::num-elements))) (:jbe '(:sub-program (out-of-bounds) (:compile-form (:result-mode :ignore) (error "Index ~D is beyond vector length ~D." index (memref array (movitz-type-slot-offset 'movitz-basic-vector 'num-elements)))))) :bit (:movl :ebx :ecx) (:movl :eax :ebx) (:shrl ,movitz:+movitz-fixnum-shift+ :ecx) (:xorl :eax :eax) (:btl :ecx (:ebx ,(binary-types:slot-offset 'movitz:movitz-basic-vector 'movitz::data))) (:jnc 'return) (:addl ,movitz:+movitz-fixnum-factor+ :eax) return))) (do-it))))) (t (vector &rest subscripts) (declare (ignore vector subscripts)) (error "Multi-dimensional arrays not implemented.")))) (defun sbit (array &rest subscripts) (numargs-case (2 (array index) (check-type array simple-bit-vector) (macrolet ((do-it () `(with-inline-assembly (:returns :eax) (:compile-two-forms (:eax :ebx) array index) (:testb ,movitz:+movitz-fixnum-zmask+ :bl) (:jnz '(:sub-program (illegal-index) (:compile-form (:result-mode :ignore) (error "Illegal index: ~S." index)))) (:cmpl :ebx (:eax ,(binary-types:slot-offset 'movitz:movitz-basic-vector 'movitz::num-elements))) (:jbe '(:sub-program (out-of-bounds) (:compile-form (:result-mode :ignore) (error "Index ~D is beyond vector length ~D." index (memref array (movitz-type-slot-offset 'movitz-basic-vector 'num-elements)))))) :bit (:movl :ebx :ecx) (:movl :eax :ebx) (:shrl ,movitz:+movitz-fixnum-shift+ :ecx) (:xorl :eax :eax) (:btl :ecx (:ebx ,(binary-types:slot-offset 'movitz:movitz-basic-vector 'movitz::data))) (:jnc 'return) (:addl ,movitz:+movitz-fixnum-factor+ :eax) return))) (do-it))) (t (vector &rest subscripts) (declare (ignore vector subscripts)) (error "Multi-dimensional arrays not implemented.")))) (defun bitref%unsafe (array index) (macrolet ((do-it () `(with-inline-assembly (:returns :eax) (:compile-two-forms (:eax :ebx) array index) (:testb ,movitz:+movitz-fixnum-zmask+ :bl) (:jnz '(:sub-program (illegal-index) (:compile-form (:result-mode :ignore) (error "Illegal index: ~S." index)))) :bit (:movl :ebx :ecx) (:movl :eax :ebx) (:shrl ,movitz:+movitz-fixnum-shift+ :ecx) (:xorl :eax :eax) (:btl :ecx (:ebx ,(binary-types:slot-offset 'movitz:movitz-basic-vector 'movitz::data))) (:jnc 'return) (:addl ,movitz:+movitz-fixnum-factor+ :eax) return))) (do-it))) (defun (setf bit) (value vector &rest subscripts) (numargs-case (3 (value vector index) (check-type value bit) (etypecase vector (indirect-vector (with-indirect-vector (indirect vector :check-type nil) (setf (aref (indirect displaced-to) (+ index (indirect displaced-offset))) value))) (simple-bit-vector (macrolet ((do-it () `(with-inline-assembly (:returns :eax) (:compile-two-forms (:eax :ebx) value vector) (:compile-form (:result-mode :edx) index) (:testb ,movitz:+movitz-fixnum-zmask+ :dl) (:jnz '(:sub-program (not-an-index) (:compile-form (:result-mode :ignore) (error "Not a vector index: ~S." index)))) (:cmpl (:ebx ,(binary-types:slot-offset 'movitz:movitz-basic-vector 'movitz::num-elements)) :edx) (:jnc '(:sub-program (illegal-index) (:compile-form (:result-mode :ignore) (error "Index ~S out of range." index)))) (:movl :edx :ecx) (:shrl ,movitz:+movitz-fixnum-shift+ :ecx) (:testl :eax :eax) (:jnz 'set-one-bit) (:btrl :ecx (:ebx ,(binary-types:slot-offset 'movitz:movitz-basic-vector 'movitz::data))) (:jmp 'return) set-one-bit (:btsl :ecx (:ebx ,(binary-types:slot-offset 'movitz:movitz-basic-vector 'movitz::data))) return))) (do-it))))) (t (value vector &rest subscripts) (declare (ignore value vector subscripts)) (error "Multi-dimensional arrays not implemented.")))) (defun (setf sbit) (value vector &rest subscripts) (numargs-case (3 (value vector index) (check-type value bit) (macrolet ((do-it () `(with-inline-assembly (:returns :eax) (:compile-two-forms (:eax :ebx) value vector) (:compile-form (:result-mode :edx) index) (:testb ,movitz:+movitz-fixnum-zmask+ :dl) (:jnz '(:sub-program (not-an-index) (:compile-form (:result-mode :ignore) (error "Not a vector index: ~S." index)))) (:cmpl (:ebx ,(binary-types:slot-offset 'movitz:movitz-basic-vector 'movitz::num-elements)) :edx) (:jnc '(:sub-program (illegal-index) (:compile-form (:result-mode :ignore) (error "Index ~S out of range." index)))) (:movl :edx :ecx) (:shrl ,movitz:+movitz-fixnum-shift+ :ecx) (:testl :eax :eax) (:jnz 'set-one-bit) (:btrl :ecx (:ebx ,(binary-types:slot-offset 'movitz:movitz-basic-vector 'movitz::data))) (:jmp 'return) set-one-bit (:btsl :ecx (:ebx ,(binary-types:slot-offset 'movitz:movitz-basic-vector 'movitz::data))) return))) (do-it))) (t (value vector &rest subscripts) (declare (ignore value vector subscripts)) (error "Multi-dimensional arrays not implemented.")))) (defun (setf bitref%unsafe) (value vector index) (macrolet ((do-it () `(progn (check-type value bit) (with-inline-assembly (:returns :eax) (:compile-two-forms (:eax :ebx) value vector) (:compile-form (:result-mode :edx) index) (:testb ,movitz:+movitz-fixnum-zmask+ :dl) (:jnz '(:sub-program (not-an-index) (:compile-form (:result-mode :ignore) (error "Not a vector index: ~S." index)))) (:movl :edx :ecx) (:shrl ,movitz:+movitz-fixnum-shift+ :ecx) (:testl :eax :eax) (:jnz 'set-one-bit) (:btrl :ecx (:ebx ,(binary-types:slot-offset 'movitz:movitz-basic-vector 'movitz::data))) (:jmp 'return) set-one-bit (:btsl :ecx (:ebx ,(binary-types:slot-offset 'movitz:movitz-basic-vector 'movitz::data))) return)))) (do-it))) ;;; u8 accessors (define-compiler-macro u8ref%unsafe (vector index) `(memref ,vector (movitz-type-slot-offset 'movitz-basic-vector 'data) :index ,index :type :unsigned-byte8)) (defun u8ref%unsafe (vector index) (u8ref%unsafe vector index)) (define-compiler-macro (setf u8ref%unsafe) (value vector index) `(setf (memref ,vector (movitz-type-slot-offset 'movitz-basic-vector 'data) :index ,index :type :unsigned-byte8) ,value)) (defun (setf u8ref%unsafe) (value vector index) (setf (u8ref%unsafe vector index) value)) u32 accessors (define-compiler-macro u32ref%unsafe (vector index) `(memref ,vector (movitz-type-slot-offset 'movitz-basic-vector 'data) :index ,index :type :unsigned-byte32)) (defun u32ref%unsafe (vector index) (compiler-macro-call u32ref%unsafe vector index)) (define-compiler-macro (setf u32ref%unsafe) (value vector index) (let ((var (gensym "setf-u32ref-value-"))) ;; Use var so as to avoid re-boxing of the u32 value. `(let ((,var ,value)) (setf (memref ,vector 2 :index ,index :type :unsigned-byte32) ,var) ,var))) (defun (setf u32ref%unsafe) (value vector index) (compiler-macro-call (setf u32ref%unsafe) value vector index)) ;;; fast vector access (defun subvector-accessors (vector &optional start end) "Check that vector is a vector, that start and end are within vector's bounds, and return basic-vector and accessors for that subsequence." (when (and start end) (assert (<= 0 start end)) (assert (<= end (array-dimension vector 0)))) (etypecase vector (indirect-vector (with-indirect-vector (indirect vector) (if (= 0 (indirect displaced-offset)) (subvector-accessors (indirect displaced-to) start end) (let ((offset (indirect displaced-offset))) (values vector (lambda (a i) (aref a (+ i offset))) (lambda (v a i) (setf (aref a (+ i offset)) v))))))) (vector (case (vector-element-type-code vector) (#.(binary-types:enum-value 'movitz::movitz-vector-element-type :any-t) (values vector #'svref%unsafe #'(setf svref%unsafe))) (#.(binary-types:enum-value 'movitz::movitz-vector-element-type :character) (values vector #'char%unsafe #'(setf char%unsafe))) (#.(binary-types:enum-value 'movitz::movitz-vector-element-type :u8) (values vector #'u8ref%unsafe #'(setf u8ref%unsafe))) (#.(binary-types:enum-value 'movitz::movitz-vector-element-type :u32) (values vector #'u32ref%unsafe #'(setf u32ref%unsafe))) (#.(binary-types:enum-value 'movitz::movitz-vector-element-type :code) (values vector #'u8ref%unsafe #'(setf u8ref%unsafe))) (#.(binary-types:enum-value 'movitz::movitz-vector-element-type :bit) (values vector #'bitref%unsafe #'(setf bitref%unsafe))) (t (warn "don't know about vector's element-type: ~S" vector) (values vector #'aref #'(setf aref))))))) (defmacro with-subvector-accessor ((name vector-form &optional start end) &body body) "Installs name as an accessor into vector-form, bound by start and end." (let ((reader (gensym "sub-vector-reader-")) (writer (gensym "sub-vector-writer-")) (vector (gensym "sub-vector-"))) `(multiple-value-bind (,vector ,reader ,writer) (subvector-accessors ,vector-form ,start ,end) (declare (ignorable ,reader ,writer)) (macrolet ((,name (index) `(accessor%unsafe (,',reader ,',writer) ,',vector ,index))) ,@body)))) (defmacro accessor%unsafe ((reader writer) &rest args) (declare (ignore writer)) `(funcall%unsafe ,reader ,@args)) (define-setf-expander accessor%unsafe ((reader writer) &rest args) ;; should collect tmp-vars from args, most probably.. (let ((store-var (gensym "accessor%unsafe-store-"))) (values nil nil (list store-var) `(funcall%unsafe ,writer ,store-var ,@args) `(funcall%unsafe ,reader ,@args)))) (defun make-basic-vector%character (length fill-pointer initial-element initial-contents) (check-type length (and fixnum (integer 0 *))) (let* ((words (+ 2 (truncate (+ length 3) 4))) (array (macrolet ((do-it () `(with-non-pointer-allocation-assembly (words :fixed-size-p t :object-register :eax) (:load-lexical (:lexical-binding length) :ecx) (:movl ,(movitz:basic-vector-type-tag :character) (:eax (:offset movitz-basic-vector type))) (:movl :ecx (:eax (:offset movitz-basic-vector num-elements)))))) (do-it)))) (cond ((integerp fill-pointer) (setf (fill-pointer array) fill-pointer)) ((or (eq t fill-pointer) (array-has-fill-pointer-p array)) (setf (fill-pointer array) length))) (cond (initial-element (check-type initial-element character) (dotimes (i length) (setf (char array i) initial-element))) (initial-contents (replace array initial-contents))) array)) (defun make-basic-vector%u32 (length fill-pointer initial-element initial-contents) (check-type length (and fixnum (integer 0 *))) (let* ((words (+ 2 length)) (array (macrolet ((do-it () `(with-non-pointer-allocation-assembly (words :fixed-size-p t :object-register :eax) (:load-lexical (:lexical-binding length) :ecx) (:movl ,(movitz:basic-vector-type-tag :u32) (:eax (:offset movitz-basic-vector type))) (:movl :ecx (:eax (:offset movitz-basic-vector num-elements)))))) (do-it)))) (cond ((integerp fill-pointer) (setf (fill-pointer array) fill-pointer)) ((or (eq t fill-pointer) (array-has-fill-pointer-p array)) (setf (fill-pointer array) length))) (cond (initial-element (check-type initial-element (unsigned-byte 32)) (dotimes (i length) (setf (u32ref%unsafe array i) initial-element))) (initial-contents (replace array initial-contents))) array)) (defun make-stack-vector (length) (let ((vector (make-basic-vector%u32 length nil nil nil))) (with-inline-assembly (:returns :nothing) (:load-lexical (:lexical-binding vector) :eax) (:movl #.(movitz:basic-vector-type-tag :stack) (:eax (:offset movitz-basic-vector type)))) (when (%basic-vector-has-fill-pointer-p vector) (setf (fill-pointer vector) length)) vector)) (defun make-basic-vector%u8 (length fill-pointer initial-element initial-contents) (check-type length (and fixnum (integer 0 *))) (let* ((words (+ 2 (truncate (+ length 3) 4))) (array (macrolet ((do-it () `(with-non-pointer-allocation-assembly (words :fixed-size-p t :object-register :eax) (:load-lexical (:lexical-binding length) :ecx) (:movl ,(movitz:basic-vector-type-tag :u8) (:eax (:offset movitz-basic-vector type))) (:movl :ecx (:eax (:offset movitz-basic-vector num-elements)))))) (do-it)))) (cond ((integerp fill-pointer) (setf (fill-pointer array) fill-pointer)) ((or (eq t fill-pointer) (array-has-fill-pointer-p array)) (setf (fill-pointer array) length))) (cond (initial-element (check-type initial-element (unsigned-byte 8)) (dotimes (i length) (setf (u8ref%unsafe array i) initial-element))) (initial-contents (replace array initial-contents))) array)) (defun make-basic-vector%bit (length fill-pointer initial-element initial-contents) (check-type length (and fixnum (integer 0 *))) (let* ((words (+ 2 (truncate (+ length 31) 32))) (array (macrolet ((do-it () `(with-non-pointer-allocation-assembly (words :fixed-size-p t :object-register :eax) (:load-lexical (:lexical-binding length) :ecx) (:movl ,(movitz:basic-vector-type-tag :bit) (:eax (:offset movitz-basic-vector type))) (:movl :ecx (:eax (:offset movitz-basic-vector num-elements)))))) (do-it)))) (cond ((integerp fill-pointer) (setf (fill-pointer array) fill-pointer)) ((or (eq t fill-pointer) (array-has-fill-pointer-p array)) (setf (fill-pointer array) length))) (cond (initial-element (check-type initial-element bit) (dotimes (i length) (setf (aref array i) initial-element))) (initial-contents (replace array initial-contents))) array)) (defun make-basic-vector%code (length fill-pointer initial-element initial-contents) (check-type length (and fixnum (integer 0 *))) (let* ((words (+ 2 (truncate (+ length 3) 4))) (array (macrolet ((do-it () `(with-non-pointer-allocation-assembly (words :fixed-size-p t :object-register :eax) (:load-lexical (:lexical-binding length) :ecx) (:movl ,(movitz:basic-vector-type-tag :code) (:eax (:offset movitz-basic-vector type))) (:movl :ecx (:eax (:offset movitz-basic-vector num-elements)))))) (do-it)))) (cond ((integerp fill-pointer) (setf (fill-pointer array) fill-pointer)) ((or (eq t fill-pointer) (array-has-fill-pointer-p array)) (setf (fill-pointer array) length))) (cond (initial-element (check-type initial-element (unsigned-byte 8)) (dotimes (i length) (setf (u8ref%unsafe array i) initial-element))) (initial-contents (replace array initial-contents))) array)) (defun make-basic-vector%t (length fill-pointer initial-element initial-contents) (check-type length (and fixnum (integer 0 *))) (let* ((words (+ 2 length))) (cond ((<= length 8) (let ((array (macrolet ((do-it () `(with-allocation-assembly (words :fixed-size-p t :object-register :eax) (:load-lexical (:lexical-binding length) :ecx) (:movl ,(movitz:basic-vector-type-tag :any-t) (:eax (:offset movitz-basic-vector type))) (:movl :ecx (:eax (:offset movitz-basic-vector num-elements))) (:addl 4 :ecx) (:andl -8 :ecx) (:jz 'init-done) (:load-lexical (:lexical-binding initial-element) :edx) init-loop (:movl :edx (:eax (:offset movitz-basic-vector data) :ecx -4)) (:subl 4 :ecx) (:jnz 'init-loop) init-done ))) (do-it)))) (cond ((integerp fill-pointer) (setf (fill-pointer array) fill-pointer)) ((or (eq t fill-pointer) (array-has-fill-pointer-p array)) (setf (fill-pointer array) length))) (when initial-contents (replace array initial-contents)) array)) (t (let* ((init-word (if (typep initial-element '(or null fixnum character)) initial-element nil)) (array (macrolet ((do-it () `(with-inline-assembly (:returns :eax) (:compile-form (:result-mode :eax) (with-non-pointer-allocation-assembly (words :fixed-size-p t :object-register :eax) (:load-lexical (:lexical-binding length) :ecx) (:movl ,(movitz:basic-vector-type-tag :u32) (:eax (:offset movitz-basic-vector type))) (:movl :ecx (:eax (:offset movitz-basic-vector num-elements))))) (:load-lexical (:lexical-binding length) :ecx) (:addl 4 :ecx) (:andl -8 :ecx) (:jz 'init-done2) (:load-lexical (:lexical-binding init-word) :edx) init-loop2 (:movl :edx (:eax (:offset movitz-basic-vector data) :ecx -4)) (:subl 4 :ecx) (:jnz 'init-loop2) init-done2 (:movl ,(movitz:basic-vector-type-tag :any-t) (:eax (:offset movitz-basic-vector type)))))) (do-it)))) (cond ((integerp fill-pointer) (setf (fill-pointer array) fill-pointer)) ((or (eq t fill-pointer) (array-has-fill-pointer-p array)) (setf (fill-pointer array) length))) (cond (initial-contents (replace array initial-contents)) ((not (eq init-word initial-element)) (fill array initial-element))) array))))) (defun make-indirect-vector (displaced-to displaced-offset fill-pointer length) (let ((x (make-basic-vector%t 4 0 nil nil))) (setf (vector-element-type-code x) #.(binary-types:enum-value 'movitz::movitz-vector-element-type :indirects)) (set-indirect-vector x displaced-to displaced-offset (vector-element-type-code displaced-to) fill-pointer length))) (defun set-indirect-vector (x displaced-to displaced-offset et-code fill-pointer length) (check-type displaced-to vector) (let ((displaced-offset (or displaced-offset 0))) (assert (<= (+ displaced-offset length) (length displaced-to)) () "Displaced-to is outside legal range.") (setf (memref x (movitz-type-slot-offset 'movitz-basic-vector 'fill-pointer) :index 1 :type :unsigned-byte8) et-code) (with-indirect-vector (indirect x) (setf (indirect displaced-to) displaced-to (indirect displaced-offset) displaced-offset (indirect fill-pointer) (etypecase fill-pointer ((eql nil) length) ((eql t) length) ((integer 0 *) fill-pointer)) (indirect length) length)) x)) (defun make-basic-vector (size element-type fill-pointer initial-element initial-contents) (let ((upgraded-element-type (upgraded-array-element-type element-type))) (cond These should be replaced by subtypep sometime . ((eq upgraded-element-type 'character) (make-basic-vector%character size fill-pointer initial-element initial-contents)) ((eq upgraded-element-type 'bit) (make-basic-vector%bit size fill-pointer initial-element initial-contents)) ((member upgraded-element-type '(u8 (unsigned-byte 8)) :test #'equal) (make-basic-vector%u8 size fill-pointer initial-element initial-contents)) ((member upgraded-element-type '(u32 (unsigned-byte 32)) :test #'equal) (make-basic-vector%u32 size fill-pointer initial-element initial-contents)) ((eq upgraded-element-type 'code) (make-basic-vector%code size fill-pointer initial-element initial-contents)) (t (make-basic-vector%t size fill-pointer initial-element initial-contents))))) (defun make-array (dimensions &key (element-type t) initial-element initial-contents adjustable fill-pointer displaced-to displaced-index-offset) (let ((size (cond ((integerp dimensions) dimensions) ((and (consp dimensions) (null (cdr dimensions))) (car dimensions)) (t (warn "Array of rank ~D not supported." (length dimensions)) (return-from make-array nil))))) ; XXX (cond (displaced-to (make-indirect-vector displaced-to displaced-index-offset fill-pointer size)) ((or adjustable (and fill-pointer (not (typep size '(unsigned-byte 14))))) (make-indirect-vector (make-basic-vector size element-type nil initial-element initial-contents) 0 fill-pointer size)) (t (make-basic-vector size element-type fill-pointer initial-element initial-contents))))) (defun adjust-array (array new-dimensions &key element-type (initial-element nil initial-element-p) initial-contents fill-pointer displaced-to displaced-index-offset) (etypecase array (indirect-vector (let ((new-length (cond ((integerp new-dimensions) new-dimensions) ((and (consp new-dimensions) (null (cdr new-dimensions))) (car new-dimensions)) (t (error "Multi-dimensional arrays not supported."))))) (with-indirect-vector (indirect array) (cond (displaced-to (check-type displaced-to vector) (set-indirect-vector array displaced-to displaced-index-offset (vector-element-type-code array) (case fill-pointer ((nil) (indirect fill-pointer)) ((t) new-length) (t fill-pointer)) new-length)) ((and (= 0 (indirect displaced-offset)) (/= new-length (array-dimension array 0))) (let* ((old (indirect displaced-to)) (new (make-array new-length :element-type (array-element-type old)))) (dotimes (i (array-dimension old 0)) (setf (aref new i) (aref old i))) (when initial-element-p (fill new initial-element :start (array-dimension old 0))) (setf (indirect displaced-to) new (indirect length) new-length) (when fill-pointer (setf (fill-pointer array) fill-pointer)))) (t (error "Sorry, don't know how to adjust ~S." array))))) array) (vector (let ((new-length (cond ((integerp new-dimensions) new-dimensions) ((and (consp new-dimensions) (null (cdr new-dimensions))) (car new-dimensions)) (t (error "Multi-dimensional arrays not supported."))))) (let ((new (if (= (array-dimension array 0) new-length) array (let* ((old array) (new (make-array new-length :element-type (array-element-type old)))) (dotimes (i (array-dimension old 0)) (setf (aref new i) (aref old i))) (when initial-element-p (fill new initial-element :start (array-dimension old 0))) new)))) (case fill-pointer ((nil)) ((t) (setf (fill-pointer new) new-length)) (t (setf (fill-pointer new) fill-pointer))) new))))) (defun adjustable-array-p (array) (typep array 'indirect-vector)) (defun vector (&rest objects) "=> vector" (declare (dynamic-extent objects)) (let* ((length (length objects)) (vector (make-array length))) (do ((i 0 (1+ i)) (p objects (cdr p))) ((endp p)) (setf (svref vector i) (car p))) vector)) (defun vector-push (new-element vector) (check-type vector vector) (let ((p (fill-pointer vector))) (declare (index p)) (when (< p (array-dimension vector 0)) (setf (aref vector p) new-element (fill-pointer vector) (1+ p)) p))) (defun vector-pop (vector) (let ((p (1- (fill-pointer vector)))) (assert (not (minusp p))) (setf (fill-pointer vector) p) (aref vector p))) (defun vector-read (vector) "Like vector-pop, only in the other direction." (let ((x (aref vector (fill-pointer vector)))) (incf (fill-pointer vector)) x)) (defun vector-read-more-p (vector) (< (fill-pointer vector) (array-dimension vector 0))) (defun vector-push-extend (new-element vector &optional extension) (check-type vector vector) (let ((p (fill-pointer vector))) (cond ((< p (array-dimension vector 0)) (setf (aref vector p) new-element (fill-pointer vector) (1+ p))) ((not (adjustable-array-p vector)) (error "Can't extend non-adjustable array.")) (t (adjust-array vector (+ (array-dimension vector 0) (or extension (max 1 (array-dimension vector 0)))) :fill-pointer (1+ p)) (setf (aref vector p) new-element))) p)) (define-compiler-macro bvref-u16 (&whole form vector offset index &environment env) (let ((actual-index (and (movitz:movitz-constantp index env) (movitz:movitz-eval index env)))) (if (not (typep actual-index '(integer 0 *))) `(bvref-u16-fallback ,vector ,offset ,index) (let ((var (gensym))) `(let ((,var ,vector)) (if (not (typep ,var 'vector-u8)) (bvref-u16-fallback ,var ,offset ,index) (with-inline-assembly (:returns :untagged-fixnum-ecx) (:compile-two-forms (:eax :ecx) ,var ,offset) (:cmpl (:eax ,(binary-types:slot-offset 'movitz::movitz-basic-vector 'movitz::num-elements)) :ecx) (:jnc '(:sub-program () (:int 69))) (:shrl ,movitz::+movitz-fixnum-shift+ :ecx) (:movw (:eax :ecx ,(+ actual-index (binary-types:slot-offset 'movitz::movitz-basic-vector 'movitz::data))) :cx) (:xchgb :cl :ch)))))))) (defun bvref-u16-fallback (vector offset index) (logior (ash (aref vector (+ index offset)) 8) (aref vector (+ index offset)))) (defun bvref-u16 (vector offset index) "View <vector> as an sequence of octets, access the big-endian 16-bit word at position <index> + <offset>." (bvref-u16 vector offset index)) (defun ensure-data-vector (vector start length) (let ((end (typecase vector ((simple-array (unsigned-byte 8) 1) (array-dimension vector 0)) (t (error "Not a data vector: ~S" vector))))) (assert (<= (+ start length) end) (vector) "Data vector too small.") vector))
null
https://raw.githubusercontent.com/PuercoPop/Movitz/7ffc41896c1e054aa43f44d64bbe9eaf3fcfa777/losp/muerte/arrays.lisp
lisp
------------------------------------------------------------------ For distribution policy, see the accompanying file COPYING. Filename: arrays.lisp Description: ------------------------------------------------------------------ element-type 0? element-type 0? t? Character? u8? Code? u32? bit? simple-vector accessors (compiler-macro-call svref%unsafe simple-vector index)) string accessors bit accessors u8 accessors Use var so as to avoid re-boxing of the u32 value. fast vector access should collect tmp-vars from args, most probably.. XXX
Copyright ( C ) 2001 - 2005 , Department of Computer Science , University of Tromso , Norway . Author : < > Created at : Sun Feb 11 23:14:04 2001 $ I d : arrays.lisp , v 1.68 2008 - 04 - 21 19:30:40 Exp $ (require :muerte/basic-macros) (require :muerte/typep) (require :muerte/memref) (provide :muerte/arrays) (in-package muerte) (defconstant array-total-size-limit most-positive-fixnum) (defconstant array-dimension-limit most-positive-fixnum) (defconstant array-rank-limit 1024) (defmacro/cross-compilation vector-double-dispatch ((s1 s2) &rest clauses) (flet ((make-double-dispatch-value (et1 et2) (+ (* #x100 (binary-types:enum-value 'movitz::movitz-vector-element-type et1)) (binary-types:enum-value 'movitz::movitz-vector-element-type et2)))) `(case (+ (ash (vector-element-type-code ,s1) 8) (vector-element-type-code ,s2)) ,@(mapcar (lambda (clause) (destructuring-bind (keys . forms) clause (if (atom keys) (cons keys forms) (cons (make-double-dispatch-value (first keys) (second keys)) forms)))) clauses)))) (defmacro with-indirect-vector ((var form &key (check-type t)) &body body) `(let ((,var ,form)) ,(when check-type `(check-type ,var indirect-vector)) (macrolet ((,var (slot) (let ((index (position slot '(displaced-to displaced-offset fill-pointer length)))) (assert index () "Unknown indirect-vector slot ~S." slot) `(memref ,',var (movitz-type-slot-offset 'movitz-basic-vector 'data) :index ,index)))) ,@body))) (define-compiler-macro vector-element-type-code (object) `(let ((x (memref ,object (movitz-type-slot-offset 'movitz-basic-vector 'element-type) :type :unsigned-byte8))) (if (/= x ,(binary-types:enum-value 'movitz::movitz-vector-element-type :indirects)) x (memref ,object (movitz-type-slot-offset 'movitz-basic-vector 'fill-pointer) :index 1 :type :unsigned-byte8)))) (defun vector-element-type-code (object) (vector-element-type-code object)) (defun (setf vector-element-type-code) (numeric-element-type vector) (check-type vector vector) (setf (memref vector (movitz-type-slot-offset 'movitz-basic-vector 'element-type) :type :unsigned-byte8) numeric-element-type)) (defun array-element-type (array) (ecase (vector-element-type-code array) (#.(binary-types:enum-value 'movitz::movitz-vector-element-type :any-t) t) (#.(binary-types:enum-value 'movitz::movitz-vector-element-type :character) 'character) (#.(binary-types:enum-value 'movitz::movitz-vector-element-type :u8) '(unsigned-byte 8)) (#.(binary-types:enum-value 'movitz::movitz-vector-element-type :u16) '(unsigned-byte 16)) (#.(binary-types:enum-value 'movitz::movitz-vector-element-type :u32) '(unsigned-byte 32)) (#.(binary-types:enum-value 'movitz::movitz-vector-element-type :bit) 'bit) (#.(binary-types:enum-value 'movitz::movitz-vector-element-type :code) 'code))) (defun upgraded-array-element-type (type-specifier &optional environment) "=> upgraded-type-specifier" We 're in dire need of subtypep .. (cond ((symbolp type-specifier) (case type-specifier ((nil character base-char standard-char) 'character) ((code) 'code) (t (let ((deriver (gethash type-specifier *derived-typespecs*))) (if (not deriver) t (upgraded-array-element-type (funcall deriver))))))) ((null type-specifier) t) ((consp type-specifier) (case (car type-specifier) ((integer) (let* ((q (cdr type-specifier)) (min (if q (pop q) '*)) (max (if q (pop q) '*))) (let ((min (if (consp min) (1+ (car min)) min)) (max (if (consp max) (1- (car max)) max))) (cond ((or (eq min '*) (eq max '*)) t) ((<= 0 min max 1) 'bit) ((<= 0 min max #xff) '(unsigned-byte 8)) ((<= 0 min max #xffff) '(unsigned-byte 16)) ((<= 0 min max #xffffffff) '(unsigned-byte 32)))))) (t (let ((deriver (gethash (car type-specifier) *derived-typespecs*))) (if (not deriver) t (upgraded-array-element-type (apply deriver (cdr type-specifier)) environment)))))) (t t))) (defun array-dimension (array axis-number) (etypecase array (indirect-vector (assert (eq 0 axis-number)) (with-indirect-vector (indirect array :check-type nil) (indirect length))) ((simple-array * 1) (assert (eq 0 axis-number)) (memref array (movitz-type-slot-offset 'movitz-basic-vector 'num-elements))))) (defun array-dimensions (array) (let (r) (dotimes (d (array-rank array)) (push (array-dimension array d) r)) (nreverse r))) (defun array-rank (array) (etypecase array (indirect-vector 1) ((simple-array * 1) 1))) (defun shrink-vector (vector new-size) (check-type vector vector) (setf (memref vector (movitz-type-slot-offset 'movitz-basic-vector 'num-elements)) new-size)) (define-compiler-macro %basic-vector-has-fill-pointer-p (vector) "Does the basic-vector have a fill-pointer?" `(with-inline-assembly (:returns :boolean-zf=1) (:compile-form (:result-mode :eax) ,vector) (:testl ,(logxor #xffffffff (* movitz:+movitz-fixnum-factor+ (1- (expt 2 14)))) (:eax ,(binary-types:slot-offset 'movitz:movitz-basic-vector 'movitz::num-elements))))) (define-compiler-macro %basic-vector-fill-pointer (vector) "Return the basic-vector's fill-pointer. The result is only valid if %basic-vector-has-fill-pointer-p is true." `(with-inline-assembly (:returns :register) (:compile-form (:result-mode :register) ,vector) (:movzxw ((:result-register) ,(binary-types:slot-offset 'movitz:movitz-basic-vector 'movitz::fill-pointer)) (:result-register)))) (defun array-has-fill-pointer-p (array) (etypecase array (indirect-vector t) ((simple-array * 1) (%basic-vector-has-fill-pointer-p array)) (array nil))) (defun fill-pointer (vector) (etypecase vector (indirect-vector (memref vector (movitz-type-slot-offset 'movitz-basic-vector 'data) :index 2)) ((simple-array * 1) (assert (%basic-vector-has-fill-pointer-p vector) (vector) "Vector has no fill-pointer.") (%basic-vector-fill-pointer vector)))) (defun shallow-copy-vector (vector) (check-type vector (simple-array * 1)) (let ((length (the fixnum (memref vector (movitz-type-slot-offset 'movitz-basic-vector 'num-elements))))) (ecase (memref vector (movitz-type-slot-offset 'movitz-basic-vector 'element-type) :type :unsigned-byte8) ((#.(binary-types:enum-value 'movitz::movitz-vector-element-type :any-t) #.(binary-types:enum-value 'movitz::movitz-vector-element-type :indirects)) (%shallow-copy-object vector (+ 2 length))) ((#.(binary-types:enum-value 'movitz::movitz-vector-element-type :u32) #.(binary-types:enum-value 'movitz::movitz-vector-element-type :stack)) (%shallow-copy-non-pointer-object vector (+ 2 length))) ((#.(binary-types:enum-value 'movitz::movitz-vector-element-type :character) #.(binary-types:enum-value 'movitz::movitz-vector-element-type :u8) #.(binary-types:enum-value 'movitz::movitz-vector-element-type :code)) (%shallow-copy-non-pointer-object vector (+ 2 (truncate (+ 3 length) 4)))) ((#.(binary-types:enum-value 'movitz::movitz-vector-element-type :u16)) (%shallow-copy-non-pointer-object vector (+ 2 (truncate (+ 1 length) 2)))) ((#.(binary-types:enum-value 'movitz::movitz-vector-element-type :bit)) (%shallow-copy-non-pointer-object vector (+ 2 (truncate (+ 31 length) 32))))))) (defun (setf fill-pointer) (new-fill-pointer vector) (etypecase vector (indirect-vector (macrolet ((do-it () `(with-inline-assembly (:returns :eax) (:compile-two-forms (:eax :ebx) new-fill-pointer vector) (:testb ,movitz:+movitz-fixnum-zmask+ :al) (:jnz 'illegal-fill-pointer) (:movl (:ebx (:offset movitz-basic-vector data) 12) :ecx) (:cmpl :ebx :ecx) (:jg '(:sub-program (illegal-fill-pointer) (:compile-form (:result-mode :ignore) (error "Illegal fill-pointer: ~W." new-fill-pointer)))) (:movl :eax (:ebx (:offset movitz-basic-vector data) 8))))) (do-it))) ((simple-array * 1) (macrolet ((do-it () `(with-inline-assembly (:returns :eax) (:compile-two-forms (:eax :ebx) new-fill-pointer vector) (:testb ,movitz:+movitz-fixnum-zmask+ :al) (:jnz 'illegal-fill-pointer) (:movl (:ebx (:offset movitz-basic-vector num-elements)) :ecx) (:testl ,(logxor #xffffffff (* movitz:+movitz-fixnum-factor+ (1- (expt 2 14)))) :ecx) (:jnz '(:sub-program () (:compile-form (:result-mode :ignore) (error "Vector has no fill-pointer.")))) (:cmpl :eax :ecx) (:jc '(:sub-program (illegal-fill-pointer) (:compile-form (:result-mode :ignore) (error "Illegal fill-pointer: ~W." new-fill-pointer)))) (:movw :ax (:ebx (:offset movitz-basic-vector fill-pointer)))))) (do-it))))) (defun vector-aref%unsafe (vector index) "No type-checking of <vector> or <index>." (with-inline-assembly (:returns :eax) (:compile-form (:result-mode :eax) vector) (:compile-form (:result-mode :ebx) index) (:movzxb (:eax -1) :ecx) (:jnz 'not-any-t) #.(cl:if (cl:plusp (cl:- movitz::+movitz-fixnum-shift+ 2)) `(:sarl ,(cl:- movitz::+movitz-fixnum-shift+ 2) :ebx) :nop) (:movl (:eax :ebx 2) :eax) (:jmp 'done) not-any-t (:shrl #.movitz::+movitz-fixnum-shift+ :ebx) element - type 1 ? (:jnz 'not-character) (:movb (:eax :ebx 2) :bl) (:xorl :eax :eax) (:movb :bl :ah) (:movb #.(movitz::tag :character) :al) (:jmp 'done) not-character (:decl :ecx) (:jnz '(:sub-program (not-u8) (:int 62) (:jmp (:pc+ -4)))) (:movzxb (:eax :ebx 2) :eax) (:shll #.movitz::+movitz-fixnum-shift+ :eax) done)) (defun (setf vector-aref%unsafe) (value vector index) (with-inline-assembly (:returns :ebx) (:compile-form (:result-mode :ebx) value) (:compile-form (:result-mode :eax) vector) (:compile-form (:result-mode :ecx) index) (:movzxb (:eax -1) :edx) (:jnz 'not-any-t) #.(cl:if (cl:plusp (cl:- movitz::+movitz-fixnum-shift+ 2)) `(:sarl ,(cl:- movitz::+movitz-fixnum-shift+ 2) :ebx) :nop) (:movl :ebx (:eax :ecx 2)) (:jmp 'done) not-any-t (:shrl #.movitz::+movitz-fixnum-shift+ :ecx) element - type 1 ? (:jnz 'not-character) (:movb :bh (:eax :ecx 2)) (:jmp 'done) not-character (:decl :edx) (:jnz '(:sub-program (not-u8) (:int 62) (:jmp (:pc+ -4)))) (:shll #.(cl:- 8 movitz::+movitz-fixnum-shift+) :ebx) (:movb :bh (:eax :ecx 2)) (:shrl #.(cl:- 8 movitz::+movitz-fixnum-shift+) :ebx) done)) (defun aref (array &rest subscripts) (numargs-case (2 (array index) (etypecase array (indirect-vector (with-indirect-vector (indirect array :check-type nil) (aref (indirect displaced-to) (+ index (indirect displaced-offset))))) (vector (macrolet ((do-it () `(with-inline-assembly (:returns :eax) (:declare-label-set basic-vector-dispatcher ,(loop with x = (make-list 9 :initial-element 'unknown) for et in '(:any-t :character :u8 :u32 :stack :code :bit) do (setf (elt x (binary-types:enum-value 'movitz::movitz-vector-element-type et)) et) finally (return x))) (:compile-two-forms (:eax :ebx) array index) (:movl (:eax ,movitz:+other-type-offset+) :ecx) (:testb ,movitz:+movitz-fixnum-zmask+ :bl) (:jnz '(:sub-program (illegal-index) (:compile-form (:result-mode :ignore) (error "Illegal index: ~S." index)))) (:shrl 8 :ecx) (:andl 7 :ecx) (:cmpl :ebx (:eax ,(binary-types:slot-offset 'movitz:movitz-basic-vector 'movitz::num-elements))) (:jbe '(:sub-program (out-of-bounds) (:compile-form (:result-mode :ignore) (error "Index ~D is beyond vector length ~D." index (memref array (movitz-type-slot-offset 'movitz-basic-vector 'num-elements)))))) (:jmp (:esi (:ecx 4) 'basic-vector-dispatcher ,(binary-types:slot-offset 'movitz:movitz-funobj 'movitz::constant0))) (:jnever '(:sub-program (unknown) (:int 100))) :u32 :stack (:movl (:eax :ebx ,(binary-types:slot-offset 'movitz:movitz-basic-vector 'movitz::data)) :ecx) (:call-local-pf box-u32-ecx) (:jmp 'return) :u8 :code (:movl :ebx :ecx) (:shrl ,movitz:+movitz-fixnum-shift+ :ecx) (:movzxb (:eax :ecx ,(binary-types:slot-offset 'movitz:movitz-basic-vector 'movitz::data)) :ecx) (:leal ((:ecx ,movitz:+movitz-fixnum-factor+)) :eax) (:jmp 'return) :character (:movl :ebx :ecx) (:movl :eax :ebx) (:shrl ,movitz:+movitz-fixnum-shift+ :ecx) (:movl ,(movitz:tag :character) :eax) (:movb (:ebx :ecx ,(binary-types:slot-offset 'movitz:movitz-basic-vector 'movitz::data)) :ah) (:jmp 'return) :bit (:movl :ebx :ecx) (:movl :eax :ebx) (:shrl ,movitz:+movitz-fixnum-shift+ :ecx) (:xorl :eax :eax) (:btl :ecx (:ebx ,(binary-types:slot-offset 'movitz:movitz-basic-vector 'movitz::data))) (:jnc 'return) (:addl ,movitz:+movitz-fixnum-factor+ :eax) (:jmp 'return) :any-t (,movitz:*compiler-nonlocal-lispval-read-segment-prefix* :movl (:eax :ebx ,(binary-types:slot-offset 'movitz:movitz-basic-vector 'movitz::data)) :eax) return))) (do-it))))) (t (vector &rest subscripts) (declare (ignore vector subscripts)) (error "Multi-dimensional arrays not implemented.")))) (defun (setf aref) (value vector &rest subscripts) (numargs-case (3 (value vector index) (etypecase vector (indirect-vector (with-indirect-vector (indirect vector :check-type nil) (setf (aref (indirect displaced-to) (+ index (indirect displaced-offset))) value))) (vector (macrolet ((do-it () `(with-inline-assembly (:returns :eax) (:compile-two-forms (:eax :ebx) value vector) (:leal (:ebx ,(- (movitz:tag :other))) :ecx) (:compile-form (:result-mode :edx) index) (:testb 7 :cl) (:jnz '(:sub-program (not-a-vector) (:movl :ebx :eax) (:load-constant vector :edx) (:int 59))) (:movl (:ebx ,movitz:+other-type-offset+) :ecx) (:andl #xffff :ecx) (:testb ,movitz:+movitz-fixnum-zmask+ :dl) (:jnz '(:sub-program (not-an-index) (:movl :edx :eax) (:load-constant index :edx) (:int 59))) (:cmpl (:ebx ,(binary-types:slot-offset 'movitz:movitz-basic-vector 'movitz::num-elements)) :edx) (:jnc '(:sub-program (illegal-index) (:compile-form (:result-mode :ignore) (error "Index ~S out of range." index)))) (:cmpl ,(movitz:basic-vector-type-tag :any-t) :ecx) (:jne 'not-any-t-vector) (,movitz:*compiler-nonlocal-lispval-write-segment-prefix* :movl :eax (:ebx :edx ,(binary-types:slot-offset 'movitz:movitz-basic-vector 'movitz::data))) (:jmp 'return) not-any-t-vector (:cmpl ,(movitz:basic-vector-type-tag :character) :ecx) (:jne 'not-character-vector) (:cmpb ,(movitz:tag :character) :al) (:jne '(:sub-program (not-a-character) (:load-constant character :edx) (:int 59))) (:movl :edx :ecx) (:shrl ,movitz:+movitz-fixnum-shift+ :ecx) (:movb :ah (:ebx :ecx ,(binary-types:slot-offset 'movitz:movitz-basic-vector 'movitz::data))) (:jmp 'return) not-character-vector (:cmpl ,(movitz:basic-vector-type-tag :u8) :ecx) (:jne 'not-u8-vector) code-vector (:testl ,(logxor #xffffffff (* #xff movitz:+movitz-fixnum-factor+)) :eax) (:jne '(:sub-program (not-an-u8) (:compile-form (:result-mode :ignore) (error "Not an (unsigned-byte 8): ~S" value)))) (:shll ,(- 8 movitz:+movitz-fixnum-shift+) :eax) (:movl :edx :ecx) (:shrl ,movitz:+movitz-fixnum-shift+ :ecx) (:movb :ah (:ebx :ecx ,(binary-types:slot-offset 'movitz:movitz-basic-vector 'movitz::data))) (:shrl ,(- 8 movitz:+movitz-fixnum-shift+) :eax) (:jmp 'return) not-u8-vector (:cmpl ,(movitz:basic-vector-type-tag :code) :ecx) (:je 'code-vector) (:cmpl ,(movitz:basic-vector-type-tag :u32) :ecx) (:jne 'not-u32-vector) (:call-local-pf unbox-u32) (:movl :ecx (:ebx :edx ,(binary-types:slot-offset 'movitz:movitz-basic-vector 'movitz::data))) (:jmp 'return) not-u32-vector (:cmpl ,(movitz:basic-vector-type-tag :bit) :ecx) (:jne 'not-bit-vector) (:testl ,(logxor #xffffffff (* #x1 movitz:+movitz-fixnum-factor+)) :eax) (:jne '(:sub-program (not-a-bit) (:compile-form (:result-mode :ignore) (error "Not a bit: ~S" value)))) (:movl :edx :ecx) (:shrl ,movitz:+movitz-fixnum-shift+ :ecx) (:testl :eax :eax) (:jnz 'set-one-bit) (:btrl :ecx (:ebx ,(binary-types:slot-offset 'movitz:movitz-basic-vector 'movitz::data))) (:jmp 'return) set-one-bit (:btsl :ecx (:ebx ,(binary-types:slot-offset 'movitz:movitz-basic-vector 'movitz::data))) (:jmp 'return) not-bit-vector (:compile-form (:result-mode :ignore) (error "Not a vector: ~S" vector)) return) )) (do-it))))) (t (value vector &rest subscripts) (declare (ignore value vector subscripts)) (error "Multi-dimensional arrays not implemented.")))) (define-compiler-macro svref%unsafe (simple-vector index) `(memref ,simple-vector (movitz-type-slot-offset 'movitz-basic-vector 'data) :index ,index)) (define-compiler-macro (setf svref%unsafe) (value simple-vector index) `(setf (memref ,simple-vector (movitz-type-slot-offset 'movitz-basic-vector 'data) :index ,index) ,value)) (defun svref%unsafe (simple-vector index) (with-inline-assembly (:returns :eax) (:compile-two-forms (:eax :ebx) simple-vector index) (:movl (:eax :ebx #.(binary-types:slot-offset 'movitz:movitz-basic-vector 'movitz::data)) :eax))) (defun (setf svref%unsafe) (value simple-vector index) (setf (svref%unsafe simple-vector index) value)) (defun svref (simple-vector index) (macrolet ((do-it () `(with-inline-assembly (:returns :eax) (:compile-two-forms (:eax :ebx) simple-vector index) (:leal (:eax ,(- (movitz::tag :other))) :ecx) (:testb 7 :cl) (:jne '(:sub-program (not-basic-simple-vector) (:compile-form (:result-mode :ignore) (error "Not a simple-vector: ~S." simple-vector)))) (:movl (:eax ,movitz:+other-type-offset+) :ecx) (:testb ,movitz:+movitz-fixnum-zmask+ :bl) (:jnz '(:sub-program (illegal-index) (:compile-form (:result-mode :ignore) (error "Illegal index: ~S." index)))) (:cmpw ,(movitz:basic-vector-type-tag :any-t) :cx) (:jne 'not-basic-simple-vector) (:cmpl :ebx (:eax (:offset movitz-basic-vector num-elements))) (:jbe 'illegal-index) (:movl (:eax :ebx (:offset movitz-basic-vector data)) :eax) ))) (do-it))) (defun (setf svref) (value simple-vector index) (macrolet ((do-it () `(with-inline-assembly (:returns :eax) (:compile-two-forms (:ebx :edx) simple-vector index) (:leal (:ebx ,(- (movitz::tag :other))) :ecx) (:testb 7 :cl) (:jne '(:sub-program (not-basic-simple-vector) (:compile-form (:result-mode :ignore) (error "Not a simple-vector: ~S." simple-vector)))) (:movl (:ebx ,movitz:+other-type-offset+) :ecx) (:testb ,movitz:+movitz-fixnum-zmask+ :dl) (:jnz '(:sub-program (illegal-index) (:compile-form (:result-mode :ignore) (error "Illegal index: ~S." index)))) (:compile-form (:result-mode :eax) value) (:cmpw ,(movitz:basic-vector-type-tag :any-t) :cx) (:jne 'not-basic-simple-vector) (:cmpl :edx (:ebx (:offset movitz-basic-vector num-elements))) (:jbe 'illegal-index) (:movl :eax (:ebx :edx (:offset movitz-basic-vector data)))))) (do-it))) (defun char (string index) (assert (below index (array-dimension string 0))) (etypecase string (simple-string (memref string (movitz-type-slot-offset 'movitz-basic-vector 'data) :index index :type :character)) (string (with-indirect-vector (indirect string) (char (indirect displaced-to) (+ index (indirect displaced-offset))))))) (defun (setf char) (value string index) (assert (below index (array-dimension string 0))) (etypecase string (simple-string (check-type value character) (setf (memref string (movitz-type-slot-offset 'movitz-basic-vector 'data) :index index :type :character) value)) (string (with-indirect-vector (indirect string) (setf (char (indirect displaced-to) (+ index (indirect displaced-offset))) value))))) (defun schar (string index) (check-type string simple-string) (assert (below index (length string))) (memref string (movitz-type-slot-offset 'movitz-basic-vector 'data) :index index :type :character)) (defun (setf schar) (value string index) (check-type string simple-string) (check-type value character) (assert (below index (length string))) (setf (memref string (movitz-type-slot-offset 'movitz-basic-vector 'data) :index index :type :character) value)) (define-compiler-macro char%unsafe (string index) `(memref ,string (movitz-type-slot-offset 'movitz-basic-vector 'data) :index ,index :type :character)) (defun char%unsafe (string index) (char%unsafe string index)) (define-compiler-macro (setf char%unsafe) (value string index) `(setf (memref ,string (movitz-type-slot-offset 'movitz-basic-vector 'data) :index ,index :type :character) ,value)) (defun (setf char%unsafe) (value string index) (setf (char%unsafe string index) value)) (defun bit (array &rest subscripts) (numargs-case (2 (array index) (etypecase array (indirect-vector (with-indirect-vector (indirect array :check-type nil) (aref (indirect displaced-to) (+ index (indirect displaced-offset))))) (simple-bit-vector (macrolet ((do-it () `(with-inline-assembly (:returns :eax) (:compile-two-forms (:eax :ebx) array index) (:testb ,movitz:+movitz-fixnum-zmask+ :bl) (:jnz '(:sub-program (illegal-index) (:compile-form (:result-mode :ignore) (error "Illegal index: ~S." index)))) (:cmpl :ebx (:eax ,(binary-types:slot-offset 'movitz:movitz-basic-vector 'movitz::num-elements))) (:jbe '(:sub-program (out-of-bounds) (:compile-form (:result-mode :ignore) (error "Index ~D is beyond vector length ~D." index (memref array (movitz-type-slot-offset 'movitz-basic-vector 'num-elements)))))) :bit (:movl :ebx :ecx) (:movl :eax :ebx) (:shrl ,movitz:+movitz-fixnum-shift+ :ecx) (:xorl :eax :eax) (:btl :ecx (:ebx ,(binary-types:slot-offset 'movitz:movitz-basic-vector 'movitz::data))) (:jnc 'return) (:addl ,movitz:+movitz-fixnum-factor+ :eax) return))) (do-it))))) (t (vector &rest subscripts) (declare (ignore vector subscripts)) (error "Multi-dimensional arrays not implemented.")))) (defun sbit (array &rest subscripts) (numargs-case (2 (array index) (check-type array simple-bit-vector) (macrolet ((do-it () `(with-inline-assembly (:returns :eax) (:compile-two-forms (:eax :ebx) array index) (:testb ,movitz:+movitz-fixnum-zmask+ :bl) (:jnz '(:sub-program (illegal-index) (:compile-form (:result-mode :ignore) (error "Illegal index: ~S." index)))) (:cmpl :ebx (:eax ,(binary-types:slot-offset 'movitz:movitz-basic-vector 'movitz::num-elements))) (:jbe '(:sub-program (out-of-bounds) (:compile-form (:result-mode :ignore) (error "Index ~D is beyond vector length ~D." index (memref array (movitz-type-slot-offset 'movitz-basic-vector 'num-elements)))))) :bit (:movl :ebx :ecx) (:movl :eax :ebx) (:shrl ,movitz:+movitz-fixnum-shift+ :ecx) (:xorl :eax :eax) (:btl :ecx (:ebx ,(binary-types:slot-offset 'movitz:movitz-basic-vector 'movitz::data))) (:jnc 'return) (:addl ,movitz:+movitz-fixnum-factor+ :eax) return))) (do-it))) (t (vector &rest subscripts) (declare (ignore vector subscripts)) (error "Multi-dimensional arrays not implemented.")))) (defun bitref%unsafe (array index) (macrolet ((do-it () `(with-inline-assembly (:returns :eax) (:compile-two-forms (:eax :ebx) array index) (:testb ,movitz:+movitz-fixnum-zmask+ :bl) (:jnz '(:sub-program (illegal-index) (:compile-form (:result-mode :ignore) (error "Illegal index: ~S." index)))) :bit (:movl :ebx :ecx) (:movl :eax :ebx) (:shrl ,movitz:+movitz-fixnum-shift+ :ecx) (:xorl :eax :eax) (:btl :ecx (:ebx ,(binary-types:slot-offset 'movitz:movitz-basic-vector 'movitz::data))) (:jnc 'return) (:addl ,movitz:+movitz-fixnum-factor+ :eax) return))) (do-it))) (defun (setf bit) (value vector &rest subscripts) (numargs-case (3 (value vector index) (check-type value bit) (etypecase vector (indirect-vector (with-indirect-vector (indirect vector :check-type nil) (setf (aref (indirect displaced-to) (+ index (indirect displaced-offset))) value))) (simple-bit-vector (macrolet ((do-it () `(with-inline-assembly (:returns :eax) (:compile-two-forms (:eax :ebx) value vector) (:compile-form (:result-mode :edx) index) (:testb ,movitz:+movitz-fixnum-zmask+ :dl) (:jnz '(:sub-program (not-an-index) (:compile-form (:result-mode :ignore) (error "Not a vector index: ~S." index)))) (:cmpl (:ebx ,(binary-types:slot-offset 'movitz:movitz-basic-vector 'movitz::num-elements)) :edx) (:jnc '(:sub-program (illegal-index) (:compile-form (:result-mode :ignore) (error "Index ~S out of range." index)))) (:movl :edx :ecx) (:shrl ,movitz:+movitz-fixnum-shift+ :ecx) (:testl :eax :eax) (:jnz 'set-one-bit) (:btrl :ecx (:ebx ,(binary-types:slot-offset 'movitz:movitz-basic-vector 'movitz::data))) (:jmp 'return) set-one-bit (:btsl :ecx (:ebx ,(binary-types:slot-offset 'movitz:movitz-basic-vector 'movitz::data))) return))) (do-it))))) (t (value vector &rest subscripts) (declare (ignore value vector subscripts)) (error "Multi-dimensional arrays not implemented.")))) (defun (setf sbit) (value vector &rest subscripts) (numargs-case (3 (value vector index) (check-type value bit) (macrolet ((do-it () `(with-inline-assembly (:returns :eax) (:compile-two-forms (:eax :ebx) value vector) (:compile-form (:result-mode :edx) index) (:testb ,movitz:+movitz-fixnum-zmask+ :dl) (:jnz '(:sub-program (not-an-index) (:compile-form (:result-mode :ignore) (error "Not a vector index: ~S." index)))) (:cmpl (:ebx ,(binary-types:slot-offset 'movitz:movitz-basic-vector 'movitz::num-elements)) :edx) (:jnc '(:sub-program (illegal-index) (:compile-form (:result-mode :ignore) (error "Index ~S out of range." index)))) (:movl :edx :ecx) (:shrl ,movitz:+movitz-fixnum-shift+ :ecx) (:testl :eax :eax) (:jnz 'set-one-bit) (:btrl :ecx (:ebx ,(binary-types:slot-offset 'movitz:movitz-basic-vector 'movitz::data))) (:jmp 'return) set-one-bit (:btsl :ecx (:ebx ,(binary-types:slot-offset 'movitz:movitz-basic-vector 'movitz::data))) return))) (do-it))) (t (value vector &rest subscripts) (declare (ignore value vector subscripts)) (error "Multi-dimensional arrays not implemented.")))) (defun (setf bitref%unsafe) (value vector index) (macrolet ((do-it () `(progn (check-type value bit) (with-inline-assembly (:returns :eax) (:compile-two-forms (:eax :ebx) value vector) (:compile-form (:result-mode :edx) index) (:testb ,movitz:+movitz-fixnum-zmask+ :dl) (:jnz '(:sub-program (not-an-index) (:compile-form (:result-mode :ignore) (error "Not a vector index: ~S." index)))) (:movl :edx :ecx) (:shrl ,movitz:+movitz-fixnum-shift+ :ecx) (:testl :eax :eax) (:jnz 'set-one-bit) (:btrl :ecx (:ebx ,(binary-types:slot-offset 'movitz:movitz-basic-vector 'movitz::data))) (:jmp 'return) set-one-bit (:btsl :ecx (:ebx ,(binary-types:slot-offset 'movitz:movitz-basic-vector 'movitz::data))) return)))) (do-it))) (define-compiler-macro u8ref%unsafe (vector index) `(memref ,vector (movitz-type-slot-offset 'movitz-basic-vector 'data) :index ,index :type :unsigned-byte8)) (defun u8ref%unsafe (vector index) (u8ref%unsafe vector index)) (define-compiler-macro (setf u8ref%unsafe) (value vector index) `(setf (memref ,vector (movitz-type-slot-offset 'movitz-basic-vector 'data) :index ,index :type :unsigned-byte8) ,value)) (defun (setf u8ref%unsafe) (value vector index) (setf (u8ref%unsafe vector index) value)) u32 accessors (define-compiler-macro u32ref%unsafe (vector index) `(memref ,vector (movitz-type-slot-offset 'movitz-basic-vector 'data) :index ,index :type :unsigned-byte32)) (defun u32ref%unsafe (vector index) (compiler-macro-call u32ref%unsafe vector index)) (define-compiler-macro (setf u32ref%unsafe) (value vector index) (let ((var (gensym "setf-u32ref-value-"))) `(let ((,var ,value)) (setf (memref ,vector 2 :index ,index :type :unsigned-byte32) ,var) ,var))) (defun (setf u32ref%unsafe) (value vector index) (compiler-macro-call (setf u32ref%unsafe) value vector index)) (defun subvector-accessors (vector &optional start end) "Check that vector is a vector, that start and end are within vector's bounds, and return basic-vector and accessors for that subsequence." (when (and start end) (assert (<= 0 start end)) (assert (<= end (array-dimension vector 0)))) (etypecase vector (indirect-vector (with-indirect-vector (indirect vector) (if (= 0 (indirect displaced-offset)) (subvector-accessors (indirect displaced-to) start end) (let ((offset (indirect displaced-offset))) (values vector (lambda (a i) (aref a (+ i offset))) (lambda (v a i) (setf (aref a (+ i offset)) v))))))) (vector (case (vector-element-type-code vector) (#.(binary-types:enum-value 'movitz::movitz-vector-element-type :any-t) (values vector #'svref%unsafe #'(setf svref%unsafe))) (#.(binary-types:enum-value 'movitz::movitz-vector-element-type :character) (values vector #'char%unsafe #'(setf char%unsafe))) (#.(binary-types:enum-value 'movitz::movitz-vector-element-type :u8) (values vector #'u8ref%unsafe #'(setf u8ref%unsafe))) (#.(binary-types:enum-value 'movitz::movitz-vector-element-type :u32) (values vector #'u32ref%unsafe #'(setf u32ref%unsafe))) (#.(binary-types:enum-value 'movitz::movitz-vector-element-type :code) (values vector #'u8ref%unsafe #'(setf u8ref%unsafe))) (#.(binary-types:enum-value 'movitz::movitz-vector-element-type :bit) (values vector #'bitref%unsafe #'(setf bitref%unsafe))) (t (warn "don't know about vector's element-type: ~S" vector) (values vector #'aref #'(setf aref))))))) (defmacro with-subvector-accessor ((name vector-form &optional start end) &body body) "Installs name as an accessor into vector-form, bound by start and end." (let ((reader (gensym "sub-vector-reader-")) (writer (gensym "sub-vector-writer-")) (vector (gensym "sub-vector-"))) `(multiple-value-bind (,vector ,reader ,writer) (subvector-accessors ,vector-form ,start ,end) (declare (ignorable ,reader ,writer)) (macrolet ((,name (index) `(accessor%unsafe (,',reader ,',writer) ,',vector ,index))) ,@body)))) (defmacro accessor%unsafe ((reader writer) &rest args) (declare (ignore writer)) `(funcall%unsafe ,reader ,@args)) (define-setf-expander accessor%unsafe ((reader writer) &rest args) (let ((store-var (gensym "accessor%unsafe-store-"))) (values nil nil (list store-var) `(funcall%unsafe ,writer ,store-var ,@args) `(funcall%unsafe ,reader ,@args)))) (defun make-basic-vector%character (length fill-pointer initial-element initial-contents) (check-type length (and fixnum (integer 0 *))) (let* ((words (+ 2 (truncate (+ length 3) 4))) (array (macrolet ((do-it () `(with-non-pointer-allocation-assembly (words :fixed-size-p t :object-register :eax) (:load-lexical (:lexical-binding length) :ecx) (:movl ,(movitz:basic-vector-type-tag :character) (:eax (:offset movitz-basic-vector type))) (:movl :ecx (:eax (:offset movitz-basic-vector num-elements)))))) (do-it)))) (cond ((integerp fill-pointer) (setf (fill-pointer array) fill-pointer)) ((or (eq t fill-pointer) (array-has-fill-pointer-p array)) (setf (fill-pointer array) length))) (cond (initial-element (check-type initial-element character) (dotimes (i length) (setf (char array i) initial-element))) (initial-contents (replace array initial-contents))) array)) (defun make-basic-vector%u32 (length fill-pointer initial-element initial-contents) (check-type length (and fixnum (integer 0 *))) (let* ((words (+ 2 length)) (array (macrolet ((do-it () `(with-non-pointer-allocation-assembly (words :fixed-size-p t :object-register :eax) (:load-lexical (:lexical-binding length) :ecx) (:movl ,(movitz:basic-vector-type-tag :u32) (:eax (:offset movitz-basic-vector type))) (:movl :ecx (:eax (:offset movitz-basic-vector num-elements)))))) (do-it)))) (cond ((integerp fill-pointer) (setf (fill-pointer array) fill-pointer)) ((or (eq t fill-pointer) (array-has-fill-pointer-p array)) (setf (fill-pointer array) length))) (cond (initial-element (check-type initial-element (unsigned-byte 32)) (dotimes (i length) (setf (u32ref%unsafe array i) initial-element))) (initial-contents (replace array initial-contents))) array)) (defun make-stack-vector (length) (let ((vector (make-basic-vector%u32 length nil nil nil))) (with-inline-assembly (:returns :nothing) (:load-lexical (:lexical-binding vector) :eax) (:movl #.(movitz:basic-vector-type-tag :stack) (:eax (:offset movitz-basic-vector type)))) (when (%basic-vector-has-fill-pointer-p vector) (setf (fill-pointer vector) length)) vector)) (defun make-basic-vector%u8 (length fill-pointer initial-element initial-contents) (check-type length (and fixnum (integer 0 *))) (let* ((words (+ 2 (truncate (+ length 3) 4))) (array (macrolet ((do-it () `(with-non-pointer-allocation-assembly (words :fixed-size-p t :object-register :eax) (:load-lexical (:lexical-binding length) :ecx) (:movl ,(movitz:basic-vector-type-tag :u8) (:eax (:offset movitz-basic-vector type))) (:movl :ecx (:eax (:offset movitz-basic-vector num-elements)))))) (do-it)))) (cond ((integerp fill-pointer) (setf (fill-pointer array) fill-pointer)) ((or (eq t fill-pointer) (array-has-fill-pointer-p array)) (setf (fill-pointer array) length))) (cond (initial-element (check-type initial-element (unsigned-byte 8)) (dotimes (i length) (setf (u8ref%unsafe array i) initial-element))) (initial-contents (replace array initial-contents))) array)) (defun make-basic-vector%bit (length fill-pointer initial-element initial-contents) (check-type length (and fixnum (integer 0 *))) (let* ((words (+ 2 (truncate (+ length 31) 32))) (array (macrolet ((do-it () `(with-non-pointer-allocation-assembly (words :fixed-size-p t :object-register :eax) (:load-lexical (:lexical-binding length) :ecx) (:movl ,(movitz:basic-vector-type-tag :bit) (:eax (:offset movitz-basic-vector type))) (:movl :ecx (:eax (:offset movitz-basic-vector num-elements)))))) (do-it)))) (cond ((integerp fill-pointer) (setf (fill-pointer array) fill-pointer)) ((or (eq t fill-pointer) (array-has-fill-pointer-p array)) (setf (fill-pointer array) length))) (cond (initial-element (check-type initial-element bit) (dotimes (i length) (setf (aref array i) initial-element))) (initial-contents (replace array initial-contents))) array)) (defun make-basic-vector%code (length fill-pointer initial-element initial-contents) (check-type length (and fixnum (integer 0 *))) (let* ((words (+ 2 (truncate (+ length 3) 4))) (array (macrolet ((do-it () `(with-non-pointer-allocation-assembly (words :fixed-size-p t :object-register :eax) (:load-lexical (:lexical-binding length) :ecx) (:movl ,(movitz:basic-vector-type-tag :code) (:eax (:offset movitz-basic-vector type))) (:movl :ecx (:eax (:offset movitz-basic-vector num-elements)))))) (do-it)))) (cond ((integerp fill-pointer) (setf (fill-pointer array) fill-pointer)) ((or (eq t fill-pointer) (array-has-fill-pointer-p array)) (setf (fill-pointer array) length))) (cond (initial-element (check-type initial-element (unsigned-byte 8)) (dotimes (i length) (setf (u8ref%unsafe array i) initial-element))) (initial-contents (replace array initial-contents))) array)) (defun make-basic-vector%t (length fill-pointer initial-element initial-contents) (check-type length (and fixnum (integer 0 *))) (let* ((words (+ 2 length))) (cond ((<= length 8) (let ((array (macrolet ((do-it () `(with-allocation-assembly (words :fixed-size-p t :object-register :eax) (:load-lexical (:lexical-binding length) :ecx) (:movl ,(movitz:basic-vector-type-tag :any-t) (:eax (:offset movitz-basic-vector type))) (:movl :ecx (:eax (:offset movitz-basic-vector num-elements))) (:addl 4 :ecx) (:andl -8 :ecx) (:jz 'init-done) (:load-lexical (:lexical-binding initial-element) :edx) init-loop (:movl :edx (:eax (:offset movitz-basic-vector data) :ecx -4)) (:subl 4 :ecx) (:jnz 'init-loop) init-done ))) (do-it)))) (cond ((integerp fill-pointer) (setf (fill-pointer array) fill-pointer)) ((or (eq t fill-pointer) (array-has-fill-pointer-p array)) (setf (fill-pointer array) length))) (when initial-contents (replace array initial-contents)) array)) (t (let* ((init-word (if (typep initial-element '(or null fixnum character)) initial-element nil)) (array (macrolet ((do-it () `(with-inline-assembly (:returns :eax) (:compile-form (:result-mode :eax) (with-non-pointer-allocation-assembly (words :fixed-size-p t :object-register :eax) (:load-lexical (:lexical-binding length) :ecx) (:movl ,(movitz:basic-vector-type-tag :u32) (:eax (:offset movitz-basic-vector type))) (:movl :ecx (:eax (:offset movitz-basic-vector num-elements))))) (:load-lexical (:lexical-binding length) :ecx) (:addl 4 :ecx) (:andl -8 :ecx) (:jz 'init-done2) (:load-lexical (:lexical-binding init-word) :edx) init-loop2 (:movl :edx (:eax (:offset movitz-basic-vector data) :ecx -4)) (:subl 4 :ecx) (:jnz 'init-loop2) init-done2 (:movl ,(movitz:basic-vector-type-tag :any-t) (:eax (:offset movitz-basic-vector type)))))) (do-it)))) (cond ((integerp fill-pointer) (setf (fill-pointer array) fill-pointer)) ((or (eq t fill-pointer) (array-has-fill-pointer-p array)) (setf (fill-pointer array) length))) (cond (initial-contents (replace array initial-contents)) ((not (eq init-word initial-element)) (fill array initial-element))) array))))) (defun make-indirect-vector (displaced-to displaced-offset fill-pointer length) (let ((x (make-basic-vector%t 4 0 nil nil))) (setf (vector-element-type-code x) #.(binary-types:enum-value 'movitz::movitz-vector-element-type :indirects)) (set-indirect-vector x displaced-to displaced-offset (vector-element-type-code displaced-to) fill-pointer length))) (defun set-indirect-vector (x displaced-to displaced-offset et-code fill-pointer length) (check-type displaced-to vector) (let ((displaced-offset (or displaced-offset 0))) (assert (<= (+ displaced-offset length) (length displaced-to)) () "Displaced-to is outside legal range.") (setf (memref x (movitz-type-slot-offset 'movitz-basic-vector 'fill-pointer) :index 1 :type :unsigned-byte8) et-code) (with-indirect-vector (indirect x) (setf (indirect displaced-to) displaced-to (indirect displaced-offset) displaced-offset (indirect fill-pointer) (etypecase fill-pointer ((eql nil) length) ((eql t) length) ((integer 0 *) fill-pointer)) (indirect length) length)) x)) (defun make-basic-vector (size element-type fill-pointer initial-element initial-contents) (let ((upgraded-element-type (upgraded-array-element-type element-type))) (cond These should be replaced by subtypep sometime . ((eq upgraded-element-type 'character) (make-basic-vector%character size fill-pointer initial-element initial-contents)) ((eq upgraded-element-type 'bit) (make-basic-vector%bit size fill-pointer initial-element initial-contents)) ((member upgraded-element-type '(u8 (unsigned-byte 8)) :test #'equal) (make-basic-vector%u8 size fill-pointer initial-element initial-contents)) ((member upgraded-element-type '(u32 (unsigned-byte 32)) :test #'equal) (make-basic-vector%u32 size fill-pointer initial-element initial-contents)) ((eq upgraded-element-type 'code) (make-basic-vector%code size fill-pointer initial-element initial-contents)) (t (make-basic-vector%t size fill-pointer initial-element initial-contents))))) (defun make-array (dimensions &key (element-type t) initial-element initial-contents adjustable fill-pointer displaced-to displaced-index-offset) (let ((size (cond ((integerp dimensions) dimensions) ((and (consp dimensions) (null (cdr dimensions))) (car dimensions)) (t (warn "Array of rank ~D not supported." (length dimensions)) (cond (displaced-to (make-indirect-vector displaced-to displaced-index-offset fill-pointer size)) ((or adjustable (and fill-pointer (not (typep size '(unsigned-byte 14))))) (make-indirect-vector (make-basic-vector size element-type nil initial-element initial-contents) 0 fill-pointer size)) (t (make-basic-vector size element-type fill-pointer initial-element initial-contents))))) (defun adjust-array (array new-dimensions &key element-type (initial-element nil initial-element-p) initial-contents fill-pointer displaced-to displaced-index-offset) (etypecase array (indirect-vector (let ((new-length (cond ((integerp new-dimensions) new-dimensions) ((and (consp new-dimensions) (null (cdr new-dimensions))) (car new-dimensions)) (t (error "Multi-dimensional arrays not supported."))))) (with-indirect-vector (indirect array) (cond (displaced-to (check-type displaced-to vector) (set-indirect-vector array displaced-to displaced-index-offset (vector-element-type-code array) (case fill-pointer ((nil) (indirect fill-pointer)) ((t) new-length) (t fill-pointer)) new-length)) ((and (= 0 (indirect displaced-offset)) (/= new-length (array-dimension array 0))) (let* ((old (indirect displaced-to)) (new (make-array new-length :element-type (array-element-type old)))) (dotimes (i (array-dimension old 0)) (setf (aref new i) (aref old i))) (when initial-element-p (fill new initial-element :start (array-dimension old 0))) (setf (indirect displaced-to) new (indirect length) new-length) (when fill-pointer (setf (fill-pointer array) fill-pointer)))) (t (error "Sorry, don't know how to adjust ~S." array))))) array) (vector (let ((new-length (cond ((integerp new-dimensions) new-dimensions) ((and (consp new-dimensions) (null (cdr new-dimensions))) (car new-dimensions)) (t (error "Multi-dimensional arrays not supported."))))) (let ((new (if (= (array-dimension array 0) new-length) array (let* ((old array) (new (make-array new-length :element-type (array-element-type old)))) (dotimes (i (array-dimension old 0)) (setf (aref new i) (aref old i))) (when initial-element-p (fill new initial-element :start (array-dimension old 0))) new)))) (case fill-pointer ((nil)) ((t) (setf (fill-pointer new) new-length)) (t (setf (fill-pointer new) fill-pointer))) new))))) (defun adjustable-array-p (array) (typep array 'indirect-vector)) (defun vector (&rest objects) "=> vector" (declare (dynamic-extent objects)) (let* ((length (length objects)) (vector (make-array length))) (do ((i 0 (1+ i)) (p objects (cdr p))) ((endp p)) (setf (svref vector i) (car p))) vector)) (defun vector-push (new-element vector) (check-type vector vector) (let ((p (fill-pointer vector))) (declare (index p)) (when (< p (array-dimension vector 0)) (setf (aref vector p) new-element (fill-pointer vector) (1+ p)) p))) (defun vector-pop (vector) (let ((p (1- (fill-pointer vector)))) (assert (not (minusp p))) (setf (fill-pointer vector) p) (aref vector p))) (defun vector-read (vector) "Like vector-pop, only in the other direction." (let ((x (aref vector (fill-pointer vector)))) (incf (fill-pointer vector)) x)) (defun vector-read-more-p (vector) (< (fill-pointer vector) (array-dimension vector 0))) (defun vector-push-extend (new-element vector &optional extension) (check-type vector vector) (let ((p (fill-pointer vector))) (cond ((< p (array-dimension vector 0)) (setf (aref vector p) new-element (fill-pointer vector) (1+ p))) ((not (adjustable-array-p vector)) (error "Can't extend non-adjustable array.")) (t (adjust-array vector (+ (array-dimension vector 0) (or extension (max 1 (array-dimension vector 0)))) :fill-pointer (1+ p)) (setf (aref vector p) new-element))) p)) (define-compiler-macro bvref-u16 (&whole form vector offset index &environment env) (let ((actual-index (and (movitz:movitz-constantp index env) (movitz:movitz-eval index env)))) (if (not (typep actual-index '(integer 0 *))) `(bvref-u16-fallback ,vector ,offset ,index) (let ((var (gensym))) `(let ((,var ,vector)) (if (not (typep ,var 'vector-u8)) (bvref-u16-fallback ,var ,offset ,index) (with-inline-assembly (:returns :untagged-fixnum-ecx) (:compile-two-forms (:eax :ecx) ,var ,offset) (:cmpl (:eax ,(binary-types:slot-offset 'movitz::movitz-basic-vector 'movitz::num-elements)) :ecx) (:jnc '(:sub-program () (:int 69))) (:shrl ,movitz::+movitz-fixnum-shift+ :ecx) (:movw (:eax :ecx ,(+ actual-index (binary-types:slot-offset 'movitz::movitz-basic-vector 'movitz::data))) :cx) (:xchgb :cl :ch)))))))) (defun bvref-u16-fallback (vector offset index) (logior (ash (aref vector (+ index offset)) 8) (aref vector (+ index offset)))) (defun bvref-u16 (vector offset index) "View <vector> as an sequence of octets, access the big-endian 16-bit word at position <index> + <offset>." (bvref-u16 vector offset index)) (defun ensure-data-vector (vector start length) (let ((end (typecase vector ((simple-array (unsigned-byte 8) 1) (array-dimension vector 0)) (t (error "Not a data vector: ~S" vector))))) (assert (<= (+ start length) end) (vector) "Data vector too small.") vector))
71ddaf942b7d50dc62aded13c247649f381bd186bf1a2bc52382666be5197ee6
clojure-lsp/clojure-lsp
settings.clj
(ns clojure-lsp.settings (:refer-clojure :exclude [get]) (:require [clojure-lsp.config :as config] [clojure.core.memoize :as memoize] [clojure.string :as string] [clojure.walk :as walk] [medley.core :as medley])) (set! *warn-on-reflection* true) (defn- typify-json [root] (walk/postwalk (fn [n] (if (string? n) (keyword n) n)) root)) (defn- clean-symbol-map [m] (->> (or m {}) (medley/map-keys #(if (string/starts-with? % "#") (re-pattern (subs % 1)) (symbol %))) (medley/map-vals typify-json))) (defn- clean-keys-map [m] (->> (or m {}) ;; (medley/map-keys keyword) (medley/map-vals typify-json))) (defn parse-source-paths [paths] (when (seq paths) (->> paths (keep #(when (string? %) (if (string/starts-with? % ":") (subs % 1) %))) (into #{}) (not-empty)))) (defn kwd-string [s] (cond (keyword? s) s (and (string? s) (string/starts-with? s ":")) (keyword (subs s 1)) (string? s) (keyword s))) (defn parse-source-aliases [aliases] (when (seq aliases) (->> aliases (keep kwd-string) (into #{}) (not-empty)))) (defn clean-client-settings [client-settings] (-> client-settings (update :dependency-scheme #(or % "zipfile")) (update :text-document-sync-kind kwd-string) (update :source-paths parse-source-paths) (update :source-aliases parse-source-aliases) (update :cljfmt-config-path #(or % ".cljfmt.edn")) (medley/update-existing-in [:cljfmt :indents] clean-symbol-map) (medley/update-existing-in [:linters] clean-keys-map) (update :document-formatting? (fnil identity true)) (update :document-range-formatting? (fnil identity true)))) (defn ^:private get-refreshed-settings [project-root-uri settings force-settings] (let [new-project-settings (config/resolve-for-root project-root-uri)] (config/deep-merge-fixing-cljfmt settings new-project-settings force-settings))) (def ttl-threshold-milis 1000) (def ^:private memoized-settings (memoize/ttl get-refreshed-settings :ttl/threshold ttl-threshold-milis)) (defn all "Get memoized settings from db. Refreshes settings if memoize threshold met." [{:keys [settings-auto-refresh? env project-root-uri settings force-settings]}] (if (or (not settings-auto-refresh?) (#{:unit-test :api-test} env)) (get-refreshed-settings project-root-uri settings force-settings) (memoized-settings project-root-uri settings force-settings))) (defn get ([db kws] (get db kws nil)) ([db kws default] (get-in (all db) kws default)))
null
https://raw.githubusercontent.com/clojure-lsp/clojure-lsp/01500c34e00efa2b4affc627bdc80e89af18f55d/lib/src/clojure_lsp/settings.clj
clojure
(medley/map-keys keyword)
(ns clojure-lsp.settings (:refer-clojure :exclude [get]) (:require [clojure-lsp.config :as config] [clojure.core.memoize :as memoize] [clojure.string :as string] [clojure.walk :as walk] [medley.core :as medley])) (set! *warn-on-reflection* true) (defn- typify-json [root] (walk/postwalk (fn [n] (if (string? n) (keyword n) n)) root)) (defn- clean-symbol-map [m] (->> (or m {}) (medley/map-keys #(if (string/starts-with? % "#") (re-pattern (subs % 1)) (symbol %))) (medley/map-vals typify-json))) (defn- clean-keys-map [m] (->> (or m {}) (medley/map-vals typify-json))) (defn parse-source-paths [paths] (when (seq paths) (->> paths (keep #(when (string? %) (if (string/starts-with? % ":") (subs % 1) %))) (into #{}) (not-empty)))) (defn kwd-string [s] (cond (keyword? s) s (and (string? s) (string/starts-with? s ":")) (keyword (subs s 1)) (string? s) (keyword s))) (defn parse-source-aliases [aliases] (when (seq aliases) (->> aliases (keep kwd-string) (into #{}) (not-empty)))) (defn clean-client-settings [client-settings] (-> client-settings (update :dependency-scheme #(or % "zipfile")) (update :text-document-sync-kind kwd-string) (update :source-paths parse-source-paths) (update :source-aliases parse-source-aliases) (update :cljfmt-config-path #(or % ".cljfmt.edn")) (medley/update-existing-in [:cljfmt :indents] clean-symbol-map) (medley/update-existing-in [:linters] clean-keys-map) (update :document-formatting? (fnil identity true)) (update :document-range-formatting? (fnil identity true)))) (defn ^:private get-refreshed-settings [project-root-uri settings force-settings] (let [new-project-settings (config/resolve-for-root project-root-uri)] (config/deep-merge-fixing-cljfmt settings new-project-settings force-settings))) (def ttl-threshold-milis 1000) (def ^:private memoized-settings (memoize/ttl get-refreshed-settings :ttl/threshold ttl-threshold-milis)) (defn all "Get memoized settings from db. Refreshes settings if memoize threshold met." [{:keys [settings-auto-refresh? env project-root-uri settings force-settings]}] (if (or (not settings-auto-refresh?) (#{:unit-test :api-test} env)) (get-refreshed-settings project-root-uri settings force-settings) (memoized-settings project-root-uri settings force-settings))) (defn get ([db kws] (get db kws nil)) ([db kws default] (get-in (all db) kws default)))
6556d074ba0f714f34881ce5ceeb78b1f17b48ebb014c8fe1347139e0554b881
danehuang/augurv2
TcLow.hs
- Copyright 2017 under the Apache License , Version 2.0 ( the " License " ) ; - you may not use this file except in compliance with the License . - You may obtain a copy of the License at - - -2.0 - - Unless required by applicable law or agreed to in writing , software - distributed under the License is distributed on an " AS IS " BASIS , - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . - See the License for the specific language governing permissions and - limitations under the License . - Copyright 2017 Daniel Eachern Huang - - 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. -} # LANGUAGE FlexibleContexts # module Low.TcLow ( mkInferCtxCtx , runTcStmt , runTcDecl ) where import Control.Monad.Reader import Control.Monad.State import Control.Monad.Except import qualified Data.Map as Map import Data.Maybe import qualified Data.Traversable as T import Debug.Trace import AstUtil.Pretty import AstUtil.Var import Comm.DistSyn import Comm.Prim import Core.CoreSyn import Low.LowSyn import Core.CoreTySyn import Low.LowpPrimSyn as P ---------------------------------------------------------------------- -- = TcLow Description {-| [Note] Contains type inference for Low programs. -} ----------------------------------- -- == Types and operations type TcM b = ExceptT String (StateT (Map.Map b Typ) IO) ----------------------------------- -- == Unification unify :: (Typ, Typ) -> TcM b Typ unify (UnitTy, UnitTy) = return UnitTy unify (IntTy, IntTy) = return IntTy unify (RealTy, RealTy) = return RealTy unify (VecTy t1, VecTy t2) = do t <- unify (t1, t2) return $ VecTy t unify (MatTy t1, MatTy t2) = do t <- unify (t1, t2) return $ MatTy t unify (ArrTy ts1 t1, ArrTy ts2 t2) = do ts <- mapM unify (zip ts1 ts2) t <- unify (t1, t2) return $ ArrTy ts t unify (t1, t2) = throwError $ "[TcLow] @unify | Failed to unify " ++ pprShow t1 ++ " with " ++ pprShow t2 unifyOverload :: [Typ] -> Typ -> TcM b Typ unifyOverload ts t2 = go ts where go (t1:tl) = catchError (unify (t1, t2)) (\_ -> go tl) go [] = throwError $ "[TcLow] @unifyOverload | None of the overloaded types unify: " ++ rendSepBy commasp ts unifyOverload2 :: [Typ] -> [Typ] -> TcM b Typ unifyOverload2 ts1 ts2 = case ts2 of [] -> throwError $ "[TcLow] @unifyOverload2 | None of the overloaded types unify." t2:tl2 -> catchError (unifyOverload ts1 t2) (\_ -> unifyOverload2 ts1 tl2) ----------------------------------- = = projRetTy :: Typ -> [Typ] -> TcM b Typ projRetTy t ts | length ts > 0 = case t of VecTy t' -> projRetTy t' (tail ts) MatTy t' -> projRetTy (VecTy t') (tail ts) _ -> throwError $ "[TcLow] @projRetTy | Cannot project: " ++ pprShow t | otherwise = return t tcExp :: (TypedVar b Typ) => Exp b -> TcM b Typ tcExp (Var x) = do tyCtx <- get case Map.lookup x tyCtx of Just ti -> return ti Nothing -> throwError $ "[TcLow] @tcExp | Lookup of variable " ++ pprShow x ++ " failed in ctx: " ++ pprShow tyCtx tcExp (Lit lit) = case lit of Int _ -> return IntTy Real _ -> return RealTy tcExp (DistOp dop dm Dirac es) = do ts <- mapM tcExp es return $ ts !! 0 tcExp (DistOp dop dm dist es) = do ts <- mapM tcExp es let ts' = map injCommTy (distArgTys' dop dm dist) case dop of Conj _ _ -> -- TODO: HACK?? return $ injCommTy (distRetTy' dop dm dist) _ -> do when (length ts /= length ts') (throwError $ "[TcLow] @tcExp | Could not match argument types " ++ rendSepBy commasp ts ++ " with expected types " ++ rendSepBy commasp ts' ++ " when checking " ++ pprShow (DistOp dop dm dist es)) mapM_ unify (zip ts ts') return $ injCommTy (distRetTy' dop dm dist) tcExp (Call ce es) = case ce of FnId fn -> error $ "[TcLow] @tcExp | FnId currently not supported: " ++ pprShow fn PrimId dm pm prim -> do ts <- mapM tcExp es let -- t = ArrTy ts (getRetTy pm prim) arrTys = mkOverloadTys ts (getPrimRetTys dm pm prim) traceM $ "[TcLow] | Checking " ++ pprShow (Call ce es) ++ " with expected type " ++ pprShowLs (getPrimTy dm pm prim) ++ " with actual type " ++ pprShowLs arrTys t <- unifyOverload2 (getPrimTy dm pm prim) arrTys return $ arrRetTy t tcExp (Proj e es) = do t <- tcExp e ts <- mapM tcExp es projRetTy t ts tcGen :: (TypedVar b Typ) => Gen b -> TcM b () tcGen (Until e1 e2) = do t1 <- tcExp e1 t2 <- tcExp e2 _ <- unify (t1, IntTy) _ <- unify (t2, IntTy) return () tcStmt :: (TypedVar b Typ) => Stmt b -> TcM b () tcStmt Skip = return () tcStmt (Exp e) = do traceM $ "[TcLow] @tcStmt | Checking: " ++ pprShow (Exp e) Enforce unit ? return () traceM $ "[TcLow] @tcStmt | Done Checking: " ++ pprShow (Exp e) tcStmt (Assign x e) = do traceM $ "[TcLow] @tcStmt | Checking: " ++ pprShow (Assign x e) t <- tcExp e modify (\tyCtx -> Map.insert x t tyCtx) traceM $ "[TcLow] @tcStmt | Done Checking: " ++ pprShow (Assign x e) tcStmt (Store x es uk e) = do traceM $ "[TcLow] @tcStmt | Checking: " ++ pprShow (Store x es uk e) ts <- mapM tcExp es mapM_ (\t -> unify (t, IntTy)) ts t <- tcExp e tyCtx <- get case Map.lookup x tyCtx of Just t' -> do baseTy <- projRetTy t' ts _ <- unify (baseTy, t) return () Nothing -> throwError $ "[TcLow] @tcStmt | Lookup of " ++ pprShow x ++ " failed in " ++ pprShow tyCtx tcStmt (Seq s1 s2) = do tcStmt s1 tcStmt s2 tcStmt (If e s1 s2) = do traceM $ "[TcLow] @tcStmt | Checking IF: " ++ pprShow (If e s1 s2) t <- tcExp e _ <- unify (t, IntTy) tcStmt s1 tcStmt s2 traceM $ "[TcLow] @tcStmt | Done Checking IF: " ++ pprShow (If e s1 s2) tcStmt (Loop lk x gen s) = do traceM $ "[TcLow] @tcStmt | Checking LOOP: " ++ pprShow (Loop lk x gen s) tcGen gen traceM $ "[TcLow] @tcStmt | Done Checking LOOP gen: " ++ pprShow gen modify (\tyCtx' -> Map.insert x IntTy tyCtx') tcStmt s traceM $ "[TcLow] @tcStmt | Done Checking LOOP: " ++ pprShow (Loop lk x gen s) tcStmt (MapRed acc x gen s e) = do tcGen gen modify (\tyCtx' -> Map.insert x IntTy tyCtx') tcStmt s t <- tcExp e modify (\tyCtx' -> Map.insert acc t tyCtx') tcDecl :: (TypedVar b Typ) => Decl b -> TcM b () tcDecl (Fun _ params allocs body retExp retTy) = do let -- Check parameter types match? paramTyM = Map.fromList params allocTyM = Map.fromList (map (\x -> (x, getType' x)) allocs) modify (\ctx -> ctx `Map.union` paramTyM `Map.union` allocTyM) tcStmt body retTy' <- case retExp of Just e -> tcExp e Nothing -> return UnitTy _ <- unify (retTy, retTy') return () ----------------------------------- -- == Instantiate instTyp :: (TypedVar b Typ) => Map.Map b Typ -> b -> ExceptT String IO b instTyp tyCtx x = case Map.lookup x tyCtx of Just t -> return $ setType x t Nothing -> throwError $ "[TcLow] @instTyp | Lookup of " ++ pprShow x ++ " failed in context: " ++ pprShow tyCtx instStmt :: (TypedVar b Typ) => Map.Map b Typ -> Stmt b -> ExceptT String IO (Stmt b) instStmt tyCtx = T.traverse (instTyp tyCtx) instDecl :: (TypedVar b Typ) => Map.Map b Typ -> Decl b -> ExceptT String IO (Decl b) instDecl tyCtx = T.traverse (instTyp tyCtx) ----------------------------------- -- == Top-level mkInferCtxCtx :: (TypedVar b Typ) => InferCtx b -> Map.Map b Typ mkInferCtxCtx inferCtx = let modDecls = ic_modDecls inferCtx dupCtx = ic_dupCtx inferCtx modDeclsCtx = Map.fromList (map (\(_, x, ty) -> (x, ty)) modDecls) dupCtxCtx = Map.fromList (map (\v -> (fromJust (Map.lookup v dupCtx), getType' v)) (getModParamIds modDecls)) shpCtx = Map.singleton (getIdxVar inferCtx) (VecTy IntTy) in modDeclsCtx `Map.union` dupCtxCtx `Map.union` shpCtx runTcStmt :: (TypedVar b Typ) => InferCtx b -> Map.Map b Typ -> Stmt b -> IO (Either String (Stmt b)) runTcStmt inferCtx ctx s = do let ctx' = mkInferCtxCtx inferCtx ctx'' = ctx `Map.union` ctx' (v, tyCtx) <- runStateT (runExceptT (tcStmt s)) ctx'' case v of Left errMsg -> return $ Left errMsg Right _ -> runExceptT (instStmt tyCtx s) runTcDecl :: (TypedVar b Typ) => InferCtx b -> Decl b -> IO (Either String (Decl b)) runTcDecl inferCtx decl = do let ctx = mkInferCtxCtx inferCtx traceM $ "[TC] | DECL: \n" ++ pprShow decl (v, tyCtx) <- runStateT (runExceptT (tcDecl decl)) ctx traceM $ "END OF TC" ++ pprShow tyCtx case v of Left errMsg -> return $ Left errMsg Right _ -> runExceptT (instDecl tyCtx decl)
null
https://raw.githubusercontent.com/danehuang/augurv2/480459bcc2eff898370a4e1b4f92b08ea3ab3f7b/compiler/augur/src/Low/TcLow.hs
haskell
-------------------------------------------------------------------- = TcLow Description | [Note] Contains type inference for Low programs. --------------------------------- == Types and operations --------------------------------- == Unification --------------------------------- TODO: HACK?? t = ArrTy ts (getRetTy pm prim) Check parameter types match? --------------------------------- == Instantiate --------------------------------- == Top-level
- Copyright 2017 under the Apache License , Version 2.0 ( the " License " ) ; - you may not use this file except in compliance with the License . - You may obtain a copy of the License at - - -2.0 - - Unless required by applicable law or agreed to in writing , software - distributed under the License is distributed on an " AS IS " BASIS , - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . - See the License for the specific language governing permissions and - limitations under the License . - Copyright 2017 Daniel Eachern Huang - - 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. -} # LANGUAGE FlexibleContexts # module Low.TcLow ( mkInferCtxCtx , runTcStmt , runTcDecl ) where import Control.Monad.Reader import Control.Monad.State import Control.Monad.Except import qualified Data.Map as Map import Data.Maybe import qualified Data.Traversable as T import Debug.Trace import AstUtil.Pretty import AstUtil.Var import Comm.DistSyn import Comm.Prim import Core.CoreSyn import Low.LowSyn import Core.CoreTySyn import Low.LowpPrimSyn as P type TcM b = ExceptT String (StateT (Map.Map b Typ) IO) unify :: (Typ, Typ) -> TcM b Typ unify (UnitTy, UnitTy) = return UnitTy unify (IntTy, IntTy) = return IntTy unify (RealTy, RealTy) = return RealTy unify (VecTy t1, VecTy t2) = do t <- unify (t1, t2) return $ VecTy t unify (MatTy t1, MatTy t2) = do t <- unify (t1, t2) return $ MatTy t unify (ArrTy ts1 t1, ArrTy ts2 t2) = do ts <- mapM unify (zip ts1 ts2) t <- unify (t1, t2) return $ ArrTy ts t unify (t1, t2) = throwError $ "[TcLow] @unify | Failed to unify " ++ pprShow t1 ++ " with " ++ pprShow t2 unifyOverload :: [Typ] -> Typ -> TcM b Typ unifyOverload ts t2 = go ts where go (t1:tl) = catchError (unify (t1, t2)) (\_ -> go tl) go [] = throwError $ "[TcLow] @unifyOverload | None of the overloaded types unify: " ++ rendSepBy commasp ts unifyOverload2 :: [Typ] -> [Typ] -> TcM b Typ unifyOverload2 ts1 ts2 = case ts2 of [] -> throwError $ "[TcLow] @unifyOverload2 | None of the overloaded types unify." t2:tl2 -> catchError (unifyOverload ts1 t2) (\_ -> unifyOverload2 ts1 tl2) = = projRetTy :: Typ -> [Typ] -> TcM b Typ projRetTy t ts | length ts > 0 = case t of VecTy t' -> projRetTy t' (tail ts) MatTy t' -> projRetTy (VecTy t') (tail ts) _ -> throwError $ "[TcLow] @projRetTy | Cannot project: " ++ pprShow t | otherwise = return t tcExp :: (TypedVar b Typ) => Exp b -> TcM b Typ tcExp (Var x) = do tyCtx <- get case Map.lookup x tyCtx of Just ti -> return ti Nothing -> throwError $ "[TcLow] @tcExp | Lookup of variable " ++ pprShow x ++ " failed in ctx: " ++ pprShow tyCtx tcExp (Lit lit) = case lit of Int _ -> return IntTy Real _ -> return RealTy tcExp (DistOp dop dm Dirac es) = do ts <- mapM tcExp es return $ ts !! 0 tcExp (DistOp dop dm dist es) = do ts <- mapM tcExp es let ts' = map injCommTy (distArgTys' dop dm dist) case dop of Conj _ _ -> return $ injCommTy (distRetTy' dop dm dist) _ -> do when (length ts /= length ts') (throwError $ "[TcLow] @tcExp | Could not match argument types " ++ rendSepBy commasp ts ++ " with expected types " ++ rendSepBy commasp ts' ++ " when checking " ++ pprShow (DistOp dop dm dist es)) mapM_ unify (zip ts ts') return $ injCommTy (distRetTy' dop dm dist) tcExp (Call ce es) = case ce of FnId fn -> error $ "[TcLow] @tcExp | FnId currently not supported: " ++ pprShow fn PrimId dm pm prim -> do ts <- mapM tcExp es arrTys = mkOverloadTys ts (getPrimRetTys dm pm prim) traceM $ "[TcLow] | Checking " ++ pprShow (Call ce es) ++ " with expected type " ++ pprShowLs (getPrimTy dm pm prim) ++ " with actual type " ++ pprShowLs arrTys t <- unifyOverload2 (getPrimTy dm pm prim) arrTys return $ arrRetTy t tcExp (Proj e es) = do t <- tcExp e ts <- mapM tcExp es projRetTy t ts tcGen :: (TypedVar b Typ) => Gen b -> TcM b () tcGen (Until e1 e2) = do t1 <- tcExp e1 t2 <- tcExp e2 _ <- unify (t1, IntTy) _ <- unify (t2, IntTy) return () tcStmt :: (TypedVar b Typ) => Stmt b -> TcM b () tcStmt Skip = return () tcStmt (Exp e) = do traceM $ "[TcLow] @tcStmt | Checking: " ++ pprShow (Exp e) Enforce unit ? return () traceM $ "[TcLow] @tcStmt | Done Checking: " ++ pprShow (Exp e) tcStmt (Assign x e) = do traceM $ "[TcLow] @tcStmt | Checking: " ++ pprShow (Assign x e) t <- tcExp e modify (\tyCtx -> Map.insert x t tyCtx) traceM $ "[TcLow] @tcStmt | Done Checking: " ++ pprShow (Assign x e) tcStmt (Store x es uk e) = do traceM $ "[TcLow] @tcStmt | Checking: " ++ pprShow (Store x es uk e) ts <- mapM tcExp es mapM_ (\t -> unify (t, IntTy)) ts t <- tcExp e tyCtx <- get case Map.lookup x tyCtx of Just t' -> do baseTy <- projRetTy t' ts _ <- unify (baseTy, t) return () Nothing -> throwError $ "[TcLow] @tcStmt | Lookup of " ++ pprShow x ++ " failed in " ++ pprShow tyCtx tcStmt (Seq s1 s2) = do tcStmt s1 tcStmt s2 tcStmt (If e s1 s2) = do traceM $ "[TcLow] @tcStmt | Checking IF: " ++ pprShow (If e s1 s2) t <- tcExp e _ <- unify (t, IntTy) tcStmt s1 tcStmt s2 traceM $ "[TcLow] @tcStmt | Done Checking IF: " ++ pprShow (If e s1 s2) tcStmt (Loop lk x gen s) = do traceM $ "[TcLow] @tcStmt | Checking LOOP: " ++ pprShow (Loop lk x gen s) tcGen gen traceM $ "[TcLow] @tcStmt | Done Checking LOOP gen: " ++ pprShow gen modify (\tyCtx' -> Map.insert x IntTy tyCtx') tcStmt s traceM $ "[TcLow] @tcStmt | Done Checking LOOP: " ++ pprShow (Loop lk x gen s) tcStmt (MapRed acc x gen s e) = do tcGen gen modify (\tyCtx' -> Map.insert x IntTy tyCtx') tcStmt s t <- tcExp e modify (\tyCtx' -> Map.insert acc t tyCtx') tcDecl :: (TypedVar b Typ) => Decl b -> TcM b () tcDecl (Fun _ params allocs body retExp retTy) = paramTyM = Map.fromList params allocTyM = Map.fromList (map (\x -> (x, getType' x)) allocs) modify (\ctx -> ctx `Map.union` paramTyM `Map.union` allocTyM) tcStmt body retTy' <- case retExp of Just e -> tcExp e Nothing -> return UnitTy _ <- unify (retTy, retTy') return () instTyp :: (TypedVar b Typ) => Map.Map b Typ -> b -> ExceptT String IO b instTyp tyCtx x = case Map.lookup x tyCtx of Just t -> return $ setType x t Nothing -> throwError $ "[TcLow] @instTyp | Lookup of " ++ pprShow x ++ " failed in context: " ++ pprShow tyCtx instStmt :: (TypedVar b Typ) => Map.Map b Typ -> Stmt b -> ExceptT String IO (Stmt b) instStmt tyCtx = T.traverse (instTyp tyCtx) instDecl :: (TypedVar b Typ) => Map.Map b Typ -> Decl b -> ExceptT String IO (Decl b) instDecl tyCtx = T.traverse (instTyp tyCtx) mkInferCtxCtx :: (TypedVar b Typ) => InferCtx b -> Map.Map b Typ mkInferCtxCtx inferCtx = let modDecls = ic_modDecls inferCtx dupCtx = ic_dupCtx inferCtx modDeclsCtx = Map.fromList (map (\(_, x, ty) -> (x, ty)) modDecls) dupCtxCtx = Map.fromList (map (\v -> (fromJust (Map.lookup v dupCtx), getType' v)) (getModParamIds modDecls)) shpCtx = Map.singleton (getIdxVar inferCtx) (VecTy IntTy) in modDeclsCtx `Map.union` dupCtxCtx `Map.union` shpCtx runTcStmt :: (TypedVar b Typ) => InferCtx b -> Map.Map b Typ -> Stmt b -> IO (Either String (Stmt b)) runTcStmt inferCtx ctx s = do let ctx' = mkInferCtxCtx inferCtx ctx'' = ctx `Map.union` ctx' (v, tyCtx) <- runStateT (runExceptT (tcStmt s)) ctx'' case v of Left errMsg -> return $ Left errMsg Right _ -> runExceptT (instStmt tyCtx s) runTcDecl :: (TypedVar b Typ) => InferCtx b -> Decl b -> IO (Either String (Decl b)) runTcDecl inferCtx decl = do let ctx = mkInferCtxCtx inferCtx traceM $ "[TC] | DECL: \n" ++ pprShow decl (v, tyCtx) <- runStateT (runExceptT (tcDecl decl)) ctx traceM $ "END OF TC" ++ pprShow tyCtx case v of Left errMsg -> return $ Left errMsg Right _ -> runExceptT (instDecl tyCtx decl)
814ffd67ae5af2f71756a2f3e1c1c7a9ef1973f98de46d9ae41dffe2f5ed4efa
CIFASIS/QuickFuzz
HTTP.hs
# LANGUAGE TemplateHaskell # # LANGUAGE FlexibleInstances # # LANGUAGE IncoherentInstances # # LANGUAGE DeriveGeneric # module Test.QuickFuzz.Gen.Network.HTTP where import Data.Default import Data.Text.Encoding (encodeUtf8) import Network.HTTP.Headers import Network.HTTP.Base import Control.DeepSeq import Test.QuickCheck import Test.QuickFuzz.Derive.Arbitrary import Test.QuickFuzz.Derive.Show import Test.QuickFuzz.Derive.NFData import Test.QuickFuzz.Gen.FormatInfo import Test.QuickFuzz.Gen.Base.ByteString import qualified Data.ByteString.Lazy.Char8 as L8 devArbitrary ''Request devShow ''Request devNFData ''Request httpRequestInfo :: FormatInfo (Request String) NoActions httpRequestInfo = def { encode = L8.pack . show , random = arbitrary , value = show , ext = "http" } devArbitrary ''Response devShow ''Response devNFData ''Response httpResponseInfo :: FormatInfo (Response String) NoActions httpResponseInfo = def { encode = L8.pack . show , random = arbitrary , value = show , ext = "http" }
null
https://raw.githubusercontent.com/CIFASIS/QuickFuzz/a1c69f028b0960c002cb83e8145f039ecc0e0a23/src/Test/QuickFuzz/Gen/Network/HTTP.hs
haskell
# LANGUAGE TemplateHaskell # # LANGUAGE FlexibleInstances # # LANGUAGE IncoherentInstances # # LANGUAGE DeriveGeneric # module Test.QuickFuzz.Gen.Network.HTTP where import Data.Default import Data.Text.Encoding (encodeUtf8) import Network.HTTP.Headers import Network.HTTP.Base import Control.DeepSeq import Test.QuickCheck import Test.QuickFuzz.Derive.Arbitrary import Test.QuickFuzz.Derive.Show import Test.QuickFuzz.Derive.NFData import Test.QuickFuzz.Gen.FormatInfo import Test.QuickFuzz.Gen.Base.ByteString import qualified Data.ByteString.Lazy.Char8 as L8 devArbitrary ''Request devShow ''Request devNFData ''Request httpRequestInfo :: FormatInfo (Request String) NoActions httpRequestInfo = def { encode = L8.pack . show , random = arbitrary , value = show , ext = "http" } devArbitrary ''Response devShow ''Response devNFData ''Response httpResponseInfo :: FormatInfo (Response String) NoActions httpResponseInfo = def { encode = L8.pack . show , random = arbitrary , value = show , ext = "http" }
a9e72d63a531f49bce355d1919c7a0d7a55a64fc5e31b89c31ea1a2164eb2d47
aelve/guide
Server.hs
# LANGUAGE FlexibleContexts # module Guide.Api.Server ( runApiServer, ) where import Imports import Network.Wai (Middleware, Request) import Network.Wai.Middleware.Cors (CorsResourcePolicy (..), corsOrigins, simpleCorsResourcePolicy) import Servant import Servant.API.Generic import Servant.Server.Generic import Servant.Swagger.UI import Guide.Api.Guider import Guide.Api.Methods import Guide.Api.Types import Guide.Api.Docs import Guide.Logger import Guide.Config import Guide.State import qualified Network.Wai.Handler.Warp as Warp import qualified Data.Acid as Acid import qualified Network.Wai.Middleware.Cors as Cors -- | The type that 'runApiServer' serves. type FullApi = Api :<|> SwaggerSchemaUI "api" "swagger.json" | Serve the API on port 4400 . runApiServer :: Logger -> Config -> Acid.AcidState GlobalState -> IO () runApiServer logger Config{..} db = do logDebugIO logger $ format "API is running on port {}" portApi let guideSettings = Warp.defaultSettings & Warp.setOnException (logException logger) & Warp.setPort portApi Warp.runSettings guideSettings $ corsPolicy $ serve (Proxy @FullApi) (fullServer db logger Config{..}) where corsPolicy :: Middleware corsPolicy = if cors then Cors.cors (const $ Just policy) else Cors.cors (const Nothing) policy :: CorsResourcePolicy policy = simpleCorsResourcePolicy -- TODO: Add Guide's frontend address (and maybe others resources) to list of ` corsOrigins ` to allow CORS requests { corsOrigins = Just ( Guide 's frontend running on localhost The /api endpoint ], True) } -- | An override for the default Warp exception handler. -- -- Logs exceptions to the given 'Logger'. logException :: Logger -> Maybe Request -> SomeException -> IO () logException logger mbReq ex = when (Warp.defaultShouldDisplayException ex) $ logErrorIO logger $ format "uncaught exception: {}; request info = {}" (show ex) (show mbReq) ---------------------------------------------------------------------------- -- Servant servers ---------------------------------------------------------------------------- | Collect API and Swagger server to united ' FullApi ' . First takes -- precedence in case of overlap. fullServer :: DB -> Logger -> Config -> Server FullApi fullServer db di config = apiServer db di config :<|> docServer -- | Collect api out of guiders and convert them to handlers. Type 'type -- Server api = ServerT api Handler' needed it. apiServer :: DB -> Logger -> Config -> Server Api apiServer db di config = do requestDetails <- ask hoistServer (Proxy @Api) (guiderToHandler (Context config db requestDetails) di) (const $ toServant site) -- | A 'Server' for Swagger docs. docServer :: Server (SwaggerSchemaUI "api" "swagger.json") docServer = swaggerSchemaUIServer apiSwaggerDoc ---------------------------------------------------------------------------- -- API handlers put together ('Site') ---------------------------------------------------------------------------- site :: Site (AsServerT Guider) site = Site { _categorySite = toServant categorySite , _itemSite = toServant itemSite , _traitSite = toServant traitSite , _searchSite = toServant searchSite } -- Individual branches categorySite :: CategorySite (AsServerT Guider) categorySite = CategorySite { _getCategories = getCategories , _getCategory = getCategory , _createCategory = createCategory , _setCategoryNotes = setCategoryNotes , _setCategoryInfo = setCategoryInfo , _deleteCategory = deleteCategory } itemSite :: ItemSite (AsServerT Guider) itemSite = ItemSite { _getItem = getItem , _createItem = createItem , _setItemInfo = setItemInfo , _setItemSummary = setItemSummary , _setItemEcosystem = setItemEcosystem , _setItemNotes = setItemNotes , _deleteItem = deleteItem , _moveItem = moveItem } traitSite :: TraitSite (AsServerT Guider) traitSite = TraitSite { _getTrait = getTrait , _createTrait = createTrait , _setTrait = setTrait , _deleteTrait = deleteTrait , _moveTrait = moveTrait } searchSite :: SearchSite (AsServerT Guider) searchSite = SearchSite { _search = search }
null
https://raw.githubusercontent.com/aelve/guide/96a338d61976344d2405a16b11567e5464820a9e/back/src/Guide/Api/Server.hs
haskell
| The type that 'runApiServer' serves. TODO: Add Guide's frontend address (and maybe others resources) | An override for the default Warp exception handler. Logs exceptions to the given 'Logger'. -------------------------------------------------------------------------- Servant servers -------------------------------------------------------------------------- precedence in case of overlap. | Collect api out of guiders and convert them to handlers. Type 'type Server api = ServerT api Handler' needed it. | A 'Server' for Swagger docs. -------------------------------------------------------------------------- API handlers put together ('Site') -------------------------------------------------------------------------- Individual branches
# LANGUAGE FlexibleContexts # module Guide.Api.Server ( runApiServer, ) where import Imports import Network.Wai (Middleware, Request) import Network.Wai.Middleware.Cors (CorsResourcePolicy (..), corsOrigins, simpleCorsResourcePolicy) import Servant import Servant.API.Generic import Servant.Server.Generic import Servant.Swagger.UI import Guide.Api.Guider import Guide.Api.Methods import Guide.Api.Types import Guide.Api.Docs import Guide.Logger import Guide.Config import Guide.State import qualified Network.Wai.Handler.Warp as Warp import qualified Data.Acid as Acid import qualified Network.Wai.Middleware.Cors as Cors type FullApi = Api :<|> SwaggerSchemaUI "api" "swagger.json" | Serve the API on port 4400 . runApiServer :: Logger -> Config -> Acid.AcidState GlobalState -> IO () runApiServer logger Config{..} db = do logDebugIO logger $ format "API is running on port {}" portApi let guideSettings = Warp.defaultSettings & Warp.setOnException (logException logger) & Warp.setPort portApi Warp.runSettings guideSettings $ corsPolicy $ serve (Proxy @FullApi) (fullServer db logger Config{..}) where corsPolicy :: Middleware corsPolicy = if cors then Cors.cors (const $ Just policy) else Cors.cors (const Nothing) policy :: CorsResourcePolicy policy = simpleCorsResourcePolicy to list of ` corsOrigins ` to allow CORS requests { corsOrigins = Just ( Guide 's frontend running on localhost The /api endpoint ], True) } logException :: Logger -> Maybe Request -> SomeException -> IO () logException logger mbReq ex = when (Warp.defaultShouldDisplayException ex) $ logErrorIO logger $ format "uncaught exception: {}; request info = {}" (show ex) (show mbReq) | Collect API and Swagger server to united ' FullApi ' . First takes fullServer :: DB -> Logger -> Config -> Server FullApi fullServer db di config = apiServer db di config :<|> docServer apiServer :: DB -> Logger -> Config -> Server Api apiServer db di config = do requestDetails <- ask hoistServer (Proxy @Api) (guiderToHandler (Context config db requestDetails) di) (const $ toServant site) docServer :: Server (SwaggerSchemaUI "api" "swagger.json") docServer = swaggerSchemaUIServer apiSwaggerDoc site :: Site (AsServerT Guider) site = Site { _categorySite = toServant categorySite , _itemSite = toServant itemSite , _traitSite = toServant traitSite , _searchSite = toServant searchSite } categorySite :: CategorySite (AsServerT Guider) categorySite = CategorySite { _getCategories = getCategories , _getCategory = getCategory , _createCategory = createCategory , _setCategoryNotes = setCategoryNotes , _setCategoryInfo = setCategoryInfo , _deleteCategory = deleteCategory } itemSite :: ItemSite (AsServerT Guider) itemSite = ItemSite { _getItem = getItem , _createItem = createItem , _setItemInfo = setItemInfo , _setItemSummary = setItemSummary , _setItemEcosystem = setItemEcosystem , _setItemNotes = setItemNotes , _deleteItem = deleteItem , _moveItem = moveItem } traitSite :: TraitSite (AsServerT Guider) traitSite = TraitSite { _getTrait = getTrait , _createTrait = createTrait , _setTrait = setTrait , _deleteTrait = deleteTrait , _moveTrait = moveTrait } searchSite :: SearchSite (AsServerT Guider) searchSite = SearchSite { _search = search }
e494a2b1dd93eeb6b66452d51722db0685a918654698e10520c410d2814d0650
JPMoresmau/scion-class-browser
Json.hs
# LANGUAGE OverloadedStrings , TypeSynonymInstances # module Scion.PersistentHoogle.Instances.Json where import Control.Applicative import Data.Aeson hiding (Result) import qualified Data.Text as T import Scion.PersistentBrowser () import Scion.PersistentHoogle.Types instance ( ToJSON a , ToJSON b , ToJSON c , ToJSON d ) = > ToJSON ( a , b , c , d ) where toJSON ( a , b , c , d ) = toJSON [ toJSON a , toJSON b , toJSON c , toJSON d ] -- {-# INLINE toJSON #-} instance ToJSON (Result) where toJSON (RPackage pids) = object [ "type" .= T.pack "package" , "results" .= pids ] toJSON (RModule mds) = object [ "type" .= T.pack "module" , "results" .= mds ] toJSON (RDeclaration decls) = object [ "type" .= T.pack "declaration" , "results" .= decls ] toJSON (RConstructor decls) = object [ "type" .= T.pack "constructor" , "results" .= decls ] toJSON (RKeyword kw) = object [ "type" .= T.pack "keyword" , "name" .= kw ] toJSON (RWarning w) = object [ "type" .= T.pack "warning" , "name" .= w ] instance FromJSON (Query) where parseJSON q = Query <$> parseJSON q
null
https://raw.githubusercontent.com/JPMoresmau/scion-class-browser/572cc2c1177bdaa9558653cc1d941508cd4c7e5b/src/Scion/PersistentHoogle/Instances/Json.hs
haskell
{-# INLINE toJSON #-}
# LANGUAGE OverloadedStrings , TypeSynonymInstances # module Scion.PersistentHoogle.Instances.Json where import Control.Applicative import Data.Aeson hiding (Result) import qualified Data.Text as T import Scion.PersistentBrowser () import Scion.PersistentHoogle.Types instance ( ToJSON a , ToJSON b , ToJSON c , ToJSON d ) = > ToJSON ( a , b , c , d ) where toJSON ( a , b , c , d ) = toJSON [ toJSON a , toJSON b , toJSON c , toJSON d ] instance ToJSON (Result) where toJSON (RPackage pids) = object [ "type" .= T.pack "package" , "results" .= pids ] toJSON (RModule mds) = object [ "type" .= T.pack "module" , "results" .= mds ] toJSON (RDeclaration decls) = object [ "type" .= T.pack "declaration" , "results" .= decls ] toJSON (RConstructor decls) = object [ "type" .= T.pack "constructor" , "results" .= decls ] toJSON (RKeyword kw) = object [ "type" .= T.pack "keyword" , "name" .= kw ] toJSON (RWarning w) = object [ "type" .= T.pack "warning" , "name" .= w ] instance FromJSON (Query) where parseJSON q = Query <$> parseJSON q
2c753ef05cdd8f7e30b18d127ce5409a72377d9d6e4ffbb5549ec72b85ebd069
hasktorch/hasktorch
Linear.hs
# LANGUAGE DataKinds # {-# LANGUAGE RankNTypes #-} # LANGUAGE TypeFamilies # # LANGUAGE TypeOperators # # LANGUAGE UndecidableInstances # module Torch.GraduallyTyped.NN.Functional.Linear where import GHC.TypeLits (Nat, Symbol, TypeError) import System.IO.Unsafe (unsafePerformIO) import Torch.GraduallyTyped.DType (DType (..), DataType (..)) import Torch.GraduallyTyped.Device (Device (..), DeviceType (..)) import Torch.GraduallyTyped.Layout (Layout (..), LayoutType (..)) import Torch.GraduallyTyped.Prelude (Reverse, Seq) import Torch.GraduallyTyped.RequiresGradient (Gradient (..), RequiresGradient (..)) import Torch.GraduallyTyped.Shape.Type (Dim (..), Name (..), Shape (..), Size (..)) import Torch.GraduallyTyped.Tensor.Type (Tensor) import Torch.GraduallyTyped.Unify (type (<+>), type (<|>)) import Torch.Internal.Cast (cast2, cast3) import qualified Torch.Internal.Managed.Native as ATen import Type.Errors.Pretty (type (%), type (<>)) -- $setup > > > import Torch . GraduallyTyped . Prelude . List ( SList ( .. ) ) > > > import Torch . -- | Compute the output shape of a linear transformation. -- > > > type InputDim = ' Dim ( ' Name " input " ) ( ' Size 5 ) > > > type OutputDim = ' Dim ( ' Name " output " ) ( ' Size 10 ) > > > type BatchDim = ' Dim ( ' Name " batch " ) ( ' Size 20 ) > > > type WeightShape = ' Shape ' [ OutputDim , InputDim ] -- >>> type BiasShape = 'Shape '[OutputDim] > > > type InputShape = ' Shape ' [ BatchDim , InputDim ] -- >>> :kind! LinearWithBiasF WeightShape BiasShape InputShape LinearWithBiasF WeightShape BiasShape InputShape : : Shape -- [Dim (Name Symbol) (Size Natural)] -- = 'Shape ' [ ' Dim ( ' Name " batch " ) ( ' Size 20 ) , ' Dim ( ' Name " output " ) ( ' Size 10 ) ] type family LinearWithBiasF (weightShape :: Shape [Dim (Name Symbol) (Size Nat)]) (biasShape :: Shape [Dim (Name Symbol) (Size Nat)]) (inputShape :: Shape [Dim (Name Symbol) (Size Nat)]) :: Shape [Dim (Name Symbol) (Size Nat)] where LinearWithBiasF ('Shape '[]) _ _ = TypeError (LinearWeightDimsErrorMessage '[]) LinearWithBiasF ('Shape '[weightDim]) _ _ = TypeError (LinearWeightDimsErrorMessage '[weightDim]) LinearWithBiasF ('Shape (weightDim ': weightDim' ': weightDim'' ': weightDims)) _ _ = TypeError (LinearWeightDimsErrorMessage (weightDim ': weightDim' ': weightDim'' ': weightDims)) LinearWithBiasF _ ('Shape '[]) _ = TypeError (LinearBiasDimsErrorMessage '[]) LinearWithBiasF _ ('Shape (biasDim ': biasDim' ': biasDims)) _ = TypeError (LinearBiasDimsErrorMessage (biasDim ': biasDim' ': biasDims)) LinearWithBiasF _ _ ('Shape '[]) = TypeError LinearInputDimsErrorMessage LinearWithBiasF ('Shape weightDims) ('Shape biasDims) ('Shape inputDims) = 'Shape (Reverse (LinearWithBiasDimsF weightDims biasDims (Reverse inputDims))) LinearWithBiasF 'UncheckedShape _ _ = 'UncheckedShape LinearWithBiasF _ 'UncheckedShape _ = 'UncheckedShape LinearWithBiasF _ _ 'UncheckedShape = 'UncheckedShape type family LinearWithBiasDimsF (weightDims :: [Dim (Name Symbol) (Size Nat)]) (biasDims :: [Dim (Name Symbol) (Size Nat)]) (reversedInputDims :: [Dim (Name Symbol) (Size Nat)]) :: [Dim (Name Symbol) (Size Nat)] where LinearWithBiasDimsF '[outputDim, inputDim] '[outputDim'] (inputDim' ': reversedInputDims) = Seq (inputDim <+> inputDim') (outputDim <+> outputDim' ': reversedInputDims) type LinearInputDimsErrorMessage = "Cannot apply the linear transformation." % "The input tensor does not have the minimum required number of dimensions." % "At least one dimension is needed, but none were found." type LinearBiasDimsErrorMessage (biasDims :: [Dim (Name Symbol) (Size Nat)]) = "Cannot apply the linear transformation." % "The bias tensor must have exactly one dimension," % "but the following dimensions were found:" % "" % " " <> biasDims <> "." % "" type LinearWeightDimsErrorMessage (weightDims :: [Dim (Name Symbol) (Size Nat)]) = "Cannot apply the linear transformation." % "The weight tensor must have exactly two dimensions," % "but the following dimensions were found:" % "" % " " <> weightDims <> "." % "" -- | Applies a linear transformation to the incoming data: -- \[ -- \mathrm{output} = \mathrm{input} \mathrm{weight}^{\intercal} + \mathrm{bias}. -- \] -- -- Supported shapes: -- -- * 'input': \((N, \ldots, \mathrm{inputFeatures})\), where \(N\) is the batch size, -- \(\ldots\) means any number of additional dimensions and -- \(\mathrm{inputFeatures}\) are the input features. -- -- * 'weight': \((\mathrm{outputFeatures}, \mathrm{inputFeatures})\) -- * ' bias ' : \((\mathrm{outputFeatures})\ ) -- * ' output ' : \((N , \ldots , \mathrm{outputFeatures})\ ) -- -- Examples: -- -- >>> inputDim = SName @"input" :&: SSize @5 > > > outputDim = SName " : & : SSize @10 > > > batchDim = SName @"batch " : & : SSize @20 > > > weightShape = SShape $ outputDim :| : inputDim :| : > > > biasShape = SShape $ outputDim :| : > > > inputShape = SShape $ batchDim :| : inputDim :| : -- >>> g <- sMkGenerator (SDevice SCPU) 0 > > > sRandn ' = sRandn . TensorSpec ( SGradient SWithoutGradient ) ( SLayout SDense ) ( SDevice SCPU ) ( SDataType SFloat ) > > > ( weight , ' ) < - sRandn ' -- [W TensorImpl.h:1463] Warning: Named tensors and all their associated APIs are an experimental feature and subject to change. Please do not use them for anything important until they are released as stable. (function operator()) -- >>> (bias, g'') <- sRandn' biasShape g' -- >>> (input, _) <- sRandn' inputShape g'' -- >>> result = linearWithBias weight bias input -- >>> :type result -- result -- :: Tensor -- ('Gradient 'WithoutGradient) -- ('Layout 'Dense) -- ('Device 'CPU) -- ('DataType 'Float) -- ('Shape ' [ ' Dim ( ' Name " batch " ) ( ' Size 20 ) , ' Dim ( ' Name " output " ) ( ' Size 10 ) ] ) linearWithBias :: forall gradient layout device dataType shape gradient' layout' device' dataType' shape' gradient'' layout'' device'' dataType'' shape''. -- | weight Tensor gradient layout device dataType shape -> -- | bias Tensor gradient' layout' device' dataType' shape' -> -- | input Tensor gradient'' layout'' device'' dataType'' shape'' -> -- | output Tensor (gradient' <|> gradient'' <|> gradient'') (layout <+> (layout' <+> layout'')) (device <+> (device' <+> device'')) (dataType <+> (dataType' <+> dataType'')) (LinearWithBiasF shape shape' shape'') linearWithBias weight bias input = unsafePerformIO $ cast3 ATen.linear_ttt input weight bias type family LinearWithoutBiasF (weightShape :: Shape [Dim (Name Symbol) (Size Nat)]) (inputShape :: Shape [Dim (Name Symbol) (Size Nat)]) :: Shape [Dim (Name Symbol) (Size Nat)] where LinearWithoutBiasF ('Shape '[]) _ = TypeError (LinearWeightDimsErrorMessage '[]) LinearWithoutBiasF ('Shape '[weightDim]) _ = TypeError (LinearWeightDimsErrorMessage '[weightDim]) LinearWithoutBiasF ('Shape (weightDim ': weightDim' ': weightDim'' ': weightDims)) _ = TypeError (LinearWeightDimsErrorMessage (weightDim ': weightDim' ': weightDim'' ': weightDims)) LinearWithoutBiasF _ ('Shape '[]) = TypeError LinearInputDimsErrorMessage LinearWithoutBiasF ('Shape weightDims) ('Shape inputDims) = 'Shape (Reverse (LinearWithoutBiasDimsF weightDims (Reverse inputDims))) LinearWithoutBiasF 'UncheckedShape _ = 'UncheckedShape LinearWithoutBiasF _ 'UncheckedShape = 'UncheckedShape type family LinearWithoutBiasDimsF (weightDims :: [Dim (Name Symbol) (Size Nat)]) (reversedInputDims :: [Dim (Name Symbol) (Size Nat)]) :: [Dim (Name Symbol) (Size Nat)] where LinearWithoutBiasDimsF '[outputDim, inputDim] (inputDim' ': reversedInputDims) = Seq (inputDim <+> inputDim') (outputDim ': reversedInputDims) linearWithoutBias :: forall gradient layout device dataType shape gradient' layout' device' dataType' shape'. -- | weight Tensor gradient layout device dataType shape -> -- | input Tensor gradient' layout' device' dataType' shape' -> -- | output Tensor (gradient <|> gradient') (layout <+> layout') (device <+> device') (dataType <+> dataType') (LinearWithoutBiasF shape shape') linearWithoutBias weight input = unsafePerformIO $ cast2 ATen.linear_tt input weight testLinearWithoutBias :: Tensor ('Gradient 'WithGradient) ('Layout 'Dense) 'UncheckedDevice ('DataType 'Float) ('Shape '[ 'Dim ('Name "output") ('Size 2)]) testLinearWithoutBias = let weight = undefined :: Tensor ('Gradient 'WithGradient) ('Layout 'Dense) ('Device 'CPU) ('DataType 'Float) ('Shape '[ 'Dim ('Name "output") ('Size 2), 'Dim ('Name "input") ('Size 1)]) input = undefined :: Tensor ('Gradient 'WithoutGradient) ('Layout 'Dense) 'UncheckedDevice ('DataType 'Float) ('Shape '[ 'Dim ('Name "input") ('Size 1)]) in linearWithoutBias weight input
null
https://raw.githubusercontent.com/hasktorch/hasktorch/cf0ed1aba9c41123ba46f7c0788a4df10fbfe1ef/experimental/gradually-typed/src/Torch/GraduallyTyped/NN/Functional/Linear.hs
haskell
# LANGUAGE RankNTypes # $setup | Compute the output shape of a linear transformation. >>> type BiasShape = 'Shape '[OutputDim] >>> :kind! LinearWithBiasF WeightShape BiasShape InputShape [Dim (Name Symbol) (Size Natural)] = 'Shape | Applies a linear transformation to the incoming data: \[ \mathrm{output} = \mathrm{input} \mathrm{weight}^{\intercal} + \mathrm{bias}. \] Supported shapes: * 'input': \((N, \ldots, \mathrm{inputFeatures})\), where \(N\) is the batch size, \(\ldots\) means any number of additional dimensions and \(\mathrm{inputFeatures}\) are the input features. * 'weight': \((\mathrm{outputFeatures}, \mathrm{inputFeatures})\) Examples: >>> inputDim = SName @"input" :&: SSize @5 >>> g <- sMkGenerator (SDevice SCPU) 0 [W TensorImpl.h:1463] Warning: Named tensors and all their associated APIs are an experimental feature and subject to change. Please do not use them for anything important until they are released as stable. (function operator()) >>> (bias, g'') <- sRandn' biasShape g' >>> (input, _) <- sRandn' inputShape g'' >>> result = linearWithBias weight bias input >>> :type result result :: Tensor ('Gradient 'WithoutGradient) ('Layout 'Dense) ('Device 'CPU) ('DataType 'Float) ('Shape | weight | bias | input | output | weight | input | output
# LANGUAGE DataKinds # # LANGUAGE TypeFamilies # # LANGUAGE TypeOperators # # LANGUAGE UndecidableInstances # module Torch.GraduallyTyped.NN.Functional.Linear where import GHC.TypeLits (Nat, Symbol, TypeError) import System.IO.Unsafe (unsafePerformIO) import Torch.GraduallyTyped.DType (DType (..), DataType (..)) import Torch.GraduallyTyped.Device (Device (..), DeviceType (..)) import Torch.GraduallyTyped.Layout (Layout (..), LayoutType (..)) import Torch.GraduallyTyped.Prelude (Reverse, Seq) import Torch.GraduallyTyped.RequiresGradient (Gradient (..), RequiresGradient (..)) import Torch.GraduallyTyped.Shape.Type (Dim (..), Name (..), Shape (..), Size (..)) import Torch.GraduallyTyped.Tensor.Type (Tensor) import Torch.GraduallyTyped.Unify (type (<+>), type (<|>)) import Torch.Internal.Cast (cast2, cast3) import qualified Torch.Internal.Managed.Native as ATen import Type.Errors.Pretty (type (%), type (<>)) > > > import Torch . GraduallyTyped . Prelude . List ( SList ( .. ) ) > > > import Torch . > > > type InputDim = ' Dim ( ' Name " input " ) ( ' Size 5 ) > > > type OutputDim = ' Dim ( ' Name " output " ) ( ' Size 10 ) > > > type BatchDim = ' Dim ( ' Name " batch " ) ( ' Size 20 ) > > > type WeightShape = ' Shape ' [ OutputDim , InputDim ] > > > type InputShape = ' Shape ' [ BatchDim , InputDim ] LinearWithBiasF WeightShape BiasShape InputShape : : Shape ' [ ' Dim ( ' Name " batch " ) ( ' Size 20 ) , ' Dim ( ' Name " output " ) ( ' Size 10 ) ] type family LinearWithBiasF (weightShape :: Shape [Dim (Name Symbol) (Size Nat)]) (biasShape :: Shape [Dim (Name Symbol) (Size Nat)]) (inputShape :: Shape [Dim (Name Symbol) (Size Nat)]) :: Shape [Dim (Name Symbol) (Size Nat)] where LinearWithBiasF ('Shape '[]) _ _ = TypeError (LinearWeightDimsErrorMessage '[]) LinearWithBiasF ('Shape '[weightDim]) _ _ = TypeError (LinearWeightDimsErrorMessage '[weightDim]) LinearWithBiasF ('Shape (weightDim ': weightDim' ': weightDim'' ': weightDims)) _ _ = TypeError (LinearWeightDimsErrorMessage (weightDim ': weightDim' ': weightDim'' ': weightDims)) LinearWithBiasF _ ('Shape '[]) _ = TypeError (LinearBiasDimsErrorMessage '[]) LinearWithBiasF _ ('Shape (biasDim ': biasDim' ': biasDims)) _ = TypeError (LinearBiasDimsErrorMessage (biasDim ': biasDim' ': biasDims)) LinearWithBiasF _ _ ('Shape '[]) = TypeError LinearInputDimsErrorMessage LinearWithBiasF ('Shape weightDims) ('Shape biasDims) ('Shape inputDims) = 'Shape (Reverse (LinearWithBiasDimsF weightDims biasDims (Reverse inputDims))) LinearWithBiasF 'UncheckedShape _ _ = 'UncheckedShape LinearWithBiasF _ 'UncheckedShape _ = 'UncheckedShape LinearWithBiasF _ _ 'UncheckedShape = 'UncheckedShape type family LinearWithBiasDimsF (weightDims :: [Dim (Name Symbol) (Size Nat)]) (biasDims :: [Dim (Name Symbol) (Size Nat)]) (reversedInputDims :: [Dim (Name Symbol) (Size Nat)]) :: [Dim (Name Symbol) (Size Nat)] where LinearWithBiasDimsF '[outputDim, inputDim] '[outputDim'] (inputDim' ': reversedInputDims) = Seq (inputDim <+> inputDim') (outputDim <+> outputDim' ': reversedInputDims) type LinearInputDimsErrorMessage = "Cannot apply the linear transformation." % "The input tensor does not have the minimum required number of dimensions." % "At least one dimension is needed, but none were found." type LinearBiasDimsErrorMessage (biasDims :: [Dim (Name Symbol) (Size Nat)]) = "Cannot apply the linear transformation." % "The bias tensor must have exactly one dimension," % "but the following dimensions were found:" % "" % " " <> biasDims <> "." % "" type LinearWeightDimsErrorMessage (weightDims :: [Dim (Name Symbol) (Size Nat)]) = "Cannot apply the linear transformation." % "The weight tensor must have exactly two dimensions," % "but the following dimensions were found:" % "" % " " <> weightDims <> "." % "" * ' bias ' : \((\mathrm{outputFeatures})\ ) * ' output ' : \((N , \ldots , \mathrm{outputFeatures})\ ) > > > outputDim = SName " : & : SSize @10 > > > batchDim = SName @"batch " : & : SSize @20 > > > weightShape = SShape $ outputDim :| : inputDim :| : > > > biasShape = SShape $ outputDim :| : > > > inputShape = SShape $ batchDim :| : inputDim :| : > > > sRandn ' = sRandn . TensorSpec ( SGradient SWithoutGradient ) ( SLayout SDense ) ( SDevice SCPU ) ( SDataType SFloat ) > > > ( weight , ' ) < - sRandn ' ' [ ' Dim ( ' Name " batch " ) ( ' Size 20 ) , ' Dim ( ' Name " output " ) ( ' Size 10 ) ] ) linearWithBias :: forall gradient layout device dataType shape gradient' layout' device' dataType' shape' gradient'' layout'' device'' dataType'' shape''. Tensor gradient layout device dataType shape -> Tensor gradient' layout' device' dataType' shape' -> Tensor gradient'' layout'' device'' dataType'' shape'' -> Tensor (gradient' <|> gradient'' <|> gradient'') (layout <+> (layout' <+> layout'')) (device <+> (device' <+> device'')) (dataType <+> (dataType' <+> dataType'')) (LinearWithBiasF shape shape' shape'') linearWithBias weight bias input = unsafePerformIO $ cast3 ATen.linear_ttt input weight bias type family LinearWithoutBiasF (weightShape :: Shape [Dim (Name Symbol) (Size Nat)]) (inputShape :: Shape [Dim (Name Symbol) (Size Nat)]) :: Shape [Dim (Name Symbol) (Size Nat)] where LinearWithoutBiasF ('Shape '[]) _ = TypeError (LinearWeightDimsErrorMessage '[]) LinearWithoutBiasF ('Shape '[weightDim]) _ = TypeError (LinearWeightDimsErrorMessage '[weightDim]) LinearWithoutBiasF ('Shape (weightDim ': weightDim' ': weightDim'' ': weightDims)) _ = TypeError (LinearWeightDimsErrorMessage (weightDim ': weightDim' ': weightDim'' ': weightDims)) LinearWithoutBiasF _ ('Shape '[]) = TypeError LinearInputDimsErrorMessage LinearWithoutBiasF ('Shape weightDims) ('Shape inputDims) = 'Shape (Reverse (LinearWithoutBiasDimsF weightDims (Reverse inputDims))) LinearWithoutBiasF 'UncheckedShape _ = 'UncheckedShape LinearWithoutBiasF _ 'UncheckedShape = 'UncheckedShape type family LinearWithoutBiasDimsF (weightDims :: [Dim (Name Symbol) (Size Nat)]) (reversedInputDims :: [Dim (Name Symbol) (Size Nat)]) :: [Dim (Name Symbol) (Size Nat)] where LinearWithoutBiasDimsF '[outputDim, inputDim] (inputDim' ': reversedInputDims) = Seq (inputDim <+> inputDim') (outputDim ': reversedInputDims) linearWithoutBias :: forall gradient layout device dataType shape gradient' layout' device' dataType' shape'. Tensor gradient layout device dataType shape -> Tensor gradient' layout' device' dataType' shape' -> Tensor (gradient <|> gradient') (layout <+> layout') (device <+> device') (dataType <+> dataType') (LinearWithoutBiasF shape shape') linearWithoutBias weight input = unsafePerformIO $ cast2 ATen.linear_tt input weight testLinearWithoutBias :: Tensor ('Gradient 'WithGradient) ('Layout 'Dense) 'UncheckedDevice ('DataType 'Float) ('Shape '[ 'Dim ('Name "output") ('Size 2)]) testLinearWithoutBias = let weight = undefined :: Tensor ('Gradient 'WithGradient) ('Layout 'Dense) ('Device 'CPU) ('DataType 'Float) ('Shape '[ 'Dim ('Name "output") ('Size 2), 'Dim ('Name "input") ('Size 1)]) input = undefined :: Tensor ('Gradient 'WithoutGradient) ('Layout 'Dense) 'UncheckedDevice ('DataType 'Float) ('Shape '[ 'Dim ('Name "input") ('Size 1)]) in linearWithoutBias weight input
a8d0e71342b4deeef26c13097c20638162d85f50d5a9b35d49291f6f0c1a642e
ftovagliari/ocamleditor
gutter.ml
OCamlEditor Copyright ( C ) 2010 - 2014 This file is part of OCamlEditor . OCamlEditor 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 . OCamlEditor 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 < / > . OCamlEditor Copyright (C) 2010-2014 Francesco Tovagliari This file is part of OCamlEditor. OCamlEditor 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. OCamlEditor 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 </>. *) (* S | chars (varying) | S | B | B | Folding | B | B | *) open Printf type t = { mutable size : int; mutable chars : int; mutable start_selection : GText.iter option; spacing : int; mutable fold_size : int; mutable fold_x : int; mutable bg_color : GDraw.color; mutable fg_color : GDraw.color; mutable border_color : GDraw.color; mutable marker_color : GDraw.color; mutable marker_bg_color : GDraw.color; mutable markers : marker list; } and marker = { kind : [`None | `Bookmark of int | `Error of string | `Warning of string]; mark : Gtk.text_mark; icon_pixbuf : GdkPixbuf.pixbuf option; mutable icon_obj : GObj.widget option; callback : (Gtk.text_mark -> bool) option; } let icon_size = 15 (** create *) let create () = { size = 0; chars = 0; start_selection = None; spacing = 2; fold_size = 0; fold_x = (-1); bg_color = `WHITE; fg_color = `WHITE; border_color = `WHITE; marker_color = `WHITE; marker_bg_color = `WHITE; markers = []; } (** create_marker *) let create_marker ?(kind=`None) ~mark ?pixbuf ?callback () = {kind=kind; mark=mark; icon_pixbuf=pixbuf; callback=callback; icon_obj=None} (** destroy_markers *) let destroy_markers gutter markers = gutter.markers <- List.filter (fun x -> not (List.memq x markers)) gutter.markers; List.iter begin fun marker -> Gaux.may marker.icon_obj ~f:(fun i -> i#destroy()); match GtkText.Mark.get_buffer marker.mark with | None -> () | Some buffer -> GtkText.Buffer.delete_mark buffer marker.mark; end markers
null
https://raw.githubusercontent.com/ftovagliari/ocamleditor/bee65cd57b712979f67c759e519ab1a0192a1c28/src/gutter.ml
ocaml
S | chars (varying) | S | B | B | Folding | B | B | * create * create_marker * destroy_markers
OCamlEditor Copyright ( C ) 2010 - 2014 This file is part of OCamlEditor . OCamlEditor 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 . OCamlEditor 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 < / > . OCamlEditor Copyright (C) 2010-2014 Francesco Tovagliari This file is part of OCamlEditor. OCamlEditor 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. OCamlEditor 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 </>. *) open Printf type t = { mutable size : int; mutable chars : int; mutable start_selection : GText.iter option; spacing : int; mutable fold_size : int; mutable fold_x : int; mutable bg_color : GDraw.color; mutable fg_color : GDraw.color; mutable border_color : GDraw.color; mutable marker_color : GDraw.color; mutable marker_bg_color : GDraw.color; mutable markers : marker list; } and marker = { kind : [`None | `Bookmark of int | `Error of string | `Warning of string]; mark : Gtk.text_mark; icon_pixbuf : GdkPixbuf.pixbuf option; mutable icon_obj : GObj.widget option; callback : (Gtk.text_mark -> bool) option; } let icon_size = 15 let create () = { size = 0; chars = 0; start_selection = None; spacing = 2; fold_size = 0; fold_x = (-1); bg_color = `WHITE; fg_color = `WHITE; border_color = `WHITE; marker_color = `WHITE; marker_bg_color = `WHITE; markers = []; } let create_marker ?(kind=`None) ~mark ?pixbuf ?callback () = {kind=kind; mark=mark; icon_pixbuf=pixbuf; callback=callback; icon_obj=None} let destroy_markers gutter markers = gutter.markers <- List.filter (fun x -> not (List.memq x markers)) gutter.markers; List.iter begin fun marker -> Gaux.may marker.icon_obj ~f:(fun i -> i#destroy()); match GtkText.Mark.get_buffer marker.mark with | None -> () | Some buffer -> GtkText.Buffer.delete_mark buffer marker.mark; end markers
3f7af9ce0497d6bdc226d0499c18ed993a81f7240e65a7b1d8b317eea59fa942
twittner/cql-io
Jobs.hs
This Source Code Form is subject to the terms of the Mozilla Public License , v. 2.0 . If a copy of the MPL was not distributed with this file , You can obtain one at /. module Database.CQL.IO.Jobs ( Jobs , new , add , destroy , showJobs ) where import Control.Applicative import Control.Concurrent.Async import Control.Concurrent.STM import Control.Monad import Control.Monad.Catch import Control.Monad.IO.Class import Database.CQL.IO.Types import Data.Map.Strict (Map) import Data.Unique import Prelude import qualified Data.Map.Strict as Map data Job = Reserved | Running !Unique !(Async ()) newtype Jobs k = Jobs (TVar (Map k Job)) new :: MonadIO m => m (Jobs k) new = liftIO $ Jobs <$> newTVarIO Map.empty add :: (MonadIO m, Ord k) => Jobs k -> k -> Bool -> IO () -> m () add (Jobs d) k replace j = liftIO $ do (ok, prev) <- atomically $ do m <- readTVar d case Map.lookup k m of Nothing -> do modifyTVar' d (Map.insert k Reserved) return (True, Nothing) Just (Running _ a) | replace -> do modifyTVar' d (Map.insert k Reserved) return (True, Just a) _ -> return (False, Nothing) when ok $ do maybe (return ()) (ignore . cancel) prev u <- newUnique a <- async $ j `finally` remove u atomically $ modifyTVar' d (Map.insert k (Running u a)) where remove u = atomically $ modifyTVar' d $ flip Map.update k $ \a -> case a of Running u' _ | u == u' -> Nothing _ -> Just a destroy :: MonadIO m => Jobs k -> m () destroy (Jobs d) = liftIO $ do items <- Map.elems <$> atomically (swapTVar d Map.empty) mapM_ f items where f (Running _ a) = ignore (cancel a) f _ = return () showJobs :: MonadIO m => Jobs k -> m [k] showJobs (Jobs d) = liftIO $ Map.keys <$> readTVarIO d
null
https://raw.githubusercontent.com/twittner/cql-io/090b436a413d961a424376c0b1dcc0c223472188/src/Database/CQL/IO/Jobs.hs
haskell
This Source Code Form is subject to the terms of the Mozilla Public License , v. 2.0 . If a copy of the MPL was not distributed with this file , You can obtain one at /. module Database.CQL.IO.Jobs ( Jobs , new , add , destroy , showJobs ) where import Control.Applicative import Control.Concurrent.Async import Control.Concurrent.STM import Control.Monad import Control.Monad.Catch import Control.Monad.IO.Class import Database.CQL.IO.Types import Data.Map.Strict (Map) import Data.Unique import Prelude import qualified Data.Map.Strict as Map data Job = Reserved | Running !Unique !(Async ()) newtype Jobs k = Jobs (TVar (Map k Job)) new :: MonadIO m => m (Jobs k) new = liftIO $ Jobs <$> newTVarIO Map.empty add :: (MonadIO m, Ord k) => Jobs k -> k -> Bool -> IO () -> m () add (Jobs d) k replace j = liftIO $ do (ok, prev) <- atomically $ do m <- readTVar d case Map.lookup k m of Nothing -> do modifyTVar' d (Map.insert k Reserved) return (True, Nothing) Just (Running _ a) | replace -> do modifyTVar' d (Map.insert k Reserved) return (True, Just a) _ -> return (False, Nothing) when ok $ do maybe (return ()) (ignore . cancel) prev u <- newUnique a <- async $ j `finally` remove u atomically $ modifyTVar' d (Map.insert k (Running u a)) where remove u = atomically $ modifyTVar' d $ flip Map.update k $ \a -> case a of Running u' _ | u == u' -> Nothing _ -> Just a destroy :: MonadIO m => Jobs k -> m () destroy (Jobs d) = liftIO $ do items <- Map.elems <$> atomically (swapTVar d Map.empty) mapM_ f items where f (Running _ a) = ignore (cancel a) f _ = return () showJobs :: MonadIO m => Jobs k -> m [k] showJobs (Jobs d) = liftIO $ Map.keys <$> readTVarIO d
ccb171675a6a0107f6f13b8271fba82405aba48d4ca7aea85fe823f2efa18208
juspay/atlas
SavedReqLocation.hs
| Copyright 2022 Juspay Technologies Pvt Ltd Licensed under the Apache License , Version 2.0 ( the " License " ) ; you may not use this file except in compliance with the License . You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing , software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . See the License for the specific language governing permissions and limitations under the License . Module : Domain . Types . SavedReqLocation Copyright : ( C ) Juspay Technologies Pvt Ltd 2019 - 2022 License : Apache 2.0 ( see the file LICENSE ) Maintainer : Stability : experimental Portability : non - portable Copyright 2022 Juspay Technologies Pvt Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Module : Domain.Types.SavedReqLocation Copyright : (C) Juspay Technologies Pvt Ltd 2019-2022 License : Apache 2.0 (see the file LICENSE) Maintainer : Stability : experimental Portability : non-portable -} module Domain.Types.SavedReqLocation where import Beckn.Prelude import Beckn.Types.Id import Domain.Types.Person (Person) import Domain.Types.SearchReqLocation (SearchReqLocationAPIEntity (..)) data SavedReqLocation = SavedReqLocation { id :: Id SavedReqLocation, lat :: Double, lon :: Double, street :: Maybe Text, door :: Maybe Text, city :: Maybe Text, state :: Maybe Text, country :: Maybe Text, building :: Maybe Text, areaCode :: Maybe Text, area :: Maybe Text, createdAt :: UTCTime, updatedAt :: UTCTime, tag :: Text, riderId :: Id Person } deriving (Generic, Show) data SavedReqLocationAPIEntity = SavedReqLocationAPIEntity { address :: SearchReqLocationAPIEntity, tag :: Text } deriving (Generic, FromJSON, ToJSON, Show, ToSchema) makeSavedReqLocationAPIEntity :: SavedReqLocation -> SavedReqLocationAPIEntity makeSavedReqLocationAPIEntity SavedReqLocation {..} = let address = SearchReqLocationAPIEntity {..} in SavedReqLocationAPIEntity { .. }
null
https://raw.githubusercontent.com/juspay/atlas/e64b227dc17887fb01c2554db21c08284d18a806/app/app-backend/src/Domain/Types/SavedReqLocation.hs
haskell
| Copyright 2022 Juspay Technologies Pvt Ltd Licensed under the Apache License , Version 2.0 ( the " License " ) ; you may not use this file except in compliance with the License . You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing , software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . See the License for the specific language governing permissions and limitations under the License . Module : Domain . Types . SavedReqLocation Copyright : ( C ) Juspay Technologies Pvt Ltd 2019 - 2022 License : Apache 2.0 ( see the file LICENSE ) Maintainer : Stability : experimental Portability : non - portable Copyright 2022 Juspay Technologies Pvt Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Module : Domain.Types.SavedReqLocation Copyright : (C) Juspay Technologies Pvt Ltd 2019-2022 License : Apache 2.0 (see the file LICENSE) Maintainer : Stability : experimental Portability : non-portable -} module Domain.Types.SavedReqLocation where import Beckn.Prelude import Beckn.Types.Id import Domain.Types.Person (Person) import Domain.Types.SearchReqLocation (SearchReqLocationAPIEntity (..)) data SavedReqLocation = SavedReqLocation { id :: Id SavedReqLocation, lat :: Double, lon :: Double, street :: Maybe Text, door :: Maybe Text, city :: Maybe Text, state :: Maybe Text, country :: Maybe Text, building :: Maybe Text, areaCode :: Maybe Text, area :: Maybe Text, createdAt :: UTCTime, updatedAt :: UTCTime, tag :: Text, riderId :: Id Person } deriving (Generic, Show) data SavedReqLocationAPIEntity = SavedReqLocationAPIEntity { address :: SearchReqLocationAPIEntity, tag :: Text } deriving (Generic, FromJSON, ToJSON, Show, ToSchema) makeSavedReqLocationAPIEntity :: SavedReqLocation -> SavedReqLocationAPIEntity makeSavedReqLocationAPIEntity SavedReqLocation {..} = let address = SearchReqLocationAPIEntity {..} in SavedReqLocationAPIEntity { .. }
0a5cc5df4051b58da066ca27b71f7102615653225e712ae809292080534d581d
larcenists/larceny
srfi-86-test.sps
Test suite for SRFI-86 ; $ Id$ ; Very basic tests , taken directly from SRFI 86 . (import (rnrs base) (rnrs io simple) (srfi :6 basic-string-ports) (srfi :86 mu-and-nu)) (define (writeln . xs) (for-each display xs) (newline)) (define (fail token . more) (writeln "Error: test failed: " token) #f) (or (equal? (alet (a (mu 1 2) ((b c) (mu 3 4))) (list a b c)) '((1 2) 3 4)) (fail 'ex1)) (or (equal? (let ((p (open-output-string))) (alet ((a (begin (display "1st" p) 1)) (b c (mu (begin (display "2nd" p) 2) 3)) (d (begin (display "3rd" p) 4)) ((e . f) (mu (begin (display "4th" p) 5) 6))) (vector (get-output-string p) (list a b c d e f)))) '#("1st2nd3rd4th" (1 2 3 4 5 (6)))) (fail 'ex2)) (or (equal? (alet* (((a b) (mu 1 2)) ((c d e) a (+ a b c) (+ a b c d)) ((f . g) (mu 5 6 7)) ((h i j . k) e 9 10 h i j)) (list a b c d e f g h i j k)) '(1 2 1 4 8 5 (6 7) 8 9 10 (8 9 10))) (fail 'ex3)) (or (equal? (alet* tag ((a 1) (a b b c (mu (+ a 2) 4 5 6)) ((d e e) b 5 (+ a b c))) (if (< a 10) (tag a 10 b c c d e d) (list a b c d e))) '(10 6 6 5 5)) (fail 'ex4)) (or (equal? (alet* ((a 1) ((b 2) (b c c (mu 3 4 5)) ((d e d (mu a b c)) . intag) . tag) (f 6)) (if (< d 10) (intag d e 10) (if (< c 10) (tag b 11 c 12 a b d intag) (list a b c d e f)))) '(1 11 12 10 3 6)) (fail 'ex5)) (or (let ((p (open-output-string))) (and (equal? (alet ((exit) (a (begin (display "1st" p) 1)) (b c (mu (begin (display "2nd" p) 2) (begin (display "3rd" p) 3)))) (display (list a b c) p) (exit 10) (display "end" p)) 10) (equal? (get-output-string p) "1st2nd3rd(1 2 3)"))) (fail 'ex6)) (or (let ((p (open-output-string))) (and (equal? (alet ((and (a (begin (display "1st" p) 1)) (b (begin (display "2nd" p) 2)) (c (begin (display "false" p) #f)) (d (begin (display "3nd" p) 3)))) (list a b c d)) #f) (equal? (get-output-string p) "1st2ndfalse"))) (fail 'ex7)) (or (equal? ((lambda (str . rest) (alet* ((len (string-length str)) (opt rest (start 0 (integer? start) (if (< start 0) 0 (if (< len start) len start))) ;true (end len (integer? end) (if (< end start) start (if (< len end) len end)))));true (substring str start end))) "abcdefg" 1 20) "bcdefg") (fail 'ex8a)) (or (equal? ((lambda (str . rest) (alet* ((len (string-length str)) (min (apply min rest)) (cat rest (start 0 (= start min) (if (< start 0) 0 (if (< len start) len start)));true (end len (integer? end) (if (< end start) start (if (< len end) len end)))));true (substring str start end))) "abcdefg" 20 1) "bcdefg") (fail 'ex8b)) (or (equal? ((lambda (str . rest) (alet ((cat rest (start 0 (and (list? start) (= 2 (length start)) (eq? 'start (car start))) (cadr start)) ; true (end (string-length str) (and (list? end) (= 2 (length end)) (eq? 'end (car end))) (cadr end)))) ; true (substring str start end))) "abcdefg" '(end 6) '(start 1)) "bcdef") (fail 'ex8c)) (define rest-list '(a 10 cc 30 40 b 20)) (or (equal? (alet ((key rest-list (a 1) (b 2) ((c 'cc) 3) . d)) (list a b c d)) '(10 2 30 (40 b 20))) (fail 'ex9a)) (or (equal? (alet ((key rest-list (a 1) (b 2) ((c 'cc) 3) #f . d)) (list a b c d)) '(10 2 30 (40 b 20))) (fail 'ex9b)) (or (equal? (alet ((key rest-list (a 1) (b 2) ((c 'cc) 3) #t . d)) (list a b c d)) '(10 20 30 (40))) (fail 'ex9c)) (define rest (list 'a 10 'd 40 "c" 30 50 'b 20)) (or (equal? (alet ((key rest (a 1) (b 2) ((c "c") 3) . d)) (list a b c d)) '(10 2 30 (d 40 50 b 20))) (fail 'ex9d)) (or (equal? (alet ((key rest (a 1) (b 2) ((c "c") 3) #f . d)) (list a b c d)) '(10 2 3 (d 40 "c" 30 50 b 20))) (fail 'ex9e)) (or (equal? (alet ((key rest (a 1) (b 2) ((c "c") 3) #t . d)) (list a b c d)) '(10 20 30 (d 40 50))) (fail 'ex9f)) (or (equal? ((lambda (m . n) (alet* ((opt n (a 10) (b 20) (c 30) . d) (key d (x 100) (y 200) (a 300))) (list m a b c x y))) 0 1 2 3 'a 30 'y 20 'x 10) '(0 30 2 3 10 20)) (fail 'ex9g)) (or (equal? ((lambda (m . n) (alet* ((key n (x 100) (y 200) (a 300) . d) (opt d (a 10) (b 20) (c 30))) (list m a b c x y))) 0 'a 30 'y 20 'x 10 1 2 3) '(0 1 2 3 10 20)) (fail 'ex9h)) (or (equal? (alet* ((a 1) (rec (a 2) (b 3) (b (lambda () c)) (c a)) (d 50)) (list a (b) c d)) '(2 2 2 50)) (fail 'ex10)) (or (equal? (alet ((a b (mu 1 2)) This is different from SRFI 71 . ((e f) (mu 5 6)) ((values g h) (values 7 8)) ((i j . k) (nu 9 '(10 11 12))) ((values l m . n) (apply values 13 '(14 15 16))) o (mu 17 18) ((values . p) (values 19 20))) (list a b c d e f g h i j k l m n o p)) '(1 2 3 4 5 6 7 8 9 10 (11 12) 13 14 (15 16) (17 18) (19 20))) (fail 'ex11)) (or (equal? (alet ((a 1) (() (define a 10) (define b 100)) (b a)) (list a b)) '(1 10)) (fail 'ex12a)) (or (equal? (alet* ((a 1) (() (define a 10) (define b 100)) (b a)) (list a b)) '(10 10)) (fail 'ex12b)) (writeln "Done.")
null
https://raw.githubusercontent.com/larcenists/larceny/fef550c7d3923deb7a5a1ccd5a628e54cf231c75/lib/SRFI/test/srfi-86-test.sps
scheme
true true true true true true
Test suite for SRFI-86 $ Id$ Very basic tests , taken directly from SRFI 86 . (import (rnrs base) (rnrs io simple) (srfi :6 basic-string-ports) (srfi :86 mu-and-nu)) (define (writeln . xs) (for-each display xs) (newline)) (define (fail token . more) (writeln "Error: test failed: " token) #f) (or (equal? (alet (a (mu 1 2) ((b c) (mu 3 4))) (list a b c)) '((1 2) 3 4)) (fail 'ex1)) (or (equal? (let ((p (open-output-string))) (alet ((a (begin (display "1st" p) 1)) (b c (mu (begin (display "2nd" p) 2) 3)) (d (begin (display "3rd" p) 4)) ((e . f) (mu (begin (display "4th" p) 5) 6))) (vector (get-output-string p) (list a b c d e f)))) '#("1st2nd3rd4th" (1 2 3 4 5 (6)))) (fail 'ex2)) (or (equal? (alet* (((a b) (mu 1 2)) ((c d e) a (+ a b c) (+ a b c d)) ((f . g) (mu 5 6 7)) ((h i j . k) e 9 10 h i j)) (list a b c d e f g h i j k)) '(1 2 1 4 8 5 (6 7) 8 9 10 (8 9 10))) (fail 'ex3)) (or (equal? (alet* tag ((a 1) (a b b c (mu (+ a 2) 4 5 6)) ((d e e) b 5 (+ a b c))) (if (< a 10) (tag a 10 b c c d e d) (list a b c d e))) '(10 6 6 5 5)) (fail 'ex4)) (or (equal? (alet* ((a 1) ((b 2) (b c c (mu 3 4 5)) ((d e d (mu a b c)) . intag) . tag) (f 6)) (if (< d 10) (intag d e 10) (if (< c 10) (tag b 11 c 12 a b d intag) (list a b c d e f)))) '(1 11 12 10 3 6)) (fail 'ex5)) (or (let ((p (open-output-string))) (and (equal? (alet ((exit) (a (begin (display "1st" p) 1)) (b c (mu (begin (display "2nd" p) 2) (begin (display "3rd" p) 3)))) (display (list a b c) p) (exit 10) (display "end" p)) 10) (equal? (get-output-string p) "1st2nd3rd(1 2 3)"))) (fail 'ex6)) (or (let ((p (open-output-string))) (and (equal? (alet ((and (a (begin (display "1st" p) 1)) (b (begin (display "2nd" p) 2)) (c (begin (display "false" p) #f)) (d (begin (display "3nd" p) 3)))) (list a b c d)) #f) (equal? (get-output-string p) "1st2ndfalse"))) (fail 'ex7)) (or (equal? ((lambda (str . rest) (alet* ((len (string-length str)) (opt rest (start 0 (integer? start) (if (< start 0) 0 (end len (integer? end) (if (< end start) start (substring str start end))) "abcdefg" 1 20) "bcdefg") (fail 'ex8a)) (or (equal? ((lambda (str . rest) (alet* ((len (string-length str)) (min (apply min rest)) (cat rest (start 0 (= start min) (if (< start 0) 0 (end len (integer? end) (if (< end start) start (substring str start end))) "abcdefg" 20 1) "bcdefg") (fail 'ex8b)) (or (equal? ((lambda (str . rest) (alet ((cat rest (start 0 (and (list? start) (= 2 (length start)) (eq? 'start (car start))) (end (string-length str) (and (list? end) (= 2 (length end)) (eq? 'end (car end))) (substring str start end))) "abcdefg" '(end 6) '(start 1)) "bcdef") (fail 'ex8c)) (define rest-list '(a 10 cc 30 40 b 20)) (or (equal? (alet ((key rest-list (a 1) (b 2) ((c 'cc) 3) . d)) (list a b c d)) '(10 2 30 (40 b 20))) (fail 'ex9a)) (or (equal? (alet ((key rest-list (a 1) (b 2) ((c 'cc) 3) #f . d)) (list a b c d)) '(10 2 30 (40 b 20))) (fail 'ex9b)) (or (equal? (alet ((key rest-list (a 1) (b 2) ((c 'cc) 3) #t . d)) (list a b c d)) '(10 20 30 (40))) (fail 'ex9c)) (define rest (list 'a 10 'd 40 "c" 30 50 'b 20)) (or (equal? (alet ((key rest (a 1) (b 2) ((c "c") 3) . d)) (list a b c d)) '(10 2 30 (d 40 50 b 20))) (fail 'ex9d)) (or (equal? (alet ((key rest (a 1) (b 2) ((c "c") 3) #f . d)) (list a b c d)) '(10 2 3 (d 40 "c" 30 50 b 20))) (fail 'ex9e)) (or (equal? (alet ((key rest (a 1) (b 2) ((c "c") 3) #t . d)) (list a b c d)) '(10 20 30 (d 40 50))) (fail 'ex9f)) (or (equal? ((lambda (m . n) (alet* ((opt n (a 10) (b 20) (c 30) . d) (key d (x 100) (y 200) (a 300))) (list m a b c x y))) 0 1 2 3 'a 30 'y 20 'x 10) '(0 30 2 3 10 20)) (fail 'ex9g)) (or (equal? ((lambda (m . n) (alet* ((key n (x 100) (y 200) (a 300) . d) (opt d (a 10) (b 20) (c 30))) (list m a b c x y))) 0 'a 30 'y 20 'x 10 1 2 3) '(0 1 2 3 10 20)) (fail 'ex9h)) (or (equal? (alet* ((a 1) (rec (a 2) (b 3) (b (lambda () c)) (c a)) (d 50)) (list a (b) c d)) '(2 2 2 50)) (fail 'ex10)) (or (equal? (alet ((a b (mu 1 2)) This is different from SRFI 71 . ((e f) (mu 5 6)) ((values g h) (values 7 8)) ((i j . k) (nu 9 '(10 11 12))) ((values l m . n) (apply values 13 '(14 15 16))) o (mu 17 18) ((values . p) (values 19 20))) (list a b c d e f g h i j k l m n o p)) '(1 2 3 4 5 6 7 8 9 10 (11 12) 13 14 (15 16) (17 18) (19 20))) (fail 'ex11)) (or (equal? (alet ((a 1) (() (define a 10) (define b 100)) (b a)) (list a b)) '(1 10)) (fail 'ex12a)) (or (equal? (alet* ((a 1) (() (define a 10) (define b 100)) (b a)) (list a b)) '(10 10)) (fail 'ex12b)) (writeln "Done.")
1cb901b00357e343a3155e1ca158b63fe76f8304a46ace6de0d158099049526c
esl/escalus
escalus.erl
%%============================================================================== Copyright 2010 Erlang Solutions Ltd. %% Licensed under the Apache License , Version 2.0 ( the " License " ) ; %% you may not use this file except in compliance with the License. %% You may obtain a copy of the License at %% %% -2.0 %% %% Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %% See the License for the specific language governing permissions and %% limitations under the License. %%============================================================================== -module(escalus). % Public API -export([suite/0, init_per_suite/1, end_per_suite/1, init_per_testcase/2, end_per_testcase/2, create_users/1, create_users/2, delete_users/1, delete_users/2, get_users/1, override/3, make_everyone_friends/1, fresh_story/3, fresh_story_with_config/3, story/3, assert/2, assert/3, assert_many/2, send/2, send_and_wait/2, wait_for_stanza/1, wait_for_stanza/2, wait_for_stanzas/2, wait_for_stanzas/3, send_iq_and_wait_for_result/2, send_iq_and_wait_for_result/3, peek_stanzas/1]). -export_type([client/0, config/0]). -include("escalus.hrl"). %%-------------------------------------------------------------------- %% Public Types %%-------------------------------------------------------------------- -type client() :: #client{}. -type config() :: escalus_config:config(). %%-------------------------------------------------------------------- %% Public API %%-------------------------------------------------------------------- -spec suite() -> [{atom(), atom()}]. suite() -> [{require, escalus_users}]. -spec init_per_suite(config()) -> config(). init_per_suite(Config) -> application:ensure_all_started(escalus), escalus_users:start(Config), escalus_fresh:start(Config), Config. -spec end_per_suite(config()) -> ok. end_per_suite(Config) -> escalus_users:stop(Config), escalus_fresh:stop(Config), ok. -spec init_per_testcase(atom(), config()) -> config(). init_per_testcase(CaseName, Config) -> Config1 = escalus_cleaner:start(Config), escalus_event:start([{tc_name, CaseName}|Config1]). -spec end_per_testcase(atom(), config()) -> ok. end_per_testcase(_CaseName, Config) -> Config1 = escalus_event:stop(Config), escalus_cleaner:stop(Config1). %%-------------------------------------------------------------------- %% Public API - forward functions from other modules %%-------------------------------------------------------------------- %% User API -spec create_users(config()) -> config(). create_users(Config) -> escalus_users:create_users(Config). -spec create_users(config(), [escalus_users:named_user()]) -> config(). create_users(Config, Users) -> escalus_users:create_users(Config, Users). -spec delete_users(config()) -> config(). delete_users(Config) -> escalus_users:delete_users(Config). -spec delete_users(config(), [escalus_users:named_user()]) -> config(). delete_users(Config, Users) -> escalus_users:delete_users(Config, Users). -spec get_users(Names) -> Result when Names :: all | [escalus_users:user_name()] | {by_name, [escalus_users:user_name()]}, Result :: [escalus_users:named_user()]. get_users(Names) -> escalus_users:get_users(Names). %% Story API -spec make_everyone_friends(config()) -> config(). make_everyone_friends(Config) -> escalus_story:make_everyone_friends(Config). -spec fresh_story(config(), [escalus_users:resource_spec()], fun()) -> any(). fresh_story(Config, ResourceCounts, Story) -> escalus_fresh:story(Config, ResourceCounts, Story). -spec fresh_story_with_config(config(), [escalus_users:resource_spec()], fun()) -> any(). fresh_story_with_config(Config, ResourceCounts, Story) -> escalus_fresh:story_with_config(Config, ResourceCounts, Story). -spec story(config(), [escalus_users:resource_spec()], fun()) -> any(). story(Config, ResourceCounts, Story) -> escalus_story:story(Config, ResourceCounts, Story). %% Assertions assert(PredSpec, Arg) -> escalus_new_assert:assert(PredSpec, Arg). assert(PredSpec, Params, Arg) -> escalus_new_assert:assert(PredSpec, Params, Arg). assert_many(Predicates, Stanzas) -> escalus_new_assert:assert_many(Predicates, Stanzas). %% Client API send(Client, Packet) -> escalus_client:send(Client, Packet). send_and_wait(Client, Packet) -> escalus_client:send_and_wait(Client, Packet). wait_for_stanza(Client) -> escalus_client:wait_for_stanza(Client). wait_for_stanza(Client, Timeout) -> escalus_client:wait_for_stanza(Client, Timeout). wait_for_stanzas(Client, Count) -> escalus_client:wait_for_stanzas(Client, Count). wait_for_stanzas(Client, Count, Timeout) -> escalus_client:wait_for_stanzas(Client, Count, Timeout). peek_stanzas(Client) -> escalus_client:peek_stanzas(Client). send_iq_and_wait_for_result(Client, Iq) -> escalus_client:send_iq_and_wait_for_result(Client, Iq). send_iq_and_wait_for_result(Client, Iq, Timeout) -> escalus_client:send_iq_and_wait_for_result(Client, Iq, Timeout). %% Other functions override(Config, OverrideName, NewValue) -> escalus_overridables:override(Config, OverrideName, NewValue).
null
https://raw.githubusercontent.com/esl/escalus/ac5e813ac96c0cdb5d5ac738d63d992f5f948585/src/escalus.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. ============================================================================== Public API -------------------------------------------------------------------- Public Types -------------------------------------------------------------------- -------------------------------------------------------------------- Public API -------------------------------------------------------------------- -------------------------------------------------------------------- Public API - forward functions from other modules -------------------------------------------------------------------- User API Story API Assertions Client API Other functions
Copyright 2010 Erlang Solutions Ltd. Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , -module(escalus). -export([suite/0, init_per_suite/1, end_per_suite/1, init_per_testcase/2, end_per_testcase/2, create_users/1, create_users/2, delete_users/1, delete_users/2, get_users/1, override/3, make_everyone_friends/1, fresh_story/3, fresh_story_with_config/3, story/3, assert/2, assert/3, assert_many/2, send/2, send_and_wait/2, wait_for_stanza/1, wait_for_stanza/2, wait_for_stanzas/2, wait_for_stanzas/3, send_iq_and_wait_for_result/2, send_iq_and_wait_for_result/3, peek_stanzas/1]). -export_type([client/0, config/0]). -include("escalus.hrl"). -type client() :: #client{}. -type config() :: escalus_config:config(). -spec suite() -> [{atom(), atom()}]. suite() -> [{require, escalus_users}]. -spec init_per_suite(config()) -> config(). init_per_suite(Config) -> application:ensure_all_started(escalus), escalus_users:start(Config), escalus_fresh:start(Config), Config. -spec end_per_suite(config()) -> ok. end_per_suite(Config) -> escalus_users:stop(Config), escalus_fresh:stop(Config), ok. -spec init_per_testcase(atom(), config()) -> config(). init_per_testcase(CaseName, Config) -> Config1 = escalus_cleaner:start(Config), escalus_event:start([{tc_name, CaseName}|Config1]). -spec end_per_testcase(atom(), config()) -> ok. end_per_testcase(_CaseName, Config) -> Config1 = escalus_event:stop(Config), escalus_cleaner:stop(Config1). -spec create_users(config()) -> config(). create_users(Config) -> escalus_users:create_users(Config). -spec create_users(config(), [escalus_users:named_user()]) -> config(). create_users(Config, Users) -> escalus_users:create_users(Config, Users). -spec delete_users(config()) -> config(). delete_users(Config) -> escalus_users:delete_users(Config). -spec delete_users(config(), [escalus_users:named_user()]) -> config(). delete_users(Config, Users) -> escalus_users:delete_users(Config, Users). -spec get_users(Names) -> Result when Names :: all | [escalus_users:user_name()] | {by_name, [escalus_users:user_name()]}, Result :: [escalus_users:named_user()]. get_users(Names) -> escalus_users:get_users(Names). -spec make_everyone_friends(config()) -> config(). make_everyone_friends(Config) -> escalus_story:make_everyone_friends(Config). -spec fresh_story(config(), [escalus_users:resource_spec()], fun()) -> any(). fresh_story(Config, ResourceCounts, Story) -> escalus_fresh:story(Config, ResourceCounts, Story). -spec fresh_story_with_config(config(), [escalus_users:resource_spec()], fun()) -> any(). fresh_story_with_config(Config, ResourceCounts, Story) -> escalus_fresh:story_with_config(Config, ResourceCounts, Story). -spec story(config(), [escalus_users:resource_spec()], fun()) -> any(). story(Config, ResourceCounts, Story) -> escalus_story:story(Config, ResourceCounts, Story). assert(PredSpec, Arg) -> escalus_new_assert:assert(PredSpec, Arg). assert(PredSpec, Params, Arg) -> escalus_new_assert:assert(PredSpec, Params, Arg). assert_many(Predicates, Stanzas) -> escalus_new_assert:assert_many(Predicates, Stanzas). send(Client, Packet) -> escalus_client:send(Client, Packet). send_and_wait(Client, Packet) -> escalus_client:send_and_wait(Client, Packet). wait_for_stanza(Client) -> escalus_client:wait_for_stanza(Client). wait_for_stanza(Client, Timeout) -> escalus_client:wait_for_stanza(Client, Timeout). wait_for_stanzas(Client, Count) -> escalus_client:wait_for_stanzas(Client, Count). wait_for_stanzas(Client, Count, Timeout) -> escalus_client:wait_for_stanzas(Client, Count, Timeout). peek_stanzas(Client) -> escalus_client:peek_stanzas(Client). send_iq_and_wait_for_result(Client, Iq) -> escalus_client:send_iq_and_wait_for_result(Client, Iq). send_iq_and_wait_for_result(Client, Iq, Timeout) -> escalus_client:send_iq_and_wait_for_result(Client, Iq, Timeout). override(Config, OverrideName, NewValue) -> escalus_overridables:override(Config, OverrideName, NewValue).
7acf64ad2557c8c29b0a48549fae6342497eacbd36bd7eb9dd11a4150ccf5d57
agentultra/postgresql-replicant
Lsn.hs
{-# LANGUAGE Strict #-} | Module : Database . PostgreSQL.Replicant . Types . Lsn Description : Types and parsers for : ( c ) , 2020 , 2021 License : : Stability : experimental Portability : POSIX /Log Sequence Number/ or LSN is a pointer to a place inside of a WAL log file . It contains the file name and an offset in bytes encoded in two parts . can be serialized into 64 - bit big - endian numbers in the binary protocol but are also represented textually in query results and other places . This module follows a similar convention to many containers libraries and should probably be imported qualified to avoid name clashes if needed . See : -pg-lsn.html Module : Database.PostgreSQL.Replicant.Types.Lsn Description : Types and parsers for LSNs Copyright : (c) James King, 2020, 2021 License : BSD3 Maintainer : Stability : experimental Portability : POSIX /Log Sequence Number/ or LSN is a pointer to a place inside of a WAL log file. It contains the file name and an offset in bytes encoded in two parts. LSNs can be serialized into 64-bit big-endian numbers in the binary protocol but are also represented textually in query results and other places. This module follows a similar convention to many containers libraries and should probably be imported qualified to avoid name clashes if needed. See: -pg-lsn.html -} module Database.PostgreSQL.Replicant.Types.Lsn where import Data.Aeson import Data.Attoparsec.ByteString.Char8 import Data.Bits import Data.Bits.Extras import Data.ByteString (ByteString ()) import qualified Data.ByteString.Lazy as BL import qualified Data.ByteString.Lazy.Builder as Builder import Data.ByteString.Lazy.Builder.ASCII (word32Hex) import Data.Serialize import Data.Word import qualified Data.Text as T import qualified Data.Text.Encoding as T import GHC.Int data LSN = LSN { filepart :: !Int32 -- ^ Filepart , offset :: !Int32 -- ^ Offset } deriving (Show, Eq) instance Ord LSN where compare (LSN l0 r0) (LSN l1 r1) = compare l0 l1 <> compare r0 r1 instance Serialize LSN where put = putInt64be . toInt64 get = fromInt64 <$> getInt64be instance ToJSON LSN where toJSON = String . T.toUpper . T.decodeUtf8 . toByteString instance FromJSON LSN where parseJSON = withText "LSN" $ \txt -> case fromByteString . T.encodeUtf8 $ txt of Left err -> fail err Right lsn -> pure lsn | Convert an LSN to a 64 - bit integer toInt64 :: LSN -> Int64 toInt64 (LSN filePart offSet) = let r = w64 filePart `shiftL` 32 in fromIntegral $ r .|. fromIntegral offSet | Convert a 64 - bit integer to an LSN fromInt64 :: Int64 -> LSN fromInt64 x = let mask = w64 $ maxBound @Word32 offSet = fromIntegral . w32 $ mask .&. fromIntegral x filePart = fromIntegral $ x `shiftR` 32 in LSN filePart offSet lsnParser :: Parser LSN lsnParser = LSN <$> (hexadecimal <* char '/') <*> hexadecimal fromByteString :: ByteString -> Either String LSN fromByteString = parseOnly lsnParser -- | Note that as of bytestring ~0.10.12.0 we don't have upper-case -- hex encoders but the patch to add them has been merged and when -- available we should switch to them toByteString :: LSN -> ByteString toByteString (LSN filepart off) = BL.toStrict $ Builder.toLazyByteString ( word32Hex (fromIntegral filepart) <> Builder.char7 '/' <> word32Hex (fromIntegral off) ) | Add a number of bytes to an LSN add :: LSN -> Int64 -> LSN add lsn bytes = fromInt64 . (+ bytes) . toInt64 $ lsn | Subtract a number of bytes from an LSN sub :: LSN -> Int64 -> LSN sub lsn bytes = fromInt64 . flip (-) bytes . toInt64 $ lsn | Subtract two LSN 's to calculate the difference of bytes between -- them. subLsn :: LSN -> LSN -> Int64 subLsn lsn1 lsn2 = toInt64 lsn1 - toInt64 lsn2
null
https://raw.githubusercontent.com/agentultra/postgresql-replicant/aa31b5a49085ac1d91ace2358bcb494e48bbd9d0/src/Database/PostgreSQL/Replicant/Types/Lsn.hs
haskell
# LANGUAGE Strict # ^ Filepart ^ Offset | Note that as of bytestring ~0.10.12.0 we don't have upper-case hex encoders but the patch to add them has been merged and when available we should switch to them them.
| Module : Database . PostgreSQL.Replicant . Types . Lsn Description : Types and parsers for : ( c ) , 2020 , 2021 License : : Stability : experimental Portability : POSIX /Log Sequence Number/ or LSN is a pointer to a place inside of a WAL log file . It contains the file name and an offset in bytes encoded in two parts . can be serialized into 64 - bit big - endian numbers in the binary protocol but are also represented textually in query results and other places . This module follows a similar convention to many containers libraries and should probably be imported qualified to avoid name clashes if needed . See : -pg-lsn.html Module : Database.PostgreSQL.Replicant.Types.Lsn Description : Types and parsers for LSNs Copyright : (c) James King, 2020, 2021 License : BSD3 Maintainer : Stability : experimental Portability : POSIX /Log Sequence Number/ or LSN is a pointer to a place inside of a WAL log file. It contains the file name and an offset in bytes encoded in two parts. LSNs can be serialized into 64-bit big-endian numbers in the binary protocol but are also represented textually in query results and other places. This module follows a similar convention to many containers libraries and should probably be imported qualified to avoid name clashes if needed. See: -pg-lsn.html -} module Database.PostgreSQL.Replicant.Types.Lsn where import Data.Aeson import Data.Attoparsec.ByteString.Char8 import Data.Bits import Data.Bits.Extras import Data.ByteString (ByteString ()) import qualified Data.ByteString.Lazy as BL import qualified Data.ByteString.Lazy.Builder as Builder import Data.ByteString.Lazy.Builder.ASCII (word32Hex) import Data.Serialize import Data.Word import qualified Data.Text as T import qualified Data.Text.Encoding as T import GHC.Int data LSN = LSN } deriving (Show, Eq) instance Ord LSN where compare (LSN l0 r0) (LSN l1 r1) = compare l0 l1 <> compare r0 r1 instance Serialize LSN where put = putInt64be . toInt64 get = fromInt64 <$> getInt64be instance ToJSON LSN where toJSON = String . T.toUpper . T.decodeUtf8 . toByteString instance FromJSON LSN where parseJSON = withText "LSN" $ \txt -> case fromByteString . T.encodeUtf8 $ txt of Left err -> fail err Right lsn -> pure lsn | Convert an LSN to a 64 - bit integer toInt64 :: LSN -> Int64 toInt64 (LSN filePart offSet) = let r = w64 filePart `shiftL` 32 in fromIntegral $ r .|. fromIntegral offSet | Convert a 64 - bit integer to an LSN fromInt64 :: Int64 -> LSN fromInt64 x = let mask = w64 $ maxBound @Word32 offSet = fromIntegral . w32 $ mask .&. fromIntegral x filePart = fromIntegral $ x `shiftR` 32 in LSN filePart offSet lsnParser :: Parser LSN lsnParser = LSN <$> (hexadecimal <* char '/') <*> hexadecimal fromByteString :: ByteString -> Either String LSN fromByteString = parseOnly lsnParser toByteString :: LSN -> ByteString toByteString (LSN filepart off) = BL.toStrict $ Builder.toLazyByteString ( word32Hex (fromIntegral filepart) <> Builder.char7 '/' <> word32Hex (fromIntegral off) ) | Add a number of bytes to an LSN add :: LSN -> Int64 -> LSN add lsn bytes = fromInt64 . (+ bytes) . toInt64 $ lsn | Subtract a number of bytes from an LSN sub :: LSN -> Int64 -> LSN sub lsn bytes = fromInt64 . flip (-) bytes . toInt64 $ lsn | Subtract two LSN 's to calculate the difference of bytes between subLsn :: LSN -> LSN -> Int64 subLsn lsn1 lsn2 = toInt64 lsn1 - toInt64 lsn2
2e4ed66f736f32aadfdd35c9d37a69d84fe3c379b7bc7f64316518e6d8065f08
ocaml-sf/learn-ocaml-corpus
pigeonhole_id.ml
let pigeonhole_sort (bound : int) (kvs : (int * 'v) list) : 'v list = List.map snd kvs (* trying to cheat *)
null
https://raw.githubusercontent.com/ocaml-sf/learn-ocaml-corpus/7dcf4d72b49863a3e37e41b3c3097aa4c6101a69/exercises/fpottier/generic_sorting/wrong/pigeonhole_id.ml
ocaml
trying to cheat
let pigeonhole_sort (bound : int) (kvs : (int * 'v) list) : 'v list =
bce69b6499f0c5c00381fe65d07524644d6e2a493533ea0c63092b43bfc9da6e
kazu-yamamoto/llrbtree
RBTree.hs
| Purely functional red - black trees . * , \"Red - Black Trees in a Functional Setting\ " , Journal of Functional Programming , 9(4 ) , pp 471 - 477 , July 1999 < #jfp99 > * , \"Red - black trees with " , Journal of functional programming , 11(04 ) , pp 425 - 432 , July 2001 Purely functional red-black trees. * Chris Okasaki, \"Red-Black Trees in a Functional Setting\", Journal of Functional Programming, 9(4), pp 471-477, July 1999 <#jfp99> * Stefan Kahrs, \"Red-black trees with types\", Journal of functional programming, 11(04), pp 425-432, July 2001 -} module Data.Set.RBTree ( -- * Data structures RBTree(..) , Color(..) , BlackHeight -- * Creating red-black trees , empty , singleton , insert , fromList -- * Converting to a list , toList -- * Membership , member -- * Deleting , delete , deleteMin , deleteMax -- * Checking , null -- * Set operations , union , intersection , difference -- * Helper functions , join , merge , split , minimum , maximum , valid , showSet , printSet ) where import Data.List (foldl') import Prelude hiding (minimum, maximum, null) ---------------------------------------------------------------- -- Part to be shared ---------------------------------------------------------------- data RBTree a = Leaf -- color is Black | Node Color !BlackHeight !(RBTree a) a !(RBTree a) deriving (Show) data Color = B -- ^ Black | R -- ^ Red deriving (Eq,Show) | Red nodes have the same BlackHeight of their parent . Red nodes have the same BlackHeight of their parent. -} type BlackHeight = Int ---------------------------------------------------------------- instance (Eq a) => Eq (RBTree a) where t1 == t2 = toList t1 == toList t2 ---------------------------------------------------------------- height :: RBTree a -> BlackHeight height Leaf = 0 height (Node _ h _ _ _) = h ---------------------------------------------------------------- | See if the red black tree is empty . > > > Data.Set.RBTree.null empty True > > > Data.Set.RBTree.null ( singleton 1 ) False See if the red black tree is empty. >>> Data.Set.RBTree.null empty True >>> Data.Set.RBTree.null (singleton 1) False -} null :: Eq a => RBTree a -> Bool null t = t == Leaf ---------------------------------------------------------------- | Empty tree . > > > height empty 0 >>> height empty 0 -} empty :: RBTree a empty = Leaf | Singleton tree . > > > height ( singleton ' a ' ) 1 >>> height (singleton 'a') 1 -} singleton :: Ord a => a -> RBTree a singleton x = Node B 1 Leaf x Leaf ---------------------------------------------------------------- | Creating a tree from a list . Worst - case : O(N log N ) > > > empty = = fromList [ ] True > > > singleton ' a ' = = fromList [ ' a ' ] True > > > fromList [ 5,3,5 ] = = fromList [ 5,3 ] True >>> empty == fromList [] True >>> singleton 'a' == fromList ['a'] True >>> fromList [5,3,5] == fromList [5,3] True -} fromList :: Ord a => [a] -> RBTree a fromList = foldl' (flip insert) empty ---------------------------------------------------------------- | Creating a list from a tree . Worst - case : O(N ) > > > toList ( fromList [ 5,3 ] ) [ 3,5 ] > > > toList empty [ ] >>> toList (fromList [5,3]) [3,5] >>> toList empty [] -} toList :: RBTree a -> [a] toList t = inorder t [] where inorder Leaf xs = xs inorder (Node _ _ l x r) xs = inorder l (x : inorder r xs) ---------------------------------------------------------------- | Checking if this element is a member of a tree ? > > > member 5 ( fromList [ 5,3 ] ) True > > > member 1 ( fromList [ 5,3 ] ) False >>> member 5 (fromList [5,3]) True >>> member 1 (fromList [5,3]) False -} member :: Ord a => a -> RBTree a -> Bool member _ Leaf = False member x (Node _ _ l y r) = case compare x y of LT -> member x l GT -> member x r EQ -> True ---------------------------------------------------------------- isBalanced :: RBTree a -> Bool isBalanced t = isBlackSame t && isRedSeparate t isBlackSame :: RBTree a -> Bool isBlackSame t = all (n==) ns where n:ns = blacks t blacks :: RBTree a -> [Int] blacks = blacks' 0 where blacks' n Leaf = [n+1] blacks' n (Node R _ l _ r) = blacks' n l ++ blacks' n r blacks' n (Node B _ l _ r) = blacks' n' l ++ blacks' n' r where n' = n + 1 isRedSeparate :: RBTree a -> Bool isRedSeparate = reds B reds :: Color -> RBTree t -> Bool reds _ Leaf = True reds R (Node R _ _ _ _) = False reds _ (Node c _ l _ r) = reds c l && reds c r isOrdered :: Ord a => RBTree a -> Bool isOrdered t = ordered $ toList t where ordered [] = True ordered [_] = True ordered (x:y:xys) = x < y && ordered (y:xys) blackHeight :: RBTree a -> Bool blackHeight Leaf = True blackHeight t@(Node B i _ _ _) = bh i t where bh n Leaf = n == 0 bh n (Node R h l _ r) = n == h' && bh n l && bh n r where h' = h - 1 bh n (Node B h l _ r) = n == h && bh n' l && bh n' r where n' = n - 1 blackHeight _ = error "blackHeight" ---------------------------------------------------------------- turnR :: RBTree a -> RBTree a turnR Leaf = error "turnR" turnR (Node _ h l x r) = Node R h l x r turnB :: RBTree a -> RBTree a turnB Leaf = error "turnB" turnB (Node _ h l x r) = Node B h l x r turnB' :: RBTree a -> RBTree a turnB' Leaf = Leaf turnB' (Node _ h l x r) = Node B h l x r ---------------------------------------------------------------- | Finding the minimum element . Worst - case : O(log N ) > > > minimum ( fromList [ 3,5,1 ] ) 1 > > > minimum empty * * * Exception : minimum >>> minimum (fromList [3,5,1]) 1 >>> minimum empty *** Exception: minimum -} minimum :: RBTree a -> a minimum (Node _ _ Leaf x _) = x minimum (Node _ _ l _ _) = minimum l minimum _ = error "minimum" | Finding the maximum element . Worst - case : O(log N ) > > > maximum ( fromList [ 3,5,1 ] ) 5 > > > maximum empty * * * Exception : maximum >>> maximum (fromList [3,5,1]) 5 >>> maximum empty *** Exception: maximum -} maximum :: RBTree a -> a maximum (Node _ _ _ x Leaf) = x maximum (Node _ _ _ _ r) = maximum r maximum _ = error "maximum" ---------------------------------------------------------------- showSet :: Show a => RBTree a -> String showSet = showSet' "" showSet' :: Show a => String -> RBTree a -> String showSet' _ Leaf = "\n" showSet' pref (Node k h l x r) = show k ++ " " ++ show x ++ " (" ++ show h ++ ")\n" ++ pref ++ "+ " ++ showSet' pref' l ++ pref ++ "+ " ++ showSet' pref' r where pref' = " " ++ pref printSet :: Show a => RBTree a -> IO () printSet = putStr . showSet ---------------------------------------------------------------- isRed :: RBTree a -> Bool isRed (Node R _ _ _ _ ) = True isRed _ = False ---------------------------------------------------------------- -- Basic operations ---------------------------------------------------------------- {-| Checking validity of a tree. -} valid :: Ord a => RBTree a -> Bool valid t = isBalanced t && blackHeight t && isOrdered t ---------------------------------------------------------------- -- | Insertion . Worst - case : O(log N ) > > > insert 5 ( fromList [ 5,3 ] ) = = fromList [ 3,5 ] True > > > insert 7 ( fromList [ 5,3 ] ) = = fromList [ 3,5,7 ] True > > > insert 5 empty = = singleton 5 True >>> insert 5 (fromList [5,3]) == fromList [3,5] True >>> insert 7 (fromList [5,3]) == fromList [3,5,7] True >>> insert 5 empty == singleton 5 True -} insert :: Ord a => a -> RBTree a -> RBTree a insert kx t = turnB (insert' kx t) insert' :: Ord a => a -> RBTree a -> RBTree a insert' kx Leaf = Node R 1 Leaf kx Leaf insert' kx s@(Node B h l x r) = case compare kx x of LT -> balanceL' h (insert' kx l) x r GT -> balanceR' h l x (insert' kx r) EQ -> s insert' kx s@(Node R h l x r) = case compare kx x of LT -> Node R h (insert' kx l) x r GT -> Node R h l x (insert' kx r) EQ -> s balanceL' :: BlackHeight -> RBTree a -> a -> RBTree a -> RBTree a balanceL' h (Node R _ (Node R _ a x b) y c) z d = Node R (h+1) (Node B h a x b) y (Node B h c z d) balanceL' h (Node R _ a x (Node R _ b y c)) z d = Node R (h+1) (Node B h a x b) y (Node B h c z d) balanceL' h l x r = Node B h l x r balanceR' :: BlackHeight -> RBTree a -> a -> RBTree a -> RBTree a balanceR' h a x (Node R _ b y (Node R _ c z d)) = Node R (h+1) (Node B h a x b) y (Node B h c z d) balanceR' h a x (Node R _ (Node R _ b y c) z d) = Node R (h+1) (Node B h a x b) y (Node B h c z d) balanceR' h l x r = Node B h l x r ---------------------------------------------------------------- balanceL :: Color -> BlackHeight -> RBTree a -> a -> RBTree a -> RBTree a balanceL B h (Node R _ (Node R _ a x b) y c) z d = Node R (h+1) (Node B h a x b) y (Node B h c z d) balanceL B h (Node R _ a x (Node R _ b y c)) z d = Node R (h+1) (Node B h a x b) y (Node B h c z d) balanceL k h l x r = Node k h l x r balanceR :: Color -> BlackHeight -> RBTree a -> a -> RBTree a -> RBTree a balanceR B h a x (Node R _ b y (Node R _ c z d)) = Node R (h+1) (Node B h a x b) y (Node B h c z d) balanceR B h a x (Node R _ (Node R _ b y c) z d) = Node R (h+1) (Node B h a x b) y (Node B h c z d) balanceR k h l x r = Node k h l x r ---------------------------------------------------------------- type RBTreeBDel a = (RBTree a, Bool) unbalancedL :: Color -> BlackHeight -> RBTree a -> a -> RBTree a -> RBTreeBDel a unbalancedL c h l@(Node B _ _ _ _) x r = (balanceL B h (turnR l) x r, c == B) unbalancedL B h (Node R lh ll lx lr@(Node B _ _ _ _)) x r = (Node B lh ll lx (balanceL B h (turnR lr) x r), False) unbalancedL _ _ _ _ _ = error "unbalancedL" The left tree lacks one Black node unbalancedR :: Color -> BlackHeight -> RBTree a -> a -> RBTree a -> (RBTree a, Bool) Decreasing one Black node in the right unbalancedR c h l x r@(Node B _ _ _ _) = (balanceR B h l x (turnR r), c == B) Taking one Red node from the right and adding it to the right as Black unbalancedR B h l x (Node R rh rl@(Node B _ _ _ _) rx rr) = (Node B rh (balanceR B h l x (turnR rl)) rx rr, False) unbalancedR _ _ _ _ _ = error "unbalancedR" ---------------------------------------------------------------- | Deleting the minimum element . Worst - case : O(log N ) > > > deleteMin ( fromList [ 5,3,7 ] ) = = fromList [ 5,7 ] True > > > deleteMin empty = = empty True >>> deleteMin (fromList [5,3,7]) == fromList [5,7] True >>> deleteMin empty == empty True -} deleteMin :: RBTree a -> RBTree a deleteMin Leaf = empty deleteMin t = turnB' s where ((s, _), _) = deleteMin' t deleteMin' :: RBTree a -> (RBTreeBDel a, a) deleteMin' Leaf = error "deleteMin'" deleteMin' (Node B _ Leaf x Leaf) = ((Leaf, True), x) deleteMin' (Node B _ Leaf x r@(Node R _ _ _ _)) = ((turnB r, False), x) deleteMin' (Node R _ Leaf x r) = ((r, False), x) deleteMin' (Node c h l x r) = if d then (tD, m) else (tD', m) where ((l',d),m) = deleteMin' l tD = unbalancedR c (h-1) l' x r tD' = (Node c h l' x r, False) ---------------------------------------------------------------- {-| Deleting the maximum >>> deleteMax (fromList [(5,"a"), (3,"b"), (7,"c")]) == fromList [(3,"b"), (5,"a")] True >>> deleteMax empty == empty True -} deleteMax :: RBTree a -> RBTree a deleteMax Leaf = empty deleteMax t = turnB' s where ((s, _), _) = deleteMax' t deleteMax' :: RBTree a -> (RBTreeBDel a, a) deleteMax' Leaf = error "deleteMax'" deleteMax' (Node B _ Leaf x Leaf) = ((Leaf, True), x) deleteMax' (Node B _ l@(Node R _ _ _ _) x Leaf) = ((turnB l, False), x) deleteMax' (Node R _ l x Leaf) = ((l, False), x) deleteMax' (Node c h l x r) = if d then (tD, m) else (tD', m) where ((r',d),m) = deleteMax' r tD = unbalancedL c (h-1) l x r' tD' = (Node c h l x r', False) ---------------------------------------------------------------- blackify :: RBTree a -> RBTreeBDel a blackify s@(Node R _ _ _ _) = (turnB s, False) blackify s = (s, True) | Deleting this element from a tree . Worst - case : O(log N ) > > > delete 5 ( fromList [ 5,3 ] ) = = singleton 3 True > > > delete 7 ( fromList [ 5,3 ] ) = = fromList [ 3,5 ] True > > > delete 5 empty = = empty True >>> delete 5 (fromList [5,3]) == singleton 3 True >>> delete 7 (fromList [5,3]) == fromList [3,5] True >>> delete 5 empty == empty True -} delete :: Ord a => a -> RBTree a -> RBTree a delete x t = turnB' s where (s,_) = delete' x t delete' :: Ord a => a -> RBTree a -> RBTreeBDel a delete' _ Leaf = (Leaf, False) delete' x (Node c h l y r) = case compare x y of LT -> let (l',d) = delete' x l t = Node c h l' y r in if d then unbalancedR c (h-1) l' y r else (t, False) GT -> let (r',d) = delete' x r t = Node c h l y r' in if d then unbalancedL c (h-1) l y r' else (t, False) EQ -> case r of Leaf -> if c == B then blackify l else (l, False) _ -> let ((r',d),m) = deleteMin' r t = Node c h l m r' in if d then unbalancedL c (h-1) l m r' else (t, False) ---------------------------------------------------------------- -- Set operations ---------------------------------------------------------------- | Joining two trees with an element . Worst - case : O(log N ) Each element of the left tree must be less than the element . Each element of the right tree must be greater than the element . Both tree must have black root . Each element of the left tree must be less than the element. Each element of the right tree must be greater than the element. Both tree must have black root. -} join :: Ord a => RBTree a -> a -> RBTree a -> RBTree a join Leaf g t2 = insert g t2 join t1 g Leaf = insert g t1 join t1 g t2 = case compare h1 h2 of LT -> turnB $ joinLT t1 g t2 h1 GT -> turnB $ joinGT t1 g t2 h2 EQ -> Node B (h1+1) t1 g t2 where h1 = height t1 h2 = height t2 -- The root of result must be red. joinLT :: Ord a => RBTree a -> a -> RBTree a -> BlackHeight -> RBTree a joinLT t1 g t2@(Node c h l x r) h1 | h == h1 = Node R (h+1) t1 g t2 | otherwise = balanceL c h (joinLT t1 g l h1) x r joinLT _ _ _ _ = error "joinLT" -- The root of result must be red. joinGT :: Ord a => RBTree a -> a -> RBTree a -> BlackHeight -> RBTree a joinGT t1@(Node c h l x r) g t2 h2 | h == h2 = Node R (h+1) t1 g t2 | otherwise = balanceR c h l x (joinGT r g t2 h2) joinGT _ _ _ _ = error "joinGT" ---------------------------------------------------------------- | Merging two trees . Worst - case : O(log N ) Each element of the left tree must be less than each element of the right tree . Both trees must have black root . Each element of the left tree must be less than each element of the right tree. Both trees must have black root. -} merge :: Ord a => RBTree a -> RBTree a -> RBTree a merge Leaf t2 = t2 merge t1 Leaf = t1 merge t1 t2 = case compare h1 h2 of LT -> turnB $ mergeLT t1 t2 h1 GT -> turnB $ mergeGT t1 t2 h2 EQ -> turnB $ mergeEQ t1 t2 where h1 = height t1 h2 = height t2 mergeLT :: Ord a => RBTree a -> RBTree a -> BlackHeight -> RBTree a mergeLT t1 t2@(Node c h l x r) h1 | h == h1 = mergeEQ t1 t2 | otherwise = balanceL c h (mergeLT t1 l h1) x r mergeLT _ _ _ = error "mergeLT" mergeGT :: Ord a => RBTree a -> RBTree a -> BlackHeight -> RBTree a mergeGT t1@(Node c h l x r) t2 h2 | h == h2 = mergeEQ t1 t2 | otherwise = balanceR c h l x (mergeGT r t2 h2) mergeGT _ _ _ = error "mergeGT" Merging two trees whose heights are the same . The root must be either a red with height + 1 for a black with height Merging two trees whose heights are the same. The root must be either a red with height + 1 for a black with height -} mergeEQ :: Ord a => RBTree a -> RBTree a -> RBTree a mergeEQ Leaf Leaf = Leaf mergeEQ t1@(Node _ h l x r) t2 | h == h2' = Node R (h+1) t1 m t2' | isRed l = Node R (h+1) (turnB l) x (Node B h r m t2') -- unnecessary for LL | isRed r = Node B h (Node R h l x rl) rx (Node R h rr m t2') | otherwise = Node B h (turnR t1) m t2' where m = minimum t2 t2' = deleteMin t2 h2' = height t2' Node R _ rl rx rr = r mergeEQ _ _ = error "mergeEQ" ---------------------------------------------------------------- | Splitting a tree . Worst - case : O(log N ) > > > split 2 ( fromList [ 5,3 ] ) = = ( empty , fromList [ 3,5 ] ) True > > > split 3 ( fromList [ 5,3 ] ) = = ( empty , singleton 5 ) True > > > split 4 ( fromList [ 5,3 ] ) = = ( singleton 3 , singleton 5 ) True > > > split 5 ( fromList [ 5,3 ] ) = = ( singleton 3 , empty ) True > > > split 6 ( fromList [ 5,3 ] ) = = ( fromList [ 3,5 ] , empty ) True >>> split 2 (fromList [5,3]) == (empty, fromList [3,5]) True >>> split 3 (fromList [5,3]) == (empty, singleton 5) True >>> split 4 (fromList [5,3]) == (singleton 3, singleton 5) True >>> split 5 (fromList [5,3]) == (singleton 3, empty) True >>> split 6 (fromList [5,3]) == (fromList [3,5], empty) True -} split :: Ord a => a -> RBTree a -> (RBTree a, RBTree a) split _ Leaf = (Leaf,Leaf) split kx (Node _ _ l x r) = case compare kx x of LT -> (lt, join gt x (turnB' r)) where (lt,gt) = split kx l GT -> (join (turnB' l) x lt, gt) where (lt,gt) = split kx r EQ -> (turnB' l, turnB' r) LL split : : a = > a - > RBTree a - > ( RBTree a , RBTree a ) split _ Leaf = ( Leaf , Leaf ) split kx ( Node _ _ l x r ) = case compare kx x of LT - > ( lt , join gt x r ) where ( lt , gt ) = split kx l GT - > ( join l x lt , gt ) where ( lt , gt ) = split kx r EQ - > ( turnB ' l , r ) split :: Ord a => a -> RBTree a -> (RBTree a, RBTree a) split _ Leaf = (Leaf,Leaf) split kx (Node _ _ l x r) = case compare kx x of LT -> (lt, join gt x r) where (lt,gt) = split kx l GT -> (join l x lt, gt) where (lt,gt) = split kx r EQ -> (turnB' l, r) -} ---------------------------------------------------------------- | Creating a union tree from two trees . Worst - case : O(N + M ) > > > union ( fromList [ 5,3 ] ) ( fromList [ 5,7 ] ) = = fromList [ 3,5,7 ] True >>> union (fromList [5,3]) (fromList [5,7]) == fromList [3,5,7] True -} union :: Ord a => RBTree a -> RBTree a -> RBTree a union t1 Leaf = t1 -- ensured Black thanks to split union Leaf t2 = turnB' t2 union t1 (Node _ _ l x r) = join (union l' l) x (union r' r) where (l',r') = split x t1 | Creating a intersection tree from trees . Worst - case : O(N + N ) > > > intersection ( fromList [ 5,3 ] ) ( fromList [ 5,7 ] ) = = singleton 5 True >>> intersection (fromList [5,3]) (fromList [5,7]) == singleton 5 True -} intersection :: Ord a => RBTree a -> RBTree a -> RBTree a intersection Leaf _ = Leaf intersection _ Leaf = Leaf intersection t1 (Node _ _ l x r) | member x t1 = join (intersection l' l) x (intersection r' r) | otherwise = merge (intersection l' l) (intersection r' r) where (l',r') = split x t1 | Creating a difference tree from trees . Worst - case : O(N + N ) > > > difference ( fromList [ 5,3 ] ) ( fromList [ 5,7 ] ) = = singleton 3 True >>> difference (fromList [5,3]) (fromList [5,7]) == singleton 3 True -} difference :: Ord a => RBTree a -> RBTree a -> RBTree a difference Leaf _ = Leaf difference t1 Leaf = t1 -- ensured Black thanks to split difference t1 (Node _ _ l x r) = merge (difference l' l) (difference r' r) where (l',r') = split x t1
null
https://raw.githubusercontent.com/kazu-yamamoto/llrbtree/36f259e36c2b320aa37bbbae9577e01fd8a27118/Data/Set/RBTree.hs
haskell
* Data structures * Creating red-black trees * Converting to a list * Membership * Deleting * Checking * Set operations * Helper functions -------------------------------------------------------------- Part to be shared -------------------------------------------------------------- color is Black ^ Black ^ Red -------------------------------------------------------------- -------------------------------------------------------------- -------------------------------------------------------------- -------------------------------------------------------------- -------------------------------------------------------------- -------------------------------------------------------------- -------------------------------------------------------------- -------------------------------------------------------------- -------------------------------------------------------------- -------------------------------------------------------------- -------------------------------------------------------------- -------------------------------------------------------------- -------------------------------------------------------------- Basic operations -------------------------------------------------------------- | Checking validity of a tree. -------------------------------------------------------------- -------------------------------------------------------------- -------------------------------------------------------------- -------------------------------------------------------------- -------------------------------------------------------------- | Deleting the maximum >>> deleteMax (fromList [(5,"a"), (3,"b"), (7,"c")]) == fromList [(3,"b"), (5,"a")] True >>> deleteMax empty == empty True -------------------------------------------------------------- -------------------------------------------------------------- Set operations -------------------------------------------------------------- The root of result must be red. The root of result must be red. -------------------------------------------------------------- unnecessary for LL -------------------------------------------------------------- -------------------------------------------------------------- ensured Black thanks to split ensured Black thanks to split
| Purely functional red - black trees . * , \"Red - Black Trees in a Functional Setting\ " , Journal of Functional Programming , 9(4 ) , pp 471 - 477 , July 1999 < #jfp99 > * , \"Red - black trees with " , Journal of functional programming , 11(04 ) , pp 425 - 432 , July 2001 Purely functional red-black trees. * Chris Okasaki, \"Red-Black Trees in a Functional Setting\", Journal of Functional Programming, 9(4), pp 471-477, July 1999 <#jfp99> * Stefan Kahrs, \"Red-black trees with types\", Journal of functional programming, 11(04), pp 425-432, July 2001 -} module Data.Set.RBTree ( RBTree(..) , Color(..) , BlackHeight , empty , singleton , insert , fromList , toList , member , delete , deleteMin , deleteMax , null , union , intersection , difference , join , merge , split , minimum , maximum , valid , showSet , printSet ) where import Data.List (foldl') import Prelude hiding (minimum, maximum, null) | Node Color !BlackHeight !(RBTree a) a !(RBTree a) deriving (Show) deriving (Eq,Show) | Red nodes have the same BlackHeight of their parent . Red nodes have the same BlackHeight of their parent. -} type BlackHeight = Int instance (Eq a) => Eq (RBTree a) where t1 == t2 = toList t1 == toList t2 height :: RBTree a -> BlackHeight height Leaf = 0 height (Node _ h _ _ _) = h | See if the red black tree is empty . > > > Data.Set.RBTree.null empty True > > > Data.Set.RBTree.null ( singleton 1 ) False See if the red black tree is empty. >>> Data.Set.RBTree.null empty True >>> Data.Set.RBTree.null (singleton 1) False -} null :: Eq a => RBTree a -> Bool null t = t == Leaf | Empty tree . > > > height empty 0 >>> height empty 0 -} empty :: RBTree a empty = Leaf | Singleton tree . > > > height ( singleton ' a ' ) 1 >>> height (singleton 'a') 1 -} singleton :: Ord a => a -> RBTree a singleton x = Node B 1 Leaf x Leaf | Creating a tree from a list . Worst - case : O(N log N ) > > > empty = = fromList [ ] True > > > singleton ' a ' = = fromList [ ' a ' ] True > > > fromList [ 5,3,5 ] = = fromList [ 5,3 ] True >>> empty == fromList [] True >>> singleton 'a' == fromList ['a'] True >>> fromList [5,3,5] == fromList [5,3] True -} fromList :: Ord a => [a] -> RBTree a fromList = foldl' (flip insert) empty | Creating a list from a tree . Worst - case : O(N ) > > > toList ( fromList [ 5,3 ] ) [ 3,5 ] > > > toList empty [ ] >>> toList (fromList [5,3]) [3,5] >>> toList empty [] -} toList :: RBTree a -> [a] toList t = inorder t [] where inorder Leaf xs = xs inorder (Node _ _ l x r) xs = inorder l (x : inorder r xs) | Checking if this element is a member of a tree ? > > > member 5 ( fromList [ 5,3 ] ) True > > > member 1 ( fromList [ 5,3 ] ) False >>> member 5 (fromList [5,3]) True >>> member 1 (fromList [5,3]) False -} member :: Ord a => a -> RBTree a -> Bool member _ Leaf = False member x (Node _ _ l y r) = case compare x y of LT -> member x l GT -> member x r EQ -> True isBalanced :: RBTree a -> Bool isBalanced t = isBlackSame t && isRedSeparate t isBlackSame :: RBTree a -> Bool isBlackSame t = all (n==) ns where n:ns = blacks t blacks :: RBTree a -> [Int] blacks = blacks' 0 where blacks' n Leaf = [n+1] blacks' n (Node R _ l _ r) = blacks' n l ++ blacks' n r blacks' n (Node B _ l _ r) = blacks' n' l ++ blacks' n' r where n' = n + 1 isRedSeparate :: RBTree a -> Bool isRedSeparate = reds B reds :: Color -> RBTree t -> Bool reds _ Leaf = True reds R (Node R _ _ _ _) = False reds _ (Node c _ l _ r) = reds c l && reds c r isOrdered :: Ord a => RBTree a -> Bool isOrdered t = ordered $ toList t where ordered [] = True ordered [_] = True ordered (x:y:xys) = x < y && ordered (y:xys) blackHeight :: RBTree a -> Bool blackHeight Leaf = True blackHeight t@(Node B i _ _ _) = bh i t where bh n Leaf = n == 0 bh n (Node R h l _ r) = n == h' && bh n l && bh n r where h' = h - 1 bh n (Node B h l _ r) = n == h && bh n' l && bh n' r where n' = n - 1 blackHeight _ = error "blackHeight" turnR :: RBTree a -> RBTree a turnR Leaf = error "turnR" turnR (Node _ h l x r) = Node R h l x r turnB :: RBTree a -> RBTree a turnB Leaf = error "turnB" turnB (Node _ h l x r) = Node B h l x r turnB' :: RBTree a -> RBTree a turnB' Leaf = Leaf turnB' (Node _ h l x r) = Node B h l x r | Finding the minimum element . Worst - case : O(log N ) > > > minimum ( fromList [ 3,5,1 ] ) 1 > > > minimum empty * * * Exception : minimum >>> minimum (fromList [3,5,1]) 1 >>> minimum empty *** Exception: minimum -} minimum :: RBTree a -> a minimum (Node _ _ Leaf x _) = x minimum (Node _ _ l _ _) = minimum l minimum _ = error "minimum" | Finding the maximum element . Worst - case : O(log N ) > > > maximum ( fromList [ 3,5,1 ] ) 5 > > > maximum empty * * * Exception : maximum >>> maximum (fromList [3,5,1]) 5 >>> maximum empty *** Exception: maximum -} maximum :: RBTree a -> a maximum (Node _ _ _ x Leaf) = x maximum (Node _ _ _ _ r) = maximum r maximum _ = error "maximum" showSet :: Show a => RBTree a -> String showSet = showSet' "" showSet' :: Show a => String -> RBTree a -> String showSet' _ Leaf = "\n" showSet' pref (Node k h l x r) = show k ++ " " ++ show x ++ " (" ++ show h ++ ")\n" ++ pref ++ "+ " ++ showSet' pref' l ++ pref ++ "+ " ++ showSet' pref' r where pref' = " " ++ pref printSet :: Show a => RBTree a -> IO () printSet = putStr . showSet isRed :: RBTree a -> Bool isRed (Node R _ _ _ _ ) = True isRed _ = False valid :: Ord a => RBTree a -> Bool valid t = isBalanced t && blackHeight t && isOrdered t | Insertion . Worst - case : O(log N ) > > > insert 5 ( fromList [ 5,3 ] ) = = fromList [ 3,5 ] True > > > insert 7 ( fromList [ 5,3 ] ) = = fromList [ 3,5,7 ] True > > > insert 5 empty = = singleton 5 True >>> insert 5 (fromList [5,3]) == fromList [3,5] True >>> insert 7 (fromList [5,3]) == fromList [3,5,7] True >>> insert 5 empty == singleton 5 True -} insert :: Ord a => a -> RBTree a -> RBTree a insert kx t = turnB (insert' kx t) insert' :: Ord a => a -> RBTree a -> RBTree a insert' kx Leaf = Node R 1 Leaf kx Leaf insert' kx s@(Node B h l x r) = case compare kx x of LT -> balanceL' h (insert' kx l) x r GT -> balanceR' h l x (insert' kx r) EQ -> s insert' kx s@(Node R h l x r) = case compare kx x of LT -> Node R h (insert' kx l) x r GT -> Node R h l x (insert' kx r) EQ -> s balanceL' :: BlackHeight -> RBTree a -> a -> RBTree a -> RBTree a balanceL' h (Node R _ (Node R _ a x b) y c) z d = Node R (h+1) (Node B h a x b) y (Node B h c z d) balanceL' h (Node R _ a x (Node R _ b y c)) z d = Node R (h+1) (Node B h a x b) y (Node B h c z d) balanceL' h l x r = Node B h l x r balanceR' :: BlackHeight -> RBTree a -> a -> RBTree a -> RBTree a balanceR' h a x (Node R _ b y (Node R _ c z d)) = Node R (h+1) (Node B h a x b) y (Node B h c z d) balanceR' h a x (Node R _ (Node R _ b y c) z d) = Node R (h+1) (Node B h a x b) y (Node B h c z d) balanceR' h l x r = Node B h l x r balanceL :: Color -> BlackHeight -> RBTree a -> a -> RBTree a -> RBTree a balanceL B h (Node R _ (Node R _ a x b) y c) z d = Node R (h+1) (Node B h a x b) y (Node B h c z d) balanceL B h (Node R _ a x (Node R _ b y c)) z d = Node R (h+1) (Node B h a x b) y (Node B h c z d) balanceL k h l x r = Node k h l x r balanceR :: Color -> BlackHeight -> RBTree a -> a -> RBTree a -> RBTree a balanceR B h a x (Node R _ b y (Node R _ c z d)) = Node R (h+1) (Node B h a x b) y (Node B h c z d) balanceR B h a x (Node R _ (Node R _ b y c) z d) = Node R (h+1) (Node B h a x b) y (Node B h c z d) balanceR k h l x r = Node k h l x r type RBTreeBDel a = (RBTree a, Bool) unbalancedL :: Color -> BlackHeight -> RBTree a -> a -> RBTree a -> RBTreeBDel a unbalancedL c h l@(Node B _ _ _ _) x r = (balanceL B h (turnR l) x r, c == B) unbalancedL B h (Node R lh ll lx lr@(Node B _ _ _ _)) x r = (Node B lh ll lx (balanceL B h (turnR lr) x r), False) unbalancedL _ _ _ _ _ = error "unbalancedL" The left tree lacks one Black node unbalancedR :: Color -> BlackHeight -> RBTree a -> a -> RBTree a -> (RBTree a, Bool) Decreasing one Black node in the right unbalancedR c h l x r@(Node B _ _ _ _) = (balanceR B h l x (turnR r), c == B) Taking one Red node from the right and adding it to the right as Black unbalancedR B h l x (Node R rh rl@(Node B _ _ _ _) rx rr) = (Node B rh (balanceR B h l x (turnR rl)) rx rr, False) unbalancedR _ _ _ _ _ = error "unbalancedR" | Deleting the minimum element . Worst - case : O(log N ) > > > deleteMin ( fromList [ 5,3,7 ] ) = = fromList [ 5,7 ] True > > > deleteMin empty = = empty True >>> deleteMin (fromList [5,3,7]) == fromList [5,7] True >>> deleteMin empty == empty True -} deleteMin :: RBTree a -> RBTree a deleteMin Leaf = empty deleteMin t = turnB' s where ((s, _), _) = deleteMin' t deleteMin' :: RBTree a -> (RBTreeBDel a, a) deleteMin' Leaf = error "deleteMin'" deleteMin' (Node B _ Leaf x Leaf) = ((Leaf, True), x) deleteMin' (Node B _ Leaf x r@(Node R _ _ _ _)) = ((turnB r, False), x) deleteMin' (Node R _ Leaf x r) = ((r, False), x) deleteMin' (Node c h l x r) = if d then (tD, m) else (tD', m) where ((l',d),m) = deleteMin' l tD = unbalancedR c (h-1) l' x r tD' = (Node c h l' x r, False) deleteMax :: RBTree a -> RBTree a deleteMax Leaf = empty deleteMax t = turnB' s where ((s, _), _) = deleteMax' t deleteMax' :: RBTree a -> (RBTreeBDel a, a) deleteMax' Leaf = error "deleteMax'" deleteMax' (Node B _ Leaf x Leaf) = ((Leaf, True), x) deleteMax' (Node B _ l@(Node R _ _ _ _) x Leaf) = ((turnB l, False), x) deleteMax' (Node R _ l x Leaf) = ((l, False), x) deleteMax' (Node c h l x r) = if d then (tD, m) else (tD', m) where ((r',d),m) = deleteMax' r tD = unbalancedL c (h-1) l x r' tD' = (Node c h l x r', False) blackify :: RBTree a -> RBTreeBDel a blackify s@(Node R _ _ _ _) = (turnB s, False) blackify s = (s, True) | Deleting this element from a tree . Worst - case : O(log N ) > > > delete 5 ( fromList [ 5,3 ] ) = = singleton 3 True > > > delete 7 ( fromList [ 5,3 ] ) = = fromList [ 3,5 ] True > > > delete 5 empty = = empty True >>> delete 5 (fromList [5,3]) == singleton 3 True >>> delete 7 (fromList [5,3]) == fromList [3,5] True >>> delete 5 empty == empty True -} delete :: Ord a => a -> RBTree a -> RBTree a delete x t = turnB' s where (s,_) = delete' x t delete' :: Ord a => a -> RBTree a -> RBTreeBDel a delete' _ Leaf = (Leaf, False) delete' x (Node c h l y r) = case compare x y of LT -> let (l',d) = delete' x l t = Node c h l' y r in if d then unbalancedR c (h-1) l' y r else (t, False) GT -> let (r',d) = delete' x r t = Node c h l y r' in if d then unbalancedL c (h-1) l y r' else (t, False) EQ -> case r of Leaf -> if c == B then blackify l else (l, False) _ -> let ((r',d),m) = deleteMin' r t = Node c h l m r' in if d then unbalancedL c (h-1) l m r' else (t, False) | Joining two trees with an element . Worst - case : O(log N ) Each element of the left tree must be less than the element . Each element of the right tree must be greater than the element . Both tree must have black root . Each element of the left tree must be less than the element. Each element of the right tree must be greater than the element. Both tree must have black root. -} join :: Ord a => RBTree a -> a -> RBTree a -> RBTree a join Leaf g t2 = insert g t2 join t1 g Leaf = insert g t1 join t1 g t2 = case compare h1 h2 of LT -> turnB $ joinLT t1 g t2 h1 GT -> turnB $ joinGT t1 g t2 h2 EQ -> Node B (h1+1) t1 g t2 where h1 = height t1 h2 = height t2 joinLT :: Ord a => RBTree a -> a -> RBTree a -> BlackHeight -> RBTree a joinLT t1 g t2@(Node c h l x r) h1 | h == h1 = Node R (h+1) t1 g t2 | otherwise = balanceL c h (joinLT t1 g l h1) x r joinLT _ _ _ _ = error "joinLT" joinGT :: Ord a => RBTree a -> a -> RBTree a -> BlackHeight -> RBTree a joinGT t1@(Node c h l x r) g t2 h2 | h == h2 = Node R (h+1) t1 g t2 | otherwise = balanceR c h l x (joinGT r g t2 h2) joinGT _ _ _ _ = error "joinGT" | Merging two trees . Worst - case : O(log N ) Each element of the left tree must be less than each element of the right tree . Both trees must have black root . Each element of the left tree must be less than each element of the right tree. Both trees must have black root. -} merge :: Ord a => RBTree a -> RBTree a -> RBTree a merge Leaf t2 = t2 merge t1 Leaf = t1 merge t1 t2 = case compare h1 h2 of LT -> turnB $ mergeLT t1 t2 h1 GT -> turnB $ mergeGT t1 t2 h2 EQ -> turnB $ mergeEQ t1 t2 where h1 = height t1 h2 = height t2 mergeLT :: Ord a => RBTree a -> RBTree a -> BlackHeight -> RBTree a mergeLT t1 t2@(Node c h l x r) h1 | h == h1 = mergeEQ t1 t2 | otherwise = balanceL c h (mergeLT t1 l h1) x r mergeLT _ _ _ = error "mergeLT" mergeGT :: Ord a => RBTree a -> RBTree a -> BlackHeight -> RBTree a mergeGT t1@(Node c h l x r) t2 h2 | h == h2 = mergeEQ t1 t2 | otherwise = balanceR c h l x (mergeGT r t2 h2) mergeGT _ _ _ = error "mergeGT" Merging two trees whose heights are the same . The root must be either a red with height + 1 for a black with height Merging two trees whose heights are the same. The root must be either a red with height + 1 for a black with height -} mergeEQ :: Ord a => RBTree a -> RBTree a -> RBTree a mergeEQ Leaf Leaf = Leaf mergeEQ t1@(Node _ h l x r) t2 | h == h2' = Node R (h+1) t1 m t2' | isRed l = Node R (h+1) (turnB l) x (Node B h r m t2') | isRed r = Node B h (Node R h l x rl) rx (Node R h rr m t2') | otherwise = Node B h (turnR t1) m t2' where m = minimum t2 t2' = deleteMin t2 h2' = height t2' Node R _ rl rx rr = r mergeEQ _ _ = error "mergeEQ" | Splitting a tree . Worst - case : O(log N ) > > > split 2 ( fromList [ 5,3 ] ) = = ( empty , fromList [ 3,5 ] ) True > > > split 3 ( fromList [ 5,3 ] ) = = ( empty , singleton 5 ) True > > > split 4 ( fromList [ 5,3 ] ) = = ( singleton 3 , singleton 5 ) True > > > split 5 ( fromList [ 5,3 ] ) = = ( singleton 3 , empty ) True > > > split 6 ( fromList [ 5,3 ] ) = = ( fromList [ 3,5 ] , empty ) True >>> split 2 (fromList [5,3]) == (empty, fromList [3,5]) True >>> split 3 (fromList [5,3]) == (empty, singleton 5) True >>> split 4 (fromList [5,3]) == (singleton 3, singleton 5) True >>> split 5 (fromList [5,3]) == (singleton 3, empty) True >>> split 6 (fromList [5,3]) == (fromList [3,5], empty) True -} split :: Ord a => a -> RBTree a -> (RBTree a, RBTree a) split _ Leaf = (Leaf,Leaf) split kx (Node _ _ l x r) = case compare kx x of LT -> (lt, join gt x (turnB' r)) where (lt,gt) = split kx l GT -> (join (turnB' l) x lt, gt) where (lt,gt) = split kx r EQ -> (turnB' l, turnB' r) LL split : : a = > a - > RBTree a - > ( RBTree a , RBTree a ) split _ Leaf = ( Leaf , Leaf ) split kx ( Node _ _ l x r ) = case compare kx x of LT - > ( lt , join gt x r ) where ( lt , gt ) = split kx l GT - > ( join l x lt , gt ) where ( lt , gt ) = split kx r EQ - > ( turnB ' l , r ) split :: Ord a => a -> RBTree a -> (RBTree a, RBTree a) split _ Leaf = (Leaf,Leaf) split kx (Node _ _ l x r) = case compare kx x of LT -> (lt, join gt x r) where (lt,gt) = split kx l GT -> (join l x lt, gt) where (lt,gt) = split kx r EQ -> (turnB' l, r) -} | Creating a union tree from two trees . Worst - case : O(N + M ) > > > union ( fromList [ 5,3 ] ) ( fromList [ 5,7 ] ) = = fromList [ 3,5,7 ] True >>> union (fromList [5,3]) (fromList [5,7]) == fromList [3,5,7] True -} union :: Ord a => RBTree a -> RBTree a -> RBTree a union Leaf t2 = turnB' t2 union t1 (Node _ _ l x r) = join (union l' l) x (union r' r) where (l',r') = split x t1 | Creating a intersection tree from trees . Worst - case : O(N + N ) > > > intersection ( fromList [ 5,3 ] ) ( fromList [ 5,7 ] ) = = singleton 5 True >>> intersection (fromList [5,3]) (fromList [5,7]) == singleton 5 True -} intersection :: Ord a => RBTree a -> RBTree a -> RBTree a intersection Leaf _ = Leaf intersection _ Leaf = Leaf intersection t1 (Node _ _ l x r) | member x t1 = join (intersection l' l) x (intersection r' r) | otherwise = merge (intersection l' l) (intersection r' r) where (l',r') = split x t1 | Creating a difference tree from trees . Worst - case : O(N + N ) > > > difference ( fromList [ 5,3 ] ) ( fromList [ 5,7 ] ) = = singleton 3 True >>> difference (fromList [5,3]) (fromList [5,7]) == singleton 3 True -} difference :: Ord a => RBTree a -> RBTree a -> RBTree a difference Leaf _ = Leaf difference t1 (Node _ _ l x r) = merge (difference l' l) (difference r' r) where (l',r') = split x t1
a8d48ceafc815fd86bca6c9f5b41e43dabef43a397115ea08549743342f5bc2b
andrewray/DefinitelyMaybeTyped
otypescript.ml
(********************************************************************************) (* file utilities *) let rec readall path = let open Unix in let h = opendir path in let rec read () = match try Some(readdir h) with _ -> None with | None -> [] | Some(x) when x<>"." && x<>".." -> (Filename.concat path x)::read() | _ -> read() in let all = read() in closedir h; all let rec findall path = let open Unix in let all = readall path in partition into sub - dirs and .d.ts files let rec classify dirs dts = function | [] -> dirs, dts | h::t -> match (stat h).st_kind with | S_DIR -> classify (h::dirs) dts t | S_REG when Filename.check_suffix h ".d.ts" -> classify dirs (h::dts) t | _ -> classify dirs dts t in let dirs, dts = classify [] [] all in List.fold_left (fun dts dir -> dts @ findall dir) dts dirs let preprocess input_name = let base = Filename.basename input_name in let output_name = Filename.concat "dump" base in let command = "cpp -P " ^ input_name ^ " " ^ output_name in Printf.printf "%s\n%!" command; Unix.system command |> ignore let with_file_in name f = let file = open_in name in try let r = f file in close_in file; r with x -> close_in file; raise x let with_file_out name f = let file = open_out name in try let r = f file in close_out file; r with x -> close_out file; raise x (********************************************************************************) (* command line *) let parse_file ?(verbose=false) name = let ast = with_file_in name (Parser.parse ~verbose:true name) in (*(if verbose then output_string stdout (Parser.to_string ast) else Summary.ast ast);*) (*Summary.Print.ast ast;*) let () = let module P = Print.Make(struct let out = print_string end) in P.print_ast ast in let base = Filename.(chop_suffix (basename name) ".d.ts") in let marshal = base ^ ".m" in let ml = base ^ ".ml" in (* marshalled ast *) (with_file_out marshal Marshal.(fun f -> to_channel f ast [])); (* output ml file *) (with_file_out ml (fun f -> match ast with | None -> () | Some(ast) -> Convert.convert (output_string f) ast)) let parse_dir dir = let open Printf in let pass, fail, exn = ref 0, ref 0, ref 0 in List.iter (fun name -> try match with_file_in name (Parser.parse name) with | Some(x) -> begin printf "pass: %s\n%!" name; incr pass end | None -> begin printf "fail: %s\n%!" name; incr fail end with _ -> begin Printf.printf "exn : %s\n%!" name; incr exn; end) (findall dir); Printf.printf "pass=%i fail=%i exn=%i\n" !pass !fail !exn let () = let open Arg in parse (align [ "-i", String(parse_file), "<file> Parse typescript definition file"; "-d", String(parse_dir), "<dir> Find all typescript definition files in directory and parse them"; "-t", Unit(Unit_tests.run), " run unit tests"; ]) (fun _ -> failwith "anon args not allowed") "otypescript"
null
https://raw.githubusercontent.com/andrewray/DefinitelyMaybeTyped/088fbb99b1eea704d37e4897de7fe18531b66fc2/app/otypescript.ml
ocaml
****************************************************************************** file utilities ****************************************************************************** command line (if verbose then output_string stdout (Parser.to_string ast) else Summary.ast ast); Summary.Print.ast ast; marshalled ast output ml file
let rec readall path = let open Unix in let h = opendir path in let rec read () = match try Some(readdir h) with _ -> None with | None -> [] | Some(x) when x<>"." && x<>".." -> (Filename.concat path x)::read() | _ -> read() in let all = read() in closedir h; all let rec findall path = let open Unix in let all = readall path in partition into sub - dirs and .d.ts files let rec classify dirs dts = function | [] -> dirs, dts | h::t -> match (stat h).st_kind with | S_DIR -> classify (h::dirs) dts t | S_REG when Filename.check_suffix h ".d.ts" -> classify dirs (h::dts) t | _ -> classify dirs dts t in let dirs, dts = classify [] [] all in List.fold_left (fun dts dir -> dts @ findall dir) dts dirs let preprocess input_name = let base = Filename.basename input_name in let output_name = Filename.concat "dump" base in let command = "cpp -P " ^ input_name ^ " " ^ output_name in Printf.printf "%s\n%!" command; Unix.system command |> ignore let with_file_in name f = let file = open_in name in try let r = f file in close_in file; r with x -> close_in file; raise x let with_file_out name f = let file = open_out name in try let r = f file in close_out file; r with x -> close_out file; raise x let parse_file ?(verbose=false) name = let ast = with_file_in name (Parser.parse ~verbose:true name) in let () = let module P = Print.Make(struct let out = print_string end) in P.print_ast ast in let base = Filename.(chop_suffix (basename name) ".d.ts") in let marshal = base ^ ".m" in let ml = base ^ ".ml" in (with_file_out marshal Marshal.(fun f -> to_channel f ast [])); (with_file_out ml (fun f -> match ast with | None -> () | Some(ast) -> Convert.convert (output_string f) ast)) let parse_dir dir = let open Printf in let pass, fail, exn = ref 0, ref 0, ref 0 in List.iter (fun name -> try match with_file_in name (Parser.parse name) with | Some(x) -> begin printf "pass: %s\n%!" name; incr pass end | None -> begin printf "fail: %s\n%!" name; incr fail end with _ -> begin Printf.printf "exn : %s\n%!" name; incr exn; end) (findall dir); Printf.printf "pass=%i fail=%i exn=%i\n" !pass !fail !exn let () = let open Arg in parse (align [ "-i", String(parse_file), "<file> Parse typescript definition file"; "-d", String(parse_dir), "<dir> Find all typescript definition files in directory and parse them"; "-t", Unit(Unit_tests.run), " run unit tests"; ]) (fun _ -> failwith "anon args not allowed") "otypescript"
6114f98e7a621143f0654d4248ff34222bdb4d5a064e8dbbacbd29d557177cd9
Haskell-OpenAPI-Code-Generator/Stripe-Haskell-Library
QuotesResourceTotalDetails.hs
{-# LANGUAGE MultiWayIf #-} CHANGE WITH CAUTION : This is a generated code file generated by -OpenAPI-Code-Generator/Haskell-OpenAPI-Client-Code-Generator . {-# LANGUAGE OverloadedStrings #-} -- | Contains the types generated from the schema QuotesResourceTotalDetails module StripeAPI.Types.QuotesResourceTotalDetails where import qualified Control.Monad.Fail import qualified Data.Aeson import qualified Data.Aeson as Data.Aeson.Encoding.Internal import qualified Data.Aeson as Data.Aeson.Types import qualified Data.Aeson as Data.Aeson.Types.FromJSON import qualified Data.Aeson as Data.Aeson.Types.Internal import qualified Data.Aeson as Data.Aeson.Types.ToJSON import qualified Data.ByteString.Char8 import qualified Data.ByteString.Char8 as Data.ByteString.Internal import qualified Data.Foldable import qualified Data.Functor import qualified Data.Maybe import qualified Data.Scientific import qualified Data.Text import qualified Data.Text.Internal import qualified Data.Time.Calendar as Data.Time.Calendar.Days import qualified Data.Time.LocalTime as Data.Time.LocalTime.Internal.ZonedTime import qualified GHC.Base import qualified GHC.Classes import qualified GHC.Int import qualified GHC.Show import qualified GHC.Types import qualified StripeAPI.Common import StripeAPI.TypeAlias import {-# SOURCE #-} StripeAPI.Types.QuotesResourceTotalDetailsResourceBreakdown import qualified Prelude as GHC.Integer.Type import qualified Prelude as GHC.Maybe -- | Defines the object schema located at @components.schemas.quotes_resource_total_details@ in the specification. data QuotesResourceTotalDetails = QuotesResourceTotalDetails { -- | amount_discount: This is the sum of all the discounts. quotesResourceTotalDetailsAmountDiscount :: GHC.Types.Int, -- | amount_shipping: This is the sum of all the shipping amounts. quotesResourceTotalDetailsAmountShipping :: (GHC.Maybe.Maybe (StripeAPI.Common.Nullable GHC.Types.Int)), -- | amount_tax: This is the sum of all the tax amounts. quotesResourceTotalDetailsAmountTax :: GHC.Types.Int, -- | breakdown: quotesResourceTotalDetailsBreakdown :: (GHC.Maybe.Maybe QuotesResourceTotalDetailsResourceBreakdown) } deriving ( GHC.Show.Show, GHC.Classes.Eq ) instance Data.Aeson.Types.ToJSON.ToJSON QuotesResourceTotalDetails where toJSON obj = Data.Aeson.Types.Internal.object (Data.Foldable.concat (["amount_discount" Data.Aeson.Types.ToJSON..= quotesResourceTotalDetailsAmountDiscount obj] : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("amount_shipping" Data.Aeson.Types.ToJSON..=)) (quotesResourceTotalDetailsAmountShipping obj) : ["amount_tax" Data.Aeson.Types.ToJSON..= quotesResourceTotalDetailsAmountTax obj] : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("breakdown" Data.Aeson.Types.ToJSON..=)) (quotesResourceTotalDetailsBreakdown obj) : GHC.Base.mempty)) toEncoding obj = Data.Aeson.Encoding.Internal.pairs (GHC.Base.mconcat (Data.Foldable.concat (["amount_discount" Data.Aeson.Types.ToJSON..= quotesResourceTotalDetailsAmountDiscount obj] : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("amount_shipping" Data.Aeson.Types.ToJSON..=)) (quotesResourceTotalDetailsAmountShipping obj) : ["amount_tax" Data.Aeson.Types.ToJSON..= quotesResourceTotalDetailsAmountTax obj] : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("breakdown" Data.Aeson.Types.ToJSON..=)) (quotesResourceTotalDetailsBreakdown obj) : GHC.Base.mempty))) instance Data.Aeson.Types.FromJSON.FromJSON QuotesResourceTotalDetails where parseJSON = Data.Aeson.Types.FromJSON.withObject "QuotesResourceTotalDetails" (\obj -> (((GHC.Base.pure QuotesResourceTotalDetails GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..: "amount_discount")) GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..:! "amount_shipping")) GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..: "amount_tax")) GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..:! "breakdown")) -- | Create a new 'QuotesResourceTotalDetails' with all required fields. mkQuotesResourceTotalDetails :: -- | 'quotesResourceTotalDetailsAmountDiscount' GHC.Types.Int -> -- | 'quotesResourceTotalDetailsAmountTax' GHC.Types.Int -> QuotesResourceTotalDetails mkQuotesResourceTotalDetails quotesResourceTotalDetailsAmountDiscount quotesResourceTotalDetailsAmountTax = QuotesResourceTotalDetails { quotesResourceTotalDetailsAmountDiscount = quotesResourceTotalDetailsAmountDiscount, quotesResourceTotalDetailsAmountShipping = GHC.Maybe.Nothing, quotesResourceTotalDetailsAmountTax = quotesResourceTotalDetailsAmountTax, quotesResourceTotalDetailsBreakdown = GHC.Maybe.Nothing }
null
https://raw.githubusercontent.com/Haskell-OpenAPI-Code-Generator/Stripe-Haskell-Library/ba4401f083ff054f8da68c741f762407919de42f/src/StripeAPI/Types/QuotesResourceTotalDetails.hs
haskell
# LANGUAGE MultiWayIf # # LANGUAGE OverloadedStrings # | Contains the types generated from the schema QuotesResourceTotalDetails # SOURCE # | Defines the object schema located at @components.schemas.quotes_resource_total_details@ in the specification. | amount_discount: This is the sum of all the discounts. | amount_shipping: This is the sum of all the shipping amounts. | amount_tax: This is the sum of all the tax amounts. | breakdown: | Create a new 'QuotesResourceTotalDetails' with all required fields. | 'quotesResourceTotalDetailsAmountDiscount' | 'quotesResourceTotalDetailsAmountTax'
CHANGE WITH CAUTION : This is a generated code file generated by -OpenAPI-Code-Generator/Haskell-OpenAPI-Client-Code-Generator . module StripeAPI.Types.QuotesResourceTotalDetails where import qualified Control.Monad.Fail import qualified Data.Aeson import qualified Data.Aeson as Data.Aeson.Encoding.Internal import qualified Data.Aeson as Data.Aeson.Types import qualified Data.Aeson as Data.Aeson.Types.FromJSON import qualified Data.Aeson as Data.Aeson.Types.Internal import qualified Data.Aeson as Data.Aeson.Types.ToJSON import qualified Data.ByteString.Char8 import qualified Data.ByteString.Char8 as Data.ByteString.Internal import qualified Data.Foldable import qualified Data.Functor import qualified Data.Maybe import qualified Data.Scientific import qualified Data.Text import qualified Data.Text.Internal import qualified Data.Time.Calendar as Data.Time.Calendar.Days import qualified Data.Time.LocalTime as Data.Time.LocalTime.Internal.ZonedTime import qualified GHC.Base import qualified GHC.Classes import qualified GHC.Int import qualified GHC.Show import qualified GHC.Types import qualified StripeAPI.Common import StripeAPI.TypeAlias import qualified Prelude as GHC.Integer.Type import qualified Prelude as GHC.Maybe data QuotesResourceTotalDetails = QuotesResourceTotalDetails quotesResourceTotalDetailsAmountDiscount :: GHC.Types.Int, quotesResourceTotalDetailsAmountShipping :: (GHC.Maybe.Maybe (StripeAPI.Common.Nullable GHC.Types.Int)), quotesResourceTotalDetailsAmountTax :: GHC.Types.Int, quotesResourceTotalDetailsBreakdown :: (GHC.Maybe.Maybe QuotesResourceTotalDetailsResourceBreakdown) } deriving ( GHC.Show.Show, GHC.Classes.Eq ) instance Data.Aeson.Types.ToJSON.ToJSON QuotesResourceTotalDetails where toJSON obj = Data.Aeson.Types.Internal.object (Data.Foldable.concat (["amount_discount" Data.Aeson.Types.ToJSON..= quotesResourceTotalDetailsAmountDiscount obj] : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("amount_shipping" Data.Aeson.Types.ToJSON..=)) (quotesResourceTotalDetailsAmountShipping obj) : ["amount_tax" Data.Aeson.Types.ToJSON..= quotesResourceTotalDetailsAmountTax obj] : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("breakdown" Data.Aeson.Types.ToJSON..=)) (quotesResourceTotalDetailsBreakdown obj) : GHC.Base.mempty)) toEncoding obj = Data.Aeson.Encoding.Internal.pairs (GHC.Base.mconcat (Data.Foldable.concat (["amount_discount" Data.Aeson.Types.ToJSON..= quotesResourceTotalDetailsAmountDiscount obj] : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("amount_shipping" Data.Aeson.Types.ToJSON..=)) (quotesResourceTotalDetailsAmountShipping obj) : ["amount_tax" Data.Aeson.Types.ToJSON..= quotesResourceTotalDetailsAmountTax obj] : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("breakdown" Data.Aeson.Types.ToJSON..=)) (quotesResourceTotalDetailsBreakdown obj) : GHC.Base.mempty))) instance Data.Aeson.Types.FromJSON.FromJSON QuotesResourceTotalDetails where parseJSON = Data.Aeson.Types.FromJSON.withObject "QuotesResourceTotalDetails" (\obj -> (((GHC.Base.pure QuotesResourceTotalDetails GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..: "amount_discount")) GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..:! "amount_shipping")) GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..: "amount_tax")) GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..:! "breakdown")) mkQuotesResourceTotalDetails :: GHC.Types.Int -> GHC.Types.Int -> QuotesResourceTotalDetails mkQuotesResourceTotalDetails quotesResourceTotalDetailsAmountDiscount quotesResourceTotalDetailsAmountTax = QuotesResourceTotalDetails { quotesResourceTotalDetailsAmountDiscount = quotesResourceTotalDetailsAmountDiscount, quotesResourceTotalDetailsAmountShipping = GHC.Maybe.Nothing, quotesResourceTotalDetailsAmountTax = quotesResourceTotalDetailsAmountTax, quotesResourceTotalDetailsBreakdown = GHC.Maybe.Nothing }
55d52deb49854fb636a5f754687ca18297cc4be808193ca5ff57d3803e8be5b1
cram2/cram
prolog-interface.lisp
;;; Copyright ( c ) 2009 , < > ;;; All rights reserved. ;;; ;;; Redistribution and use in source and binary forms, with or without ;;; modification, are permitted provided that the following conditions are met: ;;; ;;; * Redistributions of source code must retain the above copyright ;;; notice, this list of conditions and the following disclaimer. ;;; * Redistributions in binary form must reproduce the above copyright ;;; notice, this list of conditions and the following disclaimer in the ;;; documentation and/or other materials provided with the distribution. * Neither the name of Willow Garage , Inc. nor the names of its ;;; contributors may be used to endorse or promote products derived from ;;; this software without specific prior written permission. ;;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS " ;;; AND ANY EXPRESS OR 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 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. ;;; (in-package :json-prolog) (defvar *finish-marker* nil) (defvar *service-namespace* "/json_prolog") (defvar *persistent-services* (make-hash-table :test 'equal)) (defun make-query-id () (symbol-name (gensym (format nil "QUERY-~10,20$-" (ros-time))))) (define-hook cram-utilities::on-prepare-json-prolog-prove (request)) (define-hook cram-utilities::on-finish-json-prolog-prove (id)) (define-hook cram-utilities::on-json-prolog-query-next-solution-result (query-id result)) (define-hook cram-utilities::on-json-prolog-query-finish (query-id)) (defun call-prolog-service (name type &rest request) (let ((log-id (first (cram-utilities::on-prepare-json-prolog-prove request))) (service (gethash name *persistent-services*))) (unwind-protect (progn (unless (and service (persistent-service-ok service)) (setf (gethash name *persistent-services*) (make-instance 'persistent-service :service-name name :service-type type))) (let ((reconnect-tries 1)) (handler-bind ((roslisp::service-call-error #'(lambda (e) (declare (ignore e)) (ros-warn (json-prolog) "Service call failed.") (when (> reconnect-tries 0) (ros-warn (json-prolog) "Retrying...") (invoke-restart 'roslisp:reconnect) (decf reconnect-tries) (apply 'call-persistent-service (gethash name *persistent-services*) request))))) (apply 'call-persistent-service (gethash name *persistent-services*) request)))) (cram-utilities::on-finish-json-prolog-prove log-id)))) (defun prolog-result->bdgs (query-id result &key (lispify nil) (package *package*)) (unless (json_prolog_msgs-srv:ok result) (error 'simple-error :format-control "Prolog query failed: ~a." :format-arguments (list (json_prolog_msgs-srv:message result)))) (let ((*read-default-float-format* 'double-float)) (lazy-list () (cond (*finish-marker* (cram-utilities::on-json-prolog-query-finish query-id) (call-prolog-service (concatenate 'string *service-namespace* "/finish") 'json_prolog_msgs-srv:PrologFinish :id query-id) nil) (t (let ((next-value (call-prolog-service (concatenate 'string *service-namespace* "/next_solution") 'json_prolog_msgs-srv:PrologNextSolution :id query-id))) (ecase (car (rassoc (json_prolog_msgs-srv:status next-value) (symbol-codes 'json_prolog_msgs-srv:<prolognextsolution-response>))) (:no_solution nil) (:wrong_id (error 'simple-error :format-control "We seem to have lost our query. ID invalid.")) (:query_failed (error 'simple-error :format-control "Prolog query failed: ~a" :format-arguments (list (json_prolog_msgs-srv:solution next-value)))) (:ok (cont (let ((result (json-bdgs->prolog-bdgs (json_prolog_msgs-srv:solution next-value) :lispify lispify :package package))) (cram-utilities::on-json-prolog-query-next-solution-result query-id result) result)))))))))) (defun check-connection () "Returns T if the json_prolog could be found, otherwise NIL." (if (eql roslisp::*node-status* :running) (roslisp:wait-for-service (concatenate 'string *service-namespace* "/query") 0.2) (ros-warn (json-prolog) "Node is not running."))) (defun prolog (exp &key (prologify t) (lispify nil) (mode 0) (package *package*)) (let ((query-id (make-query-id))) (prolog-result->bdgs query-id (call-prolog-service (concatenate 'string *service-namespace* "/query") 'json_prolog_msgs-srv:PrologQuery :id query-id :mode mode :query (prolog->json exp :prologify prologify)) :lispify lispify :package package))) (defun prolog-1 (exp &key (mode 0) (prologify t) (lispify nil) (package *package*)) "Like PROLOG but closes the query after the first solution." (let ((bdgs (prolog exp :prologify prologify :lispify lispify :mode mode :package package))) (finish-query bdgs))) (defun prolog-simple (query-str &key (mode 0) (lispify nil) (package *package*)) "Takes a prolog expression (real prolog, not the lispy version) and evaluates it." (let ((query-id (make-query-id))) (prolog-result->bdgs query-id (call-prolog-service (concatenate 'string *service-namespace* "/simple_query") 'json_prolog_msgs-srv:PrologQuery :id query-id :mode mode :query query-str) :lispify lispify :package package))) (defun prolog-simple-1 (query-str &key (lispify nil) (mode 0) (package *package*)) "Like PROLOG-SIMPLE but closes the query after the first solution." (let ((bdgs (prolog-simple query-str :lispify lispify :mode mode :package package))) (finish-query bdgs))) (defun finish-query (result) (let ((*finish-marker* t)) (lazy-cdr (last result)) result)) (defun wait-for-prolog-service (&optional timeout) (wait-for-service (concatenate 'string *service-namespace* "/query") timeout))
null
https://raw.githubusercontent.com/cram2/cram/dcb73031ee944d04215bbff9e98b9e8c210ef6c5/cram_json_prolog/src/prolog-interface.lisp
lisp
All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. contributors may be used to endorse or promote products derived from this software without specific prior written permission. AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 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 ) 2009 , < > * Neither the name of Willow Garage , Inc. nor the names of its THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS " IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT OWNER OR LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN (in-package :json-prolog) (defvar *finish-marker* nil) (defvar *service-namespace* "/json_prolog") (defvar *persistent-services* (make-hash-table :test 'equal)) (defun make-query-id () (symbol-name (gensym (format nil "QUERY-~10,20$-" (ros-time))))) (define-hook cram-utilities::on-prepare-json-prolog-prove (request)) (define-hook cram-utilities::on-finish-json-prolog-prove (id)) (define-hook cram-utilities::on-json-prolog-query-next-solution-result (query-id result)) (define-hook cram-utilities::on-json-prolog-query-finish (query-id)) (defun call-prolog-service (name type &rest request) (let ((log-id (first (cram-utilities::on-prepare-json-prolog-prove request))) (service (gethash name *persistent-services*))) (unwind-protect (progn (unless (and service (persistent-service-ok service)) (setf (gethash name *persistent-services*) (make-instance 'persistent-service :service-name name :service-type type))) (let ((reconnect-tries 1)) (handler-bind ((roslisp::service-call-error #'(lambda (e) (declare (ignore e)) (ros-warn (json-prolog) "Service call failed.") (when (> reconnect-tries 0) (ros-warn (json-prolog) "Retrying...") (invoke-restart 'roslisp:reconnect) (decf reconnect-tries) (apply 'call-persistent-service (gethash name *persistent-services*) request))))) (apply 'call-persistent-service (gethash name *persistent-services*) request)))) (cram-utilities::on-finish-json-prolog-prove log-id)))) (defun prolog-result->bdgs (query-id result &key (lispify nil) (package *package*)) (unless (json_prolog_msgs-srv:ok result) (error 'simple-error :format-control "Prolog query failed: ~a." :format-arguments (list (json_prolog_msgs-srv:message result)))) (let ((*read-default-float-format* 'double-float)) (lazy-list () (cond (*finish-marker* (cram-utilities::on-json-prolog-query-finish query-id) (call-prolog-service (concatenate 'string *service-namespace* "/finish") 'json_prolog_msgs-srv:PrologFinish :id query-id) nil) (t (let ((next-value (call-prolog-service (concatenate 'string *service-namespace* "/next_solution") 'json_prolog_msgs-srv:PrologNextSolution :id query-id))) (ecase (car (rassoc (json_prolog_msgs-srv:status next-value) (symbol-codes 'json_prolog_msgs-srv:<prolognextsolution-response>))) (:no_solution nil) (:wrong_id (error 'simple-error :format-control "We seem to have lost our query. ID invalid.")) (:query_failed (error 'simple-error :format-control "Prolog query failed: ~a" :format-arguments (list (json_prolog_msgs-srv:solution next-value)))) (:ok (cont (let ((result (json-bdgs->prolog-bdgs (json_prolog_msgs-srv:solution next-value) :lispify lispify :package package))) (cram-utilities::on-json-prolog-query-next-solution-result query-id result) result)))))))))) (defun check-connection () "Returns T if the json_prolog could be found, otherwise NIL." (if (eql roslisp::*node-status* :running) (roslisp:wait-for-service (concatenate 'string *service-namespace* "/query") 0.2) (ros-warn (json-prolog) "Node is not running."))) (defun prolog (exp &key (prologify t) (lispify nil) (mode 0) (package *package*)) (let ((query-id (make-query-id))) (prolog-result->bdgs query-id (call-prolog-service (concatenate 'string *service-namespace* "/query") 'json_prolog_msgs-srv:PrologQuery :id query-id :mode mode :query (prolog->json exp :prologify prologify)) :lispify lispify :package package))) (defun prolog-1 (exp &key (mode 0) (prologify t) (lispify nil) (package *package*)) "Like PROLOG but closes the query after the first solution." (let ((bdgs (prolog exp :prologify prologify :lispify lispify :mode mode :package package))) (finish-query bdgs))) (defun prolog-simple (query-str &key (mode 0) (lispify nil) (package *package*)) "Takes a prolog expression (real prolog, not the lispy version) and evaluates it." (let ((query-id (make-query-id))) (prolog-result->bdgs query-id (call-prolog-service (concatenate 'string *service-namespace* "/simple_query") 'json_prolog_msgs-srv:PrologQuery :id query-id :mode mode :query query-str) :lispify lispify :package package))) (defun prolog-simple-1 (query-str &key (lispify nil) (mode 0) (package *package*)) "Like PROLOG-SIMPLE but closes the query after the first solution." (let ((bdgs (prolog-simple query-str :lispify lispify :mode mode :package package))) (finish-query bdgs))) (defun finish-query (result) (let ((*finish-marker* t)) (lazy-cdr (last result)) result)) (defun wait-for-prolog-service (&optional timeout) (wait-for-service (concatenate 'string *service-namespace* "/query") timeout))
6b1b85a3d5c47ed0ef3fdca9d17a09ccfc6456ba536c3611a686b9fce2b465d0
ruricolist/serapeum
tree-case.lisp
(in-package :serapeum.tests) (def-suite tree-case :in serapeum) (in-suite tree-case) (test tree-case (is (null (tree-case 0))) (is (= 0 (tree-case 0 (0 0)))) (is (= 0 (tree-case 0 (0 0) (1 1)))) (is (= 0 (tree-case 0 (0 0) (-1 -1)))) (is (= 0 (tree-case 0 (-1 -1) (0 0) (1 1)))) (is (= 0 (tree-case 0 ((-1 -2) -1) ((0 1 2) 0) ((3 4 5) 3)))) (is (eql 'otherwise (tree-case 0 (1 1) (otherwise 'otherwise))))) (test tree-ecase (signals error (tree-ecase 0)) (signals error (tree-ecase 0 (1 1)))) (test char-case (is (null (char-case #\a))) (is (eql #\a (char-case #\a (#\a #\a)))) (is (null (char-case #\a (#\b #\b)))) (is (eql #\a (char-case #\a ((#\a #\b #\c) #\a)))) (is (eql #\a (char-case #\a ("abcd" #\a))))) (test char-ecase (signals case-failure (char-ecase #\a)) (is (eql #\a (char-ecase #\a (#\a #\a)))) (signals case-failure (char-ecase #\a (#\b #\b))) (is (eql #\a (char-ecase #\a ((#\a #\b #\c) #\a)))) (is (eql #\a (char-ecase #\a ("abcd" #\a))))) (test char-case-error (signals type-error (char-case 2)) (signals type-error (char-ecase 2)))
null
https://raw.githubusercontent.com/ruricolist/serapeum/d98b4863d7cdcb8a1ed8478cc44ab41bdad5635b/tests/tree-case.lisp
lisp
(in-package :serapeum.tests) (def-suite tree-case :in serapeum) (in-suite tree-case) (test tree-case (is (null (tree-case 0))) (is (= 0 (tree-case 0 (0 0)))) (is (= 0 (tree-case 0 (0 0) (1 1)))) (is (= 0 (tree-case 0 (0 0) (-1 -1)))) (is (= 0 (tree-case 0 (-1 -1) (0 0) (1 1)))) (is (= 0 (tree-case 0 ((-1 -2) -1) ((0 1 2) 0) ((3 4 5) 3)))) (is (eql 'otherwise (tree-case 0 (1 1) (otherwise 'otherwise))))) (test tree-ecase (signals error (tree-ecase 0)) (signals error (tree-ecase 0 (1 1)))) (test char-case (is (null (char-case #\a))) (is (eql #\a (char-case #\a (#\a #\a)))) (is (null (char-case #\a (#\b #\b)))) (is (eql #\a (char-case #\a ((#\a #\b #\c) #\a)))) (is (eql #\a (char-case #\a ("abcd" #\a))))) (test char-ecase (signals case-failure (char-ecase #\a)) (is (eql #\a (char-ecase #\a (#\a #\a)))) (signals case-failure (char-ecase #\a (#\b #\b))) (is (eql #\a (char-ecase #\a ((#\a #\b #\c) #\a)))) (is (eql #\a (char-ecase #\a ("abcd" #\a))))) (test char-case-error (signals type-error (char-case 2)) (signals type-error (char-ecase 2)))
76245407d17aac32b22710622f60d9c5de1edc72d863b335d5a2eacbda062af9
drapanjanas/pneumatic-tubes
core.cljs
(ns group-chat.core (:require [reagent.core :as reagent] [re-frame.core :as re-frame] [group-chat.events] [group-chat.subs] [group-chat.views :as views] [group-chat.config :as config])) (when config/debug? (println "dev mode")) (defn mount-root [] (reagent/render [views/main-panel] (.getElementById js/document "app"))) (defn ^:export init [] (re-frame/dispatch-sync [:initialize-db]) (mount-root))
null
https://raw.githubusercontent.com/drapanjanas/pneumatic-tubes/ea3834ea04e06cd2d4a03da333461a474c0475f5/examples/group-chat/src/cljs/group_chat/core.cljs
clojure
(ns group-chat.core (:require [reagent.core :as reagent] [re-frame.core :as re-frame] [group-chat.events] [group-chat.subs] [group-chat.views :as views] [group-chat.config :as config])) (when config/debug? (println "dev mode")) (defn mount-root [] (reagent/render [views/main-panel] (.getElementById js/document "app"))) (defn ^:export init [] (re-frame/dispatch-sync [:initialize-db]) (mount-root))
e051a1a73f001e7c872d3dd9672bfe11f4523e960b79392dbfe862f7a79feb6f
dizengrong/erlang_game
util_random.erl
@author dzR < > %% @doc 与随机相关的一些方法 -module (util_random). -export([random_between/2]). -spec random_between(Min::integer(), Max::integer()) -> integer(). @doc从区间[Min , Max]随机一个整形 random_between(Min, Max) -> check_and_set_seed(), Min2 = Min - 1, random:uniform(Max - Min2) + Min2. check_and_set_seed() -> case erlang:get(my_random_seed) of undefined -> random:seed(now()), erlang:put(my_random_seed, true); _ -> ok end.
null
https://raw.githubusercontent.com/dizengrong/erlang_game/4598f97daa9ca5eecff292ac401dd8f903eea867/gerl/src/util/util_random.erl
erlang
@doc 与随机相关的一些方法
@author dzR < > -module (util_random). -export([random_between/2]). -spec random_between(Min::integer(), Max::integer()) -> integer(). @doc从区间[Min , Max]随机一个整形 random_between(Min, Max) -> check_and_set_seed(), Min2 = Min - 1, random:uniform(Max - Min2) + Min2. check_and_set_seed() -> case erlang:get(my_random_seed) of undefined -> random:seed(now()), erlang:put(my_random_seed, true); _ -> ok end.
7597dcd23a0803a74d07e0f64ccce6c03d0635f5cd9e92532459ed12a7759944
REPROSEC/dolev-yao-star
Spec_Frodo_Gen.ml
open Prims let (frodo_gen_matrix_shake_get_r : Prims.nat -> (FStar_UInt8.t, unit) Lib_Sequence.lseq -> Prims.nat -> (FStar_UInt8.t, unit) Lib_Sequence.lseq) = fun n -> fun seed -> fun i -> let tmp = Obj.magic (Lib_ByteSequence.nat_to_intseq_le_ Lib_IntTypes.U8 Lib_IntTypes.SEC (Prims.of_int (2)) (Lib_IntTypes.v Lib_IntTypes.U16 Lib_IntTypes.SEC (Obj.magic (FStar_UInt16.uint_to_t i)))) in let b = Lib_Sequence.concat (Prims.of_int (2)) (Prims.of_int (16)) tmp seed in Spec_SHA3.shake128 (Prims.of_int (18)) b ((Prims.of_int (2)) * n) let (frodo_gen_matrix_shake0 : Prims.nat -> Prims.nat -> (FStar_UInt8.t, unit) Lib_Sequence.lseq -> Prims.nat -> (FStar_UInt16.t, unit) Lib_Sequence.lseq -> (FStar_UInt16.t, unit) Lib_Sequence.lseq) = fun n -> fun i -> fun res_i -> fun j -> fun res0 -> Spec_Matrix.mset n n res0 i j (let n1 = Lib_ByteSequence.nat_from_intseq_le_ Lib_IntTypes.U8 Lib_IntTypes.SEC (Obj.magic (Lib_Sequence.sub ((Prims.of_int (2)) * n) res_i (j * (Prims.of_int (2))) (Prims.of_int (2)))) in FStar_UInt16.uint_to_t n1) let (frodo_gen_matrix_shake1 : Prims.nat -> (FStar_UInt8.t, unit) Lib_Sequence.lseq -> Prims.nat -> (FStar_UInt16.t, unit) Lib_Sequence.lseq -> (FStar_UInt16.t, unit) Lib_Sequence.lseq) = fun n -> fun seed -> fun i -> fun res -> let res_i = frodo_gen_matrix_shake_get_r n seed i in Lib_LoopCombinators.repeati n (frodo_gen_matrix_shake0 n i res_i) res let (frodo_gen_matrix_shake : Prims.nat -> (FStar_UInt8.t, unit) Lib_Sequence.lseq -> (FStar_UInt16.t, unit) Lib_Sequence.lseq) = fun n -> fun seed -> let res = Spec_Matrix.create n n in Lib_LoopCombinators.repeati n (frodo_gen_matrix_shake1 n seed) res let (frodo_gen_matrix_shake_4x0 : Prims.nat -> Prims.nat -> (FStar_UInt8.t, unit) Lib_Sequence.lseq -> (FStar_UInt8.t, unit) Lib_Sequence.lseq -> (FStar_UInt8.t, unit) Lib_Sequence.lseq -> (FStar_UInt8.t, unit) Lib_Sequence.lseq -> Prims.nat -> (FStar_UInt16.t, unit) Lib_Sequence.lseq -> (FStar_UInt16.t, unit) Lib_Sequence.lseq) = fun n -> fun i -> fun r0 -> fun r1 -> fun r2 -> fun r3 -> fun j -> fun res0 -> let res01 = Spec_Matrix.mset n n res0 (((Prims.of_int (4)) * i) + Prims.int_zero) j (let n1 = Lib_ByteSequence.nat_from_intseq_le_ Lib_IntTypes.U8 Lib_IntTypes.SEC (Obj.magic (Lib_Sequence.sub ((Prims.of_int (2)) * n) r0 (j * (Prims.of_int (2))) (Prims.of_int (2)))) in FStar_UInt16.uint_to_t n1) in let res02 = Spec_Matrix.mset n n res01 (((Prims.of_int (4)) * i) + Prims.int_one) j (let n1 = Lib_ByteSequence.nat_from_intseq_le_ Lib_IntTypes.U8 Lib_IntTypes.SEC (Obj.magic (Lib_Sequence.sub ((Prims.of_int (2)) * n) r1 (j * (Prims.of_int (2))) (Prims.of_int (2)))) in FStar_UInt16.uint_to_t n1) in let res03 = Spec_Matrix.mset n n res02 (((Prims.of_int (4)) * i) + (Prims.of_int (2))) j (let n1 = Lib_ByteSequence.nat_from_intseq_le_ Lib_IntTypes.U8 Lib_IntTypes.SEC (Obj.magic (Lib_Sequence.sub ((Prims.of_int (2)) * n) r2 (j * (Prims.of_int (2))) (Prims.of_int (2)))) in FStar_UInt16.uint_to_t n1) in let res04 = Spec_Matrix.mset n n res03 (((Prims.of_int (4)) * i) + (Prims.of_int (3))) j (let n1 = Lib_ByteSequence.nat_from_intseq_le_ Lib_IntTypes.U8 Lib_IntTypes.SEC (Obj.magic (Lib_Sequence.sub ((Prims.of_int (2)) * n) r3 (j * (Prims.of_int (2))) (Prims.of_int (2)))) in FStar_UInt16.uint_to_t n1) in res04 let (frodo_gen_matrix_shake_4x1_get_r : Prims.nat -> (FStar_UInt8.t, unit) Lib_Sequence.lseq -> Prims.nat -> ((FStar_UInt8.t, unit) Lib_Sequence.lseq * (FStar_UInt8.t, unit) Lib_Sequence.lseq * (FStar_UInt8.t, unit) Lib_Sequence.lseq * (FStar_UInt8.t, unit) Lib_Sequence.lseq)) = fun n -> fun seed -> fun i -> let t0 = Obj.magic (Lib_ByteSequence.nat_to_intseq_le_ Lib_IntTypes.U8 Lib_IntTypes.SEC (Prims.of_int (2)) (Lib_IntTypes.v Lib_IntTypes.U16 Lib_IntTypes.SEC (Obj.magic (FStar_UInt16.uint_to_t (((Prims.of_int (4)) * i) + Prims.int_zero))))) in let t1 = Obj.magic (Lib_ByteSequence.nat_to_intseq_le_ Lib_IntTypes.U8 Lib_IntTypes.SEC (Prims.of_int (2)) (Lib_IntTypes.v Lib_IntTypes.U16 Lib_IntTypes.SEC (Obj.magic (FStar_UInt16.uint_to_t (((Prims.of_int (4)) * i) + Prims.int_one))))) in let t2 = Obj.magic (Lib_ByteSequence.nat_to_intseq_le_ Lib_IntTypes.U8 Lib_IntTypes.SEC (Prims.of_int (2)) (Lib_IntTypes.v Lib_IntTypes.U16 Lib_IntTypes.SEC (Obj.magic (FStar_UInt16.uint_to_t (((Prims.of_int (4)) * i) + (Prims.of_int (2))))))) in let t3 = Obj.magic (Lib_ByteSequence.nat_to_intseq_le_ Lib_IntTypes.U8 Lib_IntTypes.SEC (Prims.of_int (2)) (Lib_IntTypes.v Lib_IntTypes.U16 Lib_IntTypes.SEC (Obj.magic (FStar_UInt16.uint_to_t (((Prims.of_int (4)) * i) + (Prims.of_int (3))))))) in let b0 = Lib_Sequence.concat (Prims.of_int (2)) (Prims.of_int (16)) t0 seed in let b1 = Lib_Sequence.concat (Prims.of_int (2)) (Prims.of_int (16)) t1 seed in let b2 = Lib_Sequence.concat (Prims.of_int (2)) (Prims.of_int (16)) t2 seed in let b3 = Lib_Sequence.concat (Prims.of_int (2)) (Prims.of_int (16)) t3 seed in let r0 = Spec_SHA3.shake128 (Prims.of_int (18)) b0 ((Prims.of_int (2)) * n) in let r1 = Spec_SHA3.shake128 (Prims.of_int (18)) b1 ((Prims.of_int (2)) * n) in let r2 = Spec_SHA3.shake128 (Prims.of_int (18)) b2 ((Prims.of_int (2)) * n) in let r3 = Spec_SHA3.shake128 (Prims.of_int (18)) b3 ((Prims.of_int (2)) * n) in (r0, r1, r2, r3) let (frodo_gen_matrix_shake_4x1 : Prims.nat -> (FStar_UInt8.t, unit) Lib_Sequence.lseq -> Prims.nat -> (FStar_UInt16.t, unit) Lib_Sequence.lseq -> (FStar_UInt16.t, unit) Lib_Sequence.lseq) = fun n -> fun seed -> fun i -> fun res -> let uu___ = frodo_gen_matrix_shake_4x1_get_r n seed i in match uu___ with | (r0, r1, r2, r3) -> Lib_LoopCombinators.repeati n (frodo_gen_matrix_shake_4x0 n i r0 r1 r2 r3) res let (frodo_gen_matrix_shake_4x : Prims.nat -> (FStar_UInt8.t, unit) Lib_Sequence.lseq -> (FStar_UInt16.t, unit) Lib_Sequence.lseq) = fun n -> fun seed -> let res = Spec_Matrix.create n n in let n4 = n / (Prims.of_int (4)) in Lib_LoopCombinators.repeati n4 (frodo_gen_matrix_shake_4x1 n seed) res let (frodo_gen_matrix_aes : Prims.nat -> (FStar_UInt8.t, unit) Lib_Sequence.lseq -> (FStar_UInt16.t, unit) Lib_Sequence.lseq) = fun n -> fun seed -> let res = Spec_Matrix.create n n in let key = Spec_AES.aes128_key_expansion seed in let tmp = Lib_Sequence.create (Prims.of_int (8)) (FStar_UInt16.uint_to_t Prims.int_zero) in let n1 = n / (Prims.of_int (8)) in Lib_LoopCombinators.repeati n (fun i -> fun res1 -> Lib_LoopCombinators.repeati n1 (fun j -> fun res2 -> let j1 = j * (Prims.of_int (8)) in let tmp1 = Lib_Sequence.upd (Prims.of_int (8)) tmp Prims.int_zero (FStar_UInt16.uint_to_t i) in let tmp2 = Lib_Sequence.upd (Prims.of_int (8)) tmp1 Prims.int_one (FStar_UInt16.uint_to_t j1) in let res_i = Spec_AES.aes_encrypt_block Spec_AES.AES128 key (let uu___ = Lib_Sequence.generate_blocks (Prims.of_int (2)) (Prims.of_int (8)) (Prims.of_int (8)) () (fun uu___2 -> fun uu___1 -> (Obj.magic (Lib_ByteSequence.uints_to_bytes_le_inner Lib_IntTypes.U16 Lib_IntTypes.SEC (Prims.of_int (8)) (Obj.magic tmp2))) uu___2 uu___1) (Obj.repr ()) in match uu___ with | (uu___1, o) -> Obj.magic o) in Lib_LoopCombinators.repeati (Prims.of_int (8)) (fun k -> fun res3 -> Spec_Matrix.mset n n res3 i (j1 + k) (let n2 = Lib_ByteSequence.nat_from_intseq_le_ Lib_IntTypes.U8 Lib_IntTypes.SEC (Lib_Sequence.sub (Prims.of_int (16)) res_i (k * (Prims.of_int (2))) (Prims.of_int (2))) in FStar_UInt16.uint_to_t n2)) res2) res1) res let (frodo_gen_matrix_shake1_ind : Prims.nat -> (FStar_UInt8.t, unit) Lib_Sequence.lseq -> Prims.nat -> (FStar_UInt16.t, unit) Lib_Sequence.lseq -> (FStar_UInt16.t, unit) Lib_Sequence.lseq) = fun n -> fun seed -> fun i -> fun res -> let res_i = frodo_gen_matrix_shake_get_r n seed i in Lib_LoopCombinators.repeati_inductive' n () (frodo_gen_matrix_shake0 n i res_i) res let (frodo_gen_matrix_shake_ind : Prims.nat -> (FStar_UInt8.t, unit) Lib_Sequence.lseq -> (FStar_UInt16.t, unit) Lib_Sequence.lseq) = fun n -> fun seed -> let res = Spec_Matrix.create n n in Lib_LoopCombinators.repeati_inductive' n () (frodo_gen_matrix_shake1_ind n seed) res let (frodo_gen_matrix_shake_4x1_ind : Prims.nat -> (FStar_UInt8.t, unit) Lib_Sequence.lseq -> Prims.nat -> (FStar_UInt16.t, unit) Lib_Sequence.lseq -> (FStar_UInt16.t, unit) Lib_Sequence.lseq) = fun n -> fun seed -> fun i -> fun res -> let uu___ = frodo_gen_matrix_shake_4x1_get_r n seed i in match uu___ with | (r0, r1, r2, r3) -> Lib_LoopCombinators.repeati_inductive' n () (frodo_gen_matrix_shake_4x0 n i r0 r1 r2 r3) res let (frodo_gen_matrix_shake_4x_ind : Prims.nat -> (FStar_UInt8.t, unit) Lib_Sequence.lseq -> (FStar_UInt16.t, unit) Lib_Sequence.lseq) = fun n -> fun seed -> let res = Spec_Matrix.create n n in let n4 = n / (Prims.of_int (4)) in let res1 = Lib_LoopCombinators.repeati_inductive' n4 () (frodo_gen_matrix_shake_4x1_ind n seed) res in res1
null
https://raw.githubusercontent.com/REPROSEC/dolev-yao-star/d97a8dd4d07f2322437f186e4db6a1f4d5ee9230/concrete/hacl-star-snapshot/ml/Spec_Frodo_Gen.ml
ocaml
open Prims let (frodo_gen_matrix_shake_get_r : Prims.nat -> (FStar_UInt8.t, unit) Lib_Sequence.lseq -> Prims.nat -> (FStar_UInt8.t, unit) Lib_Sequence.lseq) = fun n -> fun seed -> fun i -> let tmp = Obj.magic (Lib_ByteSequence.nat_to_intseq_le_ Lib_IntTypes.U8 Lib_IntTypes.SEC (Prims.of_int (2)) (Lib_IntTypes.v Lib_IntTypes.U16 Lib_IntTypes.SEC (Obj.magic (FStar_UInt16.uint_to_t i)))) in let b = Lib_Sequence.concat (Prims.of_int (2)) (Prims.of_int (16)) tmp seed in Spec_SHA3.shake128 (Prims.of_int (18)) b ((Prims.of_int (2)) * n) let (frodo_gen_matrix_shake0 : Prims.nat -> Prims.nat -> (FStar_UInt8.t, unit) Lib_Sequence.lseq -> Prims.nat -> (FStar_UInt16.t, unit) Lib_Sequence.lseq -> (FStar_UInt16.t, unit) Lib_Sequence.lseq) = fun n -> fun i -> fun res_i -> fun j -> fun res0 -> Spec_Matrix.mset n n res0 i j (let n1 = Lib_ByteSequence.nat_from_intseq_le_ Lib_IntTypes.U8 Lib_IntTypes.SEC (Obj.magic (Lib_Sequence.sub ((Prims.of_int (2)) * n) res_i (j * (Prims.of_int (2))) (Prims.of_int (2)))) in FStar_UInt16.uint_to_t n1) let (frodo_gen_matrix_shake1 : Prims.nat -> (FStar_UInt8.t, unit) Lib_Sequence.lseq -> Prims.nat -> (FStar_UInt16.t, unit) Lib_Sequence.lseq -> (FStar_UInt16.t, unit) Lib_Sequence.lseq) = fun n -> fun seed -> fun i -> fun res -> let res_i = frodo_gen_matrix_shake_get_r n seed i in Lib_LoopCombinators.repeati n (frodo_gen_matrix_shake0 n i res_i) res let (frodo_gen_matrix_shake : Prims.nat -> (FStar_UInt8.t, unit) Lib_Sequence.lseq -> (FStar_UInt16.t, unit) Lib_Sequence.lseq) = fun n -> fun seed -> let res = Spec_Matrix.create n n in Lib_LoopCombinators.repeati n (frodo_gen_matrix_shake1 n seed) res let (frodo_gen_matrix_shake_4x0 : Prims.nat -> Prims.nat -> (FStar_UInt8.t, unit) Lib_Sequence.lseq -> (FStar_UInt8.t, unit) Lib_Sequence.lseq -> (FStar_UInt8.t, unit) Lib_Sequence.lseq -> (FStar_UInt8.t, unit) Lib_Sequence.lseq -> Prims.nat -> (FStar_UInt16.t, unit) Lib_Sequence.lseq -> (FStar_UInt16.t, unit) Lib_Sequence.lseq) = fun n -> fun i -> fun r0 -> fun r1 -> fun r2 -> fun r3 -> fun j -> fun res0 -> let res01 = Spec_Matrix.mset n n res0 (((Prims.of_int (4)) * i) + Prims.int_zero) j (let n1 = Lib_ByteSequence.nat_from_intseq_le_ Lib_IntTypes.U8 Lib_IntTypes.SEC (Obj.magic (Lib_Sequence.sub ((Prims.of_int (2)) * n) r0 (j * (Prims.of_int (2))) (Prims.of_int (2)))) in FStar_UInt16.uint_to_t n1) in let res02 = Spec_Matrix.mset n n res01 (((Prims.of_int (4)) * i) + Prims.int_one) j (let n1 = Lib_ByteSequence.nat_from_intseq_le_ Lib_IntTypes.U8 Lib_IntTypes.SEC (Obj.magic (Lib_Sequence.sub ((Prims.of_int (2)) * n) r1 (j * (Prims.of_int (2))) (Prims.of_int (2)))) in FStar_UInt16.uint_to_t n1) in let res03 = Spec_Matrix.mset n n res02 (((Prims.of_int (4)) * i) + (Prims.of_int (2))) j (let n1 = Lib_ByteSequence.nat_from_intseq_le_ Lib_IntTypes.U8 Lib_IntTypes.SEC (Obj.magic (Lib_Sequence.sub ((Prims.of_int (2)) * n) r2 (j * (Prims.of_int (2))) (Prims.of_int (2)))) in FStar_UInt16.uint_to_t n1) in let res04 = Spec_Matrix.mset n n res03 (((Prims.of_int (4)) * i) + (Prims.of_int (3))) j (let n1 = Lib_ByteSequence.nat_from_intseq_le_ Lib_IntTypes.U8 Lib_IntTypes.SEC (Obj.magic (Lib_Sequence.sub ((Prims.of_int (2)) * n) r3 (j * (Prims.of_int (2))) (Prims.of_int (2)))) in FStar_UInt16.uint_to_t n1) in res04 let (frodo_gen_matrix_shake_4x1_get_r : Prims.nat -> (FStar_UInt8.t, unit) Lib_Sequence.lseq -> Prims.nat -> ((FStar_UInt8.t, unit) Lib_Sequence.lseq * (FStar_UInt8.t, unit) Lib_Sequence.lseq * (FStar_UInt8.t, unit) Lib_Sequence.lseq * (FStar_UInt8.t, unit) Lib_Sequence.lseq)) = fun n -> fun seed -> fun i -> let t0 = Obj.magic (Lib_ByteSequence.nat_to_intseq_le_ Lib_IntTypes.U8 Lib_IntTypes.SEC (Prims.of_int (2)) (Lib_IntTypes.v Lib_IntTypes.U16 Lib_IntTypes.SEC (Obj.magic (FStar_UInt16.uint_to_t (((Prims.of_int (4)) * i) + Prims.int_zero))))) in let t1 = Obj.magic (Lib_ByteSequence.nat_to_intseq_le_ Lib_IntTypes.U8 Lib_IntTypes.SEC (Prims.of_int (2)) (Lib_IntTypes.v Lib_IntTypes.U16 Lib_IntTypes.SEC (Obj.magic (FStar_UInt16.uint_to_t (((Prims.of_int (4)) * i) + Prims.int_one))))) in let t2 = Obj.magic (Lib_ByteSequence.nat_to_intseq_le_ Lib_IntTypes.U8 Lib_IntTypes.SEC (Prims.of_int (2)) (Lib_IntTypes.v Lib_IntTypes.U16 Lib_IntTypes.SEC (Obj.magic (FStar_UInt16.uint_to_t (((Prims.of_int (4)) * i) + (Prims.of_int (2))))))) in let t3 = Obj.magic (Lib_ByteSequence.nat_to_intseq_le_ Lib_IntTypes.U8 Lib_IntTypes.SEC (Prims.of_int (2)) (Lib_IntTypes.v Lib_IntTypes.U16 Lib_IntTypes.SEC (Obj.magic (FStar_UInt16.uint_to_t (((Prims.of_int (4)) * i) + (Prims.of_int (3))))))) in let b0 = Lib_Sequence.concat (Prims.of_int (2)) (Prims.of_int (16)) t0 seed in let b1 = Lib_Sequence.concat (Prims.of_int (2)) (Prims.of_int (16)) t1 seed in let b2 = Lib_Sequence.concat (Prims.of_int (2)) (Prims.of_int (16)) t2 seed in let b3 = Lib_Sequence.concat (Prims.of_int (2)) (Prims.of_int (16)) t3 seed in let r0 = Spec_SHA3.shake128 (Prims.of_int (18)) b0 ((Prims.of_int (2)) * n) in let r1 = Spec_SHA3.shake128 (Prims.of_int (18)) b1 ((Prims.of_int (2)) * n) in let r2 = Spec_SHA3.shake128 (Prims.of_int (18)) b2 ((Prims.of_int (2)) * n) in let r3 = Spec_SHA3.shake128 (Prims.of_int (18)) b3 ((Prims.of_int (2)) * n) in (r0, r1, r2, r3) let (frodo_gen_matrix_shake_4x1 : Prims.nat -> (FStar_UInt8.t, unit) Lib_Sequence.lseq -> Prims.nat -> (FStar_UInt16.t, unit) Lib_Sequence.lseq -> (FStar_UInt16.t, unit) Lib_Sequence.lseq) = fun n -> fun seed -> fun i -> fun res -> let uu___ = frodo_gen_matrix_shake_4x1_get_r n seed i in match uu___ with | (r0, r1, r2, r3) -> Lib_LoopCombinators.repeati n (frodo_gen_matrix_shake_4x0 n i r0 r1 r2 r3) res let (frodo_gen_matrix_shake_4x : Prims.nat -> (FStar_UInt8.t, unit) Lib_Sequence.lseq -> (FStar_UInt16.t, unit) Lib_Sequence.lseq) = fun n -> fun seed -> let res = Spec_Matrix.create n n in let n4 = n / (Prims.of_int (4)) in Lib_LoopCombinators.repeati n4 (frodo_gen_matrix_shake_4x1 n seed) res let (frodo_gen_matrix_aes : Prims.nat -> (FStar_UInt8.t, unit) Lib_Sequence.lseq -> (FStar_UInt16.t, unit) Lib_Sequence.lseq) = fun n -> fun seed -> let res = Spec_Matrix.create n n in let key = Spec_AES.aes128_key_expansion seed in let tmp = Lib_Sequence.create (Prims.of_int (8)) (FStar_UInt16.uint_to_t Prims.int_zero) in let n1 = n / (Prims.of_int (8)) in Lib_LoopCombinators.repeati n (fun i -> fun res1 -> Lib_LoopCombinators.repeati n1 (fun j -> fun res2 -> let j1 = j * (Prims.of_int (8)) in let tmp1 = Lib_Sequence.upd (Prims.of_int (8)) tmp Prims.int_zero (FStar_UInt16.uint_to_t i) in let tmp2 = Lib_Sequence.upd (Prims.of_int (8)) tmp1 Prims.int_one (FStar_UInt16.uint_to_t j1) in let res_i = Spec_AES.aes_encrypt_block Spec_AES.AES128 key (let uu___ = Lib_Sequence.generate_blocks (Prims.of_int (2)) (Prims.of_int (8)) (Prims.of_int (8)) () (fun uu___2 -> fun uu___1 -> (Obj.magic (Lib_ByteSequence.uints_to_bytes_le_inner Lib_IntTypes.U16 Lib_IntTypes.SEC (Prims.of_int (8)) (Obj.magic tmp2))) uu___2 uu___1) (Obj.repr ()) in match uu___ with | (uu___1, o) -> Obj.magic o) in Lib_LoopCombinators.repeati (Prims.of_int (8)) (fun k -> fun res3 -> Spec_Matrix.mset n n res3 i (j1 + k) (let n2 = Lib_ByteSequence.nat_from_intseq_le_ Lib_IntTypes.U8 Lib_IntTypes.SEC (Lib_Sequence.sub (Prims.of_int (16)) res_i (k * (Prims.of_int (2))) (Prims.of_int (2))) in FStar_UInt16.uint_to_t n2)) res2) res1) res let (frodo_gen_matrix_shake1_ind : Prims.nat -> (FStar_UInt8.t, unit) Lib_Sequence.lseq -> Prims.nat -> (FStar_UInt16.t, unit) Lib_Sequence.lseq -> (FStar_UInt16.t, unit) Lib_Sequence.lseq) = fun n -> fun seed -> fun i -> fun res -> let res_i = frodo_gen_matrix_shake_get_r n seed i in Lib_LoopCombinators.repeati_inductive' n () (frodo_gen_matrix_shake0 n i res_i) res let (frodo_gen_matrix_shake_ind : Prims.nat -> (FStar_UInt8.t, unit) Lib_Sequence.lseq -> (FStar_UInt16.t, unit) Lib_Sequence.lseq) = fun n -> fun seed -> let res = Spec_Matrix.create n n in Lib_LoopCombinators.repeati_inductive' n () (frodo_gen_matrix_shake1_ind n seed) res let (frodo_gen_matrix_shake_4x1_ind : Prims.nat -> (FStar_UInt8.t, unit) Lib_Sequence.lseq -> Prims.nat -> (FStar_UInt16.t, unit) Lib_Sequence.lseq -> (FStar_UInt16.t, unit) Lib_Sequence.lseq) = fun n -> fun seed -> fun i -> fun res -> let uu___ = frodo_gen_matrix_shake_4x1_get_r n seed i in match uu___ with | (r0, r1, r2, r3) -> Lib_LoopCombinators.repeati_inductive' n () (frodo_gen_matrix_shake_4x0 n i r0 r1 r2 r3) res let (frodo_gen_matrix_shake_4x_ind : Prims.nat -> (FStar_UInt8.t, unit) Lib_Sequence.lseq -> (FStar_UInt16.t, unit) Lib_Sequence.lseq) = fun n -> fun seed -> let res = Spec_Matrix.create n n in let n4 = n / (Prims.of_int (4)) in let res1 = Lib_LoopCombinators.repeati_inductive' n4 () (frodo_gen_matrix_shake_4x1_ind n seed) res in res1
93689f9c8fac38d7ded1aa3b95d8dda8a0e80b730b997919ce94c756483d1f1d
sgimenez/laby
state.ml
* Copyright ( C ) 2007 - 2014 The laby team * You have permission to copy , modify , and redistribute under the * terms of the GPL-3.0 . For full license terms , see gpl-3.0.txt . * Copyright (C) 2007-2014 The laby team * You have permission to copy, modify, and redistribute under the * terms of the GPL-3.0. For full license terms, see gpl-3.0.txt. *) type tile = [ `Void | `Wall | `Exit | `Rock | `Web | `NRock | `NWeb ] type dir = [ `N | `E | `S | `W ] type action = [ `None | `Wall_In | `Rock_In | `Exit_In | `Web_In | `Web_Out | `Exit | `No_Exit | `Carry_Exit | `Rock_Take | `Rock_Drop | `Take_Nothing | `Take_No_Space | `Drop_Nothing | `Drop_No_Space | `Say of string ] type t = { map: tile array array; pos: int * int; dir: dir; carry: [`None | `Rock ]; action: action; } let make map pos dir = { map = map; pos = pos; dir = dir; carry = `None; action = `None; } let iter_map s p = Array.iteri (fun j a -> Array.iteri (fun i t -> p i j t) a) s.map let pos s = s.pos let dir s = s.dir let carry s = s.carry let action s = s.action let copy state = let map = Array.init (Array.length state.map) (fun j -> Array.copy state.map.(j)) in { state with map = map } let get state (i, j) = if i >= 0 && j >= 0 && j < Array.length state.map && i < Array.length (state.map.(0)) then state.map.(j).(i) else `Wall let set state (i, j) t = if i >= 0 && j >= 0 && j < Array.length state.map && i < Array.length (state.map.(0)) then let map = Array.copy state.map in let row = Array.copy map.(j) in row.(i) <- t; map.(j) <- row; map else state.map let clean state = { state with action = `None; } let chg state action = { state with action = action } let left state = let turn = begin function `N -> `W | `W -> `S | `S -> `E | `E -> `N end in { state with dir = turn state.dir } let right state = let turn = begin function `N -> `E | `E -> `S | `S -> `W | `W -> `N end in { state with dir = turn state.dir } let front state = begin match state.dir with | `N -> fst state.pos, snd state.pos - 1 | `E -> fst state.pos + 1, snd state.pos | `S -> fst state.pos, snd state.pos + 1 | `W -> fst state.pos - 1, snd state.pos end let forward ?(toexit=false) state = let move pos = let pos' = front state in begin match get state pos, get state pos' with | `Web, _ -> pos, `Web_Out | _, `Rock -> pos, `Rock_In | _, `Wall -> pos, `Wall_In | _, `Exit -> if toexit then (pos', `Exit) else (pos, `Exit_In) | _, `Web -> pos', `Web_In | _, _ -> pos', `None end in let pos, action = move state.pos in { state with pos = pos; action = action } let look state = get state (front state) let log_protocol = Log.make ["protocol"] let run action state = let state = clean state in begin match action with | "forward" -> "ok", forward state | "left" -> "ok", left state | "right" -> "ok", right state | "look" -> let ans = begin match look state with | `NRock | `NWeb | `Void -> "void" | `Wall -> "wall" | `Rock -> "rock" | `Web -> "web" | `Exit -> "exit" end in ans, state | "escape" -> begin match state.carry, get state (front state) with | `None, `Exit -> "ok", forward ~toexit:true state | _, `Exit -> "error", chg state `Carry_Exit | _, _ -> "error", chg state `No_Exit end | "take" -> begin match state.carry, get state (front state) with | `None, `Rock -> "ok", { state with map = set state (front state) `Void; carry = `Rock; action = `Rock_Take; } | `Rock, `Rock -> "error", chg state `Take_No_Space | _, _ -> "error", chg state `Take_Nothing end | "drop" -> begin match state.carry, get state (front state) with | `Rock, `Void | `Rock, `Web | `Rock, `NWeb -> "ok", { state with map = set state (front state) `Rock; carry = `None; action = `Rock_Drop; } | `None, _ -> "error", chg state `Drop_Nothing | _, _ -> "error", chg state `Drop_No_Space end | a when String.length a > 4 && String.sub a 0 4 = "say " -> "ok", chg state (`Say (String.sub a 4 (String.length a - 4))) | a -> log_protocol#error ( F.x "unknown action: <action>" [ "action", F.string a; ]; ); "-", state end let size state = Array.fold_left (fun m e -> max m (Array.length e)) 0 state.map, Array.length state.map let random_walk state = if look state <> `Void || Random.int 10 = 0 then if Random.int 2 = 0 then left state else right state else forward state
null
https://raw.githubusercontent.com/sgimenez/laby/47f9560eb827790d26900bb553719afb4b0554ea/src/state.ml
ocaml
* Copyright ( C ) 2007 - 2014 The laby team * You have permission to copy , modify , and redistribute under the * terms of the GPL-3.0 . For full license terms , see gpl-3.0.txt . * Copyright (C) 2007-2014 The laby team * You have permission to copy, modify, and redistribute under the * terms of the GPL-3.0. For full license terms, see gpl-3.0.txt. *) type tile = [ `Void | `Wall | `Exit | `Rock | `Web | `NRock | `NWeb ] type dir = [ `N | `E | `S | `W ] type action = [ `None | `Wall_In | `Rock_In | `Exit_In | `Web_In | `Web_Out | `Exit | `No_Exit | `Carry_Exit | `Rock_Take | `Rock_Drop | `Take_Nothing | `Take_No_Space | `Drop_Nothing | `Drop_No_Space | `Say of string ] type t = { map: tile array array; pos: int * int; dir: dir; carry: [`None | `Rock ]; action: action; } let make map pos dir = { map = map; pos = pos; dir = dir; carry = `None; action = `None; } let iter_map s p = Array.iteri (fun j a -> Array.iteri (fun i t -> p i j t) a) s.map let pos s = s.pos let dir s = s.dir let carry s = s.carry let action s = s.action let copy state = let map = Array.init (Array.length state.map) (fun j -> Array.copy state.map.(j)) in { state with map = map } let get state (i, j) = if i >= 0 && j >= 0 && j < Array.length state.map && i < Array.length (state.map.(0)) then state.map.(j).(i) else `Wall let set state (i, j) t = if i >= 0 && j >= 0 && j < Array.length state.map && i < Array.length (state.map.(0)) then let map = Array.copy state.map in let row = Array.copy map.(j) in row.(i) <- t; map.(j) <- row; map else state.map let clean state = { state with action = `None; } let chg state action = { state with action = action } let left state = let turn = begin function `N -> `W | `W -> `S | `S -> `E | `E -> `N end in { state with dir = turn state.dir } let right state = let turn = begin function `N -> `E | `E -> `S | `S -> `W | `W -> `N end in { state with dir = turn state.dir } let front state = begin match state.dir with | `N -> fst state.pos, snd state.pos - 1 | `E -> fst state.pos + 1, snd state.pos | `S -> fst state.pos, snd state.pos + 1 | `W -> fst state.pos - 1, snd state.pos end let forward ?(toexit=false) state = let move pos = let pos' = front state in begin match get state pos, get state pos' with | `Web, _ -> pos, `Web_Out | _, `Rock -> pos, `Rock_In | _, `Wall -> pos, `Wall_In | _, `Exit -> if toexit then (pos', `Exit) else (pos, `Exit_In) | _, `Web -> pos', `Web_In | _, _ -> pos', `None end in let pos, action = move state.pos in { state with pos = pos; action = action } let look state = get state (front state) let log_protocol = Log.make ["protocol"] let run action state = let state = clean state in begin match action with | "forward" -> "ok", forward state | "left" -> "ok", left state | "right" -> "ok", right state | "look" -> let ans = begin match look state with | `NRock | `NWeb | `Void -> "void" | `Wall -> "wall" | `Rock -> "rock" | `Web -> "web" | `Exit -> "exit" end in ans, state | "escape" -> begin match state.carry, get state (front state) with | `None, `Exit -> "ok", forward ~toexit:true state | _, `Exit -> "error", chg state `Carry_Exit | _, _ -> "error", chg state `No_Exit end | "take" -> begin match state.carry, get state (front state) with | `None, `Rock -> "ok", { state with map = set state (front state) `Void; carry = `Rock; action = `Rock_Take; } | `Rock, `Rock -> "error", chg state `Take_No_Space | _, _ -> "error", chg state `Take_Nothing end | "drop" -> begin match state.carry, get state (front state) with | `Rock, `Void | `Rock, `Web | `Rock, `NWeb -> "ok", { state with map = set state (front state) `Rock; carry = `None; action = `Rock_Drop; } | `None, _ -> "error", chg state `Drop_Nothing | _, _ -> "error", chg state `Drop_No_Space end | a when String.length a > 4 && String.sub a 0 4 = "say " -> "ok", chg state (`Say (String.sub a 4 (String.length a - 4))) | a -> log_protocol#error ( F.x "unknown action: <action>" [ "action", F.string a; ]; ); "-", state end let size state = Array.fold_left (fun m e -> max m (Array.length e)) 0 state.map, Array.length state.map let random_walk state = if look state <> `Void || Random.int 10 = 0 then if Random.int 2 = 0 then left state else right state else forward state
3992dce1dc54c3b56f3fafc4ed163889dad78a093de4f75ac7163e059f8a8ef0
MaskRay/99-problems-ocaml
67.ml
type 'a tree = Leaf | Branch of 'a * 'a tree * 'a tree let rec tree_string = function | Leaf -> "" | Branch (x,l,r) -> String.concat "" [tree_string l; String.make 1 x; tree_string r]
null
https://raw.githubusercontent.com/MaskRay/99-problems-ocaml/652604f13ba7a73eee06d359b4db549b49ec9bb3/61-70/67.ml
ocaml
type 'a tree = Leaf | Branch of 'a * 'a tree * 'a tree let rec tree_string = function | Leaf -> "" | Branch (x,l,r) -> String.concat "" [tree_string l; String.make 1 x; tree_string r]
177293da1050b9c34b9fe8b6e12b38681ee32399d8d1af32d6d5dd5bd5477c12
boxer-project/boxer-sunrise
ufns.lisp
-*- Mode : Lisp ; rcs - header : " $ Header : /hope / lwhope1 - cam / hope.0 / compound/61 / LISPopengl / RCS / ufns.lisp , v 1.10.1.1 2017/01/19 11:51:03 martin Exp $ " -*- Copyright ( c ) 1987 - -2017 LispWorks Ltd. All rights reserved . (in-package "OPENGL") #| DATE : 9Oct95 | USER : ken | PROCESSED FILE : /u/ken/OpenGL/opengl/glu.h |# (fli:define-foreign-function (glu-error-string "gluErrorString" :source) ((error-code glenum)) :result-type #+mswindows (w:LPSTR :pass-by :reference) #-mswindows (:reference :lisp-string-array) :language :ansi-c) ;;; glu-error-string - Win32 implmentation includes gluErrorUnicodeStringEXT which returns a UNICODE error string . Only access this when running on NT - use glu - error - string - win ;;; to dispatch to the correct OS function. #+mswindows (fli:define-foreign-function (glu-error-unicode-string "gluErrorUnicodeStringEXT" :source) ((error-code glenum)) :result-type (w:LPWSTR :pass-by :reference)) #+mswindows (defun glu-error-string-win (glenum) (if (string= (software-type) "Windows NT") (glu-error-unicode-string glenum) (glu-error-string glenum))) (fli:define-foreign-function (glu-get-string "gluGetString" :source) ((name glenum)) :result-type #+mswindows (w:LPSTR :pass-by :reference) #-mswindows (:reference :lisp-string-array) :language :ansi-c) (fli:define-foreign-function (glu-ortho2-d "gluOrtho2D" :source) ((left gldouble) (right gldouble) (bottom gldouble) (top gldouble)) :result-type :void :language :ansi-c) (fli:define-foreign-function (glu-perspective "gluPerspective" :source) ((fovy gldouble) (aspect gldouble) (z-near gldouble) (z-far gldouble)) :result-type :void :language :ansi-c) (fli:define-foreign-function (glu-pick-matrix "gluPickMatrix" :source) ((x gldouble) (y gldouble) (width gldouble) (height gldouble) (viewport (gl-vector :signed-32 4))) :result-type :void :language :ansi-c) (fli:define-foreign-function (glu-look-at "gluLookAt" :source) ((eyex gldouble) (eyey gldouble) (eyez gldouble) (centerx gldouble) (centery gldouble) (centerz gldouble) (upx gldouble) (upy gldouble) (upz gldouble)) :result-type :void :language :ansi-c) (fli:define-foreign-function (glu-project "gluProject" :source) ((objx gldouble) (objy gldouble) (objz gldouble) (model-matrix (gl-vector :double-float 16)) (proj-matrix (gl-vector :double-float 16)) (viewport (gl-vector :signed-32 4)) winx winy :result-type (:signed :int) :language :ansi-c) (fli:define-foreign-function (glu-un-project "gluUnProject" :source) ((winx gldouble) (winy gldouble) (winz gldouble) (model-matrix (gl-vector :double-float 16)) (proj-matrix (gl-vector :double-float 16)) (viewport (gl-vector :signed-32 4)) objx (:ignore #|objt|# (:reference-return gldouble)) (:ignore #|objz|# (:reference-return gldouble))) :result-type (:signed :int) :language :ansi-c) (fli:define-foreign-function (glu-scale-image "gluScaleImage" :source) ((format glenum) (widthin glint) (heightin glint) (typein glenum) (datain gl-vector) (widthout glint) (heightout glint) (typeout glenum) (dataout gl-vector)) :result-type (:signed :int) :language :ansi-c) (fli:define-foreign-function (glu-build1-dmipmaps "gluBuild1DMipmaps" :source) ((target glenum) (components glint) (width glint) (format glenum) (type glenum) (data gl-vector)) :result-type (:signed :int) :language :ansi-c) (fli:define-foreign-function (glu-build2-dmipmaps "gluBuild2DMipmaps" :source) ((target glenum) (components glint) (width glint) (height glint) (format glenum) (type glenum) (data gl-vector)) :result-type (:signed :int) :language :ansi-c) (fli:define-c-struct (gluquadric (:foreign-name "GLUquadric") (:forward-reference-p t))) (fli:define-c-typedef (gluquadric-obj (:foreign-name "GLUquadricObj")) (:struct gluquadric)) (fli:define-foreign-function (glu-new-quadric "gluNewQuadric" :source) nil :result-type (:pointer gluquadric-obj) :language :ansi-c) (fli:define-foreign-function (glu-delete-quadric "gluDeleteQuadric" :source) ((state (:pointer gluquadric-obj))) :result-type :void :language :ansi-c) (fli:define-foreign-function (glu-quadric-normals "gluQuadricNormals" :source) ((quad-object (:pointer gluquadric-obj)) (normals glenum)) :result-type :void :language :ansi-c) (fli:define-foreign-function (glu-quadric-texture "gluQuadricTexture" :source) ((quad-object (:pointer gluquadric-obj)) (texture-coords glboolean)) :result-type :void :language :ansi-c) (fli:define-foreign-function (glu-quadric-orientation "gluQuadricOrientation" :source) ((quad-object (:pointer gluquadric-obj)) (orientation glenum)) :result-type :void :language :ansi-c) (fli:define-foreign-function (glu-quadric-draw-style "gluQuadricDrawStyle" :source) ((quad-object (:pointer gluquadric-obj)) (draw-style glenum)) :result-type :void :language :ansi-c) (fli:define-foreign-function (glu-cylinder "gluCylinder" :source) ((qobj (:pointer gluquadric-obj)) (base-radius gldouble) (top-radius gldouble) (height gldouble) (slices glint) (stacks glint)) :result-type :void :language :ansi-c) (fli:define-foreign-function (glu-disk "gluDisk" :source) ((qobj (:pointer gluquadric-obj)) (inner-radius gldouble) (outer-radius gldouble) (slices glint) (loops glint)) :result-type :void :language :ansi-c) (fli:define-foreign-function (glu-partial-disk "gluPartialDisk" :source) ((qobj (:pointer gluquadric-obj)) (inner-radius gldouble) (outer-radius gldouble) (slices glint) (loops glint) (start-angle gldouble) (sweep-angle gldouble)) :result-type :void :language :ansi-c) (fli:define-foreign-function (glu-sphere "gluSphere" :source) ((qobj (:pointer gluquadric-obj)) (radius gldouble) (slices glint) (stacks glint)) :result-type :void :language :ansi-c) (fli:define-foreign-function (glu-quadric-callback "gluQuadricCallback" :source) ((qobj (:pointer gluquadric-obj)) (which glenum) (fn (:pointer (:function nil :void)))) :result-type :void :language :ansi-c) (fli:define-c-struct (GLUtesselator (:foreign-name "GLUtesselator") (:forward-reference-p t))) (fli:define-c-typedef (glutriangulator-obj (:foreign-name "GLUtriangulatorObj")) (:struct GLUtesselator)) (fli:define-foreign-function (glu-new-tess "gluNewTess" :source) nil :result-type (:pointer glutriangulator-obj) :language :ansi-c) (fli:define-foreign-function (glu-tess-callback "gluTessCallback" :source) ((tobj (:pointer glutriangulator-obj)) (which glenum) (fn (:pointer (:function nil :void)))) :result-type :void :language :ansi-c) (fli:define-foreign-function (glu-delete-tess "gluDeleteTess" :source) ((tobj (:pointer glutriangulator-obj))) :result-type :void :language :ansi-c) (fli:define-foreign-function (glu-begin-polygon "gluBeginPolygon" :source) ((tobj (:pointer glutriangulator-obj))) :result-type :void :language :ansi-c) (fli:define-foreign-function (glu-end-polygon "gluEndPolygon" :source) ((tobj (:pointer glutriangulator-obj))) :result-type :void :language :ansi-c) (fli:define-foreign-function (glu-next-contour "gluNextContour" :source) ((tobj (:pointer glutriangulator-obj)) (type glenum)) :result-type :void :language :ansi-c) (fli:define-foreign-function (glu-tess-vertex "gluTessVertex" :source) ((tobj (:pointer glutriangulator-obj)) (v (:c-array gldouble 3)) (data (:pointer :void))) :result-type :void :language :ansi-c) (fli:define-c-struct (glunurbs (:foreign-name "GLUnurbs") (:forward-reference-p t))) (fli:define-c-typedef (glunurbs-obj (:foreign-name "GLUnurbsObj")) (:struct glunurbs)) (fli:define-foreign-function (glu-new-nurbs-renderer "gluNewNurbsRenderer" :source) nil :result-type (:pointer glunurbs-obj) :language :ansi-c) (fli:define-foreign-function (glu-delete-nurbs-renderer "gluDeleteNurbsRenderer" :source) ((nobj (:pointer glunurbs-obj))) :result-type :void :language :ansi-c) (fli:define-foreign-function (glu-begin-surface "gluBeginSurface" :source) ((nobj (:pointer glunurbs-obj))) :result-type :void :language :ansi-c) (fli:define-foreign-function (glu-begin-curve "gluBeginCurve" :source) ((nobj (:pointer glunurbs-obj))) :result-type :void :language :ansi-c) (fli:define-foreign-function (glu-end-curve "gluEndCurve" :source) ((nobj (:pointer glunurbs-obj))) :result-type :void :language :ansi-c) (fli:define-foreign-function (glu-end-surface "gluEndSurface" :source) ((nobj (:pointer glunurbs-obj))) :result-type :void :language :ansi-c) (fli:define-foreign-function (glu-begin-trim "gluBeginTrim" :source) ((nobj (:pointer glunurbs-obj))) :result-type :void :language :ansi-c) (fli:define-foreign-function (glu-end-trim "gluEndTrim" :source) ((nobj (:pointer glunurbs-obj))) :result-type :void :language :ansi-c) (fli:define-foreign-function (glu-pwl-curve "gluPwlCurve" :source) ((nobj (:pointer glunurbs-obj)) (count glint) (array (gl-vector :single-float)) (stride glint) (type glenum)) :result-type :void :language :ansi-c) (fli:define-foreign-function (glu-nurbs-curve "gluNurbsCurve" :source) ((nobj (:pointer glunurbs-obj)) (nknots glint) (knot (gl-vector :single-float)) (stride glint) (ctlarray (gl-vector :single-float)) (order glint) (type glenum)) :result-type :void :language :ansi-c) (fli:define-foreign-function (glu-nurbs-surface "gluNurbsSurface" :source) ((nobj (:pointer glunurbs-obj)) (sknot-count glint) (sknot (gl-vector :single-float)) (tknot-count glint) (tknot (gl-vector :single-float)) (s-stride glint) (t-stride glint) (ctlarray (gl-vector :single-float)) (sorder glint) (torder glint) (type glenum)) :result-type :void :language :ansi-c) (fli:define-foreign-function (glu-load-sampling-matrices "gluLoadSamplingMatrices" :source) ((nobj (:pointer glunurbs-obj)) (model-matrix (gl-vector :single-float 16)) (proj-matrix (gl-vector :single-float 16)) (viewport (gl-vector :signed-32 4))) :result-type :void :language :ansi-c) (fli:define-foreign-function (glu-nurbs-property "gluNurbsProperty" :source) ((nobj (:pointer glunurbs-obj)) (property glenum) (value glfloat)) :result-type :void :language :ansi-c) (fli:define-foreign-function (glu-get-nurbs-property "gluGetNurbsProperty" :source) ((nobj (:pointer glunurbs-obj)) (property glenum) (value (:pointer glfloat))) :result-type :void :language :ansi-c) (fli:define-foreign-function (glu-nurbs-callback "gluNurbsCallback" :source) ((nobj (:pointer glunurbs-obj)) (which glenum) (fn (:pointer (:function nil :void)))) :result-type :void :language :ansi-c)
null
https://raw.githubusercontent.com/boxer-project/boxer-sunrise/1ef5d5a65d00298b0d7a01890b3cd15d78adc1af/src/opengl/ufns.lisp
lisp
rcs - header : " $ Header : /hope / lwhope1 - cam / hope.0 / compound/61 / LISPopengl / RCS / ufns.lisp , v 1.10.1.1 2017/01/19 11:51:03 martin Exp $ " -*- DATE : 9Oct95 | USER : ken | PROCESSED FILE : /u/ken/OpenGL/opengl/glu.h glu-error-string - Win32 implmentation includes gluErrorUnicodeStringEXT which returns to dispatch to the correct OS function. objt objz
Copyright ( c ) 1987 - -2017 LispWorks Ltd. All rights reserved . (in-package "OPENGL") (fli:define-foreign-function (glu-error-string "gluErrorString" :source) ((error-code glenum)) :result-type #+mswindows (w:LPSTR :pass-by :reference) #-mswindows (:reference :lisp-string-array) :language :ansi-c) a UNICODE error string . Only access this when running on NT - use glu - error - string - win #+mswindows (fli:define-foreign-function (glu-error-unicode-string "gluErrorUnicodeStringEXT" :source) ((error-code glenum)) :result-type (w:LPWSTR :pass-by :reference)) #+mswindows (defun glu-error-string-win (glenum) (if (string= (software-type) "Windows NT") (glu-error-unicode-string glenum) (glu-error-string glenum))) (fli:define-foreign-function (glu-get-string "gluGetString" :source) ((name glenum)) :result-type #+mswindows (w:LPSTR :pass-by :reference) #-mswindows (:reference :lisp-string-array) :language :ansi-c) (fli:define-foreign-function (glu-ortho2-d "gluOrtho2D" :source) ((left gldouble) (right gldouble) (bottom gldouble) (top gldouble)) :result-type :void :language :ansi-c) (fli:define-foreign-function (glu-perspective "gluPerspective" :source) ((fovy gldouble) (aspect gldouble) (z-near gldouble) (z-far gldouble)) :result-type :void :language :ansi-c) (fli:define-foreign-function (glu-pick-matrix "gluPickMatrix" :source) ((x gldouble) (y gldouble) (width gldouble) (height gldouble) (viewport (gl-vector :signed-32 4))) :result-type :void :language :ansi-c) (fli:define-foreign-function (glu-look-at "gluLookAt" :source) ((eyex gldouble) (eyey gldouble) (eyez gldouble) (centerx gldouble) (centery gldouble) (centerz gldouble) (upx gldouble) (upy gldouble) (upz gldouble)) :result-type :void :language :ansi-c) (fli:define-foreign-function (glu-project "gluProject" :source) ((objx gldouble) (objy gldouble) (objz gldouble) (model-matrix (gl-vector :double-float 16)) (proj-matrix (gl-vector :double-float 16)) (viewport (gl-vector :signed-32 4)) winx winy :result-type (:signed :int) :language :ansi-c) (fli:define-foreign-function (glu-un-project "gluUnProject" :source) ((winx gldouble) (winy gldouble) (winz gldouble) (model-matrix (gl-vector :double-float 16)) (proj-matrix (gl-vector :double-float 16)) (viewport (gl-vector :signed-32 4)) objx :result-type (:signed :int) :language :ansi-c) (fli:define-foreign-function (glu-scale-image "gluScaleImage" :source) ((format glenum) (widthin glint) (heightin glint) (typein glenum) (datain gl-vector) (widthout glint) (heightout glint) (typeout glenum) (dataout gl-vector)) :result-type (:signed :int) :language :ansi-c) (fli:define-foreign-function (glu-build1-dmipmaps "gluBuild1DMipmaps" :source) ((target glenum) (components glint) (width glint) (format glenum) (type glenum) (data gl-vector)) :result-type (:signed :int) :language :ansi-c) (fli:define-foreign-function (glu-build2-dmipmaps "gluBuild2DMipmaps" :source) ((target glenum) (components glint) (width glint) (height glint) (format glenum) (type glenum) (data gl-vector)) :result-type (:signed :int) :language :ansi-c) (fli:define-c-struct (gluquadric (:foreign-name "GLUquadric") (:forward-reference-p t))) (fli:define-c-typedef (gluquadric-obj (:foreign-name "GLUquadricObj")) (:struct gluquadric)) (fli:define-foreign-function (glu-new-quadric "gluNewQuadric" :source) nil :result-type (:pointer gluquadric-obj) :language :ansi-c) (fli:define-foreign-function (glu-delete-quadric "gluDeleteQuadric" :source) ((state (:pointer gluquadric-obj))) :result-type :void :language :ansi-c) (fli:define-foreign-function (glu-quadric-normals "gluQuadricNormals" :source) ((quad-object (:pointer gluquadric-obj)) (normals glenum)) :result-type :void :language :ansi-c) (fli:define-foreign-function (glu-quadric-texture "gluQuadricTexture" :source) ((quad-object (:pointer gluquadric-obj)) (texture-coords glboolean)) :result-type :void :language :ansi-c) (fli:define-foreign-function (glu-quadric-orientation "gluQuadricOrientation" :source) ((quad-object (:pointer gluquadric-obj)) (orientation glenum)) :result-type :void :language :ansi-c) (fli:define-foreign-function (glu-quadric-draw-style "gluQuadricDrawStyle" :source) ((quad-object (:pointer gluquadric-obj)) (draw-style glenum)) :result-type :void :language :ansi-c) (fli:define-foreign-function (glu-cylinder "gluCylinder" :source) ((qobj (:pointer gluquadric-obj)) (base-radius gldouble) (top-radius gldouble) (height gldouble) (slices glint) (stacks glint)) :result-type :void :language :ansi-c) (fli:define-foreign-function (glu-disk "gluDisk" :source) ((qobj (:pointer gluquadric-obj)) (inner-radius gldouble) (outer-radius gldouble) (slices glint) (loops glint)) :result-type :void :language :ansi-c) (fli:define-foreign-function (glu-partial-disk "gluPartialDisk" :source) ((qobj (:pointer gluquadric-obj)) (inner-radius gldouble) (outer-radius gldouble) (slices glint) (loops glint) (start-angle gldouble) (sweep-angle gldouble)) :result-type :void :language :ansi-c) (fli:define-foreign-function (glu-sphere "gluSphere" :source) ((qobj (:pointer gluquadric-obj)) (radius gldouble) (slices glint) (stacks glint)) :result-type :void :language :ansi-c) (fli:define-foreign-function (glu-quadric-callback "gluQuadricCallback" :source) ((qobj (:pointer gluquadric-obj)) (which glenum) (fn (:pointer (:function nil :void)))) :result-type :void :language :ansi-c) (fli:define-c-struct (GLUtesselator (:foreign-name "GLUtesselator") (:forward-reference-p t))) (fli:define-c-typedef (glutriangulator-obj (:foreign-name "GLUtriangulatorObj")) (:struct GLUtesselator)) (fli:define-foreign-function (glu-new-tess "gluNewTess" :source) nil :result-type (:pointer glutriangulator-obj) :language :ansi-c) (fli:define-foreign-function (glu-tess-callback "gluTessCallback" :source) ((tobj (:pointer glutriangulator-obj)) (which glenum) (fn (:pointer (:function nil :void)))) :result-type :void :language :ansi-c) (fli:define-foreign-function (glu-delete-tess "gluDeleteTess" :source) ((tobj (:pointer glutriangulator-obj))) :result-type :void :language :ansi-c) (fli:define-foreign-function (glu-begin-polygon "gluBeginPolygon" :source) ((tobj (:pointer glutriangulator-obj))) :result-type :void :language :ansi-c) (fli:define-foreign-function (glu-end-polygon "gluEndPolygon" :source) ((tobj (:pointer glutriangulator-obj))) :result-type :void :language :ansi-c) (fli:define-foreign-function (glu-next-contour "gluNextContour" :source) ((tobj (:pointer glutriangulator-obj)) (type glenum)) :result-type :void :language :ansi-c) (fli:define-foreign-function (glu-tess-vertex "gluTessVertex" :source) ((tobj (:pointer glutriangulator-obj)) (v (:c-array gldouble 3)) (data (:pointer :void))) :result-type :void :language :ansi-c) (fli:define-c-struct (glunurbs (:foreign-name "GLUnurbs") (:forward-reference-p t))) (fli:define-c-typedef (glunurbs-obj (:foreign-name "GLUnurbsObj")) (:struct glunurbs)) (fli:define-foreign-function (glu-new-nurbs-renderer "gluNewNurbsRenderer" :source) nil :result-type (:pointer glunurbs-obj) :language :ansi-c) (fli:define-foreign-function (glu-delete-nurbs-renderer "gluDeleteNurbsRenderer" :source) ((nobj (:pointer glunurbs-obj))) :result-type :void :language :ansi-c) (fli:define-foreign-function (glu-begin-surface "gluBeginSurface" :source) ((nobj (:pointer glunurbs-obj))) :result-type :void :language :ansi-c) (fli:define-foreign-function (glu-begin-curve "gluBeginCurve" :source) ((nobj (:pointer glunurbs-obj))) :result-type :void :language :ansi-c) (fli:define-foreign-function (glu-end-curve "gluEndCurve" :source) ((nobj (:pointer glunurbs-obj))) :result-type :void :language :ansi-c) (fli:define-foreign-function (glu-end-surface "gluEndSurface" :source) ((nobj (:pointer glunurbs-obj))) :result-type :void :language :ansi-c) (fli:define-foreign-function (glu-begin-trim "gluBeginTrim" :source) ((nobj (:pointer glunurbs-obj))) :result-type :void :language :ansi-c) (fli:define-foreign-function (glu-end-trim "gluEndTrim" :source) ((nobj (:pointer glunurbs-obj))) :result-type :void :language :ansi-c) (fli:define-foreign-function (glu-pwl-curve "gluPwlCurve" :source) ((nobj (:pointer glunurbs-obj)) (count glint) (array (gl-vector :single-float)) (stride glint) (type glenum)) :result-type :void :language :ansi-c) (fli:define-foreign-function (glu-nurbs-curve "gluNurbsCurve" :source) ((nobj (:pointer glunurbs-obj)) (nknots glint) (knot (gl-vector :single-float)) (stride glint) (ctlarray (gl-vector :single-float)) (order glint) (type glenum)) :result-type :void :language :ansi-c) (fli:define-foreign-function (glu-nurbs-surface "gluNurbsSurface" :source) ((nobj (:pointer glunurbs-obj)) (sknot-count glint) (sknot (gl-vector :single-float)) (tknot-count glint) (tknot (gl-vector :single-float)) (s-stride glint) (t-stride glint) (ctlarray (gl-vector :single-float)) (sorder glint) (torder glint) (type glenum)) :result-type :void :language :ansi-c) (fli:define-foreign-function (glu-load-sampling-matrices "gluLoadSamplingMatrices" :source) ((nobj (:pointer glunurbs-obj)) (model-matrix (gl-vector :single-float 16)) (proj-matrix (gl-vector :single-float 16)) (viewport (gl-vector :signed-32 4))) :result-type :void :language :ansi-c) (fli:define-foreign-function (glu-nurbs-property "gluNurbsProperty" :source) ((nobj (:pointer glunurbs-obj)) (property glenum) (value glfloat)) :result-type :void :language :ansi-c) (fli:define-foreign-function (glu-get-nurbs-property "gluGetNurbsProperty" :source) ((nobj (:pointer glunurbs-obj)) (property glenum) (value (:pointer glfloat))) :result-type :void :language :ansi-c) (fli:define-foreign-function (glu-nurbs-callback "gluNurbsCallback" :source) ((nobj (:pointer glunurbs-obj)) (which glenum) (fn (:pointer (:function nil :void)))) :result-type :void :language :ansi-c)
ee705e8a5541455557c6ad4ec92cc1695076adb96b0e5972eb78d652bd2b24e4
plumatic/plumbing
map_test.cljc
(ns plumbing.map-test (:refer-clojure :exclude [flatten]) (:require [plumbing.core :as plumbing] [plumbing.map :as map] [clojure.string :as str] #?(:clj [clojure.test :refer :all] :cljs [cljs.test :refer-macros [is deftest testing use-fixtures]])) #?(:cljs (:require-macros [plumbing.map :as map]))) #?(:cljs (do (def Exception js/Error) (def AssertionError js/Error) (def Throwable js/Error))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Clojure immutable maps (deftest safe-select-keys-test (is (= {:a 1 :c 3} (map/safe-select-keys {:a 1 :b 2 :c 3} [:a :c]))) (is (= {} (map/safe-select-keys {:a 1 :b 2 :c 3} []))) (is (thrown? Throwable (map/safe-select-keys {:a 1 :b 2 :c 3} [:a :b :d])))) (deftest merge-disjoint-test (is (= {:a 1 :b 2 :c 3} (map/merge-disjoint {} {:a 1 :b 2} {:c 3} {}))) (is (thrown? Throwable (map/merge-disjoint {} {:a 1 :b 2} {:b 5 :c 3} {})))) (deftest merge-with-key-test (is (= {"k1" "v1" :k1 :v2} (map/merge-with-key (fn [k v1 v2] (if (string? k) v1 v2)) {"k1" "v1" :k1 :v1} {"k1" "v2" :k1 :v2})))) (deftest flatten-test (is (empty? (map/flatten nil))) (is (empty? (map/flatten {}))) (is (= [[[] :foo]] (map/flatten :foo))) (is (= {[:a] 1 [:b :c] false [:b :d :e] nil [:b :d :f] 4} (into {} (map/flatten {:a 1 :b {:c false :d {:e nil :f 4}}}))))) (deftest unflatten-test (is (= {} (map/unflatten nil))) (is (= :foo (map/unflatten [[[] :foo]]))) (is (= {:a 1 :b {:c 2 :d {:e 3 :f 4}}} (map/unflatten {[:a] 1 [:b :c] 2 [:b :d :e] 3 [:b :d :f] 4})))) (deftest map-leaves-and-path-test (is (empty? (map/map-leaves-and-path (constantly 2) nil))) (is (= {:a {:b "a,b2"} :c {:d "c,d3"} :e "e11"} (map/map-leaves-and-path (fn [ks v] (str (str/join "," (map name ks)) (inc v))) {:a {:b 1} :c {:d 2} :e 10})))) (deftest map-leaves-test (is (empty? (map/map-leaves (constantly 2) nil))) (is (= {:a {:b "1"} :c {:d "2"} :e "10"} (map/map-leaves str {:a {:b 1} :c {:d 2} :e 10}))) (is (= {:a {:b nil} :c {:d nil} :e nil} (map/map-leaves (constantly nil) {:a {:b 1} :c {:d 2} :e 10})))) (deftest keep-leaves-test (is (empty? (map/keep-leaves (constantly 2) {}))) (is (= {:a {:b "1"} :c {:d "2"} :e "10"} (map/keep-leaves str {:a {:b 1} :c {:d 2} :e 10}))) (is (= {:a {:b false} :c {:d false} :e false} (map/keep-leaves (constantly false) {:a {:b 1} :c {:d 2} :e 10}))) (is (= {} (map/keep-leaves (constantly nil) {:a {:b 1} :c {:d 2} :e 10}))) (is (= {:c {:d 10} :e 4} (map/keep-leaves #(when (even? %) %) {:a {:b 5} :c {:d 10 :e {:f 5}} :e 4})))) (def some-var "hey hey") (deftest keyword-map-test (is (= {} (map/keyword-map)) "works with no args") (is (= {:x 42} (let [x (* 2 3 7)] (map/keyword-map x)))) (is (= {:some-var "hey hey" :$ \$} (let [$ \$] (map/keyword-map some-var $))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Java mutable Maps #?(:clj (do (deftest update-key!-test (let [m (java.util.HashMap. {:a 1 :b 2})] (map/update-key! m :a inc) (is (= {:a 2 :b 2} (into {} m))) (map/update-key! m :c conj "foo") (is (= {:a 2 :b 2 :c ["foo"]} (into {} m))))) (deftest get!-test (let [m (java.util.HashMap.) a! (fn [k v] (.add ^java.util.List (map/get! m k (java.util.ArrayList.)) v)) value (fn [] (plumbing/map-vals seq m))] (is (= {} (value))) (a! :a 1) (is (= {:a [1]} (value))) (a! :a 2) (a! :b 3) (is (= {:a [1 2] :b [3]} (value))))) (defn clojureize [m] (plumbing/map-vals #(if (map? %) (into {} %) %) m)) (deftest inc-key!-test (let [m (java.util.HashMap.)] (is (= {} (clojureize m))) (map/inc-key! m :a 1.0) (is (= {:a 1.0} (clojureize m))) (map/inc-key! m :a 2.0) (map/inc-key! m :b 4.0) (is (= {:a 3.0 :b 4.0} (clojureize m))))) (deftest inc-key-in!-test (let [m (java.util.HashMap.)] (is (= {} (clojureize m))) (map/inc-key-in! m [:a :b] 1.0) (is (= {:a {:b 1.0}} (clojureize m))) (map/inc-key-in! m [:a :b] 2.0) (map/inc-key-in! m [:a :c] -1.0) (map/inc-key-in! m [:b] 4.0) (is (= {:a {:b 3.0 :c -1.0} :b 4.0} (clojureize m))))) (deftest collate-test (is (= {:a 3.0 :b 2.0} (clojureize (map/collate [[:a 1] [:b 3.0] [:a 2] [:b -1.0]]))))) (deftest deep-collate-test (is (= {:a {:b 3.0 :c -1.0} :b 4.0} (clojureize (map/deep-collate [[[:a :b] 1.0] [[:a :c] -1.0] [[:a :b] 2.0] [[:b] 4.0]]))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Ops on graphs represented as maps. (deftest topological-sort-test (is (= [:first :second :third :fourth :fifth] (map/topological-sort {:first [:second :fourth] :second [:third] :third [:fourth] :fourth [:fifth] :fifth []}))) (is (= (range 100) (map/topological-sort (into {99 []} (for [i (range 99)] [i [(inc i)]]))))) (is (= (range 99) (map/topological-sort (into {} (for [i (range 99)] [i [(inc i)]]))))) (testing "include-leaves?" (is (= (range 1000) (map/topological-sort (into {} (for [i (range 999)] [i [(inc i)]])) true)))) (testing "exception thrown if cycle" (is (thrown? Exception (map/topological-sort {:first [:second :fourth] :second [:third] :third [:fourth] :fourth [:fifth] :fifth [:first]})))))
null
https://raw.githubusercontent.com/plumatic/plumbing/e75142a40fdf83613d48c390383a7c5813c5149c/test/plumbing/map_test.cljc
clojure
Ops on graphs represented as maps.
(ns plumbing.map-test (:refer-clojure :exclude [flatten]) (:require [plumbing.core :as plumbing] [plumbing.map :as map] [clojure.string :as str] #?(:clj [clojure.test :refer :all] :cljs [cljs.test :refer-macros [is deftest testing use-fixtures]])) #?(:cljs (:require-macros [plumbing.map :as map]))) #?(:cljs (do (def Exception js/Error) (def AssertionError js/Error) (def Throwable js/Error))) Clojure immutable maps (deftest safe-select-keys-test (is (= {:a 1 :c 3} (map/safe-select-keys {:a 1 :b 2 :c 3} [:a :c]))) (is (= {} (map/safe-select-keys {:a 1 :b 2 :c 3} []))) (is (thrown? Throwable (map/safe-select-keys {:a 1 :b 2 :c 3} [:a :b :d])))) (deftest merge-disjoint-test (is (= {:a 1 :b 2 :c 3} (map/merge-disjoint {} {:a 1 :b 2} {:c 3} {}))) (is (thrown? Throwable (map/merge-disjoint {} {:a 1 :b 2} {:b 5 :c 3} {})))) (deftest merge-with-key-test (is (= {"k1" "v1" :k1 :v2} (map/merge-with-key (fn [k v1 v2] (if (string? k) v1 v2)) {"k1" "v1" :k1 :v1} {"k1" "v2" :k1 :v2})))) (deftest flatten-test (is (empty? (map/flatten nil))) (is (empty? (map/flatten {}))) (is (= [[[] :foo]] (map/flatten :foo))) (is (= {[:a] 1 [:b :c] false [:b :d :e] nil [:b :d :f] 4} (into {} (map/flatten {:a 1 :b {:c false :d {:e nil :f 4}}}))))) (deftest unflatten-test (is (= {} (map/unflatten nil))) (is (= :foo (map/unflatten [[[] :foo]]))) (is (= {:a 1 :b {:c 2 :d {:e 3 :f 4}}} (map/unflatten {[:a] 1 [:b :c] 2 [:b :d :e] 3 [:b :d :f] 4})))) (deftest map-leaves-and-path-test (is (empty? (map/map-leaves-and-path (constantly 2) nil))) (is (= {:a {:b "a,b2"} :c {:d "c,d3"} :e "e11"} (map/map-leaves-and-path (fn [ks v] (str (str/join "," (map name ks)) (inc v))) {:a {:b 1} :c {:d 2} :e 10})))) (deftest map-leaves-test (is (empty? (map/map-leaves (constantly 2) nil))) (is (= {:a {:b "1"} :c {:d "2"} :e "10"} (map/map-leaves str {:a {:b 1} :c {:d 2} :e 10}))) (is (= {:a {:b nil} :c {:d nil} :e nil} (map/map-leaves (constantly nil) {:a {:b 1} :c {:d 2} :e 10})))) (deftest keep-leaves-test (is (empty? (map/keep-leaves (constantly 2) {}))) (is (= {:a {:b "1"} :c {:d "2"} :e "10"} (map/keep-leaves str {:a {:b 1} :c {:d 2} :e 10}))) (is (= {:a {:b false} :c {:d false} :e false} (map/keep-leaves (constantly false) {:a {:b 1} :c {:d 2} :e 10}))) (is (= {} (map/keep-leaves (constantly nil) {:a {:b 1} :c {:d 2} :e 10}))) (is (= {:c {:d 10} :e 4} (map/keep-leaves #(when (even? %) %) {:a {:b 5} :c {:d 10 :e {:f 5}} :e 4})))) (def some-var "hey hey") (deftest keyword-map-test (is (= {} (map/keyword-map)) "works with no args") (is (= {:x 42} (let [x (* 2 3 7)] (map/keyword-map x)))) (is (= {:some-var "hey hey" :$ \$} (let [$ \$] (map/keyword-map some-var $))))) Java mutable Maps #?(:clj (do (deftest update-key!-test (let [m (java.util.HashMap. {:a 1 :b 2})] (map/update-key! m :a inc) (is (= {:a 2 :b 2} (into {} m))) (map/update-key! m :c conj "foo") (is (= {:a 2 :b 2 :c ["foo"]} (into {} m))))) (deftest get!-test (let [m (java.util.HashMap.) a! (fn [k v] (.add ^java.util.List (map/get! m k (java.util.ArrayList.)) v)) value (fn [] (plumbing/map-vals seq m))] (is (= {} (value))) (a! :a 1) (is (= {:a [1]} (value))) (a! :a 2) (a! :b 3) (is (= {:a [1 2] :b [3]} (value))))) (defn clojureize [m] (plumbing/map-vals #(if (map? %) (into {} %) %) m)) (deftest inc-key!-test (let [m (java.util.HashMap.)] (is (= {} (clojureize m))) (map/inc-key! m :a 1.0) (is (= {:a 1.0} (clojureize m))) (map/inc-key! m :a 2.0) (map/inc-key! m :b 4.0) (is (= {:a 3.0 :b 4.0} (clojureize m))))) (deftest inc-key-in!-test (let [m (java.util.HashMap.)] (is (= {} (clojureize m))) (map/inc-key-in! m [:a :b] 1.0) (is (= {:a {:b 1.0}} (clojureize m))) (map/inc-key-in! m [:a :b] 2.0) (map/inc-key-in! m [:a :c] -1.0) (map/inc-key-in! m [:b] 4.0) (is (= {:a {:b 3.0 :c -1.0} :b 4.0} (clojureize m))))) (deftest collate-test (is (= {:a 3.0 :b 2.0} (clojureize (map/collate [[:a 1] [:b 3.0] [:a 2] [:b -1.0]]))))) (deftest deep-collate-test (is (= {:a {:b 3.0 :c -1.0} :b 4.0} (clojureize (map/deep-collate [[[:a :b] 1.0] [[:a :c] -1.0] [[:a :b] 2.0] [[:b] 4.0]]))))))) (deftest topological-sort-test (is (= [:first :second :third :fourth :fifth] (map/topological-sort {:first [:second :fourth] :second [:third] :third [:fourth] :fourth [:fifth] :fifth []}))) (is (= (range 100) (map/topological-sort (into {99 []} (for [i (range 99)] [i [(inc i)]]))))) (is (= (range 99) (map/topological-sort (into {} (for [i (range 99)] [i [(inc i)]]))))) (testing "include-leaves?" (is (= (range 1000) (map/topological-sort (into {} (for [i (range 999)] [i [(inc i)]])) true)))) (testing "exception thrown if cycle" (is (thrown? Exception (map/topological-sort {:first [:second :fourth] :second [:third] :third [:fourth] :fourth [:fifth] :fifth [:first]})))))
ae03d13020408b31b04598e586f35907e2820b48056bacc22abe82e09d81bcd0
helium/erlang-libp2p
libp2p_swarm_sup.erl
-module(libp2p_swarm_sup). -behaviour(supervisor). %% API -export([ start_link/1, sup/1, opts/1, name/1, pubkey_bin/1, register_server/1, server/1, register_gossip_group/1, gossip_group/1, register_peerbook/1, peerbook/1 ]). %% Supervisor callbacks -export([init/1]). -define(SUP, swarm_sup). -define(SERVER, swarm_server). -define(GOSSIP_GROUP, swarm_gossip_group). -define(PEERBOOK, swarm_peerbook). -define(ADDRESS, swarm_address). -define(NAME, swarm_name). -define(OPTS, swarm_opts). %%==================================================================== %% API functions %%==================================================================== start_link(Args) -> supervisor:start_link(?MODULE, Args). -spec sup(ets:tab()) -> pid(). sup(TID) -> ets:lookup_element(TID, ?SUP, 2). register_server(TID) -> ets:insert(TID, {?SERVER, self()}). -spec server(ets:tab() | pid()) -> pid(). server(Sup) when is_pid(Sup) -> Children = supervisor:which_children(Sup), {?SERVER, Pid, _, _} = lists:keyfind(?SERVER, 1, Children), Pid; server(TID) -> ets:lookup_element(TID, ?SERVER, 2). -spec pubkey_bin(ets:tab()) -> libp2p_crypto:pubkey_bin(). pubkey_bin(TID) -> ets:lookup_element(TID, ?ADDRESS, 2). -spec name(ets:tab()) -> atom(). name(TID) -> ets:lookup_element(TID, ?NAME, 2). -spec opts(ets:tab()) -> libp2p_config:opts() | any(). opts(TID) -> case ets:lookup(TID, ?OPTS) of [{_, Opts}] -> Opts; [] -> [] end. -spec gossip_group(ets:tab()) -> pid(). gossip_group(TID) -> ets:lookup_element(TID, ?GOSSIP_GROUP, 2). register_gossip_group(TID) -> ets:insert(TID, {?GOSSIP_GROUP, self()}). register_peerbook(TID) -> ets:insert(TID, {?PEERBOOK, self()}). -spec peerbook(ets:tab()) -> pid(). peerbook(TID) -> ets:lookup_element(TID, ?PEERBOOK, 2). %%==================================================================== %% Supervisor callbacks %%==================================================================== init([Name, Opts]) -> inert:start(), TID = ets:new(Name, [public, ordered_set, named_table, {read_concurrency, true}]), ets:insert(TID, {?SUP, self()}), ets:insert(TID, {?NAME, Name}), ets:insert(TID, {?OPTS, Opts}), case proplists:get_value(libp2p_peerbook, Opts) of undefined -> true; PeerbookOpts -> case proplists:get_value(force_network_id, PeerbookOpts) of undefined -> true; NetworkID -> ets:insert(TID, {network_id, NetworkID}) end end, % Get or generate our keys {PubKey, SigFun, ECDHFun} = init_keys(Opts), ets:insert(TID, {?ADDRESS, libp2p_crypto:pubkey_to_bin(PubKey)}), GroupDeletePred = libp2p_config:get_opt(Opts, group_delete_predicate, fun(_) -> false end), SupFlags = {one_for_all, 3, 10}, ChildSpecs = [ {listeners, {libp2p_swarm_listener_sup, start_link, [TID]}, permanent, 10000, supervisor, [libp2p_swarm_listener_sup] }, {sessions, {libp2p_swarm_session_sup, start_link, [TID]}, permanent, 10000, supervisor, [libp2p_swarm_session_sup] }, {transports, {libp2p_swarm_transport_sup, start_link, [TID]}, permanent, 10000, supervisor, [libp2p_swarm_transport_sup] }, {group_mgr, {libp2p_group_mgr , start_link, [TID, GroupDeletePred]}, permanent, 10000, worker, [libp2p_group_mgr] }, {groups, {libp2p_swarm_group_sup, start_link, [TID]}, permanent, 10000, supervisor, [libp2p_swarm_group_sup] }, {?SERVER, {libp2p_swarm_server, start_link, [TID, SigFun, ECDHFun]}, permanent, 10000, worker, [libp2p_swarm_server] }, {?GOSSIP_GROUP, {libp2p_group_gossip_sup, start_link, [TID]}, permanent, 10000, supervisor, [libp2p_group_gossip_sup] }, {?PEERBOOK, {libp2p_peerbook, start_link, [TID, SigFun]}, permanent, 10000, supervisor, [libp2p_peerbook] }, {libp2p_swarm_auxiliary_sup, {libp2p_swarm_auxiliary_sup, start_link, [[TID, Opts]]}, permanent, 10000, supervisor, [libp2p_swarm_auxiliary_sup] } ], {ok, {SupFlags, ChildSpecs}}. %%==================================================================== Internal functions %%==================================================================== -spec init_keys(libp2p_swarm:swarm_opts()) -> {libp2p_crypto:pubkey(), libp2p_crypto:sig_fun(), libp2p_crypto:ecdh_fun()}. init_keys(Opts) -> case libp2p_config:get_opt(Opts, key, false) of false -> #{secret := PrivKey, public := PubKey} = libp2p_crypto:generate_keys(ecc_compact), {PubKey, libp2p_crypto:mk_sig_fun(PrivKey), libp2p_crypto:mk_ecdh_fun(PrivKey)}; {PubKey, SigFun, ECDHFun} -> {PubKey, SigFun, ECDHFun} end.
null
https://raw.githubusercontent.com/helium/erlang-libp2p/91872365acada482c2b9636a3d503ce5facab238/src/libp2p_swarm_sup.erl
erlang
API Supervisor callbacks ==================================================================== API functions ==================================================================== ==================================================================== Supervisor callbacks ==================================================================== Get or generate our keys ==================================================================== ====================================================================
-module(libp2p_swarm_sup). -behaviour(supervisor). -export([ start_link/1, sup/1, opts/1, name/1, pubkey_bin/1, register_server/1, server/1, register_gossip_group/1, gossip_group/1, register_peerbook/1, peerbook/1 ]). -export([init/1]). -define(SUP, swarm_sup). -define(SERVER, swarm_server). -define(GOSSIP_GROUP, swarm_gossip_group). -define(PEERBOOK, swarm_peerbook). -define(ADDRESS, swarm_address). -define(NAME, swarm_name). -define(OPTS, swarm_opts). start_link(Args) -> supervisor:start_link(?MODULE, Args). -spec sup(ets:tab()) -> pid(). sup(TID) -> ets:lookup_element(TID, ?SUP, 2). register_server(TID) -> ets:insert(TID, {?SERVER, self()}). -spec server(ets:tab() | pid()) -> pid(). server(Sup) when is_pid(Sup) -> Children = supervisor:which_children(Sup), {?SERVER, Pid, _, _} = lists:keyfind(?SERVER, 1, Children), Pid; server(TID) -> ets:lookup_element(TID, ?SERVER, 2). -spec pubkey_bin(ets:tab()) -> libp2p_crypto:pubkey_bin(). pubkey_bin(TID) -> ets:lookup_element(TID, ?ADDRESS, 2). -spec name(ets:tab()) -> atom(). name(TID) -> ets:lookup_element(TID, ?NAME, 2). -spec opts(ets:tab()) -> libp2p_config:opts() | any(). opts(TID) -> case ets:lookup(TID, ?OPTS) of [{_, Opts}] -> Opts; [] -> [] end. -spec gossip_group(ets:tab()) -> pid(). gossip_group(TID) -> ets:lookup_element(TID, ?GOSSIP_GROUP, 2). register_gossip_group(TID) -> ets:insert(TID, {?GOSSIP_GROUP, self()}). register_peerbook(TID) -> ets:insert(TID, {?PEERBOOK, self()}). -spec peerbook(ets:tab()) -> pid(). peerbook(TID) -> ets:lookup_element(TID, ?PEERBOOK, 2). init([Name, Opts]) -> inert:start(), TID = ets:new(Name, [public, ordered_set, named_table, {read_concurrency, true}]), ets:insert(TID, {?SUP, self()}), ets:insert(TID, {?NAME, Name}), ets:insert(TID, {?OPTS, Opts}), case proplists:get_value(libp2p_peerbook, Opts) of undefined -> true; PeerbookOpts -> case proplists:get_value(force_network_id, PeerbookOpts) of undefined -> true; NetworkID -> ets:insert(TID, {network_id, NetworkID}) end end, {PubKey, SigFun, ECDHFun} = init_keys(Opts), ets:insert(TID, {?ADDRESS, libp2p_crypto:pubkey_to_bin(PubKey)}), GroupDeletePred = libp2p_config:get_opt(Opts, group_delete_predicate, fun(_) -> false end), SupFlags = {one_for_all, 3, 10}, ChildSpecs = [ {listeners, {libp2p_swarm_listener_sup, start_link, [TID]}, permanent, 10000, supervisor, [libp2p_swarm_listener_sup] }, {sessions, {libp2p_swarm_session_sup, start_link, [TID]}, permanent, 10000, supervisor, [libp2p_swarm_session_sup] }, {transports, {libp2p_swarm_transport_sup, start_link, [TID]}, permanent, 10000, supervisor, [libp2p_swarm_transport_sup] }, {group_mgr, {libp2p_group_mgr , start_link, [TID, GroupDeletePred]}, permanent, 10000, worker, [libp2p_group_mgr] }, {groups, {libp2p_swarm_group_sup, start_link, [TID]}, permanent, 10000, supervisor, [libp2p_swarm_group_sup] }, {?SERVER, {libp2p_swarm_server, start_link, [TID, SigFun, ECDHFun]}, permanent, 10000, worker, [libp2p_swarm_server] }, {?GOSSIP_GROUP, {libp2p_group_gossip_sup, start_link, [TID]}, permanent, 10000, supervisor, [libp2p_group_gossip_sup] }, {?PEERBOOK, {libp2p_peerbook, start_link, [TID, SigFun]}, permanent, 10000, supervisor, [libp2p_peerbook] }, {libp2p_swarm_auxiliary_sup, {libp2p_swarm_auxiliary_sup, start_link, [[TID, Opts]]}, permanent, 10000, supervisor, [libp2p_swarm_auxiliary_sup] } ], {ok, {SupFlags, ChildSpecs}}. Internal functions -spec init_keys(libp2p_swarm:swarm_opts()) -> {libp2p_crypto:pubkey(), libp2p_crypto:sig_fun(), libp2p_crypto:ecdh_fun()}. init_keys(Opts) -> case libp2p_config:get_opt(Opts, key, false) of false -> #{secret := PrivKey, public := PubKey} = libp2p_crypto:generate_keys(ecc_compact), {PubKey, libp2p_crypto:mk_sig_fun(PrivKey), libp2p_crypto:mk_ecdh_fun(PrivKey)}; {PubKey, SigFun, ECDHFun} -> {PubKey, SigFun, ECDHFun} end.
e7e862abe031e013222511e060ab4e5d7c63aa6f8793869f508ad1c72e29568d
fp-works/2019-winter-Haskell-school
AParserSpec.hs
module ScrabbleSpec where import AParser import Control.Applicative import Test.Hspec main :: IO () main = hspec $ do describe "instance Functor Parser" $ do it "should map posInt parser" $ runParser ((+ 2) <$> posInt) "10x" `shouldBe` Just (12, "x") describe "abParser" $ do it "should fail if first char is not a" $ runParser abParser "bcd" `shouldBe` Nothing it "should fail if second char is not b" $ runParser abParser "acde" `shouldBe` Nothing it "should succeed if string starts with ab" $ runParser abParser "abcd" `shouldBe` Just (('a', 'b'), "cd") describe "abParser_" $ do it "should return ()" $ runParser abParser_ "abcd" `shouldBe` Just ((), "cd") describe "intPair" $ do it "should parse two int" $ runParser intPair "12 34 56" `shouldBe` Just ([12, 34], " 56") describe "instance Alternative Parser" $ do it "should use first parser" $ runParser (char '1' *> char '2' <|> char '1') "123" `shouldBe` Just ('2', "3") it "should use second parser if first fails" $ runParser (char '1' *> char '2' <|> char '1') "134" `shouldBe` Just ('1', "34") describe "intOrUppercase" $ do it "should fail if lowercase" $ runParser intOrUppercase "abc" `shouldBe` Nothing it "should parse int" $ runParser intOrUppercase "123ABC" `shouldBe` Just ((), "ABC") it "should parse uppercase" $ runParser intOrUppercase "AB123" `shouldBe` Just ((), "B123")
null
https://raw.githubusercontent.com/fp-works/2019-winter-Haskell-school/823b67f019b9e7bc0d3be36711c0cc7da4eba7d2/cis194/week10/daniel-mc/AParserSpec.hs
haskell
module ScrabbleSpec where import AParser import Control.Applicative import Test.Hspec main :: IO () main = hspec $ do describe "instance Functor Parser" $ do it "should map posInt parser" $ runParser ((+ 2) <$> posInt) "10x" `shouldBe` Just (12, "x") describe "abParser" $ do it "should fail if first char is not a" $ runParser abParser "bcd" `shouldBe` Nothing it "should fail if second char is not b" $ runParser abParser "acde" `shouldBe` Nothing it "should succeed if string starts with ab" $ runParser abParser "abcd" `shouldBe` Just (('a', 'b'), "cd") describe "abParser_" $ do it "should return ()" $ runParser abParser_ "abcd" `shouldBe` Just ((), "cd") describe "intPair" $ do it "should parse two int" $ runParser intPair "12 34 56" `shouldBe` Just ([12, 34], " 56") describe "instance Alternative Parser" $ do it "should use first parser" $ runParser (char '1' *> char '2' <|> char '1') "123" `shouldBe` Just ('2', "3") it "should use second parser if first fails" $ runParser (char '1' *> char '2' <|> char '1') "134" `shouldBe` Just ('1', "34") describe "intOrUppercase" $ do it "should fail if lowercase" $ runParser intOrUppercase "abc" `shouldBe` Nothing it "should parse int" $ runParser intOrUppercase "123ABC" `shouldBe` Just ((), "ABC") it "should parse uppercase" $ runParser intOrUppercase "AB123" `shouldBe` Just ((), "B123")
b71d0daed9a6e4a12270cd5d7a68416d7a478686db1766e1888764905753a35e
donatello/minio-hs-archived
ByteString.hs
# LANGUAGE FlexibleInstances # module Network.Minio.Data.ByteString ( stripBS , UriEncodable(..) ) where import qualified Data.ByteString as B import qualified Data.ByteString.Builder as BB import qualified Data.ByteString.Char8 as BC8 import qualified Data.ByteString.Lazy as LB import Data.Char (isSpace, toUpper) import qualified Data.Text as T import Numeric (showHex) import Lib.Prelude stripBS :: ByteString -> ByteString stripBS = BC8.dropWhile isSpace . fst . BC8.spanEnd isSpace class UriEncodable s where uriEncode :: Bool -> s -> ByteString instance UriEncodable [Char] where uriEncode encodeSlash payload = LB.toStrict $ BB.toLazyByteString $ mconcat $ map (flip uriEncodeChar encodeSlash) payload instance UriEncodable ByteString where assumes that is passed ASCII encoded strings . uriEncode encodeSlash bs = uriEncode encodeSlash $ BC8.unpack bs instance UriEncodable Text where uriEncode encodeSlash txt = uriEncode encodeSlash $ T.unpack txt -- | URI encode a char according to AWS S3 signing rules - see UriEncode ( ) at -- -v4-header-based-auth.html uriEncodeChar :: Char -> Bool -> BB.Builder uriEncodeChar '/' True = BB.byteString "%2F" uriEncodeChar '/' False = BB.char7 '/' uriEncodeChar ch _ | (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9') || (ch == '_') || (ch == '-') || (ch == '.') || (ch == '~') = BB.char7 ch | otherwise = mconcat $ map f $ B.unpack $ encodeUtf8 $ T.singleton ch where f :: Word8 -> BB.Builder f n = BB.char7 '%' <> BB.string7 hexStr where hexStr = map toUpper $ showHex q $ showHex r "" (q, r) = divMod (fromIntegral n) (16::Word8)
null
https://raw.githubusercontent.com/donatello/minio-hs-archived/c808dc1be2a5b15c2c714c0052f1d6a7bc98a809/src/Network/Minio/Data/ByteString.hs
haskell
| URI encode a char according to AWS S3 signing rules - see -v4-header-based-auth.html
# LANGUAGE FlexibleInstances # module Network.Minio.Data.ByteString ( stripBS , UriEncodable(..) ) where import qualified Data.ByteString as B import qualified Data.ByteString.Builder as BB import qualified Data.ByteString.Char8 as BC8 import qualified Data.ByteString.Lazy as LB import Data.Char (isSpace, toUpper) import qualified Data.Text as T import Numeric (showHex) import Lib.Prelude stripBS :: ByteString -> ByteString stripBS = BC8.dropWhile isSpace . fst . BC8.spanEnd isSpace class UriEncodable s where uriEncode :: Bool -> s -> ByteString instance UriEncodable [Char] where uriEncode encodeSlash payload = LB.toStrict $ BB.toLazyByteString $ mconcat $ map (flip uriEncodeChar encodeSlash) payload instance UriEncodable ByteString where assumes that is passed ASCII encoded strings . uriEncode encodeSlash bs = uriEncode encodeSlash $ BC8.unpack bs instance UriEncodable Text where uriEncode encodeSlash txt = uriEncode encodeSlash $ T.unpack txt UriEncode ( ) at uriEncodeChar :: Char -> Bool -> BB.Builder uriEncodeChar '/' True = BB.byteString "%2F" uriEncodeChar '/' False = BB.char7 '/' uriEncodeChar ch _ | (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9') || (ch == '_') || (ch == '-') || (ch == '.') || (ch == '~') = BB.char7 ch | otherwise = mconcat $ map f $ B.unpack $ encodeUtf8 $ T.singleton ch where f :: Word8 -> BB.Builder f n = BB.char7 '%' <> BB.string7 hexStr where hexStr = map toUpper $ showHex q $ showHex r "" (q, r) = divMod (fromIntegral n) (16::Word8)
f2548d20d126c3c46f87231132638035492e3c39929efc3e29a83f5f2a98febc
gstew5/cs4100-public
exp.mli
type id = string type unop = UNot type binop = | BPlus | BMinus | BTimes | BDiv (* arithmetic operators *) | BAnd (* boolean operators *) | BLt | BIntEq (* comparisons *) type exp = | EInt of int | EFloat of float | EBool of bool | EUnop of unop * exp | EBinop of binop * exp * exp | EVar of id | ELet of id * exp * exp
null
https://raw.githubusercontent.com/gstew5/cs4100-public/53c99e3e87331aa5dfa9161ca350a8e23acee739/tyckeck-example/exp.mli
ocaml
arithmetic operators boolean operators comparisons
type id = string type unop = UNot type binop = type exp = | EInt of int | EFloat of float | EBool of bool | EUnop of unop * exp | EBinop of binop * exp * exp | EVar of id | ELet of id * exp * exp
6a791c67738977ce7a1490bc2ff94152f2b901c6aa877fa17fbc13e2382faa09
EgorDm/fp-pacman
Base.hs
module Game.Rules.Base ( module Game.Rules.Rules, module Game.Rules.BaseRules ) where import Game.Rules.Rules import Game.Rules.BaseRules
null
https://raw.githubusercontent.com/EgorDm/fp-pacman/19781c92c97641b0a01b8f1554f50f19ff6d3bf4/src/Game/Rules/Base.hs
haskell
module Game.Rules.Base ( module Game.Rules.Rules, module Game.Rules.BaseRules ) where import Game.Rules.Rules import Game.Rules.BaseRules
79708d07ed8127770861f05bae70883e118302d6ac30c002a10337f2db24507b
Armael/conch
common.ml
let die ~where fmt = Format.kasprintf (fun s -> Format.fprintf Format.err_formatter "ERR (%s): %s\n" where s; exit 1 ) fmt type ident = string module IdentMap : Map.S with type key := ident = Map.Make(String) module IdentSet : Set.S with type elt := ident = Set.Make(String) type const = | C8 of int | C16 of int type comparison = | Lt | Gt | Eq | Neq type binary_op = | Oadd | Osub | Odiv | Omul | Oand | Oor | Oxor | Ocmp of comparison type external_function = | EF_putchar | EF_malloc | EF_out | EF_in8 | EF_in16 let bytes_of_const = function | C8 x -> [x] | C16 x -> [(x lsr 8) land 0xff; x land 0xff] let string_of_op = function | Oadd -> "+" | Osub -> "-" | Odiv -> "/" | Omul -> "*" | Oand -> "and" | Oor -> "or" | Oxor -> "xor" | Ocmp Lt -> "<" | Ocmp Gt -> ">" | Ocmp Eq -> "=" | Ocmp Neq -> "!=" let string_of_builtin = function | EF_putchar -> "putchar" | EF_malloc -> "malloc" | EF_out -> "out" | EF_in8 -> "in8" | EF_in16 -> "in16" let string_of_const = function | C8 x -> string_of_int x | C16 x -> "#" ^ string_of_int x
null
https://raw.githubusercontent.com/Armael/conch/8a72f98a8d29cb8f678a69db95d5b68964304053/lib/common.ml
ocaml
let die ~where fmt = Format.kasprintf (fun s -> Format.fprintf Format.err_formatter "ERR (%s): %s\n" where s; exit 1 ) fmt type ident = string module IdentMap : Map.S with type key := ident = Map.Make(String) module IdentSet : Set.S with type elt := ident = Set.Make(String) type const = | C8 of int | C16 of int type comparison = | Lt | Gt | Eq | Neq type binary_op = | Oadd | Osub | Odiv | Omul | Oand | Oor | Oxor | Ocmp of comparison type external_function = | EF_putchar | EF_malloc | EF_out | EF_in8 | EF_in16 let bytes_of_const = function | C8 x -> [x] | C16 x -> [(x lsr 8) land 0xff; x land 0xff] let string_of_op = function | Oadd -> "+" | Osub -> "-" | Odiv -> "/" | Omul -> "*" | Oand -> "and" | Oor -> "or" | Oxor -> "xor" | Ocmp Lt -> "<" | Ocmp Gt -> ">" | Ocmp Eq -> "=" | Ocmp Neq -> "!=" let string_of_builtin = function | EF_putchar -> "putchar" | EF_malloc -> "malloc" | EF_out -> "out" | EF_in8 -> "in8" | EF_in16 -> "in16" let string_of_const = function | C8 x -> string_of_int x | C16 x -> "#" ^ string_of_int x
02d16303d1ef4cc676fa248ea34d86b1a5730a9bf9fae2647125630ff94aa12b
softwarelanguageslab/maf
R5RS_various_grid-1.scm
; Changes: * removed : 1 * added : 0 * swaps : 0 * negated predicates : 1 ; * swapped branches: 0 ; * calls to id fun: 0 (letrec ((make-grid (lambda (start dims) (let ((v (make-vector (car dims) start))) (if (not (null? (cdr dims))) (letrec ((loop (lambda (i) (if (>= i (car dims)) #t (begin (vector-set! v i (make-grid start (cdr dims))) (loop (+ i 1))))))) (loop 0)) #t) v))) (grid-ref (lambda (g n) (if (null? (cdr n)) (vector-ref g (car n)) (grid-ref (vector-ref g (car n)) (cdr n))))) (grid-set! (lambda (g v n) (if (null? (cdr n)) (vector-set! g (car n) v) (grid-set! (vector-ref g (car n)) v (cdr n))))) (t (make-grid 0 (__toplevel_cons 4 (__toplevel_cons 5 (__toplevel_cons 6 ()))))) (u (make-grid #f (__toplevel_cons 2 (__toplevel_cons 2 ()))))) (if (<change> (equal? (grid-ref t (__toplevel_cons 2 (__toplevel_cons 2 (__toplevel_cons 3 ())))) 0) (not (equal? (grid-ref t (__toplevel_cons 2 (__toplevel_cons 2 (__toplevel_cons 3 ())))) 0))) (if (begin (grid-set! t 24 (__toplevel_cons 2 (__toplevel_cons 2 (__toplevel_cons 3 ())))) (equal? (grid-ref t (__toplevel_cons 2 (__toplevel_cons 2 (__toplevel_cons 3 ())))) 24)) (if (equal? (grid-ref t (__toplevel_cons 1 (__toplevel_cons 0 ()))) (make-vector 6 0)) (begin (<change> (grid-set! t #t (__toplevel_cons 1 (__toplevel_cons 0 ()))) ()) (equal? (grid-ref t (__toplevel_cons 1 (__toplevel_cons 0 ()))) #t)) #f) #f) #f))
null
https://raw.githubusercontent.com/softwarelanguageslab/maf/11acedf56b9bf0c8e55ddb6aea754b6766d8bb40/test/changes/scheme/generated/R5RS_various_grid-1.scm
scheme
Changes: * swapped branches: 0 * calls to id fun: 0
* removed : 1 * added : 0 * swaps : 0 * negated predicates : 1 (letrec ((make-grid (lambda (start dims) (let ((v (make-vector (car dims) start))) (if (not (null? (cdr dims))) (letrec ((loop (lambda (i) (if (>= i (car dims)) #t (begin (vector-set! v i (make-grid start (cdr dims))) (loop (+ i 1))))))) (loop 0)) #t) v))) (grid-ref (lambda (g n) (if (null? (cdr n)) (vector-ref g (car n)) (grid-ref (vector-ref g (car n)) (cdr n))))) (grid-set! (lambda (g v n) (if (null? (cdr n)) (vector-set! g (car n) v) (grid-set! (vector-ref g (car n)) v (cdr n))))) (t (make-grid 0 (__toplevel_cons 4 (__toplevel_cons 5 (__toplevel_cons 6 ()))))) (u (make-grid #f (__toplevel_cons 2 (__toplevel_cons 2 ()))))) (if (<change> (equal? (grid-ref t (__toplevel_cons 2 (__toplevel_cons 2 (__toplevel_cons 3 ())))) 0) (not (equal? (grid-ref t (__toplevel_cons 2 (__toplevel_cons 2 (__toplevel_cons 3 ())))) 0))) (if (begin (grid-set! t 24 (__toplevel_cons 2 (__toplevel_cons 2 (__toplevel_cons 3 ())))) (equal? (grid-ref t (__toplevel_cons 2 (__toplevel_cons 2 (__toplevel_cons 3 ())))) 24)) (if (equal? (grid-ref t (__toplevel_cons 1 (__toplevel_cons 0 ()))) (make-vector 6 0)) (begin (<change> (grid-set! t #t (__toplevel_cons 1 (__toplevel_cons 0 ()))) ()) (equal? (grid-ref t (__toplevel_cons 1 (__toplevel_cons 0 ()))) #t)) #f) #f) #f))