_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 |
|---|---|---|---|---|---|---|---|---|
d6813df901384a4b58eb66cbcda1b7122d66883611484b4d1e2e59f9fe7f6ede | fredlund/McErlang | mce_mon_wrap.erl | 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 the copyright holders 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 HOLDERS AND 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.
@author
2006 - 2009
%% @doc
@private
-module(mce_mon_wrap).
-export([init/1,stateChange/3,monitorType/0]).
-behaviour(mce_behav_monitor).
init({F,InitState}) ->
{ok,{F,InitState}}.
stateChange(Arg1,{F,State},Arg3) ->
case F(Arg1,State,Arg3) of
{ok,NewState} ->
{ok,{F,NewState}};
Other ->
Other
end.
monitorType() ->
safety.
| null | https://raw.githubusercontent.com/fredlund/McErlang/25b38a38a729fdb3c3d2afb9be016bbb14237792/monitors/src/mce_mon_wrap.erl | erlang | 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 the copyright holders 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
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS
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.
@doc | Copyright ( c ) 2009 ,
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
BE LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR
@author
2006 - 2009
@private
-module(mce_mon_wrap).
-export([init/1,stateChange/3,monitorType/0]).
-behaviour(mce_behav_monitor).
init({F,InitState}) ->
{ok,{F,InitState}}.
stateChange(Arg1,{F,State},Arg3) ->
case F(Arg1,State,Arg3) of
{ok,NewState} ->
{ok,{F,NewState}};
Other ->
Other
end.
monitorType() ->
safety.
|
0893657198953bf74c914e51f43d9c7ae4ce3a0725df65decab68b5b16482d61 | turtl/api | admin.lisp | (in-package :turtl)
(defparameter *admin-page*
(file-contents (concatenate 'string (namestring *root*) "views/admin.html"))
"Holds the admin page.")
(route (:get "/admin") (req res)
"Get the admin page, populated with our data."
( setf * admin - page * ( file - contents ( concatenate ' string ( namestring * root * ) " views / admin.html " ) ) )
(alet* ((admin-stats (get-admin-stats))
(admin-log #())
(html (populate-stats *admin-page* admin-stats))
(html (populate-log html admin-log)))
(send-response res :body html)))
| null | https://raw.githubusercontent.com/turtl/api/20ab4cc91128921300913b885eb1e201a5e0fc3f/controllers/admin.lisp | lisp | (in-package :turtl)
(defparameter *admin-page*
(file-contents (concatenate 'string (namestring *root*) "views/admin.html"))
"Holds the admin page.")
(route (:get "/admin") (req res)
"Get the admin page, populated with our data."
( setf * admin - page * ( file - contents ( concatenate ' string ( namestring * root * ) " views / admin.html " ) ) )
(alet* ((admin-stats (get-admin-stats))
(admin-log #())
(html (populate-stats *admin-page* admin-stats))
(html (populate-log html admin-log)))
(send-response res :body html)))
| |
63653e0cd84d752e743c2f9794abffd39765db403ac881134c9be245875d5975 | tochicool/bitcoin-dca | API.hs | module BitcoinDCA.Explorer.Esplora.API
( module BitcoinDCA.Explorer.Esplora.API.Types,
module BitcoinDCA.Explorer.Esplora.API.Client,
)
where
import BitcoinDCA.Explorer.Esplora.API.Client
import BitcoinDCA.Explorer.Esplora.API.Types
| null | https://raw.githubusercontent.com/tochicool/bitcoin-dca/642016f54595194127fcbd24ff11e0d7b358b011/src/BitcoinDCA/Explorer/Esplora/API.hs | haskell | module BitcoinDCA.Explorer.Esplora.API
( module BitcoinDCA.Explorer.Esplora.API.Types,
module BitcoinDCA.Explorer.Esplora.API.Client,
)
where
import BitcoinDCA.Explorer.Esplora.API.Client
import BitcoinDCA.Explorer.Esplora.API.Types
| |
bf0f6973d4cf539c74573907ba55539f426632b2797fe56a93a757f89bddafa9 | ha-mo-we/Racer | tracer-interface.lisp | -*- Mode : Lisp ; Syntax : Ansi - Common - Lisp ; Package : TOOLS ; Base : 10 -*-
Copyright ( c ) 1998 - 2014 ,
, , .
;;; All rights reserved.
Racer is distributed under the following BSD 3 - clause license
;;; 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 Racer 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
VOLKER HAARSLEV , RALF MOELLER , NOR 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 :tools)
(defparameter *tracer-tools-menu* nil)
(defvar *tracer-restore-lisp-functions* nil)
(defun tracer-make-point (h &optional v)
(list h v))
(defun tracer-point-v (p)
(declare (ignore p)))
(defclass tracer-simple-view
()
((nick-name :reader view-nick-name :initarg :view-nick-name))
)
(defmethod view-nick-name ((view t))
)
(defmethod tracer-view-container ((view tracer-simple-view))
view)
(defclass tracer-menu-item
(tracer-simple-view capi:menu-item)
())
(defmethod tracer-menu-item-enable ((item tracer-menu-item))
)
(defmethod tracer-menu-item-disable ((item tracer-menu-item))
)
(defmethod tracer-menu-item-enabled-p ((menu tracer-menu-item))
)
(defclass tracer-dialog
(tracer-simple-view capi:interface)
())
(defmethod tracer-view-named (nickname (dialog tracer-dialog))
(third (capi:layout-description (capi:pane-layout dialog))))
(defmethod tracer-window-select ((w tracer-dialog))
;(capi:raise-interface w)
)
(defmethod get-selected-items ((dialog tracer-dialog))
(capi:choice-selected-items (third (capi:layout-description (capi:pane-layout dialog)))))
(defclass tracer-menu
(tracer-simple-view capi:menu)
())
(defmethod tracer-find-menu-item ((menu tracer-menu) title)
)
(defmethod tracer-menu-items ((menu tracer-menu)
&optional (menu-item-class 'tracer-menu-element))
(capi:menu-items menu))
(defclass tracer-pull-down-menu
(tracer-menu)
())
(defun tracer-insert-menu-item-after-menu-item (menu
reference-menu-item
inserted-menu-item)
(declare (ignore menu reference-menu-item inserted-menu-item)))
(defclass tracer-table-dialog-item
()
())
(defclass tracer-sequence-dialog-item
(tracer-simple-view tracer-table-dialog-item capi:list-panel)
()
(:default-initargs
:vertical-scroll t
:items-count-function 'length
:items-get-function (lambda (list n)
(nth n list))
:items-map-function (lambda (items fn collect-results-p)
(if collect-results-p
(mapcar fn items)
(loop for item in items
do (funcall fn item))))
))
(defmethod tracer-view-container ((view tracer-sequence-dialog-item))
(capi:element-interface view))
(defmethod get-selected-items ((table tracer-sequence-dialog-item))
(capi:choice-selected-items table))
(defmethod tracer-cell-select ((item tracer-sequence-dialog-item) h &optional v)
(setf (capi:choice-selected-item item) h))
(defmethod tracer-scroll-to-cell ((item tracer-sequence-dialog-item) h &optional v)
(tracer-cell-select item h v)
( capi : scroll item ' : vertical ' : page 5 )
)
(defmethod tracer-cell-deselect ((item tracer-sequence-dialog-item) h &optional v)
)
(defmethod tracer-selected-cells ((item tracer-sequence-dialog-item))
(capi:choice-selected-items item))
(defmethod tracer-redraw-cell ((item tracer-sequence-dialog-item) h &optional v)
(capi:redisplay-collection-item item h))
(defmethod tracer-table-sequence ((item tracer-sequence-dialog-item))
(capi:collection-items item))
(defmethod tracer-index-to-cell ((item tracer-sequence-dialog-item) index)
(elt (capi:collection-items item) index))
(defmethod tracer-set-table-sequence ((table tracer-sequence-dialog-item) seq)
(setf (capi:collection-items table) seq))
(defmethod tracer-set-table-sequence ((dialog tracer-dialog) seq)
(setf (capi:collection-items (third (capi:layout-description (capi:pane-layout dialog))))
seq))
(defmethod tracer-update-table-sequence ((table tracer-sequence-dialog-item)
changed-entry
new-seq)
(let* ((seq (capi:collection-items table))
(pre-cdr (loop for last-cdr = nil then list
for list on seq
for elem = (first list)
when (eq elem changed-entry)
do (return last-cdr))))
(if pre-cdr
(progn
(setf (cdr pre-cdr) new-seq)
(setf (capi:collection-items table) seq)
needed to get old CAPI caches invalidated
)
(setf (capi:collection-items table) new-seq))))
(defun tracer-command-key-p ()
)
(defun tracer-option-key-p ()
)
(defun tracer-control-key-p ()
)
(defun tracer-double-click-p ()
)
(defun tracer-ed-beep ()
#+:macosx (cocoa:ns-beep)
#+:win32 (win32:message-beep "1"))
(defun tracer-get-string-from-user (message
&key
initial-string
(window-title ""))
(declare (ignore window-title))
(capi:prompt-for-string message :initial-value initial-string))
(defun tracer-edit-definition (name)
(loop for symbol in (find-all-symbols name)
until (editor:find-source-command nil symbol t)))
(defun tracer-find-window (title &optional class)
(declare (ignore title class)))
(defclass tracer-buffered-output-stream-mixin
()
())
(defmethod tracer-stream-force-output ((stream tracer-buffered-output-stream-mixin))
)
| null | https://raw.githubusercontent.com/ha-mo-we/Racer/d690841d10015c7a75b1ded393fcf0a33092c4de/source/tracer-interface.lisp | lisp | Syntax : Ansi - Common - Lisp ; Package : TOOLS ; Base : 10 -*-
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.
to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES, LOSS OF USE, DATA, OR PROFITS, OR BUSINESS
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.
(capi:raise-interface w) |
Copyright ( c ) 1998 - 2014 ,
, , .
Racer is distributed under the following BSD 3 - clause license
Neither the name Racer nor the names of its contributors may be used
CONTRIBUTORS " AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING ,
VOLKER HAARSLEV , RALF MOELLER , NOR FOR ANY
DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL
INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER
(in-package :tools)
(defparameter *tracer-tools-menu* nil)
(defvar *tracer-restore-lisp-functions* nil)
(defun tracer-make-point (h &optional v)
(list h v))
(defun tracer-point-v (p)
(declare (ignore p)))
(defclass tracer-simple-view
()
((nick-name :reader view-nick-name :initarg :view-nick-name))
)
(defmethod view-nick-name ((view t))
)
(defmethod tracer-view-container ((view tracer-simple-view))
view)
(defclass tracer-menu-item
(tracer-simple-view capi:menu-item)
())
(defmethod tracer-menu-item-enable ((item tracer-menu-item))
)
(defmethod tracer-menu-item-disable ((item tracer-menu-item))
)
(defmethod tracer-menu-item-enabled-p ((menu tracer-menu-item))
)
(defclass tracer-dialog
(tracer-simple-view capi:interface)
())
(defmethod tracer-view-named (nickname (dialog tracer-dialog))
(third (capi:layout-description (capi:pane-layout dialog))))
(defmethod tracer-window-select ((w tracer-dialog))
)
(defmethod get-selected-items ((dialog tracer-dialog))
(capi:choice-selected-items (third (capi:layout-description (capi:pane-layout dialog)))))
(defclass tracer-menu
(tracer-simple-view capi:menu)
())
(defmethod tracer-find-menu-item ((menu tracer-menu) title)
)
(defmethod tracer-menu-items ((menu tracer-menu)
&optional (menu-item-class 'tracer-menu-element))
(capi:menu-items menu))
(defclass tracer-pull-down-menu
(tracer-menu)
())
(defun tracer-insert-menu-item-after-menu-item (menu
reference-menu-item
inserted-menu-item)
(declare (ignore menu reference-menu-item inserted-menu-item)))
(defclass tracer-table-dialog-item
()
())
(defclass tracer-sequence-dialog-item
(tracer-simple-view tracer-table-dialog-item capi:list-panel)
()
(:default-initargs
:vertical-scroll t
:items-count-function 'length
:items-get-function (lambda (list n)
(nth n list))
:items-map-function (lambda (items fn collect-results-p)
(if collect-results-p
(mapcar fn items)
(loop for item in items
do (funcall fn item))))
))
(defmethod tracer-view-container ((view tracer-sequence-dialog-item))
(capi:element-interface view))
(defmethod get-selected-items ((table tracer-sequence-dialog-item))
(capi:choice-selected-items table))
(defmethod tracer-cell-select ((item tracer-sequence-dialog-item) h &optional v)
(setf (capi:choice-selected-item item) h))
(defmethod tracer-scroll-to-cell ((item tracer-sequence-dialog-item) h &optional v)
(tracer-cell-select item h v)
( capi : scroll item ' : vertical ' : page 5 )
)
(defmethod tracer-cell-deselect ((item tracer-sequence-dialog-item) h &optional v)
)
(defmethod tracer-selected-cells ((item tracer-sequence-dialog-item))
(capi:choice-selected-items item))
(defmethod tracer-redraw-cell ((item tracer-sequence-dialog-item) h &optional v)
(capi:redisplay-collection-item item h))
(defmethod tracer-table-sequence ((item tracer-sequence-dialog-item))
(capi:collection-items item))
(defmethod tracer-index-to-cell ((item tracer-sequence-dialog-item) index)
(elt (capi:collection-items item) index))
(defmethod tracer-set-table-sequence ((table tracer-sequence-dialog-item) seq)
(setf (capi:collection-items table) seq))
(defmethod tracer-set-table-sequence ((dialog tracer-dialog) seq)
(setf (capi:collection-items (third (capi:layout-description (capi:pane-layout dialog))))
seq))
(defmethod tracer-update-table-sequence ((table tracer-sequence-dialog-item)
changed-entry
new-seq)
(let* ((seq (capi:collection-items table))
(pre-cdr (loop for last-cdr = nil then list
for list on seq
for elem = (first list)
when (eq elem changed-entry)
do (return last-cdr))))
(if pre-cdr
(progn
(setf (cdr pre-cdr) new-seq)
(setf (capi:collection-items table) seq)
needed to get old CAPI caches invalidated
)
(setf (capi:collection-items table) new-seq))))
(defun tracer-command-key-p ()
)
(defun tracer-option-key-p ()
)
(defun tracer-control-key-p ()
)
(defun tracer-double-click-p ()
)
(defun tracer-ed-beep ()
#+:macosx (cocoa:ns-beep)
#+:win32 (win32:message-beep "1"))
(defun tracer-get-string-from-user (message
&key
initial-string
(window-title ""))
(declare (ignore window-title))
(capi:prompt-for-string message :initial-value initial-string))
(defun tracer-edit-definition (name)
(loop for symbol in (find-all-symbols name)
until (editor:find-source-command nil symbol t)))
(defun tracer-find-window (title &optional class)
(declare (ignore title class)))
(defclass tracer-buffered-output-stream-mixin
()
())
(defmethod tracer-stream-force-output ((stream tracer-buffered-output-stream-mixin))
)
|
88a15a280bdf18e3b74add0404e936e62dfc19337685108d39a63b7f0748bb28 | henry-hz/erlang-trader | oms_sup.erl |
-module(oms_sup).
-behaviour(supervisor).
%% API
-export([start_link/0]).
%% Supervisor callbacks
-export([init/1]).
%% Helper macro for declaring children of supervisor
-define(CHILD(I, Type), {I, {I, start_link, []}, permanent, 5000, Type, [I]}).
%% ===================================================================
%% API functions
%% ===================================================================
start_link() ->
supervisor:start_link({local, ?MODULE}, ?MODULE, []).
%% ===================================================================
%% Supervisor callbacks
%% ===================================================================
init([]) ->
{ok, { {one_for_one, 5, 10}, []} }.
| null | https://raw.githubusercontent.com/henry-hz/erlang-trader/5ec6a20902a894e0c29712f199bb6be3fad68a3b/oms/src/oms_sup.erl | erlang | API
Supervisor callbacks
Helper macro for declaring children of supervisor
===================================================================
API functions
===================================================================
===================================================================
Supervisor callbacks
=================================================================== |
-module(oms_sup).
-behaviour(supervisor).
-export([start_link/0]).
-export([init/1]).
-define(CHILD(I, Type), {I, {I, start_link, []}, permanent, 5000, Type, [I]}).
start_link() ->
supervisor:start_link({local, ?MODULE}, ?MODULE, []).
init([]) ->
{ok, { {one_for_one, 5, 10}, []} }.
|
bddc4aa842dc29a7df36f9940628fa6cff2873201abb48c37881a626f4573bef | glguy/advent2019 | Day13.hs | {-# Language ImportQualifiedPost #-}
|
Module : Main
Description : Day 13 solution
Copyright : ( c ) , 2019
License : ISC
Maintainer :
< >
Module : Main
Description : Day 13 solution
Copyright : (c) Eric Mertens, 2019
License : ISC
Maintainer :
<>
-}
module Main (main) where
import Advent (getIntcodeInput)
import Data.Map (Map)
import Data.Map qualified as Map
import Intcode (Effect(..), new, run, set)
main :: IO ()
main =
do mach <- new <$> getIntcodeInput 13
print (part1 (run mach ))
print (part2 0 0 0 (run (set 0 2 mach)))
part1 :: Effect -> Int
part1 = Map.size . Map.filter (2==) . getImage Map.empty
getImage :: Map (Int, Int) Int -> Effect -> Map (Int, Int) Int
getImage m (Output x (Output y (Output t e))) = getImage (Map.insert (x,y) t m) e
getImage m _ = m
part2 :: Int -> Int -> Int -> Effect -> Int
part2 ball paddle score effect =
case effect of
Output x (Output y (Output t effect'))
| t == 4 -> part2 x paddle score effect'
| t == 3 -> part2 ball x score effect'
| x == (-1), y == 0 -> part2 ball paddle t effect'
| otherwise -> part2 ball paddle score effect'
Input f -> part2 ball paddle score (f (signum (ball - paddle)))
_ -> score
| null | https://raw.githubusercontent.com/glguy/advent2019/13f3be89535c12cbae761a6d4165432a2459ccd5/execs/Day13.hs | haskell | # Language ImportQualifiedPost # | |
Module : Main
Description : Day 13 solution
Copyright : ( c ) , 2019
License : ISC
Maintainer :
< >
Module : Main
Description : Day 13 solution
Copyright : (c) Eric Mertens, 2019
License : ISC
Maintainer :
<>
-}
module Main (main) where
import Advent (getIntcodeInput)
import Data.Map (Map)
import Data.Map qualified as Map
import Intcode (Effect(..), new, run, set)
main :: IO ()
main =
do mach <- new <$> getIntcodeInput 13
print (part1 (run mach ))
print (part2 0 0 0 (run (set 0 2 mach)))
part1 :: Effect -> Int
part1 = Map.size . Map.filter (2==) . getImage Map.empty
getImage :: Map (Int, Int) Int -> Effect -> Map (Int, Int) Int
getImage m (Output x (Output y (Output t e))) = getImage (Map.insert (x,y) t m) e
getImage m _ = m
part2 :: Int -> Int -> Int -> Effect -> Int
part2 ball paddle score effect =
case effect of
Output x (Output y (Output t effect'))
| t == 4 -> part2 x paddle score effect'
| t == 3 -> part2 ball x score effect'
| x == (-1), y == 0 -> part2 ball paddle t effect'
| otherwise -> part2 ball paddle score effect'
Input f -> part2 ball paddle score (f (signum (ball - paddle)))
_ -> score
|
6251990777831869531c6afb04015d1988ff5e3f13cc7864610b521d75b3808a | hpyhacking/openpoker | deal_cards.erl | -module(deal_cards).
-behaviour(op_exch_mod).
-export([start/2, dispatch/2]).
-include("openpoker.hrl").
start([N, Type], Ctx) ->
start([N, Type, 0], Ctx);
start([0, private, _T], Ctx) -> {stop, Ctx};
start([N, private, T], Ctx = #texas{b = B, seats = S}) ->
Seats = seat:lookup(?PS_STANDING, S, B),
start([N-1, private], draw(Seats, Ctx#texas{deal_timeout = T}));
start([0, shared, _T], Ctx) -> {stop, Ctx};
start([N, shared, T], Ctx) ->
start([N-1, shared, T], draw_shared(Ctx#texas{deal_timeout = T})).
dispatch(_R, _Ctx) ->
ok.
%%%
%%% private
%%%
draw([], Ctx) -> Ctx;
draw([H = #seat{hand = Hand, pid = PId, sn = SN, process = P, identity = Identity}|T], Ctx = #texas{gid = Id, deck = D, seats = S}) ->
{Card, ND} = deck:draw(D),
NS = H#seat{ hand = hand:add(Hand, Card) },
player:notify(P, #notify_private{game = Id, player = PId, sn = SN, card = Card}),
game:broadcast(#notify_draw{game = Id, player = PId, sn = SN, card = 0}, Ctx, [Identity]),
timer:sleep(Ctx#texas.deal_timeout),
draw(T, Ctx#texas{ seats = seat:set(NS, S), deck = ND}).
draw_shared(Ctx = #texas{gid = Id, deck = D, board = B}) ->
{Card, ND} = deck:draw(D),
game:broadcast(#notify_shared{ game = Id, card = Card }, Ctx),
timer:sleep(Ctx#texas.deal_timeout),
Ctx#texas{ board = [Card|B], deck = ND }.
| null | https://raw.githubusercontent.com/hpyhacking/openpoker/643193c94f34096cdcfcd610bdb1f18e7bf1e45e/src/mods/deal_cards.erl | erlang |
private
| -module(deal_cards).
-behaviour(op_exch_mod).
-export([start/2, dispatch/2]).
-include("openpoker.hrl").
start([N, Type], Ctx) ->
start([N, Type, 0], Ctx);
start([0, private, _T], Ctx) -> {stop, Ctx};
start([N, private, T], Ctx = #texas{b = B, seats = S}) ->
Seats = seat:lookup(?PS_STANDING, S, B),
start([N-1, private], draw(Seats, Ctx#texas{deal_timeout = T}));
start([0, shared, _T], Ctx) -> {stop, Ctx};
start([N, shared, T], Ctx) ->
start([N-1, shared, T], draw_shared(Ctx#texas{deal_timeout = T})).
dispatch(_R, _Ctx) ->
ok.
draw([], Ctx) -> Ctx;
draw([H = #seat{hand = Hand, pid = PId, sn = SN, process = P, identity = Identity}|T], Ctx = #texas{gid = Id, deck = D, seats = S}) ->
{Card, ND} = deck:draw(D),
NS = H#seat{ hand = hand:add(Hand, Card) },
player:notify(P, #notify_private{game = Id, player = PId, sn = SN, card = Card}),
game:broadcast(#notify_draw{game = Id, player = PId, sn = SN, card = 0}, Ctx, [Identity]),
timer:sleep(Ctx#texas.deal_timeout),
draw(T, Ctx#texas{ seats = seat:set(NS, S), deck = ND}).
draw_shared(Ctx = #texas{gid = Id, deck = D, board = B}) ->
{Card, ND} = deck:draw(D),
game:broadcast(#notify_shared{ game = Id, card = Card }, Ctx),
timer:sleep(Ctx#texas.deal_timeout),
Ctx#texas{ board = [Card|B], deck = ND }.
|
21b273460e5be05c407a3c73ad10431ded85c479e3e73d04fc7a2b57bcd9b018 | NorfairKing/smos | Import.hs | module Smos.Web.Server.Handler.Import (module X) where
import Data.Text as X (Text)
import Data.Time as X
import Data.Word as X
import Path as X
import Smos.Client as X hiding (Fragment, Unique)
import Smos.Web.Server.Constants as X
import Smos.Web.Server.Foundation as X
import Smos.Web.Server.SmosSession as X
import Smos.Web.Server.Static as X
import Smos.Web.Server.TUI as X
import Smos.Web.Server.Widget as X
import Text.Printf as X
import Text.Time.Pretty as X
import Yesod as X hiding (Header, addHeader, parseTime)
import Yesod.Auth as X
import Yesod.WebSockets as X
| null | https://raw.githubusercontent.com/NorfairKing/smos/82707699b446bc431f5233e5dc18c7ec3dd679fd/smos-web-server/src/Smos/Web/Server/Handler/Import.hs | haskell | module Smos.Web.Server.Handler.Import (module X) where
import Data.Text as X (Text)
import Data.Time as X
import Data.Word as X
import Path as X
import Smos.Client as X hiding (Fragment, Unique)
import Smos.Web.Server.Constants as X
import Smos.Web.Server.Foundation as X
import Smos.Web.Server.SmosSession as X
import Smos.Web.Server.Static as X
import Smos.Web.Server.TUI as X
import Smos.Web.Server.Widget as X
import Text.Printf as X
import Text.Time.Pretty as X
import Yesod as X hiding (Header, addHeader, parseTime)
import Yesod.Auth as X
import Yesod.WebSockets as X
| |
b03e74f3a86624d1ee918032e3b6a82beb71e56e9e88114a3225b5a346768777 | binaryage/chromex | chrome_storage_area.cljs | (ns chromex.protocols.chrome-storage-area
(:refer-clojure :exclude [get remove set]))
(defprotocol IChromeStorageArea
"a wrapper for #type-StorageArea"
(get-native-storage-area [this])
(get [this] [this keys])
(get-bytes-in-use [this] [this keys])
(set [this items])
(remove [this keys])
(clear [this]))
| null | https://raw.githubusercontent.com/binaryage/chromex/33834ba5dd4f4238a3c51f99caa0416f30c308c5/src/lib/chromex/protocols/chrome_storage_area.cljs | clojure | (ns chromex.protocols.chrome-storage-area
(:refer-clojure :exclude [get remove set]))
(defprotocol IChromeStorageArea
"a wrapper for #type-StorageArea"
(get-native-storage-area [this])
(get [this] [this keys])
(get-bytes-in-use [this] [this keys])
(set [this items])
(remove [this keys])
(clear [this]))
| |
e287e7450ffc27065b1a35648b3db7fff79163fbaebbc1dd3e3cd329a5dccb5a | luxingwen/emqx_persistence_plugin | emqx_persistence_plugin_sup.erl | %%%-------------------------------------------------------------------
%% @doc emqx_persistence_plugin top level supervisor.
%% @end
%%%-------------------------------------------------------------------
-module(emqx_persistence_plugin_sup).
-include("emqx_persistence_plugin.hrl").
-define(ECPOOL_WORKER, emqx_persistence_plugin_cli).
-behaviour(supervisor).
-export([start_link/0]).
-export([init/1]).
start_link() ->
supervisor:start_link({local, ?MODULE}, ?MODULE, []).
init(_) ->
case application:get_env(?APP, enable_persistence) of
{ok, true} ->
{ok, ServerCfg} = application:get_env(?APP, server),
PoolSpec = ecpool:pool_spec(?APP, ?APP, ?ECPOOL_WORKER, ServerCfg),
{ok, {{one_for_one, 10, 100}, [PoolSpec]}};
_ ->
{ok, {{one_for_one, 10, 100}, []}}
end.
| null | https://raw.githubusercontent.com/luxingwen/emqx_persistence_plugin/5e27679c56578ba2f2f787549910702bcbc31dee/src/emqx_persistence_plugin_sup.erl | erlang | -------------------------------------------------------------------
@doc emqx_persistence_plugin top level supervisor.
@end
------------------------------------------------------------------- |
-module(emqx_persistence_plugin_sup).
-include("emqx_persistence_plugin.hrl").
-define(ECPOOL_WORKER, emqx_persistence_plugin_cli).
-behaviour(supervisor).
-export([start_link/0]).
-export([init/1]).
start_link() ->
supervisor:start_link({local, ?MODULE}, ?MODULE, []).
init(_) ->
case application:get_env(?APP, enable_persistence) of
{ok, true} ->
{ok, ServerCfg} = application:get_env(?APP, server),
PoolSpec = ecpool:pool_spec(?APP, ?APP, ?ECPOOL_WORKER, ServerCfg),
{ok, {{one_for_one, 10, 100}, [PoolSpec]}};
_ ->
{ok, {{one_for_one, 10, 100}, []}}
end.
|
f68de6e97cdbdbef761345f2cb42dd3a89152a685a6602854ef11e5b50ab3060 | manuel-serrano/bigloo | rgctree.scm | ;*=====================================================================*/
* serrano / prgm / project / bigloo / / runtime / Rgc / rgctree.scm * /
;* ------------------------------------------------------------- */
* Author : * /
* Creation : We d Sep 9 17:51:46 1998 * /
* Last change : Sun Aug 25 09:11:40 2019 ( serrano ) * /
;* ------------------------------------------------------------- */
;* The construction of the tree from the list representation. */
;*=====================================================================*/
;*---------------------------------------------------------------------*/
;* The module */
;*---------------------------------------------------------------------*/
(module __rgc_tree
(import __rgc_set
__rgc_config
__error)
(use __type
__bigloo
__tvector
__structure
__param
__object
__thread
__bexit
__bignum
__rgc
__bit
__r4_numbers_6_5
__r4_numbers_6_5_fixnum
__r4_numbers_6_5_flonum
__r4_numbers_6_5_flonum_dtoa
__r4_characters_6_6
__r4_equivalence_6_2
__r4_booleans_6_1
__r4_symbols_6_4
__r4_strings_6_7
__r4_pairs_and_lists_6_3
__r4_input_6_10_2
__r4_control_features_6_9
__r5_control_features_6_4
__r4_ports_6_10_1
__r4_output_6_10_3
__r4_vectors_6_8)
(include "Rgc/rgc-node.sch")
(export (regular-tree->node tree)
(print-node node)
(print-followpos followpos)
(reset-tree!)))
;*---------------------------------------------------------------------*/
;* regular-tree->node ... */
;*---------------------------------------------------------------------*/
(define (regular-tree->node tree)
the first think to compute is the number of position in that tree .
;; that number is simply the number of char we find.
(set! *position-number* (regular-tree-position-number tree))
;; we initialize the position vector
(init-positions!)
;; we initialize the vector that will holds the followpos
(init-followpos!)
(let ((tree (tree->node tree)))
;; we are done with the tree we return the tree and the followpos
(values tree *followpos* *positions* *submatches*)))
;*---------------------------------------------------------------------*/
;* *position-number* & *positions* ... */
;* ------------------------------------------------------------- */
;* The number of positions the compiled tree may holds and a vector */
;* making the association between the position and the character at */
;* that position. */
;*---------------------------------------------------------------------*/
(define *position-number* #unspecified)
(define *positions* #unspecified)
(define *submatches* #unspecified)
;*---------------------------------------------------------------------*/
;* regular-tree-position-number ... */
;*---------------------------------------------------------------------*/
(define (regular-tree-position-number tree)
(let loop ((tree tree)
(num 0))
(cond
((null? tree)
num)
((pair? (car tree))
(loop (cdr tree) (loop (car tree) num)))
((fixnum? (car tree))
(loop (cdr tree) (+fx num 1)))
(else
(loop (cdr tree) num)))))
;*---------------------------------------------------------------------*/
;* init-positions! ... */
;*---------------------------------------------------------------------*/
(define (init-positions!)
(set! *current-position* -1)
(set! *positions* (make-vector *position-number* -1))
(set! *submatches* (make-vector *position-number* '())))
;*---------------------------------------------------------------------*/
;* *current-position* ... */
;*---------------------------------------------------------------------*/
(define *current-position* #unspecified)
;*---------------------------------------------------------------------*/
;* get-new-position ... */
;*---------------------------------------------------------------------*/
(define (get-new-position char)
(set! *current-position* (+fx *current-position* 1))
(vector-set! *positions* *current-position* char)
*current-position*)
;*---------------------------------------------------------------------*/
;* tree->node ... */
;*---------------------------------------------------------------------*/
(define (tree->node tree)
(cond
((fixnum? tree)
(integer->node tree))
((eq? tree 'epsilon)
(epsilon->node tree))
((not (pair? tree))
(error #f "RGC:Illegal tree" tree))
(else
(case (car tree)
((or) (or->node (cdr tree)))
((sequence) (sequence->node (cdr tree)))
((*) (*->node (cadr tree)))
((submatch) (submatch->node (cdr tree)))
((bol) (bol->node (cdr tree)))
(else (error #f "RGC:Unknown function" tree))))))
;*---------------------------------------------------------------------*/
;* integer->node ... */
;*---------------------------------------------------------------------*/
(define (integer->node tree)
(let ((position (get-new-position tree))
(firstpos (make-rgcset *position-number*))
(lastpos (make-rgcset *position-number*)))
(rgcset-add! firstpos position)
(rgcset-add! lastpos position)
(node firstpos lastpos #f)))
;*---------------------------------------------------------------------*/
;* epsilon->node ... */
;*---------------------------------------------------------------------*/
(define (epsilon->node tree)
(let ((firstpos (make-rgcset *position-number*))
(lastpos (make-rgcset *position-number*)))
(node firstpos lastpos #t)))
;*---------------------------------------------------------------------*/
;* binary->node ... */
;*---------------------------------------------------------------------*/
(define (binary->node bin-op ts)
(if (null? ts)
(tree->node 'epsilon)
(let loop ((ts ts))
(if (null? (cdr ts))
(tree->node (car ts))
(bin-op (tree->node (car ts)) (loop (cdr ts)))))))
;*---------------------------------------------------------------------*/
;* or->node ... */
;*---------------------------------------------------------------------*/
(define (or->node ts)
(define (or2->node n1 n2)
(let* ((firstpos (rgcset-or (node-firstpos n1) (node-firstpos n2)))
(lastpos (rgcset-or (node-lastpos n1) (node-lastpos n2)))
(nullable? (or (node-nullable? n1) (node-nullable? n2))))
(node firstpos lastpos nullable?)))
(binary->node or2->node ts))
;*---------------------------------------------------------------------*/
;* sequence->node ... */
;*---------------------------------------------------------------------*/
(define (sequence->node ts)
(define (sequence2->node n1 n2)
(let ((firstpos (if (node-nullable? n1)
(rgcset-or (node-firstpos n1) (node-firstpos n2))
(node-firstpos n1)))
(lastpos (if (node-nullable? n2)
(rgcset-or (node-lastpos n1) (node-lastpos n2))
(node-lastpos n2)))
(nullable? (and (node-nullable? n2) (node-nullable? n1))))
;; we adjust the followpos
(for-each-rgcset (lambda (i)
(followpos-add! i (node-firstpos n2)))
(node-lastpos n1))
;; we are node done
(node firstpos lastpos nullable?)))
(binary->node sequence2->node ts))
;*---------------------------------------------------------------------*/
;* *->node ... */
;*---------------------------------------------------------------------*/
(define (*->node expr)
(let* ((sub-node (tree->node expr))
(firstpos (node-firstpos sub-node))
(lastpos (node-lastpos sub-node)))
;; we set the followpos property
(for-each-rgcset (lambda (i)
(followpos-add! i firstpos))
lastpos)
;; and we return the new node
(node firstpos lastpos #t)))
;*---------------------------------------------------------------------*/
;* submatch->node ... */
;*---------------------------------------------------------------------*/
(define (submatch->node expr)
(match-case expr
((?rule ?submatch ?expr)
(let* ((node (tree->node expr))
(firstpos (node-firstpos node))
(lastpos (node-lastpos node))
(nullable? (node-nullable? node)))
* ( print " submatch : " rule " " submatch " " expr ) * /
;* (print "firstpos: " (rgcset->list firstpos)) */
* ( print " lastpos : " ( rgcset->list lastpos ) ) * /
;* (print "nullable: " nullable?) */
(for-each-rgcset (lambda (i)
(submatch-start-add! i nullable? rule submatch))
firstpos)
(for-each-rgcset (lambda (i)
(submatch-stop-add! i rule submatch))
lastpos)
node))
(else
(error #f "RGC:Unknown function" expr))))
;*---------------------------------------------------------------------*/
;* bol->node ... */
;*---------------------------------------------------------------------*/
(define (bol->node expr)
(let* ((node (tree->node expr))
(firstpos (node-firstpos node))
(lastpos (node-lastpos node)))
(node firstpos lastpos #f)))
;*---------------------------------------------------------------------*/
;* init-followpos! ... */
;*---------------------------------------------------------------------*/
(define (init-followpos!)
(let ((followpos (make-vector *position-number*)))
(let loop ((i 0))
(if (=fx *position-number* i)
(set! *followpos* followpos)
(begin
(vector-set! followpos i (make-rgcset *position-number*))
(loop (+fx i 1)))))))
;*---------------------------------------------------------------------*/
;* *followpos* ... */
;*---------------------------------------------------------------------*/
(define *followpos* #unspecified)
;*---------------------------------------------------------------------*/
;* followpos-add! ... */
;*---------------------------------------------------------------------*/
(define (followpos-add! i rgcset)
(rgcset-or! (vector-ref *followpos* i) rgcset))
;*---------------------------------------------------------------------*/
* submatch - start - add ! ... * /
;*---------------------------------------------------------------------*/
(define (submatch-start-add! position nullable? match submatch)
(let ((cell (vector-ref *submatches* position)))
(if (not (pair? cell))
(vector-set! *submatches*
position
(cons (list (list nullable? match submatch)) '()))
(set-car! cell (cons (list nullable? match submatch) (car cell))))))
;*---------------------------------------------------------------------*/
* submatch - stop - add ! ... * /
;*---------------------------------------------------------------------*/
(define (submatch-stop-add! position match submatch)
(let ((cell (vector-ref *submatches* position)))
(if (not (pair? cell))
(vector-set! *submatches*
position
(cons '() (list (cons match submatch))))
(set-cdr! cell (cons (cons match submatch) (cdr cell))))))
;*---------------------------------------------------------------------*/
;* reset-tree! ... */
;*---------------------------------------------------------------------*/
(define (reset-tree!)
(set! *followpos* #unspecified)
(set! *positions* #unspecified)
(set! *submatches* #unspecified)
(set! *position-number* #unspecified))
;*---------------------------------------------------------------------*/
;* print-followpos ... */
;*---------------------------------------------------------------------*/
(define (print-followpos fp)
(print "========= FOLLOWPOS ==============================")
(print "number of pos: " (vector-length fp))
'(let ((sz (vector-length fp)))
(let loop ((i 0))
(if (<fx i sz)
(begin
(print i ": " (reverse (rgcset->list (vector-ref fp i))))
(loop (+fx i 1))))))
(print "=================================================="))
;*---------------------------------------------------------------------*/
;* print-node ... */
;*---------------------------------------------------------------------*/
(define (print-node node)
'blop)
| null | https://raw.githubusercontent.com/manuel-serrano/bigloo/eb650ed4429155f795a32465e009706bbf1b8d74/runtime/Rgc/rgctree.scm | scheme | *=====================================================================*/
* ------------------------------------------------------------- */
* ------------------------------------------------------------- */
* The construction of the tree from the list representation. */
*=====================================================================*/
*---------------------------------------------------------------------*/
* The module */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* regular-tree->node ... */
*---------------------------------------------------------------------*/
that number is simply the number of char we find.
we initialize the position vector
we initialize the vector that will holds the followpos
we are done with the tree we return the tree and the followpos
*---------------------------------------------------------------------*/
* *position-number* & *positions* ... */
* ------------------------------------------------------------- */
* The number of positions the compiled tree may holds and a vector */
* making the association between the position and the character at */
* that position. */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* regular-tree-position-number ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* init-positions! ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* *current-position* ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* get-new-position ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* tree->node ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* integer->node ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* epsilon->node ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* binary->node ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* or->node ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* sequence->node ... */
*---------------------------------------------------------------------*/
we adjust the followpos
we are node done
*---------------------------------------------------------------------*/
* *->node ... */
*---------------------------------------------------------------------*/
we set the followpos property
and we return the new node
*---------------------------------------------------------------------*/
* submatch->node ... */
*---------------------------------------------------------------------*/
* (print "firstpos: " (rgcset->list firstpos)) */
* (print "nullable: " nullable?) */
*---------------------------------------------------------------------*/
* bol->node ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* init-followpos! ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* *followpos* ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* followpos-add! ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* reset-tree! ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* print-followpos ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* print-node ... */
*---------------------------------------------------------------------*/ | * serrano / prgm / project / bigloo / / runtime / Rgc / rgctree.scm * /
* Author : * /
* Creation : We d Sep 9 17:51:46 1998 * /
* Last change : Sun Aug 25 09:11:40 2019 ( serrano ) * /
(module __rgc_tree
(import __rgc_set
__rgc_config
__error)
(use __type
__bigloo
__tvector
__structure
__param
__object
__thread
__bexit
__bignum
__rgc
__bit
__r4_numbers_6_5
__r4_numbers_6_5_fixnum
__r4_numbers_6_5_flonum
__r4_numbers_6_5_flonum_dtoa
__r4_characters_6_6
__r4_equivalence_6_2
__r4_booleans_6_1
__r4_symbols_6_4
__r4_strings_6_7
__r4_pairs_and_lists_6_3
__r4_input_6_10_2
__r4_control_features_6_9
__r5_control_features_6_4
__r4_ports_6_10_1
__r4_output_6_10_3
__r4_vectors_6_8)
(include "Rgc/rgc-node.sch")
(export (regular-tree->node tree)
(print-node node)
(print-followpos followpos)
(reset-tree!)))
(define (regular-tree->node tree)
the first think to compute is the number of position in that tree .
(set! *position-number* (regular-tree-position-number tree))
(init-positions!)
(init-followpos!)
(let ((tree (tree->node tree)))
(values tree *followpos* *positions* *submatches*)))
(define *position-number* #unspecified)
(define *positions* #unspecified)
(define *submatches* #unspecified)
(define (regular-tree-position-number tree)
(let loop ((tree tree)
(num 0))
(cond
((null? tree)
num)
((pair? (car tree))
(loop (cdr tree) (loop (car tree) num)))
((fixnum? (car tree))
(loop (cdr tree) (+fx num 1)))
(else
(loop (cdr tree) num)))))
(define (init-positions!)
(set! *current-position* -1)
(set! *positions* (make-vector *position-number* -1))
(set! *submatches* (make-vector *position-number* '())))
(define *current-position* #unspecified)
(define (get-new-position char)
(set! *current-position* (+fx *current-position* 1))
(vector-set! *positions* *current-position* char)
*current-position*)
(define (tree->node tree)
(cond
((fixnum? tree)
(integer->node tree))
((eq? tree 'epsilon)
(epsilon->node tree))
((not (pair? tree))
(error #f "RGC:Illegal tree" tree))
(else
(case (car tree)
((or) (or->node (cdr tree)))
((sequence) (sequence->node (cdr tree)))
((*) (*->node (cadr tree)))
((submatch) (submatch->node (cdr tree)))
((bol) (bol->node (cdr tree)))
(else (error #f "RGC:Unknown function" tree))))))
(define (integer->node tree)
(let ((position (get-new-position tree))
(firstpos (make-rgcset *position-number*))
(lastpos (make-rgcset *position-number*)))
(rgcset-add! firstpos position)
(rgcset-add! lastpos position)
(node firstpos lastpos #f)))
(define (epsilon->node tree)
(let ((firstpos (make-rgcset *position-number*))
(lastpos (make-rgcset *position-number*)))
(node firstpos lastpos #t)))
(define (binary->node bin-op ts)
(if (null? ts)
(tree->node 'epsilon)
(let loop ((ts ts))
(if (null? (cdr ts))
(tree->node (car ts))
(bin-op (tree->node (car ts)) (loop (cdr ts)))))))
(define (or->node ts)
(define (or2->node n1 n2)
(let* ((firstpos (rgcset-or (node-firstpos n1) (node-firstpos n2)))
(lastpos (rgcset-or (node-lastpos n1) (node-lastpos n2)))
(nullable? (or (node-nullable? n1) (node-nullable? n2))))
(node firstpos lastpos nullable?)))
(binary->node or2->node ts))
(define (sequence->node ts)
(define (sequence2->node n1 n2)
(let ((firstpos (if (node-nullable? n1)
(rgcset-or (node-firstpos n1) (node-firstpos n2))
(node-firstpos n1)))
(lastpos (if (node-nullable? n2)
(rgcset-or (node-lastpos n1) (node-lastpos n2))
(node-lastpos n2)))
(nullable? (and (node-nullable? n2) (node-nullable? n1))))
(for-each-rgcset (lambda (i)
(followpos-add! i (node-firstpos n2)))
(node-lastpos n1))
(node firstpos lastpos nullable?)))
(binary->node sequence2->node ts))
(define (*->node expr)
(let* ((sub-node (tree->node expr))
(firstpos (node-firstpos sub-node))
(lastpos (node-lastpos sub-node)))
(for-each-rgcset (lambda (i)
(followpos-add! i firstpos))
lastpos)
(node firstpos lastpos #t)))
(define (submatch->node expr)
(match-case expr
((?rule ?submatch ?expr)
(let* ((node (tree->node expr))
(firstpos (node-firstpos node))
(lastpos (node-lastpos node))
(nullable? (node-nullable? node)))
* ( print " submatch : " rule " " submatch " " expr ) * /
* ( print " lastpos : " ( rgcset->list lastpos ) ) * /
(for-each-rgcset (lambda (i)
(submatch-start-add! i nullable? rule submatch))
firstpos)
(for-each-rgcset (lambda (i)
(submatch-stop-add! i rule submatch))
lastpos)
node))
(else
(error #f "RGC:Unknown function" expr))))
(define (bol->node expr)
(let* ((node (tree->node expr))
(firstpos (node-firstpos node))
(lastpos (node-lastpos node)))
(node firstpos lastpos #f)))
(define (init-followpos!)
(let ((followpos (make-vector *position-number*)))
(let loop ((i 0))
(if (=fx *position-number* i)
(set! *followpos* followpos)
(begin
(vector-set! followpos i (make-rgcset *position-number*))
(loop (+fx i 1)))))))
(define *followpos* #unspecified)
(define (followpos-add! i rgcset)
(rgcset-or! (vector-ref *followpos* i) rgcset))
* submatch - start - add ! ... * /
(define (submatch-start-add! position nullable? match submatch)
(let ((cell (vector-ref *submatches* position)))
(if (not (pair? cell))
(vector-set! *submatches*
position
(cons (list (list nullable? match submatch)) '()))
(set-car! cell (cons (list nullable? match submatch) (car cell))))))
* submatch - stop - add ! ... * /
(define (submatch-stop-add! position match submatch)
(let ((cell (vector-ref *submatches* position)))
(if (not (pair? cell))
(vector-set! *submatches*
position
(cons '() (list (cons match submatch))))
(set-cdr! cell (cons (cons match submatch) (cdr cell))))))
(define (reset-tree!)
(set! *followpos* #unspecified)
(set! *positions* #unspecified)
(set! *submatches* #unspecified)
(set! *position-number* #unspecified))
(define (print-followpos fp)
(print "========= FOLLOWPOS ==============================")
(print "number of pos: " (vector-length fp))
'(let ((sz (vector-length fp)))
(let loop ((i 0))
(if (<fx i sz)
(begin
(print i ": " (reverse (rgcset->list (vector-ref fp i))))
(loop (+fx i 1))))))
(print "=================================================="))
(define (print-node node)
'blop)
|
26573671aa917b71889e032be5558fdcfb698affcfef83f6005c72cde556155f | hyperfiddle/electric | hfql6.clj | (ns dustin.hfql6
(:require
[clojure.walk :refer [walk prewalk postwalk]]
[contrib.do :refer [via* Do-via *this !]]
[dustin.fiddle :refer :all]
[dustin.hf-nav :refer :all]
[meander.epsilon :as m :refer [match rewrite]]
[minitest :refer [tests]]))
; Simple
(def ast '{(submission needle) {:dustingetz/gender :db/ident}})
(def ast {:dustingetz/gender :db/ident})
(def ast :db/ident)
(def ast '(:db/ident %))
(def ast '(submission needle))
(def ast '(submission needle))
(defn fmap [k v] ; not yet a functor
; apply on the way in
(let [
result (hf-nav k v)
]
; reconstruct on the way out
{k result}))
(comment
{:dustingetz/gender :db/ident}
(-> % :dustingetz/gender :db/ident) := :male
((comp :db/ident :dustingetz/gender) %) := :male
((partial hf-nav :dustingetz/gender) 17592186045440) := ::female
(fmap :dustingetz/gender 17592186045440)
:= #:dustingetz{:gender :dustingetz/female}
(fmap :db/ident (fmap :dustingetz/gender 17592186045440))
:= {:dustingetz/gender {:db/ident :male}}
(fmap :db/ident %)
:= {:db/ident :male}
)
; rewrite :asdf := ((hf-nav :asdf %))
; This is supposed to be a functor?
; What is the Functor type?
; recur with scope?
; Factor out the scope point? Higher order?
(defn apply-scope [sexp scope]
(let [[f & asks] sexp
args (map #(get scope %) asks)]
(cons f args)
#_(clojure.core/apply (clojure.core/resolve f) args)))
(defn hf-pull [pat v scope] ; remove v by put % in scope
#_{:pre [(doto pat (println 'hf-pull v scope))]
:post [(doto % (println 'hf-pull))]}
(match pat
(m/pred keyword? ?k)
{?k (hf-nav ?k v)}
(!xs ...)
{(seq !xs) (apply-scope !xs scope)}
one entry
(let [v (hf-pull ?kf v scope)
scope (merge scope {?kf v})
v (hf-pull ?pat v scope)]
{?k v})
{ & ( m / seqable [ ( ! xs ... ) ? pat ] ) }
;(let [v (apply-scope !xs scope)
; scope (merge scope {f v})
; v (hf-pull ?pat v scope)]
; {(seq !xs) v})
?_ (doto ?_ (println 'unmatched))
))
; defmacro hf-pull?
; how much of this can be a rewrite , known statically?
; The shape actually is static in the cardinality-1 case
; so can we compile to something static
; or does the evaluation depend on the database entity | null | https://raw.githubusercontent.com/hyperfiddle/electric/1c6c3891cbf13123fef8d33e6555d300f0dac134/scratch/dustin/y2020/hfql/hfql6.clj | clojure | Simple
not yet a functor
apply on the way in
reconstruct on the way out
rewrite :asdf := ((hf-nav :asdf %))
This is supposed to be a functor?
What is the Functor type?
recur with scope?
Factor out the scope point? Higher order?
remove v by put % in scope
(let [v (apply-scope !xs scope)
scope (merge scope {f v})
v (hf-pull ?pat v scope)]
{(seq !xs) v})
defmacro hf-pull?
how much of this can be a rewrite , known statically?
The shape actually is static in the cardinality-1 case
so can we compile to something static
or does the evaluation depend on the database entity | (ns dustin.hfql6
(:require
[clojure.walk :refer [walk prewalk postwalk]]
[contrib.do :refer [via* Do-via *this !]]
[dustin.fiddle :refer :all]
[dustin.hf-nav :refer :all]
[meander.epsilon :as m :refer [match rewrite]]
[minitest :refer [tests]]))
(def ast '{(submission needle) {:dustingetz/gender :db/ident}})
(def ast {:dustingetz/gender :db/ident})
(def ast :db/ident)
(def ast '(:db/ident %))
(def ast '(submission needle))
(def ast '(submission needle))
(let [
result (hf-nav k v)
]
{k result}))
(comment
{:dustingetz/gender :db/ident}
(-> % :dustingetz/gender :db/ident) := :male
((comp :db/ident :dustingetz/gender) %) := :male
((partial hf-nav :dustingetz/gender) 17592186045440) := ::female
(fmap :dustingetz/gender 17592186045440)
:= #:dustingetz{:gender :dustingetz/female}
(fmap :db/ident (fmap :dustingetz/gender 17592186045440))
:= {:dustingetz/gender {:db/ident :male}}
(fmap :db/ident %)
:= {:db/ident :male}
)
(defn apply-scope [sexp scope]
(let [[f & asks] sexp
args (map #(get scope %) asks)]
(cons f args)
#_(clojure.core/apply (clojure.core/resolve f) args)))
#_{:pre [(doto pat (println 'hf-pull v scope))]
:post [(doto % (println 'hf-pull))]}
(match pat
(m/pred keyword? ?k)
{?k (hf-nav ?k v)}
(!xs ...)
{(seq !xs) (apply-scope !xs scope)}
one entry
(let [v (hf-pull ?kf v scope)
scope (merge scope {?kf v})
v (hf-pull ?pat v scope)]
{?k v})
{ & ( m / seqable [ ( ! xs ... ) ? pat ] ) }
?_ (doto ?_ (println 'unmatched))
))
|
f4d2ae0f4734390e7c971fc1f8b317e6e4fdc08bd750d45efc1fa8e4992e3d02 | nervous-systems/eulalie | instance_data.cljc | (ns eulalie.instance-data
(:require #?@(:clj
[[clj-time.format :as time.format]
[clj-time.coerce :as time.coerce]]
:cljs
[[cljs-time.format :as time.format]
[cljs-time.coerce :as time.coerce]])
[glossop.core :as g
#? (:clj :refer :cljs :refer-macros) [go-catching <?]]
[#? (:clj clojure.core.async :cljs cljs.core.async) :as async]
[clojure.string :as str]
[eulalie.platform :as platform]
[eulalie.util :as util]
[clojure.set :as set]
[camel-snake-kebab.core :as csk]
[camel-snake-kebab.extras :as csk-extras]))
(defn- parse-json-body [x]
Amazon 's war against Content - Type continues
(if (and x (pos? (count x)) (= (subs x 0 1) "{"))
(csk-extras/transform-keys csk/->kebab-case-keyword (platform/decode-json x))
x))
(defn retrieve!
"(retrieve! [:latest :dynamic :instance-identity :document] {:parse-json true})"
[path &
[{:keys [host parse-json chan close?]
:or {host "169.254.169.254"
close? true}}]]
(let [path (cond-> path (not (coll? path)) vector)
url (str "http://" host ":80/"
(str/join "/"
(map name path)))]
(cond->
(go-catching
(let [{:keys [error body status] :as response}
(<? (platform/http-get! url))]
(cond error error
(= status 200) (cond-> body parse-json parse-json-body)
:else nil)))
chan (async/pipe chan close?))))
#?(:clj (def retrieve!! (comp g/<?! retrieve!)))
(defn metadata!
"(metadata! [:iam :security-credentials])"
[path & [args]]
(retrieve! (flatten (conj [:latest :meta-data] path)) args))
#?(:clj (def metadata!! (comp g/<?! metadata!)))
(defn instance-identity!
"(instance-identity! :document {:parse-json true})"
[path & [args]]
(retrieve!
(flatten (conj [:latest :dynamic :instance-identity] path))
args))
#?(:clj (def instance-identity!! (comp g/<?! instance-identity!)))
(defn identity-key! [k & [args]]
(go-catching
(-> (instance-identity! :document (assoc args :parse-json true))
<?
(get (keyword k)))))
#?(:clj (def identity-key!! (comp g/<?! identity-key!)))
(defn default-iam-role! [& [args]]
(go-catching
(some-> (metadata! [:iam :security-credentials] args) <?
(util/to-first-match "\n") not-empty)))
#?(:clj (def default-iam-role!! (comp g/<?! default-iam-role!)))
(let [seconds-formatter (time.format/formatters :date-time-no-ms)]
(defn from-iso-seconds [x]
(time.coerce/to-long (time.format/parse seconds-formatter x))))
(defn- tidy-iam-creds [{:keys [expiration] :as m}]
(let [m (set/rename-keys m {:access-key-id :access-key
:secret-access-key :secret-key})]
(cond-> m
expiration (assoc :expiration (from-iso-seconds expiration)))))
(defn iam-credentials! [role & [{:keys [chan close?] :or {close? true}}]]
(cond->
(go-catching
(-> (metadata!
[:iam :security-credentials (name role)]
{:parse-json true})
<?
tidy-iam-creds))
chan (async/pipe chan close?)))
#?(:clj (def iam-credentials!! (comp g/<?! iam-credentials!)))
(defn default-iam-credentials! [& [{:keys [chan close?] :or {close? true}}]]
(cond->
(go-catching
(when-let [default-role (<? (default-iam-role!))]
(<? (iam-credentials! default-role))))
chan (async/pipe chan close?)))
#?(:clj (def default-iam-credentials!! (comp g/<?! default-iam-credentials!)))
| null | https://raw.githubusercontent.com/nervous-systems/eulalie/ee435987278f5ed628f576700b716d9d0bc17c61/src/eulalie/instance_data.cljc | clojure | (ns eulalie.instance-data
(:require #?@(:clj
[[clj-time.format :as time.format]
[clj-time.coerce :as time.coerce]]
:cljs
[[cljs-time.format :as time.format]
[cljs-time.coerce :as time.coerce]])
[glossop.core :as g
#? (:clj :refer :cljs :refer-macros) [go-catching <?]]
[#? (:clj clojure.core.async :cljs cljs.core.async) :as async]
[clojure.string :as str]
[eulalie.platform :as platform]
[eulalie.util :as util]
[clojure.set :as set]
[camel-snake-kebab.core :as csk]
[camel-snake-kebab.extras :as csk-extras]))
(defn- parse-json-body [x]
Amazon 's war against Content - Type continues
(if (and x (pos? (count x)) (= (subs x 0 1) "{"))
(csk-extras/transform-keys csk/->kebab-case-keyword (platform/decode-json x))
x))
(defn retrieve!
"(retrieve! [:latest :dynamic :instance-identity :document] {:parse-json true})"
[path &
[{:keys [host parse-json chan close?]
:or {host "169.254.169.254"
close? true}}]]
(let [path (cond-> path (not (coll? path)) vector)
url (str "http://" host ":80/"
(str/join "/"
(map name path)))]
(cond->
(go-catching
(let [{:keys [error body status] :as response}
(<? (platform/http-get! url))]
(cond error error
(= status 200) (cond-> body parse-json parse-json-body)
:else nil)))
chan (async/pipe chan close?))))
#?(:clj (def retrieve!! (comp g/<?! retrieve!)))
(defn metadata!
"(metadata! [:iam :security-credentials])"
[path & [args]]
(retrieve! (flatten (conj [:latest :meta-data] path)) args))
#?(:clj (def metadata!! (comp g/<?! metadata!)))
(defn instance-identity!
"(instance-identity! :document {:parse-json true})"
[path & [args]]
(retrieve!
(flatten (conj [:latest :dynamic :instance-identity] path))
args))
#?(:clj (def instance-identity!! (comp g/<?! instance-identity!)))
(defn identity-key! [k & [args]]
(go-catching
(-> (instance-identity! :document (assoc args :parse-json true))
<?
(get (keyword k)))))
#?(:clj (def identity-key!! (comp g/<?! identity-key!)))
(defn default-iam-role! [& [args]]
(go-catching
(some-> (metadata! [:iam :security-credentials] args) <?
(util/to-first-match "\n") not-empty)))
#?(:clj (def default-iam-role!! (comp g/<?! default-iam-role!)))
(let [seconds-formatter (time.format/formatters :date-time-no-ms)]
(defn from-iso-seconds [x]
(time.coerce/to-long (time.format/parse seconds-formatter x))))
(defn- tidy-iam-creds [{:keys [expiration] :as m}]
(let [m (set/rename-keys m {:access-key-id :access-key
:secret-access-key :secret-key})]
(cond-> m
expiration (assoc :expiration (from-iso-seconds expiration)))))
(defn iam-credentials! [role & [{:keys [chan close?] :or {close? true}}]]
(cond->
(go-catching
(-> (metadata!
[:iam :security-credentials (name role)]
{:parse-json true})
<?
tidy-iam-creds))
chan (async/pipe chan close?)))
#?(:clj (def iam-credentials!! (comp g/<?! iam-credentials!)))
(defn default-iam-credentials! [& [{:keys [chan close?] :or {close? true}}]]
(cond->
(go-catching
(when-let [default-role (<? (default-iam-role!))]
(<? (iam-credentials! default-role))))
chan (async/pipe chan close?)))
#?(:clj (def default-iam-credentials!! (comp g/<?! default-iam-credentials!)))
| |
9b35696b90177f6aaac1d70063ab28b795f2e07f4976a3dee909bd451a338266 | gvannest/piscine_OCaml | ft_countdown.ml | let rec ft_countdown n =
if n <= 0
then
begin
print_int 0;
print_char '\n'
end
else
begin
print_int n;
print_char '\n';
ft_countdown (n - 1)
end
let main () =
ft_countdown 9;
ft_countdown 0;
ft_countdown (-3)
let () = main () | null | https://raw.githubusercontent.com/gvannest/piscine_OCaml/2533c6152cfb46c637d48a6d0718f7c7262b3ba6/d00/ex01/ft_countdown.ml | ocaml | let rec ft_countdown n =
if n <= 0
then
begin
print_int 0;
print_char '\n'
end
else
begin
print_int n;
print_char '\n';
ft_countdown (n - 1)
end
let main () =
ft_countdown 9;
ft_countdown 0;
ft_countdown (-3)
let () = main () | |
5bed8d64c9ef2cac0250f4d4a5f5e40591e2653e267ddeaf1f5e1067f7cf2a4b | xoken/xoken-core | Util.hs | |
Module : Network . . Test . Util
Copyright : Xoken Labs
License : Open BSV License
Stability : experimental
Portability : POSIX
Module : Network.Xoken.Test.Util
Copyright : Xoken Labs
License : Open BSV License
Stability : experimental
Portability : POSIX
-}
module Network.Xoken.Test.Util where
import Data.ByteString (ByteString, pack)
import Data.Time.Clock (UTCTime(..))
import Data.Time.Clock.POSIX (posixSecondsToUTCTime)
import Data.Word (Word32)
import Test.QuickCheck
| Arbitrary strict ' ByteString ' .
arbitraryBS :: Gen ByteString
arbitraryBS = pack <$> arbitrary
| Arbitrary non - empty strict ByteString
arbitraryBS1 :: Gen ByteString
arbitraryBS1 = pack <$> listOf1 arbitrary
| Arbitrary strict ByteString of a given length
arbitraryBSn :: Int -> Gen ByteString
arbitraryBSn n = pack <$> vectorOf n arbitrary
| Arbitrary UTCTime that generates dates after 01 Jan 1970 01:00:00 CET
arbitraryUTCTime :: Gen UTCTime
arbitraryUTCTime = do
w <- arbitrary :: Gen Word32
return $ posixSecondsToUTCTime $ realToFrac w
-- | Generate a Maybe from a Gen a
arbitraryMaybe :: Gen a -> Gen (Maybe a)
arbitraryMaybe g = frequency [(1, return Nothing), (5, Just <$> g)]
| null | https://raw.githubusercontent.com/xoken/xoken-core/34399655febdc8c0940da7983489f0c9d58c35d2/core/src/Network/Xoken/Test/Util.hs | haskell | | Generate a Maybe from a Gen a | |
Module : Network . . Test . Util
Copyright : Xoken Labs
License : Open BSV License
Stability : experimental
Portability : POSIX
Module : Network.Xoken.Test.Util
Copyright : Xoken Labs
License : Open BSV License
Stability : experimental
Portability : POSIX
-}
module Network.Xoken.Test.Util where
import Data.ByteString (ByteString, pack)
import Data.Time.Clock (UTCTime(..))
import Data.Time.Clock.POSIX (posixSecondsToUTCTime)
import Data.Word (Word32)
import Test.QuickCheck
| Arbitrary strict ' ByteString ' .
arbitraryBS :: Gen ByteString
arbitraryBS = pack <$> arbitrary
| Arbitrary non - empty strict ByteString
arbitraryBS1 :: Gen ByteString
arbitraryBS1 = pack <$> listOf1 arbitrary
| Arbitrary strict ByteString of a given length
arbitraryBSn :: Int -> Gen ByteString
arbitraryBSn n = pack <$> vectorOf n arbitrary
| Arbitrary UTCTime that generates dates after 01 Jan 1970 01:00:00 CET
arbitraryUTCTime :: Gen UTCTime
arbitraryUTCTime = do
w <- arbitrary :: Gen Word32
return $ posixSecondsToUTCTime $ realToFrac w
arbitraryMaybe :: Gen a -> Gen (Maybe a)
arbitraryMaybe g = frequency [(1, return Nothing), (5, Just <$> g)]
|
86acfcf2d630a0dfd7db087d20fc2b66e689758d6c921915778a280e279b30c6 | sellout/Kilns | syntax.lisp | (in-package #:kilns)
(defvar *paired-chars*
'((#\( . #\))
(#\[ . #\])
(#\{ . #\})))
(defvar *kilns-readtable* (copy-readtable))
(setf (readtable-case *kilns-readtable*) :invert)
(defvar *reading-name-p* nil
"Indicates whether we are currently reading a message name, and therefore
should treat ?x as a name-variable instead of a process-variable.")
;;; FIXME: this is broken. Use in read-process once it works
(defmacro quote-atom (form)
`(if (listp ',form)
,form
',form))
(defun read-process (type stream char)
(let ((name (let ((*reading-name-p* t)) (read stream t))))
(destructuring-bind (&optional process continuation)
(read-delimited-list (cdr (assoc char *paired-chars*)) stream t)
(if continuation
`(,type (if (listp ',name) ,name ',name)
,process
(if (listp ',continuation) ,continuation ',continuation))
(if process
`(,type (if (listp ',name) ,name ',name) ,process)
`(,type (if (listp ',name) ,name ',name)))))))
(defun variable-reader (stream char)
(declare (ignore char))
(if *reading-name-p*
`(make-instance 'name-variable :name ',(read stream t))
`(make-instance 'process-variable :name ',(read stream t))))
(defun kell-reader (stream char)
(read-process 'kell stream char))
(defun message-reader (stream char)
(read-process 'message stream char))
(set-macro-character #\? #'variable-reader nil *kilns-readtable*)
(set-macro-character #\[ #'kell-reader nil *kilns-readtable*)
(set-macro-character #\] (get-macro-character #\) nil) nil *kilns-readtable*)
(set-macro-character #\{ #'message-reader nil *kilns-readtable*)
(set-macro-character #\} (get-macro-character #\) nil) nil *kilns-readtable*)
(defun par (&rest processes)
(apply #'parallel-composition processes))
The syntax of the Kell calculus is given in Figure 1 . It is parameterized by
the pattern language used to define patterns ξ in triggers ξ ␣ P.
;;; P ::= 0 | x | ξ␣P | νa.P | a␣P␣.P | P|P | a[P].P a∈N, x∈V
;;; Names and Variables
;;;
;;; We assume an infinite set N of names, and an infinite set V of process
;;; variables. We assume that N ∩ V = ∅. We let a, b, n, m and their decorated
variants range over N ; and p , q , x , y range over V. The set L of identifiers
;;; is defined as L = N ∪ V.
;;;
;;; Processes
;;;
Terms in the Kell calculus grammar are called processes .
We note K L the set of Kell calculus processes with patterns in pattern
;;; language L. In most cases the pattern language used is obvious from the
;;; context, and we simply write K. We let P, Q, R, S, T and their decorated
variants range over processes . We call message a process of the form a ␣ P ␣ .Q.
;;; We let M, N and their decorated variants range over messages and parallel
composition of messages . We call a process of the form a[P].Q.
The name a in a a[P ] .Q is called the name of the . In a of
;;; the form a[… | aj[Pj] | …] we call subkells the processes aj[Pj].
;;; Abbreviations and conventions
;;;
;;; We abbreviate a␣P␣ a message of the form a␣P␣.0. We abbreviate a a message
of the form a ␣ 0 ␣ . We abbreviate a[P ] a of the form a[P].0 . In a term
;;; νa.P, the scope extends as far to the right as possible. In a term ξ␣P, the
;;; scope of ␣ extends as far to the left and to the right as possible. Thus,
;;; a␣c␣ | b[y] ␣ P | Q stands for (a␣c␣ | b[y])␣(P | Q). We use standard
;;; abbreviations from the the π-calculus: νa1…aq.P for νa1.…νaq.P, or νã.P if
;;; ã = (a1…aq). By convention, if the name vector ã is null, then νã.P =∆ P.
;;; Also, we abuse notation and note ã the set {a1, …, an}, where ã is the
;;; vector a1…an. We note ∏j∈J Pj, J = {1, …, n} the parallel composition
;;; (P1 | (… (Pn−1 | Pn) …)). By convention, if J = ∅, then ∏j∈J Pj =∆ 0.
;;;
;;; For the definition of the operational semantics of the calculus, we use
;;; additional terms called annotated messages. Annotated messages comprise:
;;; – Local messages: a local message is a term of the form a␣P␣. We write Mm
;;; for a multiset of local messages.
– Up messages : an up message is a term of the form a ␣ P ␣ ↑b . We write for
;;; a multiset of up messages.
– Down messages : a down message is a term of the form a ␣ P ␣ ↓b . We write
;;; for a multiset of down messages.
– messages : a message is a term of the form a[P ] . We write Mk for
a multiset of messages .
;;;
;;; We write M for a multiset of annotated messages. Some of these terms are not
processes , namely those in and ; they are only used for matching
;;; purposes. We often write these multisets as parallel compositions of
;;; annotated messages.
;;;
Let Mm be a multiset of local messages . We write Mm↑b for the multiset of up
;;; messages {m↑b | m ∈ Mm}, and Mm↓b for the multiset of down messages
;;; {m↓b | m ∈ Mm}.
;;;
;;; Let M = {mjnj | j ∈ J} be an arbitrary multiset (where the multiplicity of
element mj is nj ) . We note M.supp = { mj | j ∈ J } the support set of M , i.e.
;;; the smallest set to which elements of M belong.
| null | https://raw.githubusercontent.com/sellout/Kilns/467ba599f457812daea41a7c56f74a1ec1cdc9b2/src/syntax.lisp | lisp | FIXME: this is broken. Use in read-process once it works
P ::= 0 | x | ξ␣P | νa.P | a␣P␣.P | P|P | a[P].P a∈N, x∈V
Names and Variables
We assume an infinite set N of names, and an infinite set V of process
variables. We assume that N ∩ V = ∅. We let a, b, n, m and their decorated
and p , q , x , y range over V. The set L of identifiers
is defined as L = N ∪ V.
Processes
language L. In most cases the pattern language used is obvious from the
context, and we simply write K. We let P, Q, R, S, T and their decorated
We let M, N and their decorated variants range over messages and parallel
the form a[… | aj[Pj] | …] we call subkells the processes aj[Pj].
Abbreviations and conventions
We abbreviate a␣P␣ a message of the form a␣P␣.0. We abbreviate a a message
νa.P, the scope extends as far to the right as possible. In a term ξ␣P, the
scope of ␣ extends as far to the left and to the right as possible. Thus,
a␣c␣ | b[y] ␣ P | Q stands for (a␣c␣ | b[y])␣(P | Q). We use standard
abbreviations from the the π-calculus: νa1…aq.P for νa1.…νaq.P, or νã.P if
ã = (a1…aq). By convention, if the name vector ã is null, then νã.P =∆ P.
Also, we abuse notation and note ã the set {a1, …, an}, where ã is the
vector a1…an. We note ∏j∈J Pj, J = {1, …, n} the parallel composition
(P1 | (… (Pn−1 | Pn) …)). By convention, if J = ∅, then ∏j∈J Pj =∆ 0.
For the definition of the operational semantics of the calculus, we use
additional terms called annotated messages. Annotated messages comprise:
– Local messages: a local message is a term of the form a␣P␣. We write Mm
for a multiset of local messages.
a multiset of up messages.
for a multiset of down messages.
We write M for a multiset of annotated messages. Some of these terms are not
they are only used for matching
purposes. We often write these multisets as parallel compositions of
annotated messages.
messages {m↑b | m ∈ Mm}, and Mm↓b for the multiset of down messages
{m↓b | m ∈ Mm}.
Let M = {mjnj | j ∈ J} be an arbitrary multiset (where the multiplicity of
the smallest set to which elements of M belong. | (in-package #:kilns)
(defvar *paired-chars*
'((#\( . #\))
(#\[ . #\])
(#\{ . #\})))
(defvar *kilns-readtable* (copy-readtable))
(setf (readtable-case *kilns-readtable*) :invert)
(defvar *reading-name-p* nil
"Indicates whether we are currently reading a message name, and therefore
should treat ?x as a name-variable instead of a process-variable.")
(defmacro quote-atom (form)
`(if (listp ',form)
,form
',form))
(defun read-process (type stream char)
(let ((name (let ((*reading-name-p* t)) (read stream t))))
(destructuring-bind (&optional process continuation)
(read-delimited-list (cdr (assoc char *paired-chars*)) stream t)
(if continuation
`(,type (if (listp ',name) ,name ',name)
,process
(if (listp ',continuation) ,continuation ',continuation))
(if process
`(,type (if (listp ',name) ,name ',name) ,process)
`(,type (if (listp ',name) ,name ',name)))))))
(defun variable-reader (stream char)
(declare (ignore char))
(if *reading-name-p*
`(make-instance 'name-variable :name ',(read stream t))
`(make-instance 'process-variable :name ',(read stream t))))
(defun kell-reader (stream char)
(read-process 'kell stream char))
(defun message-reader (stream char)
(read-process 'message stream char))
(set-macro-character #\? #'variable-reader nil *kilns-readtable*)
(set-macro-character #\[ #'kell-reader nil *kilns-readtable*)
(set-macro-character #\] (get-macro-character #\) nil) nil *kilns-readtable*)
(set-macro-character #\{ #'message-reader nil *kilns-readtable*)
(set-macro-character #\} (get-macro-character #\) nil) nil *kilns-readtable*)
(defun par (&rest processes)
(apply #'parallel-composition processes))
The syntax of the Kell calculus is given in Figure 1 . It is parameterized by
the pattern language used to define patterns ξ in triggers ξ ␣ P.
Terms in the Kell calculus grammar are called processes .
We note K L the set of Kell calculus processes with patterns in pattern
variants range over processes . We call message a process of the form a ␣ P ␣ .Q.
composition of messages . We call a process of the form a[P].Q.
The name a in a a[P ] .Q is called the name of the . In a of
of the form a ␣ 0 ␣ . We abbreviate a[P ] a of the form a[P].0 . In a term
– Up messages : an up message is a term of the form a ␣ P ␣ ↑b . We write for
– Down messages : a down message is a term of the form a ␣ P ␣ ↓b . We write
– messages : a message is a term of the form a[P ] . We write Mk for
a multiset of messages .
Let Mm be a multiset of local messages . We write Mm↑b for the multiset of up
element mj is nj ) . We note M.supp = { mj | j ∈ J } the support set of M , i.e.
|
6a0e7a47a640021bb898355bf4a795043af60f057359de5a71ea8ec9e03cc838 | bobbae/gosling-emacs | rmail.ml | ; $Header: RCS/rmail.ml,v 1.5 83/05/18 13:41:16 thomas Exp $
(message "Loading the mail system, please wait...")
(setq-default rmail-pathalias 0)
(setq-default mail-headers-to-ignore
"received|origin|via|message-id|status|remailed-to|remailed-date")
(setq-default &mail-headers-to-ignore "")
(sit-for 0)
; Unix Emacs RMail facility. implements rmail (read mail) and
; smail (send mail).
; "rmail" is used for reading mail. Executing it places your incoming
; mailbox into a window and enters a special command interpretation loop.
; The commands that it understands are:
; p move to the previous message.
; n move to the next message.
; f move forward in the current message.
; b move backward in the current message.
; o go to other window (usually current message window.)
; d delete the current message.
; u undelete the last deleted message.
; r reply to the current message.
; q quit out of RMail, appending all undeleted messages to mbox.
; "smail" is used for sending mail. It places you in a buffer for
; constructing the message and locally defines a few commands:
; ^X^S send the mail -- if all went well the window will disappear,
; otherwise a message indicating which addresses failed will appear
; at the bottom of the acreen. Unfortunatly, the way the mailers on
; Unix work, the message will have been sent to those addresses which
; succeded and not to the others, so you have to delete some
; addresses and fix up the others before you resend the message.
; ^Xt positions you in the To: field of the message.
; ^Xc positions you in the Cc: field of the message, creating it if it
; doesn't already exist.
; The abbrev facility is used for mail address expansion,
; the file /usr/local/lib/emacs/RMailAbbrevs should contain
; abbrev definitions to expand login names to their
; proper mail address. This gets used at CMU since we have
; 7 VAXen, 4 10's and countless 11's; remembering where a
; person usually logs in is nearly impossible.
; ^Xs positions you in the Subject: field of the message.
; ^Xa positions you to the end of the body of the message, ready to
; append more text.
(defun
(rmail mbx entry-name ; The top level mail reader
(setq mbx (concat (getenv "HOME") "/Messages/"))
(message "Please wait while I read your mail file...")
(sit-for 0)
(save-window-excursion
(pop-to-buffer "rmail-directory")
(setq mode-line-format
(concat " Mail from message file "
(substr mbx 1 -1)
" %M %[%p%]"))
(setq needs-checkpointing 0)
(if (! (is-bound &IN_RMAIL&))
(progn
(if buffer-is-modified (write-current-file))
(set-mark)
(if (! prefix-argument-provided)
(filter-region
(concat "/usr/local/lib/emacs/collectmail "
mbx
" $HOME/BlindBox /usr/spool/mail/$USER"))
)
(read-file (concat mbx "Directory"))
(beginning-of-file)
(if (! (eolp)) (insert-character '\n'))
(setq case-fold-search 1)
(setq mode-string "RMail")
(mail-ignore-headers mail-headers-to-ignore)
(position-on-dirent)
(pick-up-message)
(sit-for 0)
(message "Type ESC-^Z to exit rmail; ? for help")
(progn &IN_RMAIL&
(recursive-edit))
(pop-to-buffer "rmail-directory")
(erase-messages)
(if buffer-is-modified (write-current-file))
)
(progn
(end-of-file)
(set-mark)
(filter-region
(concat "/usr/local/lib/emacs/collectmail - "
mbx
" $HOME/BlindBox /usr/spool/mail/$USER"))
(position-on-dirent)
(beginning-of-line)
(write-current-file)
)
)
)
(novalue)
)
)
(defun
(mail-ignore-headers
(setq mail-headers-to-ignore (arg 1 ": mail-ignore-headers "))
(if (!= mail-headers-to-ignore "")
(save-excursion
(temp-use-buffer "Scratch")
(erase-buffer)
(insert-string mail-headers-to-ignore)
(beginning-of-file)
(error-occured (replace-string "|" ":\\|^"))
(insert-character '\^')
(set-mark)
(end-of-file)
(insert-character ':')
(setq &mail-headers-to-ignore (region-to-string))
)
(setq &mail-headers-to-ignore "")
)
)
(position-on-dirent
(pop-to-buffer "rmail-directory")
(if (= (buffer-size) 0) (read-file (concat mbx "Directory")))
(if (! (looking-at "^>[^0-9\n]*\\([0-9][0-9]*\\)"))
(progn
(beginning-of-file)
(if (error-occured (re-search-forward ""))
(progn
(beginning-of-file)
(if (error-occured (search-forward "^ N"))
(end-of-file))
(rmail-mark)
(if (! (looking-at "^>[^0-9\n]*\\([0-9][0-9]*\\)"))
(error-message "No messages"))))
))
(region-around-match 1)
(setq entry-name (region-to-string))
(beginning-of-line)
)
)
(defun
(pick-up-message
(position-on-dirent)
(save-excursion
(pop-to-buffer "current-message")
(set-rmail-mode-line-format)
(setq needs-checkpointing 0)
(read-file (concat mbx entry-name))
(beginning-of-file)
(setq case-fold-search 1)
(set-mark)
(if (! prefix-argument-provided)
(error-occured
(save-restriction
(re-search-forward "^$")
(narrow-region)
(beginning-of-file)
(while (!= &mail-headers-to-ignore "")
(re-search-forward &mail-headers-to-ignore)
(beginning-of-line)
(mail-extend-field)
(forward-character)
(erase-region))
(error-occured (re-replace-string "\nvia:.*" ""))
(error-occured (re-replace-string "\nmail-from:.*" ""))
(error-occured (re-replace-string "\norigin:.*" ""))))
)
(setq buffer-is-modified 0)
)
)
)
(defun
(erase-messages
(save-excursion
(pop-to-buffer "rmail-directory")
(beginning-of-file)
(error-occured (re-replace-string "^.N" " "))
(error-occured fn
(while 1
(re-search-forward "^.D[^0-9\n]*\\([0-9]*\\)")
(region-around-match 1)
(unlink-file (concat mbx (region-to-string)))
(beginning-of-line)
(set-mark)
(end-of-line)
(forward-character)
(erase-region)
)
)
)
)
)
(defun
(rmail-com
(argc)
(rmail)
(exit-emacs)
)
)
(defun
(smail-com i
(declare-global exit-when-through)
(pop-to-buffer "send-mail")
(setq needs-checkpointing 0)
(setq case-fold-search 1)
(erase-buffer)
(if (! (is-bound read-mail-abbrevs))
(progn (declare-global read-mail-abbrevs)
(quietly-read-abbrev-file "/usr/local/lib/emacs/RMailAbbrevs")
)
)
(use-abbrev-table "RMail")
(setq i 1)
(newline)
(while (> (argc) i)
(if (!= (substr (argv i) 1 1) "-")
(progn
(insert-string (argv i))
(if (> (argc) i) (insert-character ','))
)
)
(setq i (+ i 1))
)
(newline)
(do-mail-setup)
(exit-emacs)
)
(rmail-next-page
(save-excursion
(pop-to-buffer "current-message")
(next-page)
(set-rmail-mode-line-format)
))
(rmail-previous-page
(save-excursion
(pop-to-buffer "current-message")
(previous-page)
(set-rmail-mode-line-format)
))
(rmail-all-headers
(provide-prefix-argument 1 (pick-up-message)))
(rmail-top-of-message
(save-excursion
(pop-to-buffer "current-message")
(beginning-of-file)
(set-rmail-mode-line-format)
)
)
(rmail-pass-headers
(save-excursion
(pop-to-buffer "current-message")
(beginning-of-file)
(if (error-occured (re-search-forward "^\n\n*"))
(end-of-file))
(line-to-top-of-window)
(set-rmail-mode-line-format)
)
)
)
(defun
(set-rmail-mode-line-format
(save-excursion
(end-of-file)
(setq mode-line-format
(if (dot-is-visible)
" Current message %[%p %M%]"
" Current message %[%p %M%] --More--")))
))
(defun
(rmail-next-message
(position-on-dirent)
(delete-next-character)
(insert-character ' ')
(beginning-of-line)
(next-line)
(if (eobp) (progn (previous-line)
(message "You're at the last message already")))
(delete-next-character)
(insert-character '>')
(backward-character)
(pick-up-message)
)
)
(defun
(rmail-previous-message
(position-on-dirent)
(delete-next-character)
(insert-character ' ')
(beginning-of-line)
(previous-line)
(if (bobp) (progn (next-line)
(message "You're at the first message")))
(delete-next-character)
(insert-character '>')
(backward-character)
(pick-up-message)
)
)
(defun
(rmail-delete-message
(position-on-dirent)
(forward-character)
(delete-next-character)
(insert-character 'D')
(beginning-of-line)
)
(rmail-delete-message-next
(rmail-delete-message)
(rmail-next-message)
)
(rmail-delete-message-previous
(rmail-delete-message)
(rmail-previous-message)
)
)
(defun
(rmail-undelete-message
(position-on-dirent)
(forward-character)
(delete-next-character)
(insert-character ' ')
(beginning-of-line)
)
)
(autoload "&info" "info.ml")
(defun
(rmail-help
(&info "emacs" "rmail")))
(defun
(rmail-reply
(save-window-excursion
(rmail-setup-reply)
(do-mail-setup)
)
(position-on-dirent)
(if (looking-at "^>[N ]")
(progn
(forward-character)
(delete-next-character)
(insert-character 'A')
(beginning-of-line)))
)
)
(defun
(rmail-setup-reply subject dest excess
(setq subject "")
(setq dest "")
(setq excess "")
(pop-to-buffer "current-message")
(setq case-fold-search 1)
(beginning-of-file)
(search-forward "\n\n")
(set-mark)
(beginning-of-file)
(narrow-region)
(error-occured
(re-search-forward "^Subject:[ \t]*\\(.*\\)")
(region-around-match 1)
(setq subject (region-to-string))
(if (!= (substr subject 1 3) "Re:")
(setq subject (concat "Re: " subject))
)
)
(beginning-of-file)
(error-occured
(if (error-occured (re-search-forward
"^reply-to:[ \t]*\\(.*\\)"))
(if (error-occured (re-search-forward
"^from:[ \t]*\\(.*\\)"))
(re-search-forward "^from[ \t]*\\(.[^ \t]*\\)")
)
)
(region-around-match 1)
(exchange-dot-and-mark)
(save-restriction
(narrow-region)
(if (looking-at ".*<\\(.*\\)>")
(region-around-match 1)))
(setq dest (region-to-string))
)
(beginning-of-file)
(error-occured edest
(save-excursion
(temp-use-buffer "Scratch Stuff")
(setq needs-checkpointing 0)
(erase-buffer)
(insert-string dest)
(set-mark)
(beginning-of-file)
(error-occured
(re-replace-string
" *at *[^,\n]*\\| *@ *[^,\n]*\\| *([^)\n]*)\\| *<[^>\n]*>"
""))
(setq edest (region-to-string)))
(if (error-occured
(re-search-forward "^date:[ \t]*"))
(re-search-forward "^from[ \t]*.[^ \t]*[ \t]*"))
(set-mark)
(end-of-line)
(setq excess (concat
"In-Reply-To: "
edest "'s message of "
(region-to-string)
"\n"))
)
(widen-region)
(pop-to-buffer "send-mail")
(setq case-fold-search 1)
(erase-buffer)
(insert-string subject)
(newline)
(insert-string dest)
(newline)
(insert-string excess)
(error-occured
(beginning-of-file)
(search-forward "In-Reply-To: ")
; (replace-string ":" "")
)
)
)
(defun
(rmail-unmark
(error-occured
(position-on-dirent)
(delete-next-character)
(insert-character ' ')
(beginning-of-line)))
(rmail-mark
(if (error-occured
(beginning-of-line)
(if (eobp)
(re-search-reverse "^.")
(progn
(re-search-forward "^.")
(beginning-of-line)))
(delete-next-character)
(insert-character '>')
(beginning-of-line)
(position-on-dirent)
(pick-up-message)
)
(message "No messages"))
)
)
(defun
(rmail-search-forward
(rmail-unmark)
(error-occured (re-search-forward
(get-tty-string "Search forward: ")))
(rmail-mark)
)
)
(defun
(rmail-search-reverse
(rmail-unmark)
(error-occured (re-search-reverse
(get-tty-string "Search reverse: ")))
(rmail-mark)
)
)
(defun
(rmail-goto-message n
(setq n (get-tty-string "Goto message: "))
(rmail-unmark)
(beginning-of-file)
(provide-prefix-argument n (next-line))
(rmail-mark)
)
)
(defun
(rmail-first-message
(rmail-unmark)
(beginning-of-file)
(rmail-mark)
)
)
(defun
(rmail-last-message
(rmail-unmark)
(end-of-file)
(rmail-mark)
)
)
(defun
(rmail-skip n
(if (! prefix-argument-provided)
(setq n (get-tty-string "Skip messages: "))
(setq n prefix-argument))
(rmail-unmark)
(provide-prefix-argument n (next-line))
(rmail-mark)
)
)
(defun (rmail-but-mark
(save-excursion (rmail-unmark))
(rmail-mark)))
(defun (rmail-but-delete
(rmail-but-mark)
(rmail-delete-message)))
(defun
(mail-insert
(mail-append)
(save-excursion
(insert-string "\n_________________________________\n")
(yank-buffer "current-message"))
(re-replace-string "^From \\|^Date:" ">&"))
(mail-noblind-exit
(setq mail-append-blind 0)
(exit-emacs))
)
(defun
(smail ; initiate mail sending
(save-window-excursion
(pop-to-buffer "send-mail")
(setq case-fold-search 1)
(erase-buffer)
(do-mail-setup)
)
(novalue)
)
; set things up in a mail sending buffer.
(do-mail-setup mail-do-send mail-append-blind
(beginning-of-file) ; makemail is a tiny little C program that
(set-mark) ; builds a prototype mail header from an
(end-of-file) ; input subject and destination.
(setq mode-string "SMail")
(setq mail-do-send 1)
(setq mail-append-blind 1)
(if (! (is-bound read-mail-abbrevs))
(progn (declare-global read-mail-abbrevs)
(quietly-read-abbrev-file "/usr/local/lib/emacs/RMailAbbrevs")
)
)
(use-abbrev-table "RMail")
(filter-region "/usr/local/lib/emacs/makemail")
(beginning-of-file)
(search-forward "hErE<!}")
(delete-previous-word)
(setq abbrev-mode (= (current-column) 5))
(setq right-margin 72)
(change-file-name "~/live.letter")
(remove-all-local-bindings)
(local-bind-to-key "rmail-help" "\^X?")
(local-bind-to-key "mail-to" "\^Zt")
(local-bind-to-key "mail-append" "\^Za")
(local-bind-to-key "mail-bcc" "\^Zb")
(local-bind-to-key "mail-cc" "\^Zc")
(local-bind-to-key "mail-subject" "\^Zs")
(local-bind-to-key "mail-fetch-field" "\^Zf")
(local-bind-to-key "mail-insert" "\^Zi")
(local-bind-to-key "mail-noblind-exit" "\^X\^C")
; (local-bind-to-key "exit-emacs" "\^X\^F")
(local-bind-to-key "mail-abort-send" "\^X\^A")
(local-bind-to-key "justify-paragraph" "\ej")
(message "Type ESC-^Z to send the message; ^X^A to abort; ^X? for help.")
(while mail-do-send
(save-excursion
(recursive-edit)
(if mail-do-send
(progn
(message "Sending...")
(sit-for 0))))
(if mail-do-send (send-mail)))
)
)
(defun
(mail-abort-send
(if (!= "y" (substr (get-tty-string
"Do you really want to abort the message? ")
1 1))
(error-message "Turkey!"))
(setq mail-do-send 0)
(exit-emacs))
(mail-to ; move to the "To:" field
(abbrev-expand)
(setq abbrev-mode 1)
(mail-position-on-field "to")
(setq left-margin 10)
)
(mail-subject ; move to the "Subject:" field
(abbrev-expand)
(setq abbrev-mode 0)
(mail-position-on-field "subject")
(setq left-margin 10)
)
(mail-fetch-field ; fetch a field from the current message
field-name field-contents
(setq field-name (get-tty-string ": field name "))
(save-excursion
(temp-use-buffer "current-message")
(beginning-of-file)
(setq case-fold-search 1)
(re-search-forward (concat "^" field-name "[^\n: ]*:[ \t]*"))
(mail-extend-field)
(setq field-contents (region-to-string))
)
(insert-string field-contents)
)
(mail-append ; move to the body
(abbrev-expand)
(setq abbrev-mode 0)
(end-of-file)
(setq left-margin 1)
)
(mail-cc ; move to the "cc:" field.
(abbrev-expand)
(setq abbrev-mode 1)
(if (= (provide-prefix-argument 1 (mail-position-on-field "cc")) -1)
(progn
(mail-position-on-field "to")
(insert-string "\nCc: "))
)
(setq left-margin 10)
)
(mail-bcc
(abbrev-expand)
(setq abbrev-mode 1)
(if (= (provide-prefix-argument 1 (mail-position-on-field "bcc")) -1)
(progn
(mail-position-on-field "to")
(insert-string "\nBcc: "))
)
(setq left-margin 10)
)
(mail-position-on-field field
(save-restriction
(beginning-of-file)
(set-mark)
(if (error-occured (search-forward "\n\n"))
(end-of-file)
(backward-character))
(narrow-region)
(beginning-of-file)
(setq field (arg 1 ": mail-position-on-field "))
(if (error-occured (re-search-forward (concat "^" field ":")))
(if prefix-argument-provided
-1
(progn
(end-of-file)
(backward-character)
(set-mark)
(insert-string "\n" field ": ")
(case-region-capitalize)
(set-mark)
0
)
)
(progn
(mail-extend-field)
0
)
)
)
)
(mail-extend-field
(set-mark)
(while (progn (end-of-line)
(looking-at "\n[ \t]"))
(forward-character))
)
(send-mail addresses ; finally send the mail
(abbrev-expand)
(beginning-of-file)
(if (error-occured (re-search-forward "^$"))
(end-of-file))
(set-mark)
(beginning-of-file)
(narrow-region)
(setq addresses "")
; (error-occured
; (re-search-forward "^to:[ \t]*")
; (mail-extend-field)
; (setq addresses (region-to-string)))
; (beginning-of-file)
; (error-occured
; (re-search-forward "^cc:[ \t]*")
; (mail-extend-field)
; (setq addresses (concat addresses ","
; (region-to-string))))
(widen-region)
; (message "sending...")
; (save-excursion
; (temp-use-buffer "Scratch Stuff")
; (setq needs-checkpointing 0)
; (erase-buffer)
; (insert-string addresses)
; (beginning-of-file)
; (error-occured (re-replace-string "[\t\n]" " "))
; (error-occured (re-replace-string " *([^(]*)" ""))
; (error-occured (re-replace-string "[^,]*<\\([^>,]*\\)>" "\\1"))
; (error-occured (re-replace-string " *at *" "@"))
; (error-occured (re-replace-string " *" "."))
; (error-occured (re-replace-string "\\.*,\\.*" " "))
; (error-occured (replace-string "!" "\\!"))
; (error-occured (re-replace-string "^ *\\|[ .][ .]*$" ""))
; (set-mark)
; (end-of-file)
; (setq addresses (region-to-string))
; )
; (message "Sending to " addresses " ...")(sit-for 0)
(end-of-file)
(if (! (bolp)) (newline))
(if mail-append-blind
(progn
(mail-position-on-field "bcc")
(insert-string ", " (users-login-name))
))
(beginning-of-file)
(set-mark)
(end-of-file)
(filter-region "/usr/lib/sendmail -i -t")
(if (= (buffer-size) 0)
(progn
(setq mail-do-send 0)
(message (concat "Mail sent"))
(setq buffer-is-modified 0)
)
(progn T
(beginning-of-file)
(set-mark)
(end-of-file)
(copy-region-to-buffer "Delivery-errors")
(beginning-of-file)
(error-occured (re-replace-string "\n\n* *" "; "))
(end-of-line)
(setq T (region-to-string))
(erase-buffer)
(yank-from-killbuffer)
(beginning-of-file)
(error-occured
(re-search-forward "^to:[^>\n]*"))
(save-excursion
(pop-to-buffer " Minibuf")
(previous-window)
(if (> (window-height) 4)
(progn
(split-current-window)
(while (> (window-height) 2)
(shrink-window))
(switch-to-buffer "Delivery-errors"))
(pop-to-buffer "Delivery-errors"))
(beginning-of-file))
(message T))
)
)
(abbrev-expand
(insert-character ' ')
(delete-previous-character)
)
)
(declare-global rmail-default-log)
(setq rmail-default-log "~/TextMessage")
(defun
(rmail-append file
(setq file (get-tty-string (concat ": append-message-to-file ["
rmail-default-log "] ")))
(if (= file "") (setq file rmail-default-log))
(save-excursion
(temp-use-buffer "current-message")
(append-to-file file))
(setq rmail-default-log file)
)
(rmail-shell
(save-window-excursion
(shell)
(message "Type ESC-^Z to resume mail reading")
(recursive-edit))
)
)
(defun (rmail-query-exit
(if (!= "y" (substr (get-tty-string
"Do you really want to abort mail reading? ")
1 1))
(error-message "Turkey!"))
(exit-emacs)
)
)
(save-excursion i
(temp-use-buffer "rmail-directory")
(define-keymap "rmail-commands")
(define-keymap "rmail-esc-commands")
(define-keymap "rmail-^x-commands")
(define-keymap "rmail-^z-commands")
(use-local-map "rmail-esc-commands")
(setq i 0)
(while (< i 128)
(local-bind-to-key "illegal-operation" i)
(setq i (+ i 1)))
(use-local-map "rmail-^x-commands")
(setq i 0)
(while (< i 128)
(local-bind-to-key "illegal-operation" i)
(setq i (+ i 1)))
(use-local-map "rmail-^z-commands")
(setq i 0)
(while (< i 128)
(local-bind-to-key "illegal-operation" i)
(setq i (+ i 1)))
(use-local-map "rmail-commands")
(setq i 0)
(while (< i 128)
(local-bind-to-key "illegal-operation" i)
(setq i (+ i 1)))
(local-bind-to-key "rmail-esc-commands" "\e")
(local-bind-to-key "rmail-^x-commands" '^x')
(local-bind-to-key "rmail-^z-commands" '^z')
; innocuous commands which we want to keep
(remove-local-binding '^a')
(remove-local-binding '^b')
(remove-local-binding '^e')
(remove-local-binding '^f')
(remove-local-binding '^l')
(remove-local-binding '^n')
(remove-local-binding '^p')
(remove-local-binding '^r')
(remove-local-binding '^s')
(remove-local-binding '^u')
(remove-local-binding '^v')
(remove-local-binding "\^X\^B")
(remove-local-binding "\^X\^F")
(remove-local-binding "\^X\^O")
(remove-local-binding "\^X\^S")
(remove-local-binding "\^X\^V")
(remove-local-binding "\^X\^X")
(remove-local-binding "\^X\^Z")
(remove-local-binding "\^X(")
(remove-local-binding "\^X)")
(remove-local-binding "\^X/")
(remove-local-binding "\^X0")
(remove-local-binding "\^X1")
(remove-local-binding "\^X2")
(remove-local-binding "\^X4")
(remove-local-binding "\^X<")
(remove-local-binding "\^X>")
(remove-local-binding "\^XB")
(remove-local-binding "\^XI")
(remove-local-binding "\^XM")
(remove-local-binding "\^X^")
(remove-local-binding "\^Xb")
(remove-local-binding "\^Xd")
(remove-local-binding "\^Xe")
(remove-local-binding "\^Xk")
(remove-local-binding "\^Xm")
(remove-local-binding "\^Xn")
(remove-local-binding "\^Xo")
(remove-local-binding "\^Xp")
(remove-local-binding "\^Xr")
(remove-local-binding "\^Xv")
(remove-local-binding "\^Z\^Z")
(remove-local-binding "\e\^@")
(remove-local-binding "\e\^B")
(remove-local-binding "\e\^F")
(remove-local-binding "\e\^H")
(remove-local-binding "\e\^R")
(remove-local-binding "\e\^S")
(remove-local-binding "\e\^V")
(remove-local-binding "\e\^Z")
(remove-local-binding "\e\e")
(remove-local-binding "\e!")
(remove-local-binding "\e#")
(remove-local-binding "\e%")
(remove-local-binding "\e-")
(remove-local-binding "\e/")
(remove-local-binding "\e0")
(remove-local-binding "\e1")
(remove-local-binding "\e2")
(remove-local-binding "\e3")
(remove-local-binding "\e4")
(remove-local-binding "\e5")
(remove-local-binding "\e6")
(remove-local-binding "\e7")
(remove-local-binding "\e8")
(remove-local-binding "\e9")
(remove-local-binding "\e<")
(remove-local-binding "\e=")
(remove-local-binding "\e>")
(remove-local-binding "\e?")
(remove-local-binding "\e@")
(remove-local-binding "\eG")
(remove-local-binding "\eM")
(remove-local-binding "\eZ")
(remove-local-binding "\eb")
(remove-local-binding "\ef")
(remove-local-binding "\eg")
(remove-local-binding "\eo")
(remove-local-binding "\es")
(remove-local-binding "\ev")
(remove-local-binding "\ex")
(remove-local-binding "\ez")
(remove-local-binding '^_')
(local-bind-to-key "meta-digit" "1")
(local-bind-to-key "meta-digit" "2")
(local-bind-to-key "meta-digit" "3")
(local-bind-to-key "meta-digit" "4")
(local-bind-to-key "meta-digit" "5")
(local-bind-to-key "meta-digit" "6")
(local-bind-to-key "meta-digit" "7")
(local-bind-to-key "meta-digit" "8")
(local-bind-to-key "meta-digit" "9")
(local-bind-to-key "meta-digit" "0")
(local-bind-to-key "meta-minus" "-")
(local-bind-to-key "rmail-previous-page" '^H')
(local-bind-to-key "rmail-next-page" ' ')
(local-bind-to-key "rmail-top-of-message" '^m')
(local-bind-to-key "rmail-top-of-message" '^j')
(local-bind-to-key "rmail-pass-headers" 't')
(local-bind-to-key "rmail-all-headers" 'T')
(local-bind-to-key "rmail-next-message" 'n')
(local-bind-to-key "rmail-previous-message" 'p')
(local-bind-to-key "next-window" 'o')
(local-bind-to-key "rmail-delete-message-next" 'd')
(local-bind-to-key "rmail-delete-message-previous" 'D')
(local-bind-to-key "rmail-delete-message" '^d')
(local-bind-to-key "rmail-undelete-message" 'u')
(local-bind-to-key "rmail-query-exit" "\^G")
(local-bind-to-key "rmail-help" '?')
(local-bind-to-key "Pop-level" 'q')
(local-bind-to-key "rmail-reply" 'r')
(local-bind-to-key "smail" 'm')
(local-bind-to-key "rmail-goto-message" 'g')
(local-bind-to-key "rmail-first-message" '<')
(local-bind-to-key "rmail-last-message" '>')
(local-bind-to-key "rmail-but-mark" '.')
(local-bind-to-key "rmail-skip" 's')
(local-bind-to-key "rmail-append" 'a')
(local-bind-to-key "execute-extended-command" ':')
(local-bind-to-key "rmail" "i"); incorporate new messages
)
| null | https://raw.githubusercontent.com/bobbae/gosling-emacs/8fdda532abbffb0c952251a0b5a4857e0f27495a/lib/maclib/utah/std/rmail.ml | ocaml | ; $Header: RCS/rmail.ml,v 1.5 83/05/18 13:41:16 thomas Exp $
(message "Loading the mail system, please wait...")
(setq-default rmail-pathalias 0)
(setq-default mail-headers-to-ignore
"received|origin|via|message-id|status|remailed-to|remailed-date")
(setq-default &mail-headers-to-ignore "")
(sit-for 0)
; Unix Emacs RMail facility. implements rmail (read mail) and
; smail (send mail).
; "rmail" is used for reading mail. Executing it places your incoming
; mailbox into a window and enters a special command interpretation loop.
; The commands that it understands are:
; p move to the previous message.
; n move to the next message.
; f move forward in the current message.
; b move backward in the current message.
; o go to other window (usually current message window.)
; d delete the current message.
; u undelete the last deleted message.
; r reply to the current message.
; q quit out of RMail, appending all undeleted messages to mbox.
; "smail" is used for sending mail. It places you in a buffer for
; constructing the message and locally defines a few commands:
; ^X^S send the mail -- if all went well the window will disappear,
; otherwise a message indicating which addresses failed will appear
; at the bottom of the acreen. Unfortunatly, the way the mailers on
; Unix work, the message will have been sent to those addresses which
; succeded and not to the others, so you have to delete some
; addresses and fix up the others before you resend the message.
; ^Xt positions you in the To: field of the message.
; ^Xc positions you in the Cc: field of the message, creating it if it
; doesn't already exist.
; The abbrev facility is used for mail address expansion,
; the file /usr/local/lib/emacs/RMailAbbrevs should contain
; abbrev definitions to expand login names to their
; proper mail address. This gets used at CMU since we have
; 7 VAXen, 4 10's and countless 11's; remembering where a
; person usually logs in is nearly impossible.
; ^Xs positions you in the Subject: field of the message.
; ^Xa positions you to the end of the body of the message, ready to
; append more text.
(defun
(rmail mbx entry-name ; The top level mail reader
(setq mbx (concat (getenv "HOME") "/Messages/"))
(message "Please wait while I read your mail file...")
(sit-for 0)
(save-window-excursion
(pop-to-buffer "rmail-directory")
(setq mode-line-format
(concat " Mail from message file "
(substr mbx 1 -1)
" %M %[%p%]"))
(setq needs-checkpointing 0)
(if (! (is-bound &IN_RMAIL&))
(progn
(if buffer-is-modified (write-current-file))
(set-mark)
(if (! prefix-argument-provided)
(filter-region
(concat "/usr/local/lib/emacs/collectmail "
mbx
" $HOME/BlindBox /usr/spool/mail/$USER"))
)
(read-file (concat mbx "Directory"))
(beginning-of-file)
(if (! (eolp)) (insert-character '\n'))
(setq case-fold-search 1)
(setq mode-string "RMail")
(mail-ignore-headers mail-headers-to-ignore)
(position-on-dirent)
(pick-up-message)
(sit-for 0)
(message "Type ESC-^Z to exit rmail; ? for help")
(progn &IN_RMAIL&
(recursive-edit))
(pop-to-buffer "rmail-directory")
(erase-messages)
(if buffer-is-modified (write-current-file))
)
(progn
(end-of-file)
(set-mark)
(filter-region
(concat "/usr/local/lib/emacs/collectmail - "
mbx
" $HOME/BlindBox /usr/spool/mail/$USER"))
(position-on-dirent)
(beginning-of-line)
(write-current-file)
)
)
)
(novalue)
)
)
(defun
(mail-ignore-headers
(setq mail-headers-to-ignore (arg 1 ": mail-ignore-headers "))
(if (!= mail-headers-to-ignore "")
(save-excursion
(temp-use-buffer "Scratch")
(erase-buffer)
(insert-string mail-headers-to-ignore)
(beginning-of-file)
(error-occured (replace-string "|" ":\\|^"))
(insert-character '\^')
(set-mark)
(end-of-file)
(insert-character ':')
(setq &mail-headers-to-ignore (region-to-string))
)
(setq &mail-headers-to-ignore "")
)
)
(position-on-dirent
(pop-to-buffer "rmail-directory")
(if (= (buffer-size) 0) (read-file (concat mbx "Directory")))
(if (! (looking-at "^>[^0-9\n]*\\([0-9][0-9]*\\)"))
(progn
(beginning-of-file)
(if (error-occured (re-search-forward ""))
(progn
(beginning-of-file)
(if (error-occured (search-forward "^ N"))
(end-of-file))
(rmail-mark)
(if (! (looking-at "^>[^0-9\n]*\\([0-9][0-9]*\\)"))
(error-message "No messages"))))
))
(region-around-match 1)
(setq entry-name (region-to-string))
(beginning-of-line)
)
)
(defun
(pick-up-message
(position-on-dirent)
(save-excursion
(pop-to-buffer "current-message")
(set-rmail-mode-line-format)
(setq needs-checkpointing 0)
(read-file (concat mbx entry-name))
(beginning-of-file)
(setq case-fold-search 1)
(set-mark)
(if (! prefix-argument-provided)
(error-occured
(save-restriction
(re-search-forward "^$")
(narrow-region)
(beginning-of-file)
(while (!= &mail-headers-to-ignore "")
(re-search-forward &mail-headers-to-ignore)
(beginning-of-line)
(mail-extend-field)
(forward-character)
(erase-region))
(error-occured (re-replace-string "\nvia:.*" ""))
(error-occured (re-replace-string "\nmail-from:.*" ""))
(error-occured (re-replace-string "\norigin:.*" ""))))
)
(setq buffer-is-modified 0)
)
)
)
(defun
(erase-messages
(save-excursion
(pop-to-buffer "rmail-directory")
(beginning-of-file)
(error-occured (re-replace-string "^.N" " "))
(error-occured fn
(while 1
(re-search-forward "^.D[^0-9\n]*\\([0-9]*\\)")
(region-around-match 1)
(unlink-file (concat mbx (region-to-string)))
(beginning-of-line)
(set-mark)
(end-of-line)
(forward-character)
(erase-region)
)
)
)
)
)
(defun
(rmail-com
(argc)
(rmail)
(exit-emacs)
)
)
(defun
(smail-com i
(declare-global exit-when-through)
(pop-to-buffer "send-mail")
(setq needs-checkpointing 0)
(setq case-fold-search 1)
(erase-buffer)
(if (! (is-bound read-mail-abbrevs))
(progn (declare-global read-mail-abbrevs)
(quietly-read-abbrev-file "/usr/local/lib/emacs/RMailAbbrevs")
)
)
(use-abbrev-table "RMail")
(setq i 1)
(newline)
(while (> (argc) i)
(if (!= (substr (argv i) 1 1) "-")
(progn
(insert-string (argv i))
(if (> (argc) i) (insert-character ','))
)
)
(setq i (+ i 1))
)
(newline)
(do-mail-setup)
(exit-emacs)
)
(rmail-next-page
(save-excursion
(pop-to-buffer "current-message")
(next-page)
(set-rmail-mode-line-format)
))
(rmail-previous-page
(save-excursion
(pop-to-buffer "current-message")
(previous-page)
(set-rmail-mode-line-format)
))
(rmail-all-headers
(provide-prefix-argument 1 (pick-up-message)))
(rmail-top-of-message
(save-excursion
(pop-to-buffer "current-message")
(beginning-of-file)
(set-rmail-mode-line-format)
)
)
(rmail-pass-headers
(save-excursion
(pop-to-buffer "current-message")
(beginning-of-file)
(if (error-occured (re-search-forward "^\n\n*"))
(end-of-file))
(line-to-top-of-window)
(set-rmail-mode-line-format)
)
)
)
(defun
(set-rmail-mode-line-format
(save-excursion
(end-of-file)
(setq mode-line-format
(if (dot-is-visible)
" Current message %[%p %M%]"
" Current message %[%p %M%] --More--")))
))
(defun
(rmail-next-message
(position-on-dirent)
(delete-next-character)
(insert-character ' ')
(beginning-of-line)
(next-line)
(if (eobp) (progn (previous-line)
(message "You're at the last message already")))
(delete-next-character)
(insert-character '>')
(backward-character)
(pick-up-message)
)
)
(defun
(rmail-previous-message
(position-on-dirent)
(delete-next-character)
(insert-character ' ')
(beginning-of-line)
(previous-line)
(if (bobp) (progn (next-line)
(message "You're at the first message")))
(delete-next-character)
(insert-character '>')
(backward-character)
(pick-up-message)
)
)
(defun
(rmail-delete-message
(position-on-dirent)
(forward-character)
(delete-next-character)
(insert-character 'D')
(beginning-of-line)
)
(rmail-delete-message-next
(rmail-delete-message)
(rmail-next-message)
)
(rmail-delete-message-previous
(rmail-delete-message)
(rmail-previous-message)
)
)
(defun
(rmail-undelete-message
(position-on-dirent)
(forward-character)
(delete-next-character)
(insert-character ' ')
(beginning-of-line)
)
)
(autoload "&info" "info.ml")
(defun
(rmail-help
(&info "emacs" "rmail")))
(defun
(rmail-reply
(save-window-excursion
(rmail-setup-reply)
(do-mail-setup)
)
(position-on-dirent)
(if (looking-at "^>[N ]")
(progn
(forward-character)
(delete-next-character)
(insert-character 'A')
(beginning-of-line)))
)
)
(defun
(rmail-setup-reply subject dest excess
(setq subject "")
(setq dest "")
(setq excess "")
(pop-to-buffer "current-message")
(setq case-fold-search 1)
(beginning-of-file)
(search-forward "\n\n")
(set-mark)
(beginning-of-file)
(narrow-region)
(error-occured
(re-search-forward "^Subject:[ \t]*\\(.*\\)")
(region-around-match 1)
(setq subject (region-to-string))
(if (!= (substr subject 1 3) "Re:")
(setq subject (concat "Re: " subject))
)
)
(beginning-of-file)
(error-occured
(if (error-occured (re-search-forward
"^reply-to:[ \t]*\\(.*\\)"))
(if (error-occured (re-search-forward
"^from:[ \t]*\\(.*\\)"))
(re-search-forward "^from[ \t]*\\(.[^ \t]*\\)")
)
)
(region-around-match 1)
(exchange-dot-and-mark)
(save-restriction
(narrow-region)
(if (looking-at ".*<\\(.*\\)>")
(region-around-match 1)))
(setq dest (region-to-string))
)
(beginning-of-file)
(error-occured edest
(save-excursion
(temp-use-buffer "Scratch Stuff")
(setq needs-checkpointing 0)
(erase-buffer)
(insert-string dest)
(set-mark)
(beginning-of-file)
(error-occured
(re-replace-string
" *at *[^,\n]*\\| *@ *[^,\n]*\\| *([^)\n]*)\\| *<[^>\n]*>"
""))
(setq edest (region-to-string)))
(if (error-occured
(re-search-forward "^date:[ \t]*"))
(re-search-forward "^from[ \t]*.[^ \t]*[ \t]*"))
(set-mark)
(end-of-line)
(setq excess (concat
"In-Reply-To: "
edest "'s message of "
(region-to-string)
"\n"))
)
(widen-region)
(pop-to-buffer "send-mail")
(setq case-fold-search 1)
(erase-buffer)
(insert-string subject)
(newline)
(insert-string dest)
(newline)
(insert-string excess)
(error-occured
(beginning-of-file)
(search-forward "In-Reply-To: ")
; (replace-string ":" "")
)
)
)
(defun
(rmail-unmark
(error-occured
(position-on-dirent)
(delete-next-character)
(insert-character ' ')
(beginning-of-line)))
(rmail-mark
(if (error-occured
(beginning-of-line)
(if (eobp)
(re-search-reverse "^.")
(progn
(re-search-forward "^.")
(beginning-of-line)))
(delete-next-character)
(insert-character '>')
(beginning-of-line)
(position-on-dirent)
(pick-up-message)
)
(message "No messages"))
)
)
(defun
(rmail-search-forward
(rmail-unmark)
(error-occured (re-search-forward
(get-tty-string "Search forward: ")))
(rmail-mark)
)
)
(defun
(rmail-search-reverse
(rmail-unmark)
(error-occured (re-search-reverse
(get-tty-string "Search reverse: ")))
(rmail-mark)
)
)
(defun
(rmail-goto-message n
(setq n (get-tty-string "Goto message: "))
(rmail-unmark)
(beginning-of-file)
(provide-prefix-argument n (next-line))
(rmail-mark)
)
)
(defun
(rmail-first-message
(rmail-unmark)
(beginning-of-file)
(rmail-mark)
)
)
(defun
(rmail-last-message
(rmail-unmark)
(end-of-file)
(rmail-mark)
)
)
(defun
(rmail-skip n
(if (! prefix-argument-provided)
(setq n (get-tty-string "Skip messages: "))
(setq n prefix-argument))
(rmail-unmark)
(provide-prefix-argument n (next-line))
(rmail-mark)
)
)
(defun (rmail-but-mark
(save-excursion (rmail-unmark))
(rmail-mark)))
(defun (rmail-but-delete
(rmail-but-mark)
(rmail-delete-message)))
(defun
(mail-insert
(mail-append)
(save-excursion
(insert-string "\n_________________________________\n")
(yank-buffer "current-message"))
(re-replace-string "^From \\|^Date:" ">&"))
(mail-noblind-exit
(setq mail-append-blind 0)
(exit-emacs))
)
(defun
(smail ; initiate mail sending
(save-window-excursion
(pop-to-buffer "send-mail")
(setq case-fold-search 1)
(erase-buffer)
(do-mail-setup)
)
(novalue)
)
; set things up in a mail sending buffer.
(do-mail-setup mail-do-send mail-append-blind
(beginning-of-file) ; makemail is a tiny little C program that
(set-mark) ; builds a prototype mail header from an
(end-of-file) ; input subject and destination.
(setq mode-string "SMail")
(setq mail-do-send 1)
(setq mail-append-blind 1)
(if (! (is-bound read-mail-abbrevs))
(progn (declare-global read-mail-abbrevs)
(quietly-read-abbrev-file "/usr/local/lib/emacs/RMailAbbrevs")
)
)
(use-abbrev-table "RMail")
(filter-region "/usr/local/lib/emacs/makemail")
(beginning-of-file)
(search-forward "hErE<!}")
(delete-previous-word)
(setq abbrev-mode (= (current-column) 5))
(setq right-margin 72)
(change-file-name "~/live.letter")
(remove-all-local-bindings)
(local-bind-to-key "rmail-help" "\^X?")
(local-bind-to-key "mail-to" "\^Zt")
(local-bind-to-key "mail-append" "\^Za")
(local-bind-to-key "mail-bcc" "\^Zb")
(local-bind-to-key "mail-cc" "\^Zc")
(local-bind-to-key "mail-subject" "\^Zs")
(local-bind-to-key "mail-fetch-field" "\^Zf")
(local-bind-to-key "mail-insert" "\^Zi")
(local-bind-to-key "mail-noblind-exit" "\^X\^C")
; (local-bind-to-key "exit-emacs" "\^X\^F")
(local-bind-to-key "mail-abort-send" "\^X\^A")
(local-bind-to-key "justify-paragraph" "\ej")
(message "Type ESC-^Z to send the message; ^X^A to abort; ^X? for help.")
(while mail-do-send
(save-excursion
(recursive-edit)
(if mail-do-send
(progn
(message "Sending...")
(sit-for 0))))
(if mail-do-send (send-mail)))
)
)
(defun
(mail-abort-send
(if (!= "y" (substr (get-tty-string
"Do you really want to abort the message? ")
1 1))
(error-message "Turkey!"))
(setq mail-do-send 0)
(exit-emacs))
(mail-to ; move to the "To:" field
(abbrev-expand)
(setq abbrev-mode 1)
(mail-position-on-field "to")
(setq left-margin 10)
)
(mail-subject ; move to the "Subject:" field
(abbrev-expand)
(setq abbrev-mode 0)
(mail-position-on-field "subject")
(setq left-margin 10)
)
(mail-fetch-field ; fetch a field from the current message
field-name field-contents
(setq field-name (get-tty-string ": field name "))
(save-excursion
(temp-use-buffer "current-message")
(beginning-of-file)
(setq case-fold-search 1)
(re-search-forward (concat "^" field-name "[^\n: ]*:[ \t]*"))
(mail-extend-field)
(setq field-contents (region-to-string))
)
(insert-string field-contents)
)
(mail-append ; move to the body
(abbrev-expand)
(setq abbrev-mode 0)
(end-of-file)
(setq left-margin 1)
)
(mail-cc ; move to the "cc:" field.
(abbrev-expand)
(setq abbrev-mode 1)
(if (= (provide-prefix-argument 1 (mail-position-on-field "cc")) -1)
(progn
(mail-position-on-field "to")
(insert-string "\nCc: "))
)
(setq left-margin 10)
)
(mail-bcc
(abbrev-expand)
(setq abbrev-mode 1)
(if (= (provide-prefix-argument 1 (mail-position-on-field "bcc")) -1)
(progn
(mail-position-on-field "to")
(insert-string "\nBcc: "))
)
(setq left-margin 10)
)
(mail-position-on-field field
(save-restriction
(beginning-of-file)
(set-mark)
(if (error-occured (search-forward "\n\n"))
(end-of-file)
(backward-character))
(narrow-region)
(beginning-of-file)
(setq field (arg 1 ": mail-position-on-field "))
(if (error-occured (re-search-forward (concat "^" field ":")))
(if prefix-argument-provided
-1
(progn
(end-of-file)
(backward-character)
(set-mark)
(insert-string "\n" field ": ")
(case-region-capitalize)
(set-mark)
0
)
)
(progn
(mail-extend-field)
0
)
)
)
)
(mail-extend-field
(set-mark)
(while (progn (end-of-line)
(looking-at "\n[ \t]"))
(forward-character))
)
(send-mail addresses ; finally send the mail
(abbrev-expand)
(beginning-of-file)
(if (error-occured (re-search-forward "^$"))
(end-of-file))
(set-mark)
(beginning-of-file)
(narrow-region)
(setq addresses "")
; (error-occured
; (re-search-forward "^to:[ \t]*")
; (mail-extend-field)
; (setq addresses (region-to-string)))
; (beginning-of-file)
; (error-occured
; (re-search-forward "^cc:[ \t]*")
; (mail-extend-field)
; (setq addresses (concat addresses ","
; (region-to-string))))
(widen-region)
; (message "sending...")
; (save-excursion
; (temp-use-buffer "Scratch Stuff")
; (setq needs-checkpointing 0)
; (erase-buffer)
; (insert-string addresses)
; (beginning-of-file)
; (error-occured (re-replace-string "[\t\n]" " "))
; (error-occured (re-replace-string " *([^(]*)" ""))
; (error-occured (re-replace-string "[^,]*<\\([^>,]*\\)>" "\\1"))
; (error-occured (re-replace-string " *at *" "@"))
; (error-occured (re-replace-string " *" "."))
; (error-occured (re-replace-string "\\.*,\\.*" " "))
; (error-occured (replace-string "!" "\\!"))
; (error-occured (re-replace-string "^ *\\|[ .][ .]*$" ""))
; (set-mark)
; (end-of-file)
; (setq addresses (region-to-string))
; )
; (message "Sending to " addresses " ...")(sit-for 0)
(end-of-file)
(if (! (bolp)) (newline))
(if mail-append-blind
(progn
(mail-position-on-field "bcc")
(insert-string ", " (users-login-name))
))
(beginning-of-file)
(set-mark)
(end-of-file)
(filter-region "/usr/lib/sendmail -i -t")
(if (= (buffer-size) 0)
(progn
(setq mail-do-send 0)
(message (concat "Mail sent"))
(setq buffer-is-modified 0)
)
(progn T
(beginning-of-file)
(set-mark)
(end-of-file)
(copy-region-to-buffer "Delivery-errors")
(beginning-of-file)
(error-occured (re-replace-string "\n\n* *" "; "))
(end-of-line)
(setq T (region-to-string))
(erase-buffer)
(yank-from-killbuffer)
(beginning-of-file)
(error-occured
(re-search-forward "^to:[^>\n]*"))
(save-excursion
(pop-to-buffer " Minibuf")
(previous-window)
(if (> (window-height) 4)
(progn
(split-current-window)
(while (> (window-height) 2)
(shrink-window))
(switch-to-buffer "Delivery-errors"))
(pop-to-buffer "Delivery-errors"))
(beginning-of-file))
(message T))
)
)
(abbrev-expand
(insert-character ' ')
(delete-previous-character)
)
)
(declare-global rmail-default-log)
(setq rmail-default-log "~/TextMessage")
(defun
(rmail-append file
(setq file (get-tty-string (concat ": append-message-to-file ["
rmail-default-log "] ")))
(if (= file "") (setq file rmail-default-log))
(save-excursion
(temp-use-buffer "current-message")
(append-to-file file))
(setq rmail-default-log file)
)
(rmail-shell
(save-window-excursion
(shell)
(message "Type ESC-^Z to resume mail reading")
(recursive-edit))
)
)
(defun (rmail-query-exit
(if (!= "y" (substr (get-tty-string
"Do you really want to abort mail reading? ")
1 1))
(error-message "Turkey!"))
(exit-emacs)
)
)
(save-excursion i
(temp-use-buffer "rmail-directory")
(define-keymap "rmail-commands")
(define-keymap "rmail-esc-commands")
(define-keymap "rmail-^x-commands")
(define-keymap "rmail-^z-commands")
(use-local-map "rmail-esc-commands")
(setq i 0)
(while (< i 128)
(local-bind-to-key "illegal-operation" i)
(setq i (+ i 1)))
(use-local-map "rmail-^x-commands")
(setq i 0)
(while (< i 128)
(local-bind-to-key "illegal-operation" i)
(setq i (+ i 1)))
(use-local-map "rmail-^z-commands")
(setq i 0)
(while (< i 128)
(local-bind-to-key "illegal-operation" i)
(setq i (+ i 1)))
(use-local-map "rmail-commands")
(setq i 0)
(while (< i 128)
(local-bind-to-key "illegal-operation" i)
(setq i (+ i 1)))
(local-bind-to-key "rmail-esc-commands" "\e")
(local-bind-to-key "rmail-^x-commands" '^x')
(local-bind-to-key "rmail-^z-commands" '^z')
; innocuous commands which we want to keep
(remove-local-binding '^a')
(remove-local-binding '^b')
(remove-local-binding '^e')
(remove-local-binding '^f')
(remove-local-binding '^l')
(remove-local-binding '^n')
(remove-local-binding '^p')
(remove-local-binding '^r')
(remove-local-binding '^s')
(remove-local-binding '^u')
(remove-local-binding '^v')
(remove-local-binding "\^X\^B")
(remove-local-binding "\^X\^F")
(remove-local-binding "\^X\^O")
(remove-local-binding "\^X\^S")
(remove-local-binding "\^X\^V")
(remove-local-binding "\^X\^X")
(remove-local-binding "\^X\^Z")
(remove-local-binding "\^X(")
(remove-local-binding "\^X)")
(remove-local-binding "\^X/")
(remove-local-binding "\^X0")
(remove-local-binding "\^X1")
(remove-local-binding "\^X2")
(remove-local-binding "\^X4")
(remove-local-binding "\^X<")
(remove-local-binding "\^X>")
(remove-local-binding "\^XB")
(remove-local-binding "\^XI")
(remove-local-binding "\^XM")
(remove-local-binding "\^X^")
(remove-local-binding "\^Xb")
(remove-local-binding "\^Xd")
(remove-local-binding "\^Xe")
(remove-local-binding "\^Xk")
(remove-local-binding "\^Xm")
(remove-local-binding "\^Xn")
(remove-local-binding "\^Xo")
(remove-local-binding "\^Xp")
(remove-local-binding "\^Xr")
(remove-local-binding "\^Xv")
(remove-local-binding "\^Z\^Z")
(remove-local-binding "\e\^@")
(remove-local-binding "\e\^B")
(remove-local-binding "\e\^F")
(remove-local-binding "\e\^H")
(remove-local-binding "\e\^R")
(remove-local-binding "\e\^S")
(remove-local-binding "\e\^V")
(remove-local-binding "\e\^Z")
(remove-local-binding "\e\e")
(remove-local-binding "\e!")
(remove-local-binding "\e#")
(remove-local-binding "\e%")
(remove-local-binding "\e-")
(remove-local-binding "\e/")
(remove-local-binding "\e0")
(remove-local-binding "\e1")
(remove-local-binding "\e2")
(remove-local-binding "\e3")
(remove-local-binding "\e4")
(remove-local-binding "\e5")
(remove-local-binding "\e6")
(remove-local-binding "\e7")
(remove-local-binding "\e8")
(remove-local-binding "\e9")
(remove-local-binding "\e<")
(remove-local-binding "\e=")
(remove-local-binding "\e>")
(remove-local-binding "\e?")
(remove-local-binding "\e@")
(remove-local-binding "\eG")
(remove-local-binding "\eM")
(remove-local-binding "\eZ")
(remove-local-binding "\eb")
(remove-local-binding "\ef")
(remove-local-binding "\eg")
(remove-local-binding "\eo")
(remove-local-binding "\es")
(remove-local-binding "\ev")
(remove-local-binding "\ex")
(remove-local-binding "\ez")
(remove-local-binding '^_')
(local-bind-to-key "meta-digit" "1")
(local-bind-to-key "meta-digit" "2")
(local-bind-to-key "meta-digit" "3")
(local-bind-to-key "meta-digit" "4")
(local-bind-to-key "meta-digit" "5")
(local-bind-to-key "meta-digit" "6")
(local-bind-to-key "meta-digit" "7")
(local-bind-to-key "meta-digit" "8")
(local-bind-to-key "meta-digit" "9")
(local-bind-to-key "meta-digit" "0")
(local-bind-to-key "meta-minus" "-")
(local-bind-to-key "rmail-previous-page" '^H')
(local-bind-to-key "rmail-next-page" ' ')
(local-bind-to-key "rmail-top-of-message" '^m')
(local-bind-to-key "rmail-top-of-message" '^j')
(local-bind-to-key "rmail-pass-headers" 't')
(local-bind-to-key "rmail-all-headers" 'T')
(local-bind-to-key "rmail-next-message" 'n')
(local-bind-to-key "rmail-previous-message" 'p')
(local-bind-to-key "next-window" 'o')
(local-bind-to-key "rmail-delete-message-next" 'd')
(local-bind-to-key "rmail-delete-message-previous" 'D')
(local-bind-to-key "rmail-delete-message" '^d')
(local-bind-to-key "rmail-undelete-message" 'u')
(local-bind-to-key "rmail-query-exit" "\^G")
(local-bind-to-key "rmail-help" '?')
(local-bind-to-key "Pop-level" 'q')
(local-bind-to-key "rmail-reply" 'r')
(local-bind-to-key "smail" 'm')
(local-bind-to-key "rmail-goto-message" 'g')
(local-bind-to-key "rmail-first-message" '<')
(local-bind-to-key "rmail-last-message" '>')
(local-bind-to-key "rmail-but-mark" '.')
(local-bind-to-key "rmail-skip" 's')
(local-bind-to-key "rmail-append" 'a')
(local-bind-to-key "execute-extended-command" ':')
(local-bind-to-key "rmail" "i"); incorporate new messages
)
| |
0b02c4f21c82410b96f2dfd14ce3313856c28fdad4beb708f95504ac5bd78b8b | RDTK/generator | package.lisp | ;;;; package.lisp --- Package definition for the resources module.
;;;;
Copyright ( C ) 2019 Jan Moringen
;;;;
Author : < >
(cl:defpackage #:build-generator.resources
(:use
#:cl
#:alexandria
#:more-conditions)
;; Conditions
(:export
#:entry-does-not-exist-error
#:name
#:group
#:group-does-not-exist-error
#:name
#:resources)
;; Name protocol
(:export
#:name)
;; Size protocol
(:export
#:octet-count)
;; Entry protocol
(:export
#:content
#:info)
;; Group protocol
(:export
#:parent
#:entries
also ` setf '
#:add-file)
;; Resources protocol
(:export
also ` setf '
#:ensure-datum)
;; Global resource group registry
(:export
#:make-group
#:find-group*))
| null | https://raw.githubusercontent.com/RDTK/generator/8d9e6e47776f2ccb7b5ed934337d2db50ecbe2f5/src/resources/package.lisp | lisp | package.lisp --- Package definition for the resources module.
Conditions
Name protocol
Size protocol
Entry protocol
Group protocol
Resources protocol
Global resource group registry | Copyright ( C ) 2019 Jan Moringen
Author : < >
(cl:defpackage #:build-generator.resources
(:use
#:cl
#:alexandria
#:more-conditions)
(:export
#:entry-does-not-exist-error
#:name
#:group
#:group-does-not-exist-error
#:name
#:resources)
(:export
#:name)
(:export
#:octet-count)
(:export
#:content
#:info)
(:export
#:parent
#:entries
also ` setf '
#:add-file)
(:export
also ` setf '
#:ensure-datum)
(:export
#:make-group
#:find-group*))
|
756e6780aa566486c8d5cc934fb81a25900c7c43c9ee32803e1a679a3e62b033 | finnishtransportagency/harja | kokonaishintaiset.cljs | (ns harja.tiedot.vesivaylat.urakka.toimenpiteet.kokonaishintaiset
(:require [reagent.core :refer [atom]]
[tuck.core :as tuck]
[harja.loki :refer [log error]]
[harja.domain.vesivaylat.toimenpide :as to]
[harja.domain.vesivaylat.vayla :as va]
[harja.domain.vesivaylat.turvalaite :as tu]
[harja.domain.vesivaylat.kiintio :as kiintio]
[harja.domain.urakka :as ur]
[cljs.core.async :as async :refer [<!]]
[harja.pvm :as pvm]
[harja.tiedot.urakka :as u]
[harja.tiedot.navigaatio :as nav]
[harja.ui.protokollat :as protokollat]
[harja.ui.viesti :as viesti]
[harja.asiakas.kommunikaatio :as k]
[harja.tyokalut.spec-apurit :as spec-apurit]
[cljs.spec.alpha :as s]
[harja.tiedot.vesivaylat.urakka.toimenpiteet.jaettu :as jaettu]
[harja.tyokalut.tuck :as tuck-tyokalut]
[reagent.core :as r])
(:require-macros [cljs.core.async.macros :refer [go]]
[reagent.ratom :refer [reaction]]))
(defonce tila
(atom {:valinnat {:urakka-id nil
:sopimus-id nil
:aikavali [nil nil]
:vaylatyyppi nil
:vayla nil
:tyolaji nil
:tyoluokka nil
:toimenpide nil
:vain-vikailmoitukset? false}
:nakymassa? false
:toimenpiteiden-haku-kaynnissa? false
:kiintioiden-haku-kaynnissa? false
:infolaatikko-nakyvissa {} ; tunniste -> boolean
:valittu-kiintio-id nil
:kiintioon-liittaminen-kaynnissa? false
:liitteen-lisays-kaynnissa? false
:liitteen-poisto-kaynnissa? false
:toimenpiteet nil
:turvalaitteet-kartalla nil
:karttataso-nakyvissa? false
:korostetut-turvalaitteet nil
:korostettu-kiintio false
:avoimet-kiintiot #{}}))
(defonce karttataso-kokonaishintaisten-turvalaitteet (r/cursor tila [:karttataso-nakyvissa?]))
(defonce turvalaitteet-kartalla (r/cursor tila [:turvalaitteet-kartalla]))
(def valinnat
(reaction
(when (:nakymassa? @tila)
{:urakka-id (:id @nav/valittu-urakka)
:sopimus-id (first @u/valittu-sopimusnumero)
:aikavali @u/valittu-aikavali})))
(def vaylahaku
(reify protokollat/Haku
(hae [_ teksti]
(go (let [vastaus (<! (k/post! :hae-vaylat {:hakuteksti teksti
:vaylatyyppi (get-in @tila [:valinnat :vaylatyyppi])}))]
vastaus)))))
(def turvalaitehaku
(reify protokollat/Haku
(hae [_ teksti]
(go (let [vastaus (<! (k/post! :hae-turvalaitteet-tekstilla {:hakuteksti teksti}))]
vastaus)))))
(defrecord Nakymassa? [nakymassa?])
(defrecord PaivitaValinnat [tiedot])
(defrecord HaeToimenpiteet [valinnat])
(defrecord ToimenpiteetHaettu [toimenpiteet])
(defrecord ToimenpiteetEiHaettu [virhe])
(defrecord HaeKiintiot [])
(defrecord KiintiotHaettu [kiintiot])
(defrecord KiintiotEiHaettu [virhe])
(defrecord ValitseKiintio [kiintio-id])
(defrecord SiirraValitutYksikkohintaisiin [])
(defrecord LiitaToimenpiteetKiintioon [])
(defrecord ToimenpiteetLiitettyKiintioon [vastaus])
(defrecord ToimenpiteetEiLiitettyKiintioon [])
(defrecord AvaaKiintio [id])
(defrecord SuljeKiintio [id])
(defrecord KorostaKiintioKartalla [kiintio])
(defrecord PoistaKiintionKorostus [])
(def valiaikainen-kiintio
{::kiintio/nimi "Kiintiöttömät"
::kiintio/id -1})
(defn kiintiottomat-toimenpiteet-valiaikaisiin-kiintioihin [toimenpiteet]
(for [to toimenpiteet]
(assoc to ::to/kiintio (or (::to/kiintio to)
valiaikainen-kiintio))))
(defn kiintio-korostettu? [kiintio {:keys [korostettu-kiintio]}]
(boolean
(when-not (false? korostettu-kiintio)
(= (::kiintio/id kiintio) korostettu-kiintio))))
(defn poista-kiintion-korostus [app]
(assoc app :korostettu-kiintio false))
(extend-protocol tuck/Event
Nakymassa?
(process-event [{nakymassa? :nakymassa?} app]
(assoc app :nakymassa? nakymassa?
:karttataso-nakyvissa? nakymassa?))
PaivitaValinnat
Valintojen päivittäminen laukaisee aina myös ( ellei ole ) ,
jotta näkymä pysyy synkassa valintojen kanssa
(process-event [{tiedot :tiedot} app]
(let [uudet-valinnat (merge (:valinnat app)
(select-keys tiedot jaettu/valintojen-avaimet))
haku (tuck/send-async! ->HaeToimenpiteet)]
(go (haku uudet-valinnat))
(assoc app :valinnat uudet-valinnat)))
SiirraValitutYksikkohintaisiin
(process-event [_ app]
(jaettu/siirra-valitut! :siirra-toimenpiteet-yksikkohintaisiin app))
HaeToimenpiteet
(process-event [{valinnat :valinnat} app]
(if (and (not (:toimenpiteiden-haku-kaynnissa? app))
(some? (:urakka-id valinnat)))
(-> app
(tuck-tyokalut/post! :hae-kokonaishintaiset-toimenpiteet
(jaettu/toimenpiteiden-hakukyselyn-argumentit valinnat)
{:onnistui ->ToimenpiteetHaettu
:epaonnistui ->ToimenpiteetEiHaettu})
(assoc :toimenpiteiden-haku-kaynnissa? true))
app))
ToimenpiteetHaettu
(process-event [{toimenpiteet :toimenpiteet} app]
(let [turvalaitteet-kartalle (tuck/send-async! jaettu/->HaeToimenpiteidenTurvalaitteetKartalle)]
(go (turvalaitteet-kartalle toimenpiteet))
(assoc app :toimenpiteet (-> toimenpiteet
jaettu/korosta-harjassa-luodut
kiintiottomat-toimenpiteet-valiaikaisiin-kiintioihin
jaettu/toimenpiteet-aikajarjestyksessa)
:toimenpiteiden-haku-kaynnissa? false)))
ToimenpiteetEiHaettu
(process-event [_ app]
(viesti/nayta! "Toimenpiteiden haku epäonnistui!" :danger)
(assoc app :toimenpiteiden-haku-kaynnissa? false))
HaeKiintiot
(process-event [_ app]
(if-not (:kiintioiden-haku-kaynnissa? app)
(-> app
(tuck-tyokalut/post! :hae-kiintiot
{::kiintio/urakka-id (get-in app [:valinnat :urakka-id])
::kiintio/sopimus-id (get-in app [:valinnat :sopimus-id])}
{:onnistui ->KiintiotHaettu
:epaonnistui ->KiintiotEiHaettu})
(assoc :kiintioiden-haku-kaynnissa? true))
app))
KiintiotHaettu
(process-event [{kiintiot :kiintiot} app]
(assoc app :kiintiot kiintiot
:kiintioiden-haku-kaynnissa? false))
KiintiotEiHaettu
(process-event [_ app]
(viesti/nayta! "Kiintiöiden haku epäonnistui!" :danger)
(assoc app :kiintioiden-haku-kaynnissa? false))
ValitseKiintio
(process-event [{kiintio-id :kiintio-id} app]
(assoc app :valittu-kiintio-id kiintio-id))
LiitaToimenpiteetKiintioon
(process-event [_ app]
(if-not (:kiintioon-liittaminen-kaynnissa? app)
(-> app
(tuck-tyokalut/post! :liita-toimenpiteet-kiintioon
{::kiintio/id (:valittu-kiintio-id app)
::kiintio/urakka-id (get-in app [:valinnat :urakka-id])
::to/idt (map ::to/id (jaettu/valitut-toimenpiteet (:toimenpiteet app)))}
{:onnistui ->ToimenpiteetLiitettyKiintioon
:epaonnistui ->ToimenpiteetEiLiitettyKiintioon})
(assoc :kiintioon-liittaminen-kaynnissa? true))
app))
ToimenpiteetLiitettyKiintioon
(process-event [{vastaus :vastaus} app]
(let [toimenpidehaku (tuck/send-async! ->HaeToimenpiteet)]
(viesti/nayta! (jaettu/toimenpiteiden-toiminto-suoritettu (count (::to/idt vastaus)) "liitetty") :success)
(go (toimenpidehaku (:valinnat app)))
(assoc app :kiintioon-liittaminen-kaynnissa? false
:valittu-kiintio-id nil)))
ToimenpiteetEiLiitettyKiintioon
(process-event [_ app]
(viesti/nayta! "Toimenpiteiden liittäminen kiintiöön epäonnistui!" :danger)
(assoc app :kiintioon-liittaminen-kaynnissa? false))
AvaaKiintio
(process-event [{id :id} app]
(if (nil? (:avoimet-kiintiot app))
(assoc app :avoimet-kiintiot #{id})
(update app :avoimet-kiintiot conj id)))
SuljeKiintio
(process-event [{id :id} app]
(if (nil? (:avoimet-kiintiot app))
app
(update app :avoimet-kiintiot disj id)))
KorostaKiintioKartalla
(process-event [{kiintio :kiintio} {:keys [toimenpiteet] :as app}]
(let [korostettavat-turvalaitteet (->>
toimenpiteet
(filter #(= (get-in % [::to/kiintio ::kiintio/id]) (::kiintio/id kiintio)))
(map (comp ::tu/turvalaitenro ::to/turvalaite))
(into #{}))]
(-> (jaettu/korosta-kartalla korostettavat-turvalaitteet app)
(assoc :korostettu-kiintio (::kiintio/id kiintio)))))
PoistaKiintionKorostus
(process-event [_ app]
(->> app
(poista-kiintion-korostus)
(jaettu/korosta-kartalla nil))))
| null | https://raw.githubusercontent.com/finnishtransportagency/harja/488b1e096f0611e175221d74ba4f2ffed6bea8f1/src/cljs/harja/tiedot/vesivaylat/urakka/toimenpiteet/kokonaishintaiset.cljs | clojure | tunniste -> boolean | (ns harja.tiedot.vesivaylat.urakka.toimenpiteet.kokonaishintaiset
(:require [reagent.core :refer [atom]]
[tuck.core :as tuck]
[harja.loki :refer [log error]]
[harja.domain.vesivaylat.toimenpide :as to]
[harja.domain.vesivaylat.vayla :as va]
[harja.domain.vesivaylat.turvalaite :as tu]
[harja.domain.vesivaylat.kiintio :as kiintio]
[harja.domain.urakka :as ur]
[cljs.core.async :as async :refer [<!]]
[harja.pvm :as pvm]
[harja.tiedot.urakka :as u]
[harja.tiedot.navigaatio :as nav]
[harja.ui.protokollat :as protokollat]
[harja.ui.viesti :as viesti]
[harja.asiakas.kommunikaatio :as k]
[harja.tyokalut.spec-apurit :as spec-apurit]
[cljs.spec.alpha :as s]
[harja.tiedot.vesivaylat.urakka.toimenpiteet.jaettu :as jaettu]
[harja.tyokalut.tuck :as tuck-tyokalut]
[reagent.core :as r])
(:require-macros [cljs.core.async.macros :refer [go]]
[reagent.ratom :refer [reaction]]))
(defonce tila
(atom {:valinnat {:urakka-id nil
:sopimus-id nil
:aikavali [nil nil]
:vaylatyyppi nil
:vayla nil
:tyolaji nil
:tyoluokka nil
:toimenpide nil
:vain-vikailmoitukset? false}
:nakymassa? false
:toimenpiteiden-haku-kaynnissa? false
:kiintioiden-haku-kaynnissa? false
:valittu-kiintio-id nil
:kiintioon-liittaminen-kaynnissa? false
:liitteen-lisays-kaynnissa? false
:liitteen-poisto-kaynnissa? false
:toimenpiteet nil
:turvalaitteet-kartalla nil
:karttataso-nakyvissa? false
:korostetut-turvalaitteet nil
:korostettu-kiintio false
:avoimet-kiintiot #{}}))
(defonce karttataso-kokonaishintaisten-turvalaitteet (r/cursor tila [:karttataso-nakyvissa?]))
(defonce turvalaitteet-kartalla (r/cursor tila [:turvalaitteet-kartalla]))
(def valinnat
(reaction
(when (:nakymassa? @tila)
{:urakka-id (:id @nav/valittu-urakka)
:sopimus-id (first @u/valittu-sopimusnumero)
:aikavali @u/valittu-aikavali})))
(def vaylahaku
(reify protokollat/Haku
(hae [_ teksti]
(go (let [vastaus (<! (k/post! :hae-vaylat {:hakuteksti teksti
:vaylatyyppi (get-in @tila [:valinnat :vaylatyyppi])}))]
vastaus)))))
(def turvalaitehaku
(reify protokollat/Haku
(hae [_ teksti]
(go (let [vastaus (<! (k/post! :hae-turvalaitteet-tekstilla {:hakuteksti teksti}))]
vastaus)))))
(defrecord Nakymassa? [nakymassa?])
(defrecord PaivitaValinnat [tiedot])
(defrecord HaeToimenpiteet [valinnat])
(defrecord ToimenpiteetHaettu [toimenpiteet])
(defrecord ToimenpiteetEiHaettu [virhe])
(defrecord HaeKiintiot [])
(defrecord KiintiotHaettu [kiintiot])
(defrecord KiintiotEiHaettu [virhe])
(defrecord ValitseKiintio [kiintio-id])
(defrecord SiirraValitutYksikkohintaisiin [])
(defrecord LiitaToimenpiteetKiintioon [])
(defrecord ToimenpiteetLiitettyKiintioon [vastaus])
(defrecord ToimenpiteetEiLiitettyKiintioon [])
(defrecord AvaaKiintio [id])
(defrecord SuljeKiintio [id])
(defrecord KorostaKiintioKartalla [kiintio])
(defrecord PoistaKiintionKorostus [])
(def valiaikainen-kiintio
{::kiintio/nimi "Kiintiöttömät"
::kiintio/id -1})
(defn kiintiottomat-toimenpiteet-valiaikaisiin-kiintioihin [toimenpiteet]
(for [to toimenpiteet]
(assoc to ::to/kiintio (or (::to/kiintio to)
valiaikainen-kiintio))))
(defn kiintio-korostettu? [kiintio {:keys [korostettu-kiintio]}]
(boolean
(when-not (false? korostettu-kiintio)
(= (::kiintio/id kiintio) korostettu-kiintio))))
(defn poista-kiintion-korostus [app]
(assoc app :korostettu-kiintio false))
(extend-protocol tuck/Event
Nakymassa?
(process-event [{nakymassa? :nakymassa?} app]
(assoc app :nakymassa? nakymassa?
:karttataso-nakyvissa? nakymassa?))
PaivitaValinnat
Valintojen päivittäminen laukaisee aina myös ( ellei ole ) ,
jotta näkymä pysyy synkassa valintojen kanssa
(process-event [{tiedot :tiedot} app]
(let [uudet-valinnat (merge (:valinnat app)
(select-keys tiedot jaettu/valintojen-avaimet))
haku (tuck/send-async! ->HaeToimenpiteet)]
(go (haku uudet-valinnat))
(assoc app :valinnat uudet-valinnat)))
SiirraValitutYksikkohintaisiin
(process-event [_ app]
(jaettu/siirra-valitut! :siirra-toimenpiteet-yksikkohintaisiin app))
HaeToimenpiteet
(process-event [{valinnat :valinnat} app]
(if (and (not (:toimenpiteiden-haku-kaynnissa? app))
(some? (:urakka-id valinnat)))
(-> app
(tuck-tyokalut/post! :hae-kokonaishintaiset-toimenpiteet
(jaettu/toimenpiteiden-hakukyselyn-argumentit valinnat)
{:onnistui ->ToimenpiteetHaettu
:epaonnistui ->ToimenpiteetEiHaettu})
(assoc :toimenpiteiden-haku-kaynnissa? true))
app))
ToimenpiteetHaettu
(process-event [{toimenpiteet :toimenpiteet} app]
(let [turvalaitteet-kartalle (tuck/send-async! jaettu/->HaeToimenpiteidenTurvalaitteetKartalle)]
(go (turvalaitteet-kartalle toimenpiteet))
(assoc app :toimenpiteet (-> toimenpiteet
jaettu/korosta-harjassa-luodut
kiintiottomat-toimenpiteet-valiaikaisiin-kiintioihin
jaettu/toimenpiteet-aikajarjestyksessa)
:toimenpiteiden-haku-kaynnissa? false)))
ToimenpiteetEiHaettu
(process-event [_ app]
(viesti/nayta! "Toimenpiteiden haku epäonnistui!" :danger)
(assoc app :toimenpiteiden-haku-kaynnissa? false))
HaeKiintiot
(process-event [_ app]
(if-not (:kiintioiden-haku-kaynnissa? app)
(-> app
(tuck-tyokalut/post! :hae-kiintiot
{::kiintio/urakka-id (get-in app [:valinnat :urakka-id])
::kiintio/sopimus-id (get-in app [:valinnat :sopimus-id])}
{:onnistui ->KiintiotHaettu
:epaonnistui ->KiintiotEiHaettu})
(assoc :kiintioiden-haku-kaynnissa? true))
app))
KiintiotHaettu
(process-event [{kiintiot :kiintiot} app]
(assoc app :kiintiot kiintiot
:kiintioiden-haku-kaynnissa? false))
KiintiotEiHaettu
(process-event [_ app]
(viesti/nayta! "Kiintiöiden haku epäonnistui!" :danger)
(assoc app :kiintioiden-haku-kaynnissa? false))
ValitseKiintio
(process-event [{kiintio-id :kiintio-id} app]
(assoc app :valittu-kiintio-id kiintio-id))
LiitaToimenpiteetKiintioon
(process-event [_ app]
(if-not (:kiintioon-liittaminen-kaynnissa? app)
(-> app
(tuck-tyokalut/post! :liita-toimenpiteet-kiintioon
{::kiintio/id (:valittu-kiintio-id app)
::kiintio/urakka-id (get-in app [:valinnat :urakka-id])
::to/idt (map ::to/id (jaettu/valitut-toimenpiteet (:toimenpiteet app)))}
{:onnistui ->ToimenpiteetLiitettyKiintioon
:epaonnistui ->ToimenpiteetEiLiitettyKiintioon})
(assoc :kiintioon-liittaminen-kaynnissa? true))
app))
ToimenpiteetLiitettyKiintioon
(process-event [{vastaus :vastaus} app]
(let [toimenpidehaku (tuck/send-async! ->HaeToimenpiteet)]
(viesti/nayta! (jaettu/toimenpiteiden-toiminto-suoritettu (count (::to/idt vastaus)) "liitetty") :success)
(go (toimenpidehaku (:valinnat app)))
(assoc app :kiintioon-liittaminen-kaynnissa? false
:valittu-kiintio-id nil)))
ToimenpiteetEiLiitettyKiintioon
(process-event [_ app]
(viesti/nayta! "Toimenpiteiden liittäminen kiintiöön epäonnistui!" :danger)
(assoc app :kiintioon-liittaminen-kaynnissa? false))
AvaaKiintio
(process-event [{id :id} app]
(if (nil? (:avoimet-kiintiot app))
(assoc app :avoimet-kiintiot #{id})
(update app :avoimet-kiintiot conj id)))
SuljeKiintio
(process-event [{id :id} app]
(if (nil? (:avoimet-kiintiot app))
app
(update app :avoimet-kiintiot disj id)))
KorostaKiintioKartalla
(process-event [{kiintio :kiintio} {:keys [toimenpiteet] :as app}]
(let [korostettavat-turvalaitteet (->>
toimenpiteet
(filter #(= (get-in % [::to/kiintio ::kiintio/id]) (::kiintio/id kiintio)))
(map (comp ::tu/turvalaitenro ::to/turvalaite))
(into #{}))]
(-> (jaettu/korosta-kartalla korostettavat-turvalaitteet app)
(assoc :korostettu-kiintio (::kiintio/id kiintio)))))
PoistaKiintionKorostus
(process-event [_ app]
(->> app
(poista-kiintion-korostus)
(jaettu/korosta-kartalla nil))))
|
394fc266d425c32211f8073c9f3a42dab5ed1ae31429c70fe950ac076cbbb2cc | marick/fp-oo | ts_primes.clj | (ns solutions.ts-primes
(:use midje.sweet))
(load-file "solutions/primes.clj")
Exercise 1
(fact
(multiples 2)
=> [4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50 52 54
56 58 60 62 64 66 68 70 72 74 76 78 80 82 84 86 88 90 92 94 96 98 100]
(multiples 3)
=> [6 9 12 15 18 21 24 27 30 33 36 39 42 45 48 51 54 57 60 63 66 69 72 75 78 81
84 87 90 93 96 99])
Exercise 2
(fact
((set nonprimes) 4) => truthy
((set nonprimes) 5) => falsey
((set nonprimes) 100) => truthy)
Exercise 3
(fact
primes => [2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97])
| null | https://raw.githubusercontent.com/marick/fp-oo/434937826d794d6fe02b3e9a62cf5b4fbc314412/test/solutions/ts_primes.clj | clojure | (ns solutions.ts-primes
(:use midje.sweet))
(load-file "solutions/primes.clj")
Exercise 1
(fact
(multiples 2)
=> [4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50 52 54
56 58 60 62 64 66 68 70 72 74 76 78 80 82 84 86 88 90 92 94 96 98 100]
(multiples 3)
=> [6 9 12 15 18 21 24 27 30 33 36 39 42 45 48 51 54 57 60 63 66 69 72 75 78 81
84 87 90 93 96 99])
Exercise 2
(fact
((set nonprimes) 4) => truthy
((set nonprimes) 5) => falsey
((set nonprimes) 100) => truthy)
Exercise 3
(fact
primes => [2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97])
| |
8a20667b88b2876cece748444a92bef172b4c7a9f76919c6d1928e991c9f0ffc | input-output-hk/ouroboros-network | ChainSel.hs | {-# LANGUAGE DeriveAnyClass #-}
# LANGUAGE DeriveGeneric #
{-# LANGUAGE EmptyCase #-}
{-# LANGUAGE FlexibleContexts #-}
# LANGUAGE GADTs #
# LANGUAGE LambdaCase #
# LANGUAGE PolyKinds #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeApplications #
-- | Infrastructure for doing chain selection across eras
module Ouroboros.Consensus.HardFork.Combinator.Protocol.ChainSel (
AcrossEraSelection (..)
, WithBlockNo (..)
, acrossEraSelection
, mapWithBlockNo
) where
import Data.Kind (Type)
import Data.SOP.Strict
import Ouroboros.Consensus.Block
import Ouroboros.Consensus.Protocol.Abstract
import Ouroboros.Consensus.TypeFamilyWrappers
import GHC.Generics (Generic)
import NoThunks.Class (NoThunks)
import Ouroboros.Consensus.HardFork.Combinator.Abstract.SingleEraBlock
import Ouroboros.Consensus.HardFork.Combinator.Util.Tails (Tails (..))
{-------------------------------------------------------------------------------
Configuration
-------------------------------------------------------------------------------}
data AcrossEraSelection :: Type -> Type -> Type where
-- | Just compare block numbers
--
This is a useful default when two eras run totally different consensus
-- protocols, and we just want to choose the longer chain.
CompareBlockNo :: AcrossEraSelection x y
| Two eras using the same ' SelectView ' . In this case , we can just compare
-- chains even across eras, as the chain ordering is fully captured by
' SelectView ' and its ' Ord ' instance .
CompareSameSelectView ::
SelectView (BlockProtocol x) ~ SelectView (BlockProtocol y)
=> AcrossEraSelection x y
------------------------------------------------------------------------------
Compare two eras
------------------------------------------------------------------------------
Compare two eras
-------------------------------------------------------------------------------}
acrossEras ::
forall blk blk'. SingleEraBlock blk
=> WithBlockNo WrapSelectView blk
-> WithBlockNo WrapSelectView blk'
-> AcrossEraSelection blk blk'
-> Ordering
acrossEras (WithBlockNo bnoL (WrapSelectView l))
(WithBlockNo bnoR (WrapSelectView r)) = \case
CompareBlockNo -> compare bnoL bnoR
CompareSameSelectView -> compare l r
acrossEraSelection ::
All SingleEraBlock xs
=> Tails AcrossEraSelection xs
-> WithBlockNo (NS WrapSelectView) xs
-> WithBlockNo (NS WrapSelectView) xs
-> Ordering
acrossEraSelection = \ffs l r ->
goLeft ffs (distribBlockNo l, distribBlockNo r)
where
goLeft ::
All SingleEraBlock xs
=> Tails AcrossEraSelection xs
-> ( NS (WithBlockNo WrapSelectView) xs
, NS (WithBlockNo WrapSelectView) xs
)
-> Ordering
goLeft TNil = \(a, _) -> case a of {}
goLeft (TCons fs ffs') = \case
(Z a, Z b) -> compare (dropBlockNo a) (dropBlockNo b)
(Z a, S b) -> goRight a fs b
(S a, Z b) -> invert $ goRight b fs a
(S a, S b) -> goLeft ffs' (a, b)
goRight ::
forall x xs. (SingleEraBlock x, All SingleEraBlock xs)
=> WithBlockNo WrapSelectView x
-> NP (AcrossEraSelection x) xs
-> NS (WithBlockNo WrapSelectView) xs
-> Ordering
goRight a = go
where
go :: forall xs'. All SingleEraBlock xs'
=> NP (AcrossEraSelection x) xs'
-> NS (WithBlockNo WrapSelectView) xs'
-> Ordering
go Nil b = case b of {}
go (f :* _) (Z b) = acrossEras a b f
go (_ :* fs) (S b) = go fs b
{-------------------------------------------------------------------------------
WithBlockNo
-------------------------------------------------------------------------------}
data WithBlockNo (f :: k -> Type) (a :: k) = WithBlockNo {
getBlockNo :: BlockNo
, dropBlockNo :: f a
}
deriving (Show, Eq, Generic, NoThunks)
mapWithBlockNo :: (f x -> g y) -> WithBlockNo f x -> WithBlockNo g y
mapWithBlockNo f (WithBlockNo bno fx) = WithBlockNo bno (f fx)
distribBlockNo :: SListI xs => WithBlockNo (NS f) xs -> NS (WithBlockNo f) xs
distribBlockNo (WithBlockNo b ns) = hmap (WithBlockNo b) ns
{-------------------------------------------------------------------------------
Auxiliary
-------------------------------------------------------------------------------}
invert :: Ordering -> Ordering
invert LT = GT
invert GT = LT
invert EQ = EQ
| null | https://raw.githubusercontent.com/input-output-hk/ouroboros-network/0aff5cf05f09bb56d4ac40f0090c636d5893dfb2/ouroboros-consensus/src/Ouroboros/Consensus/HardFork/Combinator/Protocol/ChainSel.hs | haskell | # LANGUAGE DeriveAnyClass #
# LANGUAGE EmptyCase #
# LANGUAGE FlexibleContexts #
| Infrastructure for doing chain selection across eras
------------------------------------------------------------------------------
Configuration
------------------------------------------------------------------------------
| Just compare block numbers
protocols, and we just want to choose the longer chain.
chains even across eras, as the chain ordering is fully captured by
----------------------------------------------------------------------------
----------------------------------------------------------------------------
-----------------------------------------------------------------------------}
------------------------------------------------------------------------------
WithBlockNo
------------------------------------------------------------------------------
------------------------------------------------------------------------------
Auxiliary
------------------------------------------------------------------------------ | # LANGUAGE DeriveGeneric #
# LANGUAGE GADTs #
# LANGUAGE LambdaCase #
# LANGUAGE PolyKinds #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeApplications #
module Ouroboros.Consensus.HardFork.Combinator.Protocol.ChainSel (
AcrossEraSelection (..)
, WithBlockNo (..)
, acrossEraSelection
, mapWithBlockNo
) where
import Data.Kind (Type)
import Data.SOP.Strict
import Ouroboros.Consensus.Block
import Ouroboros.Consensus.Protocol.Abstract
import Ouroboros.Consensus.TypeFamilyWrappers
import GHC.Generics (Generic)
import NoThunks.Class (NoThunks)
import Ouroboros.Consensus.HardFork.Combinator.Abstract.SingleEraBlock
import Ouroboros.Consensus.HardFork.Combinator.Util.Tails (Tails (..))
data AcrossEraSelection :: Type -> Type -> Type where
This is a useful default when two eras run totally different consensus
CompareBlockNo :: AcrossEraSelection x y
| Two eras using the same ' SelectView ' . In this case , we can just compare
' SelectView ' and its ' Ord ' instance .
CompareSameSelectView ::
SelectView (BlockProtocol x) ~ SelectView (BlockProtocol y)
=> AcrossEraSelection x y
Compare two eras
Compare two eras
acrossEras ::
forall blk blk'. SingleEraBlock blk
=> WithBlockNo WrapSelectView blk
-> WithBlockNo WrapSelectView blk'
-> AcrossEraSelection blk blk'
-> Ordering
acrossEras (WithBlockNo bnoL (WrapSelectView l))
(WithBlockNo bnoR (WrapSelectView r)) = \case
CompareBlockNo -> compare bnoL bnoR
CompareSameSelectView -> compare l r
acrossEraSelection ::
All SingleEraBlock xs
=> Tails AcrossEraSelection xs
-> WithBlockNo (NS WrapSelectView) xs
-> WithBlockNo (NS WrapSelectView) xs
-> Ordering
acrossEraSelection = \ffs l r ->
goLeft ffs (distribBlockNo l, distribBlockNo r)
where
goLeft ::
All SingleEraBlock xs
=> Tails AcrossEraSelection xs
-> ( NS (WithBlockNo WrapSelectView) xs
, NS (WithBlockNo WrapSelectView) xs
)
-> Ordering
goLeft TNil = \(a, _) -> case a of {}
goLeft (TCons fs ffs') = \case
(Z a, Z b) -> compare (dropBlockNo a) (dropBlockNo b)
(Z a, S b) -> goRight a fs b
(S a, Z b) -> invert $ goRight b fs a
(S a, S b) -> goLeft ffs' (a, b)
goRight ::
forall x xs. (SingleEraBlock x, All SingleEraBlock xs)
=> WithBlockNo WrapSelectView x
-> NP (AcrossEraSelection x) xs
-> NS (WithBlockNo WrapSelectView) xs
-> Ordering
goRight a = go
where
go :: forall xs'. All SingleEraBlock xs'
=> NP (AcrossEraSelection x) xs'
-> NS (WithBlockNo WrapSelectView) xs'
-> Ordering
go Nil b = case b of {}
go (f :* _) (Z b) = acrossEras a b f
go (_ :* fs) (S b) = go fs b
data WithBlockNo (f :: k -> Type) (a :: k) = WithBlockNo {
getBlockNo :: BlockNo
, dropBlockNo :: f a
}
deriving (Show, Eq, Generic, NoThunks)
mapWithBlockNo :: (f x -> g y) -> WithBlockNo f x -> WithBlockNo g y
mapWithBlockNo f (WithBlockNo bno fx) = WithBlockNo bno (f fx)
distribBlockNo :: SListI xs => WithBlockNo (NS f) xs -> NS (WithBlockNo f) xs
distribBlockNo (WithBlockNo b ns) = hmap (WithBlockNo b) ns
invert :: Ordering -> Ordering
invert LT = GT
invert GT = LT
invert EQ = EQ
|
c32a061316be73e67747a57a29b68fb80f69e5ef5d2ecd6240d33de6bb1be74d | kendroe/CoqRewriter | lex.mli | * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
*
* REWRITELIB
*
* lex.mli
*
* Signature for lexical analysis module
*
* ( C ) 2017 ,
*
* This program is free software : you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation , either version 3 of the License , or
* ( at your option ) any later version .
*
* This program is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
* GNU General Public License for more details .
*
* You should have received a copy of the GNU General Public License
* along with this program . If not , see < / > .
* will be provided when the work is complete .
*
* For a commercial license , contact Roe Mobile Development , LLC at
*
*
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
*
* REWRITELIB
*
* lex.mli
*
* Signature for lexical analysis module
*
* (C) 2017, Kenneth Roe
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see </>.
* will be provided when the work is complete.
*
* For a commercial license, contact Roe Mobile Development, LLC at
*
*
*****************************************************************************)
type token = ID of string
| SYMBOL of string
| QUOTE of string
| C_QUOTE of char
| NUMBER of int
| RAT of int * int
| SPECIAL of string
| TVAR of string * string * int ;;
exception Failure of token list ;;
val tokenize_rc: string -> string -> (token * string * int * int * int * int) list ;;
val tokenize: string -> token list ;;
val print_tokens: (token list) -> string ;;
val print_tokens2: ((token * string * int * int * int * int) list) -> string ;;
| null | https://raw.githubusercontent.com/kendroe/CoqRewriter/ddf5dc2ea51105d5a2dc87c99f0d364cf2b8ebf5/plugin/src/lex.mli | ocaml | * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
*
* REWRITELIB
*
* lex.mli
*
* Signature for lexical analysis module
*
* ( C ) 2017 ,
*
* This program is free software : you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation , either version 3 of the License , or
* ( at your option ) any later version .
*
* This program is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
* GNU General Public License for more details .
*
* You should have received a copy of the GNU General Public License
* along with this program . If not , see < / > .
* will be provided when the work is complete .
*
* For a commercial license , contact Roe Mobile Development , LLC at
*
*
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
*
* REWRITELIB
*
* lex.mli
*
* Signature for lexical analysis module
*
* (C) 2017, Kenneth Roe
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see </>.
* will be provided when the work is complete.
*
* For a commercial license, contact Roe Mobile Development, LLC at
*
*
*****************************************************************************)
type token = ID of string
| SYMBOL of string
| QUOTE of string
| C_QUOTE of char
| NUMBER of int
| RAT of int * int
| SPECIAL of string
| TVAR of string * string * int ;;
exception Failure of token list ;;
val tokenize_rc: string -> string -> (token * string * int * int * int * int) list ;;
val tokenize: string -> token list ;;
val print_tokens: (token list) -> string ;;
val print_tokens2: ((token * string * int * int * int * int) list) -> string ;;
| |
17528f6ee63d36d9c0d5b9608c0e5c48e6d9b9c871b089a1ac83b3be824699ba | JHU-PL-Lab/jaylang | uid.mli | open Batteries;;
(** The abstract type of UIDs in the system. *)
type uid
* A function which returns a fresh UID .
val next_uid : unit -> uid
(** A function to compare UIDs. *)
val compare_uid : uid -> uid -> int
(** A function to check UIDs for equality. *)
val equal_uid : uid -> uid -> bool
(** A pretty-printer for UIDs. *)
val pp_uid : Format.formatter -> uid -> unit
* A function to convert a UID to a string .
val show_uid : uid -> string
(** An ordering module for UIDs. *)
module Uid_ord : Interfaces.OrderedType with type t = uid
(** A dictionary data structure for UIDs. *)
module Uid_map : BatMap.S with type key = uid
| null | https://raw.githubusercontent.com/JHU-PL-Lab/jaylang/484b3876986a515fb57b11768a1b3b50418cde0c/src/ddpa-utils/uid.mli | ocaml | * The abstract type of UIDs in the system.
* A function to compare UIDs.
* A function to check UIDs for equality.
* A pretty-printer for UIDs.
* An ordering module for UIDs.
* A dictionary data structure for UIDs. | open Batteries;;
type uid
* A function which returns a fresh UID .
val next_uid : unit -> uid
val compare_uid : uid -> uid -> int
val equal_uid : uid -> uid -> bool
val pp_uid : Format.formatter -> uid -> unit
* A function to convert a UID to a string .
val show_uid : uid -> string
module Uid_ord : Interfaces.OrderedType with type t = uid
module Uid_map : BatMap.S with type key = uid
|
6820c4062128e4fea1119303c54728b876779c82cf04c995a8cfe52fb44e4b18 | footprintanalytics/footprint-web | add_implicit_clauses.clj | (ns metabase.query-processor.middleware.add-implicit-clauses
"Middlware for adding an implicit `:fields` and `:order-by` clauses to certain queries."
(:require [clojure.tools.logging :as log]
[clojure.walk :as walk]
[metabase.mbql.schema :as mbql.s]
[metabase.mbql.util :as mbql.u]
[metabase.models.field :refer [Field]]
[metabase.models.table :as table]
[metabase.query-processor.error-type :as qp.error-type]
[metabase.query-processor.store :as qp.store]
[metabase.types :as types]
[metabase.util :as u]
[metabase.util.i18n :refer [trs tru]]
[metabase.util.schema :as su]
[schema.core :as s]
[toucan.db :as db]))
;;; +----------------------------------------------------------------------------------------------------------------+
;;; | Add Implicit Fields |
;;; +----------------------------------------------------------------------------------------------------------------+
(defn- table->sorted-fields*
[table-id]
(db/select [Field :id :base_type :effective_type :coercion_strategy :semantic_type]
:table_id table-id
:active true
:visibility_type [:not-in ["sensitive" "retired"]]
:parent_id nil
{:order-by table/field-order-rule}))
(defn- table->sorted-fields
"Return a sequence of all Fields for table that we'd normally include in the equivalent of a `SELECT *`."
[table-id]
(if (qp.store/initialized?)
cache duplicate calls to this function in the same QP run .
(qp.store/cached-fn [::table-sorted-fields (u/the-id table-id)] #(table->sorted-fields* table-id))
if QP store is not initialized do n't try to cache the value ( this is mainly for the benefit of tests and code
that uses this outside of the normal QP execution context )
(table->sorted-fields* table-id)))
(s/defn sorted-implicit-fields-for-table :- mbql.s/Fields
"For use when adding implicit Field IDs to a query. Return a sequence of field clauses, sorted by the rules listed
in [[metabase.query-processor.sort]], for all the Fields in a given Table."
[table-id :- su/IntGreaterThanZero]
(let [fields (table->sorted-fields table-id)]
(when (empty? fields)
(throw (ex-info (tru "No fields found for table {0}." (pr-str (:name (qp.store/table table-id))))
{:table-id table-id
:type qp.error-type/invalid-query})))
(mapv
(fn [field]
implicit datetime get bucketing of ` : default ` . This is so other middleware does n't try to give it
;; default bucketing of `:day`
[:field (u/the-id field) (when (types/temporal-field? field)
{:temporal-unit :default})])
fields)))
(s/defn ^:private source-metadata->fields :- mbql.s/Fields
"Get implicit Fields for a query with a `:source-query` that has `source-metadata`."
[source-metadata :- (su/non-empty [mbql.s/SourceQueryMetadata])]
(distinct
(for [{field-name :name, base-type :base_type, field-id :id, field-ref :field_ref} source-metadata]
;; return field-ref directly if it's a `:field` clause already. It might include important info such as
` : join - alias ` or ` : source - field ` . Remove binning / temporal bucketing info . The Field should already be getting
;; bucketed in the source query; don't need to apply bucketing again in the parent query.
(or (some-> (mbql.u/match-one field-ref :field)
(mbql.u/update-field-options dissoc :binning :temporal-unit))
otherwise construct a field reference that can be used to refer to this Field .
(if field-id
If we have a Field ID , return a ` : field ` ( i d ) clause
[:field field-id nil]
otherwise return a ` : field ` ( name ) clause , e.g. for a Field that 's the result of an aggregation or
;; expression
[:field field-name {:base-type base-type}])))))
(s/defn ^:private should-add-implicit-fields?
"Whether we should add implicit Fields to this query. True if all of the following are true:
* The query has either a `:source-table`, *or* a `:source-query` with `:source-metadata` for it
* The query has no breakouts
* The query has no aggregations"
[{:keys [fields source-table source-query source-metadata]
breakouts :breakout
aggregations :aggregation} :- mbql.s/MBQLQuery]
;; if someone is trying to include an explicit `source-query` but isn't specifiying `source-metadata` warn that
;; there's nothing we can do to help them
(when (and source-query
(empty? source-metadata)
(qp.store/initialized?))
by ' caching ' this result , this log message will only be shown once for a given QP run .
(qp.store/cached [::should-add-implicit-fields-warning]
(log/warn (str (trs "Warning: cannot determine fields for an explicit `source-query` unless you also include `source-metadata`.")
\newline
(trs "Query: {0}" (u/pprint-to-str source-query))))))
;; Determine whether we can add the implicit `:fields`
(and (or source-table
(and source-query (seq source-metadata)))
(every? empty? [aggregations breakouts fields])))
(s/defn ^:private add-implicit-fields
"For MBQL queries with no aggregation, add a `:fields` key containing all Fields in the source Table as well as any
expressions definied in the query."
[{source-table-id :source-table, :keys [expressions source-metadata], :as inner-query}]
(if-not (should-add-implicit-fields? inner-query)
inner-query
(let [fields (if source-table-id
(sorted-implicit-fields-for-table source-table-id)
(source-metadata->fields source-metadata))
;; generate a new expression ref clause for each expression defined in the query.
expressions (for [[expression-name] expressions]
;; TODO - we need to wrap this in `u/qualified-name` because `:expressions` uses
;; keywords as keys. We can remove this call once we fix that.
[:expression (u/qualified-name expression-name)])]
if the Table has no , throw an Exception , because there is no way for us to proceed
(when-not (seq fields)
(throw (ex-info (tru "Table ''{0}'' has no Fields associated with it." (:name (qp.store/table source-table-id)))
{:type qp.error-type/invalid-query})))
;; add the fields & expressions under the `:fields` clause
(assoc inner-query :fields (vec (concat fields expressions))))))
;;; +----------------------------------------------------------------------------------------------------------------+
;;; | Add Implicit Breakout Order Bys |
;;; +----------------------------------------------------------------------------------------------------------------+
(s/defn ^:private add-implicit-breakout-order-by :- mbql.s/MBQLQuery
"Fields specified in `breakout` should add an implicit ascending `order-by` subclause *unless* that Field is already
*explicitly* referenced in `order-by`."
[{breakouts :breakout, :as inner-query} :- mbql.s/MBQLQuery]
Add a new [: asc < breakout - field > ] clause for each breakout . The cool thing is ` add - order - by - clause ` will
automatically ignore new ones that are reference already in the order - by clause
(reduce mbql.u/add-order-by-clause inner-query (for [breakout breakouts]
[:asc breakout])))
;;; +----------------------------------------------------------------------------------------------------------------+
;;; | Middleware |
;;; +----------------------------------------------------------------------------------------------------------------+
(defn add-implicit-mbql-clauses
"Add implicit clauses such as `:fields` and `:order-by` to an 'inner' MBQL query as needed."
[form]
(walk/postwalk
(fn [form]
;; add implicit clauses to any 'inner query', except for joins themselves (we should still add implicit clauses
;; like `:fields` to source queries *inside* joins)
(if (and (map? form)
((some-fn :source-table :source-query) form)
(not (:condition form)))
(-> form add-implicit-breakout-order-by add-implicit-fields)
form))
form))
(defn add-implicit-clauses
"Add an implicit `fields` clause to queries with no `:aggregation`, `breakout`, or explicit `:fields` clauses.
Add implicit `:order-by` clauses for fields specified in a `:breakout`."
[{query-type :type, :as query}]
(if (= query-type :native)
query
(update query :query add-implicit-mbql-clauses)))
| null | https://raw.githubusercontent.com/footprintanalytics/footprint-web/d3090d943dd9fcea493c236f79e7ef8a36ae17fc/src/metabase/query_processor/middleware/add_implicit_clauses.clj | clojure | +----------------------------------------------------------------------------------------------------------------+
| Add Implicit Fields |
+----------------------------------------------------------------------------------------------------------------+
default bucketing of `:day`
return field-ref directly if it's a `:field` clause already. It might include important info such as
bucketed in the source query; don't need to apply bucketing again in the parent query.
expression
if someone is trying to include an explicit `source-query` but isn't specifiying `source-metadata` warn that
there's nothing we can do to help them
Determine whether we can add the implicit `:fields`
generate a new expression ref clause for each expression defined in the query.
TODO - we need to wrap this in `u/qualified-name` because `:expressions` uses
keywords as keys. We can remove this call once we fix that.
add the fields & expressions under the `:fields` clause
+----------------------------------------------------------------------------------------------------------------+
| Add Implicit Breakout Order Bys |
+----------------------------------------------------------------------------------------------------------------+
+----------------------------------------------------------------------------------------------------------------+
| Middleware |
+----------------------------------------------------------------------------------------------------------------+
add implicit clauses to any 'inner query', except for joins themselves (we should still add implicit clauses
like `:fields` to source queries *inside* joins) | (ns metabase.query-processor.middleware.add-implicit-clauses
"Middlware for adding an implicit `:fields` and `:order-by` clauses to certain queries."
(:require [clojure.tools.logging :as log]
[clojure.walk :as walk]
[metabase.mbql.schema :as mbql.s]
[metabase.mbql.util :as mbql.u]
[metabase.models.field :refer [Field]]
[metabase.models.table :as table]
[metabase.query-processor.error-type :as qp.error-type]
[metabase.query-processor.store :as qp.store]
[metabase.types :as types]
[metabase.util :as u]
[metabase.util.i18n :refer [trs tru]]
[metabase.util.schema :as su]
[schema.core :as s]
[toucan.db :as db]))
(defn- table->sorted-fields*
[table-id]
(db/select [Field :id :base_type :effective_type :coercion_strategy :semantic_type]
:table_id table-id
:active true
:visibility_type [:not-in ["sensitive" "retired"]]
:parent_id nil
{:order-by table/field-order-rule}))
(defn- table->sorted-fields
"Return a sequence of all Fields for table that we'd normally include in the equivalent of a `SELECT *`."
[table-id]
(if (qp.store/initialized?)
cache duplicate calls to this function in the same QP run .
(qp.store/cached-fn [::table-sorted-fields (u/the-id table-id)] #(table->sorted-fields* table-id))
if QP store is not initialized do n't try to cache the value ( this is mainly for the benefit of tests and code
that uses this outside of the normal QP execution context )
(table->sorted-fields* table-id)))
(s/defn sorted-implicit-fields-for-table :- mbql.s/Fields
"For use when adding implicit Field IDs to a query. Return a sequence of field clauses, sorted by the rules listed
in [[metabase.query-processor.sort]], for all the Fields in a given Table."
[table-id :- su/IntGreaterThanZero]
(let [fields (table->sorted-fields table-id)]
(when (empty? fields)
(throw (ex-info (tru "No fields found for table {0}." (pr-str (:name (qp.store/table table-id))))
{:table-id table-id
:type qp.error-type/invalid-query})))
(mapv
(fn [field]
implicit datetime get bucketing of ` : default ` . This is so other middleware does n't try to give it
[:field (u/the-id field) (when (types/temporal-field? field)
{:temporal-unit :default})])
fields)))
(s/defn ^:private source-metadata->fields :- mbql.s/Fields
"Get implicit Fields for a query with a `:source-query` that has `source-metadata`."
[source-metadata :- (su/non-empty [mbql.s/SourceQueryMetadata])]
(distinct
(for [{field-name :name, base-type :base_type, field-id :id, field-ref :field_ref} source-metadata]
` : join - alias ` or ` : source - field ` . Remove binning / temporal bucketing info . The Field should already be getting
(or (some-> (mbql.u/match-one field-ref :field)
(mbql.u/update-field-options dissoc :binning :temporal-unit))
otherwise construct a field reference that can be used to refer to this Field .
(if field-id
If we have a Field ID , return a ` : field ` ( i d ) clause
[:field field-id nil]
otherwise return a ` : field ` ( name ) clause , e.g. for a Field that 's the result of an aggregation or
[:field field-name {:base-type base-type}])))))
(s/defn ^:private should-add-implicit-fields?
"Whether we should add implicit Fields to this query. True if all of the following are true:
* The query has either a `:source-table`, *or* a `:source-query` with `:source-metadata` for it
* The query has no breakouts
* The query has no aggregations"
[{:keys [fields source-table source-query source-metadata]
breakouts :breakout
aggregations :aggregation} :- mbql.s/MBQLQuery]
(when (and source-query
(empty? source-metadata)
(qp.store/initialized?))
by ' caching ' this result , this log message will only be shown once for a given QP run .
(qp.store/cached [::should-add-implicit-fields-warning]
(log/warn (str (trs "Warning: cannot determine fields for an explicit `source-query` unless you also include `source-metadata`.")
\newline
(trs "Query: {0}" (u/pprint-to-str source-query))))))
(and (or source-table
(and source-query (seq source-metadata)))
(every? empty? [aggregations breakouts fields])))
(s/defn ^:private add-implicit-fields
"For MBQL queries with no aggregation, add a `:fields` key containing all Fields in the source Table as well as any
expressions definied in the query."
[{source-table-id :source-table, :keys [expressions source-metadata], :as inner-query}]
(if-not (should-add-implicit-fields? inner-query)
inner-query
(let [fields (if source-table-id
(sorted-implicit-fields-for-table source-table-id)
(source-metadata->fields source-metadata))
expressions (for [[expression-name] expressions]
[:expression (u/qualified-name expression-name)])]
if the Table has no , throw an Exception , because there is no way for us to proceed
(when-not (seq fields)
(throw (ex-info (tru "Table ''{0}'' has no Fields associated with it." (:name (qp.store/table source-table-id)))
{:type qp.error-type/invalid-query})))
(assoc inner-query :fields (vec (concat fields expressions))))))
(s/defn ^:private add-implicit-breakout-order-by :- mbql.s/MBQLQuery
"Fields specified in `breakout` should add an implicit ascending `order-by` subclause *unless* that Field is already
*explicitly* referenced in `order-by`."
[{breakouts :breakout, :as inner-query} :- mbql.s/MBQLQuery]
Add a new [: asc < breakout - field > ] clause for each breakout . The cool thing is ` add - order - by - clause ` will
automatically ignore new ones that are reference already in the order - by clause
(reduce mbql.u/add-order-by-clause inner-query (for [breakout breakouts]
[:asc breakout])))
(defn add-implicit-mbql-clauses
"Add implicit clauses such as `:fields` and `:order-by` to an 'inner' MBQL query as needed."
[form]
(walk/postwalk
(fn [form]
(if (and (map? form)
((some-fn :source-table :source-query) form)
(not (:condition form)))
(-> form add-implicit-breakout-order-by add-implicit-fields)
form))
form))
(defn add-implicit-clauses
"Add an implicit `fields` clause to queries with no `:aggregation`, `breakout`, or explicit `:fields` clauses.
Add implicit `:order-by` clauses for fields specified in a `:breakout`."
[{query-type :type, :as query}]
(if (= query-type :native)
query
(update query :query add-implicit-mbql-clauses)))
|
390573b020caf479b163c60ce52d7b69154127ce82b5d28830f022db5caf6edc | rabbitmq/rabbitmq-mqtt | rabbit_mqtt_sup.erl | 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 ) 2007 - 2020 VMware , Inc. or its affiliates . All rights reserved .
%%
-module(rabbit_mqtt_sup).
-behaviour(supervisor2).
-include_lib("rabbit_common/include/rabbit.hrl").
-export([start_link/2, init/1, stop_listeners/0]).
-define(TCP_PROTOCOL, 'mqtt').
-define(TLS_PROTOCOL, 'mqtt/ssl').
start_link(Listeners, []) ->
supervisor2:start_link({local, ?MODULE}, ?MODULE, [Listeners]).
init([{Listeners, SslListeners0}]) ->
NumTcpAcceptors = application:get_env(rabbitmq_mqtt, num_tcp_acceptors, 10),
{ok, SocketOpts} = application:get_env(rabbitmq_mqtt, tcp_listen_options),
{SslOpts, NumSslAcceptors, SslListeners}
= case SslListeners0 of
[] -> {none, 0, []};
_ -> {rabbit_networking:ensure_ssl(),
application:get_env(rabbitmq_mqtt, num_ssl_acceptors, 10),
case rabbit_networking:poodle_check('MQTT') of
ok -> SslListeners0;
danger -> []
end}
end,
{ok, {{one_for_all, 10, 10},
[{rabbit_mqtt_retainer_sup,
{rabbit_mqtt_retainer_sup, start_link, [{local, rabbit_mqtt_retainer_sup}]},
transient, ?SUPERVISOR_WAIT, supervisor, [rabbit_mqtt_retainer_sup]} |
listener_specs(fun tcp_listener_spec/1,
[SocketOpts, NumTcpAcceptors], Listeners) ++
listener_specs(fun ssl_listener_spec/1,
[SocketOpts, SslOpts, NumSslAcceptors], SslListeners)]}}.
stop_listeners() ->
rabbit_networking:stop_ranch_listener_of_protocol(?TCP_PROTOCOL),
rabbit_networking:stop_ranch_listener_of_protocol(?TLS_PROTOCOL),
ok.
%%
%% Implementation
%%
listener_specs(Fun, Args, Listeners) ->
[Fun([Address | Args]) ||
Listener <- Listeners,
Address <- rabbit_networking:tcp_listener_addresses(Listener)].
tcp_listener_spec([Address, SocketOpts, NumAcceptors]) ->
rabbit_networking:tcp_listener_spec(
rabbit_mqtt_listener_sup, Address, SocketOpts,
transport(?TCP_PROTOCOL), rabbit_mqtt_connection_sup, [],
mqtt, NumAcceptors, "MQTT TCP listener").
ssl_listener_spec([Address, SocketOpts, SslOpts, NumAcceptors]) ->
rabbit_networking:tcp_listener_spec(
rabbit_mqtt_listener_sup, Address, SocketOpts ++ SslOpts,
transport(?TLS_PROTOCOL), rabbit_mqtt_connection_sup, [],
'mqtt/ssl', NumAcceptors, "MQTT TLS listener").
transport(Protocol) ->
case Protocol of
?TCP_PROTOCOL -> ranch_tcp;
?TLS_PROTOCOL -> ranch_ssl
end.
| null | https://raw.githubusercontent.com/rabbitmq/rabbitmq-mqtt/817971bfec4461630a2ef7e27d4fa9f4c4fb8ff9/src/rabbit_mqtt_sup.erl | erlang |
Implementation
| 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 ) 2007 - 2020 VMware , Inc. or its affiliates . All rights reserved .
-module(rabbit_mqtt_sup).
-behaviour(supervisor2).
-include_lib("rabbit_common/include/rabbit.hrl").
-export([start_link/2, init/1, stop_listeners/0]).
-define(TCP_PROTOCOL, 'mqtt').
-define(TLS_PROTOCOL, 'mqtt/ssl').
start_link(Listeners, []) ->
supervisor2:start_link({local, ?MODULE}, ?MODULE, [Listeners]).
init([{Listeners, SslListeners0}]) ->
NumTcpAcceptors = application:get_env(rabbitmq_mqtt, num_tcp_acceptors, 10),
{ok, SocketOpts} = application:get_env(rabbitmq_mqtt, tcp_listen_options),
{SslOpts, NumSslAcceptors, SslListeners}
= case SslListeners0 of
[] -> {none, 0, []};
_ -> {rabbit_networking:ensure_ssl(),
application:get_env(rabbitmq_mqtt, num_ssl_acceptors, 10),
case rabbit_networking:poodle_check('MQTT') of
ok -> SslListeners0;
danger -> []
end}
end,
{ok, {{one_for_all, 10, 10},
[{rabbit_mqtt_retainer_sup,
{rabbit_mqtt_retainer_sup, start_link, [{local, rabbit_mqtt_retainer_sup}]},
transient, ?SUPERVISOR_WAIT, supervisor, [rabbit_mqtt_retainer_sup]} |
listener_specs(fun tcp_listener_spec/1,
[SocketOpts, NumTcpAcceptors], Listeners) ++
listener_specs(fun ssl_listener_spec/1,
[SocketOpts, SslOpts, NumSslAcceptors], SslListeners)]}}.
stop_listeners() ->
rabbit_networking:stop_ranch_listener_of_protocol(?TCP_PROTOCOL),
rabbit_networking:stop_ranch_listener_of_protocol(?TLS_PROTOCOL),
ok.
listener_specs(Fun, Args, Listeners) ->
[Fun([Address | Args]) ||
Listener <- Listeners,
Address <- rabbit_networking:tcp_listener_addresses(Listener)].
tcp_listener_spec([Address, SocketOpts, NumAcceptors]) ->
rabbit_networking:tcp_listener_spec(
rabbit_mqtt_listener_sup, Address, SocketOpts,
transport(?TCP_PROTOCOL), rabbit_mqtt_connection_sup, [],
mqtt, NumAcceptors, "MQTT TCP listener").
ssl_listener_spec([Address, SocketOpts, SslOpts, NumAcceptors]) ->
rabbit_networking:tcp_listener_spec(
rabbit_mqtt_listener_sup, Address, SocketOpts ++ SslOpts,
transport(?TLS_PROTOCOL), rabbit_mqtt_connection_sup, [],
'mqtt/ssl', NumAcceptors, "MQTT TLS listener").
transport(Protocol) ->
case Protocol of
?TCP_PROTOCOL -> ranch_tcp;
?TLS_PROTOCOL -> ranch_ssl
end.
|
7d64441bdf573a1848b636e31f5fb827e6fa557c5259a346773a458076c77137 | arielnetworks/cl-markup | readmacro.lisp | (in-package :cl-markup)
(defun markup-reader (stream char arg)
(declare (ignore char arg))
`(markup ,(read stream t nil t)))
(defun %enable-markup-syntax ()
(setf *readtable* (copy-readtable))
(set-dispatch-macro-character #\# #\M #'markup-reader))
(defmacro enable-markup-syntax ()
'(eval-when (:compile-toplevel :load-toplevel :execute)
(%enable-markup-syntax)))
| null | https://raw.githubusercontent.com/arielnetworks/cl-markup/e0eb7debf4bdff98d1f49d0f811321a6a637b390/src/readmacro.lisp | lisp | (in-package :cl-markup)
(defun markup-reader (stream char arg)
(declare (ignore char arg))
`(markup ,(read stream t nil t)))
(defun %enable-markup-syntax ()
(setf *readtable* (copy-readtable))
(set-dispatch-macro-character #\# #\M #'markup-reader))
(defmacro enable-markup-syntax ()
'(eval-when (:compile-toplevel :load-toplevel :execute)
(%enable-markup-syntax)))
| |
ba29bd129734860e775de93acb8c98befaf0361fe09f1b7345828a782d5ba910 | thheller/shadow | api.cljs | (ns shadow.api
(:require-macros [shadow.api :as m])
(:require [cljs.reader :as reader]
[shadow.dom :as dom]
[clojure.string :as str]
[shadow.util :as util :refer (log)]))
(def ready-ref
(atom {}))
(def load-order-ref
(atom []))
(defn script->dom-el [script]
(when-let [dom-ref (dom/data script :ref)]
(condp = dom-ref
"none"
nil
"self"
script
"parent"
(dom/get-parent script)
"previous-sibling"
(dom/get-previous-sibling script)
"next-sibling"
(dom/get-next-sibling script)
(throw (ex-info "script tag with invalid dom ref" {:dom-ref dom-ref :script script})))))
(defn run-script-tag
"a <script type=\"shadow/run\" data-fn=\"js-fn\">edn-args</script> tag is meant to embed calls to javascript in html
instead of writing the javascript inline, we only define the call and its args + the location in the dom
we want to reference. this allows the javascript to be loaded as late as possible, avoids unknown reference errors,
does not litter the html with $(function() {}); and since a dom reference point is provided it makes it more
logical to reference dom elements via the server, no need to mess with id/class selectors.
script tags will be executed as soon as the js module is loaded (assuming it called module-ready), not on dom ready
which means it triggers earlier"
[script]
(let [init-fn
(dom/data script :fn)
args
(dom/get-html script)
args
(when (and args (not= "" args))
(reader/read-string args))
dom-el
(script->dom-el script)
args
(if dom-el
(cons dom-el args)
args)]
(let [queued-fn (goog/getObjectByName init-fn)]
(if queued-fn
(do (log "init" init-fn)
(apply queued-fn args))
(log "unknown init function" init-fn args)))))
(defn script-tags-for-ns [ns-name]
(let [ns-name (str/replace ns-name #"-" "_")]
(for [script
(dom/query "script[type=\"shadow/run\"]")
:let
[fn (dom/data script :fn)
fn-ns (.substring fn 0 (.lastIndexOf fn "."))]
:when
(= ns-name fn-ns)]
script
)))
(defn run-embedded-tags
"use after calling (dom/set-html node html) and that html may contain embedded script tags
only runs tags when the namespace of the function is already loaded, if the ns is not yet loaded to ns-ready function
will pick remaining tags"
[node]
(doseq [script
(dom/query "script[type=\"shadow/run\"]" node)
:let
[fn (dom/data script :fn)
fn-ns (.substring fn 0 (.lastIndexOf fn "."))]
:when
(contains? @ready-ref fn-ns)]
(run-script-tag script)))
(defn run-tags-for-ns [ns-name]
(log "ns-ready" ns-name)
(doseq [script (script-tags-for-ns ns-name)]
(run-script-tag script)))
(defn restart []
(doseq [ns-name
@load-order-ref
:let
[{:keys [reloadable] :as opts}
(get @ready-ref ns-name)]
:when reloadable]
(run-tags-for-ns ns-name)
))
(defn ^:export ns-ready*
"use (ns-ready) macro, do not use this directly"
[ns-name opts]
;; use setTimeout so the blocking load of a script
does n't continue to block while running the init fns
;; don't run things twice, not live-reload friendly
(when-not (contains? @ready-ref ns-name)
(swap! ready-ref assoc ns-name opts)
(swap! load-order-ref conj ns-name)
(js/setTimeout #(run-tags-for-ns ns-name) 0)))
| null | https://raw.githubusercontent.com/thheller/shadow/beab6586a9782ceb3e2a4bfa2935fb8756e13d2c/src/main/shadow/api.cljs | clojure | and since a dom reference point is provided it makes it more
use setTimeout so the blocking load of a script
don't run things twice, not live-reload friendly | (ns shadow.api
(:require-macros [shadow.api :as m])
(:require [cljs.reader :as reader]
[shadow.dom :as dom]
[clojure.string :as str]
[shadow.util :as util :refer (log)]))
(def ready-ref
(atom {}))
(def load-order-ref
(atom []))
(defn script->dom-el [script]
(when-let [dom-ref (dom/data script :ref)]
(condp = dom-ref
"none"
nil
"self"
script
"parent"
(dom/get-parent script)
"previous-sibling"
(dom/get-previous-sibling script)
"next-sibling"
(dom/get-next-sibling script)
(throw (ex-info "script tag with invalid dom ref" {:dom-ref dom-ref :script script})))))
(defn run-script-tag
"a <script type=\"shadow/run\" data-fn=\"js-fn\">edn-args</script> tag is meant to embed calls to javascript in html
instead of writing the javascript inline, we only define the call and its args + the location in the dom
we want to reference. this allows the javascript to be loaded as late as possible, avoids unknown reference errors,
logical to reference dom elements via the server, no need to mess with id/class selectors.
script tags will be executed as soon as the js module is loaded (assuming it called module-ready), not on dom ready
which means it triggers earlier"
[script]
(let [init-fn
(dom/data script :fn)
args
(dom/get-html script)
args
(when (and args (not= "" args))
(reader/read-string args))
dom-el
(script->dom-el script)
args
(if dom-el
(cons dom-el args)
args)]
(let [queued-fn (goog/getObjectByName init-fn)]
(if queued-fn
(do (log "init" init-fn)
(apply queued-fn args))
(log "unknown init function" init-fn args)))))
(defn script-tags-for-ns [ns-name]
(let [ns-name (str/replace ns-name #"-" "_")]
(for [script
(dom/query "script[type=\"shadow/run\"]")
:let
[fn (dom/data script :fn)
fn-ns (.substring fn 0 (.lastIndexOf fn "."))]
:when
(= ns-name fn-ns)]
script
)))
(defn run-embedded-tags
"use after calling (dom/set-html node html) and that html may contain embedded script tags
only runs tags when the namespace of the function is already loaded, if the ns is not yet loaded to ns-ready function
will pick remaining tags"
[node]
(doseq [script
(dom/query "script[type=\"shadow/run\"]" node)
:let
[fn (dom/data script :fn)
fn-ns (.substring fn 0 (.lastIndexOf fn "."))]
:when
(contains? @ready-ref fn-ns)]
(run-script-tag script)))
(defn run-tags-for-ns [ns-name]
(log "ns-ready" ns-name)
(doseq [script (script-tags-for-ns ns-name)]
(run-script-tag script)))
(defn restart []
(doseq [ns-name
@load-order-ref
:let
[{:keys [reloadable] :as opts}
(get @ready-ref ns-name)]
:when reloadable]
(run-tags-for-ns ns-name)
))
(defn ^:export ns-ready*
"use (ns-ready) macro, do not use this directly"
[ns-name opts]
does n't continue to block while running the init fns
(when-not (contains? @ready-ref ns-name)
(swap! ready-ref assoc ns-name opts)
(swap! load-order-ref conj ns-name)
(js/setTimeout #(run-tags-for-ns ns-name) 0)))
|
088d9f4df58cbbff88b052cd4f28251d8fb90840d7fc130cec2a183b5e18ed44 | haskelling/aoc2020 | 11a.hs | import AOC
main = interact f
f = count '#' . concat . mapnbsC nbs8 g
where
g x ns = case x of
'L' -> if count '#' ns == 0 then '#' else 'L'
'#' -> if count '#' ns >= 4 then 'L' else '#'
x -> x
| null | https://raw.githubusercontent.com/haskelling/aoc2020/0f0e44ad16d3eda4add1f05684070dd161010d75/11a.hs | haskell | import AOC
main = interact f
f = count '#' . concat . mapnbsC nbs8 g
where
g x ns = case x of
'L' -> if count '#' ns == 0 then '#' else 'L'
'#' -> if count '#' ns >= 4 then 'L' else '#'
x -> x
| |
6968b0bd75fc03c4d99bd95e1f57db71b48471e2827c14aaf4d86731de3bdafe | OCamlPro/ocplib-endian | le_ocaml_401.ml | let get_uint16 s off =
if Sys.big_endian
then swap16 (get_16 s off)
else get_16 s off
[@@ocaml.inline]
let get_int16 s off =
((get_uint16 s off) lsl ( Sys.int_size - 16 )) asr ( Sys.int_size - 16 )
[@@ocaml.inline]
let get_int32 s off =
if Sys.big_endian
then swap32 (get_32 s off)
else get_32 s off
[@@ocaml.inline]
let get_int64 s off =
if Sys.big_endian
then swap64 (get_64 s off)
else get_64 s off
[@@ocaml.inline]
let set_int16 s off v =
if Sys.big_endian
then (set_16 s off (swap16 v))
else set_16 s off v
[@@ocaml.inline]
let set_int32 s off v =
if Sys.big_endian
then set_32 s off (swap32 v)
else set_32 s off v
[@@ocaml.inline]
let set_int64 s off v =
if Sys.big_endian
then set_64 s off (swap64 v)
else set_64 s off v
[@@ocaml.inline]
| null | https://raw.githubusercontent.com/OCamlPro/ocplib-endian/10292cd3ffa4d23d737e3f855ad04f22d3d95460/src/le_ocaml_401.ml | ocaml | let get_uint16 s off =
if Sys.big_endian
then swap16 (get_16 s off)
else get_16 s off
[@@ocaml.inline]
let get_int16 s off =
((get_uint16 s off) lsl ( Sys.int_size - 16 )) asr ( Sys.int_size - 16 )
[@@ocaml.inline]
let get_int32 s off =
if Sys.big_endian
then swap32 (get_32 s off)
else get_32 s off
[@@ocaml.inline]
let get_int64 s off =
if Sys.big_endian
then swap64 (get_64 s off)
else get_64 s off
[@@ocaml.inline]
let set_int16 s off v =
if Sys.big_endian
then (set_16 s off (swap16 v))
else set_16 s off v
[@@ocaml.inline]
let set_int32 s off v =
if Sys.big_endian
then set_32 s off (swap32 v)
else set_32 s off v
[@@ocaml.inline]
let set_int64 s off v =
if Sys.big_endian
then set_64 s off (swap64 v)
else set_64 s off v
[@@ocaml.inline]
| |
a338a56d662af540ce39f5a7c4b710e2dea2bac5b096297b25ade55a4dcb561b | clojure-garden/clojure-garden | user.clj | (ns user)
(defn dev
[]
(require 'dev)
(in-ns 'dev))
| null | https://raw.githubusercontent.com/clojure-garden/clojure-garden/363c2b538aea6006e93a3fc80e3ae0becbd78736/modules/backend/dev/src/user.clj | clojure | (ns user)
(defn dev
[]
(require 'dev)
(in-ns 'dev))
| |
c72b89e28049c2ba8ebce040a0bc99be4cb47214c2a697f9f0a6bd5c917edcc2 | dbuenzli/carcass | help.ml | ---------------------------------------------------------------------------
Copyright ( c ) 2016 . All rights reserved .
Distributed under the ISC license , see terms at the end of the file .
---------------------------------------------------------------------------
Copyright (c) 2016 Daniel C. Bünzli. All rights reserved.
Distributed under the ISC license, see terms at the end of the file.
---------------------------------------------------------------------------*)
let carcass_manual = "Carcass manual"
let version = "%%VERSION%%"
(* Help manuals *)
let basics =
("CARCASS-BASICS", 7, "", version, carcass_manual),
[ `S "NAME";
`P "carcass-basics - short introduction to carcass";
`S "DESCRIPTION";
`P "carcass helps you to create software project boilerplate. This can
range from a single source file with your copyright and licensing
information to whole project scaffoldings.";
`S "SETUP";
`P "The first thing you should do after having installed carcass is
to invoke:";
`Pre "> carcass setup";
`P "This will ask you a few questions to setup your personal information
in the ~/.carcass/flesh file and copy a few default bones and bodies
to ~/.carcass.";
`P "Having done this take the time to further adjust your personal
variables in ~/.carcass/flesh according to your wishes.";
`S "CONCEPTS";
`P "There are three kinds of files in carcass:";
`I ("$(i,flesh) files", "These files hold sequences of variable definitions.
See for example the ~/.carcass/flesh file.");
`I ("$(i,bone) files", "Bone files allow to create a single file. They
are arbitrary files located in a carcass directory. Files which
are detected as text files (i.e. without a null byte) will be parsed
as UTF-8 encoded file and have variable references of the
form \\$(VAR) substituted with the definitions found in flesh
files.");
`I ("$(i,body) files", "Body files allow to create whole file hierarchies
out of bones and flesh. They are the files located in a carcass
directory that end with `.body`.");
`P "To each kind of file there is a corresponding carcass command. Let's
review them in turn.";
`S "FLESH";
`P "The $(b,flesh) command looks up a flesh variable by its identifier,
evaluates its definition and writes the result on stdout. For example:";
`Pre "> carcass flesh contact";
`P "To see the raw, unevaluated, definition of a variable, use the
$(b,-r) option.";
`Pre "> carcass flesh -r copyright_year";
`P "The $(b,-p) option outputs all variables, in flesh file syntax, that
are prefixed by the given identifier. The $(b,-l) option prepends the
output with the location of the definition. Using this, the following
invocation:";
`Pre "> carcass flesh -r -l -p \"\"";
`P "Lists all variable definitions with their location; the empty string
is the prefix of any any string. See carcass-flesh(1) for
more information about the $(b,flesh) command.";
`S "BONE";
`P "The $(b,bone) command looks up a bone by its identifier,
evaluates its variable references according to the flesh in
the environment and writes the result on stdout.";
`Pre "> carcass bone ocaml/src";
`P "If a variable definition can't be found, it will ask for it
interactively. It is also possible to define or
override variables on the command line:";
`Pre "> carcass bone ocaml/src copyright_year 2008";
`P "The bone command also supports the $(b,-r) and $(b,-l) options
to access the raw definition and output, on stderr,
the location of the bone.";
`Pre "> carcass bone -r -l ocaml/src";
`P "To get the list of available bones use:";
`Pre "> carcass info bones";
`P "See carcass-bone(1) for more information about the $(b,bone) command.
Regarding bones you may also find the $(b,match) command useful but
I let you read about it in carcass-match(1).";
`S "BODY";
`P "The $(b,body) command looks up a body by its identifier. This in turn
looks up the bones and bodies it is made of, evaluates their variable
references according to the flesh in the environment and creates the
file hierarchy it defines in a given destination directory. For example
the following creates an OCaml module (mli/ml files) in the /tmp
directory:";
`Pre "> carcass body ocaml/mod /tmp";
`P "Here again it is possible to specify flesh variables on the command
line.";
`Pre "> carcass body ocaml/mod /tmp name m";
`P "Carcass never overwrites files without confirming, unless the
option $(b,--force) is used. The raw definition and location of the
bone can be consulted with the usual options:";
`Pre "> carcass body -r -l ocaml/mod";
`P "To get the list of available bodies issue:";
`Pre "> carcass info bodies";
`P "And if you'd like more information about their variables and purpose
use:";
`Pre "> carcass info bodies -d";
`P "See carcass-body(1) for more information about the $(b,body) command.";
`S "LOOKUP PROCEDURES";
`P "Flesh, bones and bodies definitions are looked up according to
procedures that are defined precisely in carcass-lookup(5).";
`S "ADDING NEW BONES AND BODIES";
`P "To add new bones and bodies simply create files in your ~/.carcass
directory. The examples there with the help of the formal
definitions of carcass-syntax(5) should be sufficient to get
you started.";
`P "One note about the bones and bodies that you find in ~/.carcass
that start with an '_'. These can be consulted like any other body
or bone, however they don't get listed by 'carcass info'; unless the
$(b,--hidden) option is used.";
`S "TROUBLESHOOTING";
`P "If the output doesn't quite correspond to what you expect, remember
that most commands have the $(b,-r) and $(b,-l) options to output
raw definitions and their location. Invoking the tool with $(b,-v) may
also help in figuring out where the bones and bodies are picked
up from.";
`S "SEE ALSO";
`P "carcass(1), carcass-syntax(5), carcass-lookup(5)" ]
let lookup =
("CARCASS-LOOKUP", 5, "", version, carcass_manual),
[ `S "NAME";
`P "carcass-lookup - carcass lookup procedures";
`S "FLESH VARIABLE LOOKUP";
`P "Most commands allow to define variables: on the command line as
positional arguments, in flesh files specified via the
$(b,--flesh) option and in carcass directories specified via
the $(b,--carcass) option.";
`P "In a flesh file the last (re)definition takes over.";
`P "For a given variable identifier the first definition found in
the following order takes over the others:";
`I ("1. Positional command line arguments", "Starting from the rightmost
$(i,ID) $(i,DEF) pair.");
`I ("2. Command line flesh files", "Starting from the rightmost one, any
file specified with the $(b,--flesh) option.");
`I ("3. Command line carcass directory flesh files",
"Starting from the rightmost one,
any file $(i,DIR)/flesh with $(i,DIR) specified by the
$(b,--carcass) option.");
`I ("4. Default carcass directories", "First the .carcass/flesh files
from the current working directory up to the root path
unless the option $(b,--no-dot-dirs) is specified. Then in the
~/.carcass/flesh file unless the option $(b,--no-user-dir) is
specified.");
`P "The following variables, if undefined by the lookup procedure are
automatically defined by carcass:";
`I ("CARCASS_YEAR",
"Holds the year CE in which the program was started.");
`I ("CARCASS_MATCH_*",
"All variables of this form hold the empty string.");
`P "Depending on the command, remaining undefined variables may be asked
interactively.";
`S "BONE LOOKUP";
`P "If a bone identifier is absolute or starts with './', then the
corresponding file, if it exists, is read as the bone. If the bone
identifier is '-' then it is read from standard input. Otherwise
if the bone identifier is a relative path, the first file matching
the path in the list of carcass directories is taken as the bone.";
`P "For a given bone identifier $(i,BONE_ID) the lookup order is the
following:";
`I ("1. Command line carcass directories", "Starting from the
rightmost one, the file $(i,DIR)/$(i,BONE_ID) if it exists
with $(i,DIR) specified by the $(b,--carcass) option.");
`I ("2. Default carcass directories", "First the .carcass/$(i,BONE_ID)
from the current working directory up to the root path
unless the option $(b,--no-dot-dirs) is specified. Then the the
~/.carcass/$(i,BONE_ID) file unless the option $(b,--no-user-dir) is
specified.");
`S "BODY LOOKUP";
`P "Body lookup works exactly like bone lookup (see above) except that
it can be specified either by $(i,BODY_ID) or $(i,BODY_ID).body.
In the first case the '.body' extension is automatically added
to the requested path identifier before looking up. Note that in
body files, body identifiers must be specified with the extension
otherwise they are taken as being bone identifiers."
] @ Cli.see_also_main_man
let syntax =
("CARCASS-SYNTAX", 5, "", version, carcass_manual),
[ `S "NAME";
`P "carcass-syntax - syntax of carcass files";
`S "DESCRIPTION";
`P "At the lexical level, carcass files are sequences of keywords
and $(b,atoms) separated by $(b,white space) and $(b,comments).";
`P "$(b,variable identifiers) are restricted forms of atoms and
$(b,variable references) are used to refer to the value of
variables. Atoms with variable references are called $(b,patterns).";
`P "We first describe these basic elements before proceding to the
definition of the syntax of $(b,flesh), $(b,bone) and
$(b,body) files.";
`S "CHARACTER STREAM PROCESSING";
`P "Leaving out binary bone files, carcass only interprets valid
UTF-8 \ encoded files.";
`P "If an initial BOM character (U+FEFF) is present it is
discarded. In flesh and body files the newline functions CR
(U+000D), CRLF (<U+000D, U+000A>) and NEL (U+0085) are
normalized to LF (U+000A). The newlines of bone files are however
left untouched.";
`P "The grammar productions below are defined on the resulting
stream of Unicode scalar values.";
`S "WHITE SPACE";
`P "White space is space, horizontal tabulation, line feed, line tabulation
and form feed. White space delineates atoms and keywords.";
`Pre "$(i,white) ::= U+0020 | U+0009 | 0x000A | U+000B | U+000C";
`S "COMMENTS";
`P "Outside quoted atoms (see below) a hash
(#, U+0023) and anything that follows is ignored until the next LF
(\\\\n, U+000A) and treated as white space.";
`Pre "\
$(i,comment) ::= $(i,hash) [^$(i,lf)]* $(i,lf)
$(i,lf) ::= U+000A
$(i,hash) ::= U+0023";
`S "ATOMS";
`P "An atom is either any sequence of characters except white space
or a quoted atom, any sequence sequence of characters
between quotation marks (\", U+0022). For example abc and \"abc\"
are respectively an atom and a quoted atom and represent the same
atom.";
`P "Quoted atoms can be split across lines using a backslash
(\\\\, U+005C); in this case initial spaces (U+0020) or
tabs (U+0009) on the following line are discarded. Quoted atoms can
also contain white space and escape sequences which are started
by a backslash character (\\\\, U+005C). The following
escape sequences are recognized:";
`I ("\\\\\\\\",
"denotes U+005C, a backslash character"); `Noblank;
`I ("\\\\\"",
"denotes U+0022, a double quote character"); `Noblank;
`I ("\\\\ ",
"denotes U+0020, a space character"); `Noblank;
`I ("\\\\n",
"denotes U+000A, a line feed character");
`P "Any other character following a backslash is an illegal sequence
of characters.";
`P "The grammar of atoms is:";
`Pre "\
\ $(i,atom) ::= [^$(i,aend)]+ | $(i,quote) $(i,qachar)* $(i,quote)
$(i,aend) ::= $(i,white) | $(i,quote) | $(i,hash)
$(i,qachar) ::= [^$(i,quote) $(i,bslash)] | $(i,bslash) ($(i,bslash) \
| $(i,quote) | $(i,space) | $(i,n))
$(i,quote) ::= U+0022
$(i,bslash) ::= U+005C
$(i,space) ::= U+0020
$(i,n) ::= U+006E";
`S "VARIABLE IDENTIFIERS";
`P "Variable identifiers are sequences of any US-ASCII letter,
digit or underscore ('_', U+005F). Variable identifiers are case
insensitive with respect to US-ASCII case maps.";
`Pre
"$(i,id) ::= (U+0030-U+0039 | U+0041-U+005A | U+0061-U+007A | U+005F)+";
`S "VARIABLE REFERENCES";
`P "Variables references are of the form \\$(VAR) where VAR is a
$(b,variable identifier). In the context where variable references \
are interpreted a literal \\$ must always be escaped by \\$\\$.";
`P "Variable references can be followed by an optional transform using
the syntax \\$(VAR,transform). The following transforms are defined.";
`I ("\\$(VAR,uncapitalize)", "Uncapitalizes the first letter of VAR's
definition according to US-ASCII case maps.");
`I ("\\$(VAR,capitalize)", "Capitalizes the first letter of VAR's
definition according to US-ASCII case maps.");
`I ("\\$(VAR,lowercase)", "Lowercases the letters of VAR's
definition according to US-ASCII case maps.");
`I ("\\$(VAR,uppercase)", "Uppercases the letters of VAR's
definition according to US-ASCII case maps.");
`I ("\\$(VAR,indent(ATOM))", "Prefixes each line of VAR's
definition with the string ATOM. Lines that result in whitespace
only are collapsed to an empty line.");
`P "In context where variable references need to be recognized they
are according to the following grammar.";
`Pre "\
\ $(i,ref) ::= $(i,dollar) $(i,lpar) $(i,refc) $(i,rpar)
$(i,refc) ::= $(i,id) | $(i,id) $(i,comma) $(i,transform)
$(i,transform) ::= $(i,id) [ $(i,lpar) $(i,atom) $(i,rpar) ]
$(i,dollar) ::= U+0024
$(i,comma) ::= U+002C
$(i,lpar) ::= U+0028
$(i,rpar) ::= U+0029";
`S "PATTERNS";
`P "Patterns are atoms (quoted or not) in which variable references are
recognized";
`Pre "$(i,pat) ::= $(i,atom)";
`S "FLESH FILES";
`P "Flesh files are sequences of variable definitions. A variable
definition is a variable identifier and a pattern defining
the variable value.";
`Pre "\
$(i,flesh) ::= ($(i,id) $(i,pat))*
";
`S "BONE FILES";
`P "Bone files are either UTF-8 encoded files in which variable references
are recognized or binary files (detected by the presence of a NULL
byte) which are arbitrary, uninterpreted, sequence of bytes.";
`S "BODY FILES";
`P "Body files start with a documentation directive, followed
by a sequence of variable documentation directives and end
with a sequence of bind directives.";
`P "The body documentation directive 'doc' specifies a synopsis and
long description for the body.";
`P "A variable documentation directive 'var' specifies documentation
for a variable identifier (used for interactive variable
definition).";
`P "A bind directive 'bind' specifies a relative path as a pattern
and a bone or body identifier to bind to the path's content. Note
that unlike command line tool arguments these identifiers cannot
be absolute or start with ./, and body identifiers have to be
specified with their .body extension otherwise they are taken
to be bone identifiers.";
`Pre "\
$(i,body) ::= $(i,doc) $(i,var)* $(i,bind)*
$(i,doc) ::= \"doc\" $(i,atom) $(i,atom)
$(i,var) ::= \"var\" $(i,id) $(i,atom)
$(i,bind) ::= \"bind\" $(i,pat) $(i,atom)";
] @ Cli.see_also_main_man
(* Help command *)
let pages =
[ "basics", basics;
"lookup", lookup;
"syntax", syntax; ]
let help man_format topic commands = match topic with
| None -> `Help (man_format, None)
| Some topic ->
let topics = "topics" :: commands @ (List.map fst pages) in
let topics = List.sort compare topics in
let conv, _ = Cmdliner.Arg.enum (List.rev_map (fun s -> (s, s)) topics) in
match conv topic with
| `Error e -> `Error (false, e)
| `Ok t when List.mem t commands -> `Help (man_format, Some t)
| `Ok t when t = "topics" ->
Fmt.pr "@[<v>%a@]@." Fmt.(list string) topics;
`Ok 0
| `Ok t ->
let man = try List.assoc t pages with Not_found -> assert false in
Fmt.pr "%a" (Cmdliner.Manpage.print man_format) man;
`Ok 0
(* Command line interface *)
open Cmdliner
let topic =
let doc = "The topic to get help on, `topics' lists the topic." in
Arg.(value & pos 0 (some string) None & info [] ~docv:"TOPIC" ~doc)
let doc = "show help about carcass"
let man =
[ `S "DESCRIPTION";
`P "The $(tname) command shows help about carcass.";
`P "Use `topics' as $(i,TOPIC) to get a list of topics.";
] @ Cli.see_also_main_man
let cmd =
let info = Term.info "help" ~doc ~man in
let t = Term.(ret (const help $ Term.man_format $ topic $
Term.choice_names))
in
(t, info)
---------------------------------------------------------------------------
Copyright ( c ) 2016
Permission to use , copy , modify , and/or distribute this software for any
purpose with or without fee is hereby granted , provided that the above
copyright notice and this permission notice appear in all copies .
THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE .
---------------------------------------------------------------------------
Copyright (c) 2016 Daniel C. Bünzli
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
---------------------------------------------------------------------------*)
| null | https://raw.githubusercontent.com/dbuenzli/carcass/1221231b1e3d9ba5b7697707d0e7e901d51ac376/src-bin/help.ml | ocaml | Help manuals
Help command
Command line interface | ---------------------------------------------------------------------------
Copyright ( c ) 2016 . All rights reserved .
Distributed under the ISC license , see terms at the end of the file .
---------------------------------------------------------------------------
Copyright (c) 2016 Daniel C. Bünzli. All rights reserved.
Distributed under the ISC license, see terms at the end of the file.
---------------------------------------------------------------------------*)
let carcass_manual = "Carcass manual"
let version = "%%VERSION%%"
let basics =
("CARCASS-BASICS", 7, "", version, carcass_manual),
[ `S "NAME";
`P "carcass-basics - short introduction to carcass";
`S "DESCRIPTION";
`P "carcass helps you to create software project boilerplate. This can
range from a single source file with your copyright and licensing
information to whole project scaffoldings.";
`S "SETUP";
`P "The first thing you should do after having installed carcass is
to invoke:";
`Pre "> carcass setup";
`P "This will ask you a few questions to setup your personal information
in the ~/.carcass/flesh file and copy a few default bones and bodies
to ~/.carcass.";
`P "Having done this take the time to further adjust your personal
variables in ~/.carcass/flesh according to your wishes.";
`S "CONCEPTS";
`P "There are three kinds of files in carcass:";
`I ("$(i,flesh) files", "These files hold sequences of variable definitions.
See for example the ~/.carcass/flesh file.");
`I ("$(i,bone) files", "Bone files allow to create a single file. They
are arbitrary files located in a carcass directory. Files which
are detected as text files (i.e. without a null byte) will be parsed
as UTF-8 encoded file and have variable references of the
form \\$(VAR) substituted with the definitions found in flesh
files.");
`I ("$(i,body) files", "Body files allow to create whole file hierarchies
out of bones and flesh. They are the files located in a carcass
directory that end with `.body`.");
`P "To each kind of file there is a corresponding carcass command. Let's
review them in turn.";
`S "FLESH";
`P "The $(b,flesh) command looks up a flesh variable by its identifier,
evaluates its definition and writes the result on stdout. For example:";
`Pre "> carcass flesh contact";
`P "To see the raw, unevaluated, definition of a variable, use the
$(b,-r) option.";
`Pre "> carcass flesh -r copyright_year";
`P "The $(b,-p) option outputs all variables, in flesh file syntax, that
are prefixed by the given identifier. The $(b,-l) option prepends the
output with the location of the definition. Using this, the following
invocation:";
`Pre "> carcass flesh -r -l -p \"\"";
`P "Lists all variable definitions with their location; the empty string
is the prefix of any any string. See carcass-flesh(1) for
more information about the $(b,flesh) command.";
`S "BONE";
`P "The $(b,bone) command looks up a bone by its identifier,
evaluates its variable references according to the flesh in
the environment and writes the result on stdout.";
`Pre "> carcass bone ocaml/src";
`P "If a variable definition can't be found, it will ask for it
interactively. It is also possible to define or
override variables on the command line:";
`Pre "> carcass bone ocaml/src copyright_year 2008";
`P "The bone command also supports the $(b,-r) and $(b,-l) options
to access the raw definition and output, on stderr,
the location of the bone.";
`Pre "> carcass bone -r -l ocaml/src";
`P "To get the list of available bones use:";
`Pre "> carcass info bones";
`P "See carcass-bone(1) for more information about the $(b,bone) command.
Regarding bones you may also find the $(b,match) command useful but
I let you read about it in carcass-match(1).";
`S "BODY";
`P "The $(b,body) command looks up a body by its identifier. This in turn
looks up the bones and bodies it is made of, evaluates their variable
references according to the flesh in the environment and creates the
file hierarchy it defines in a given destination directory. For example
the following creates an OCaml module (mli/ml files) in the /tmp
directory:";
`Pre "> carcass body ocaml/mod /tmp";
`P "Here again it is possible to specify flesh variables on the command
line.";
`Pre "> carcass body ocaml/mod /tmp name m";
`P "Carcass never overwrites files without confirming, unless the
option $(b,--force) is used. The raw definition and location of the
bone can be consulted with the usual options:";
`Pre "> carcass body -r -l ocaml/mod";
`P "To get the list of available bodies issue:";
`Pre "> carcass info bodies";
`P "And if you'd like more information about their variables and purpose
use:";
`Pre "> carcass info bodies -d";
`P "See carcass-body(1) for more information about the $(b,body) command.";
`S "LOOKUP PROCEDURES";
`P "Flesh, bones and bodies definitions are looked up according to
procedures that are defined precisely in carcass-lookup(5).";
`S "ADDING NEW BONES AND BODIES";
`P "To add new bones and bodies simply create files in your ~/.carcass
directory. The examples there with the help of the formal
definitions of carcass-syntax(5) should be sufficient to get
you started.";
`P "One note about the bones and bodies that you find in ~/.carcass
that start with an '_'. These can be consulted like any other body
or bone, however they don't get listed by 'carcass info'; unless the
$(b,--hidden) option is used.";
`S "TROUBLESHOOTING";
`P "If the output doesn't quite correspond to what you expect, remember
that most commands have the $(b,-r) and $(b,-l) options to output
raw definitions and their location. Invoking the tool with $(b,-v) may
also help in figuring out where the bones and bodies are picked
up from.";
`S "SEE ALSO";
`P "carcass(1), carcass-syntax(5), carcass-lookup(5)" ]
let lookup =
("CARCASS-LOOKUP", 5, "", version, carcass_manual),
[ `S "NAME";
`P "carcass-lookup - carcass lookup procedures";
`S "FLESH VARIABLE LOOKUP";
`P "Most commands allow to define variables: on the command line as
positional arguments, in flesh files specified via the
$(b,--flesh) option and in carcass directories specified via
the $(b,--carcass) option.";
`P "In a flesh file the last (re)definition takes over.";
`P "For a given variable identifier the first definition found in
the following order takes over the others:";
`I ("1. Positional command line arguments", "Starting from the rightmost
$(i,ID) $(i,DEF) pair.");
`I ("2. Command line flesh files", "Starting from the rightmost one, any
file specified with the $(b,--flesh) option.");
`I ("3. Command line carcass directory flesh files",
"Starting from the rightmost one,
any file $(i,DIR)/flesh with $(i,DIR) specified by the
$(b,--carcass) option.");
`I ("4. Default carcass directories", "First the .carcass/flesh files
from the current working directory up to the root path
unless the option $(b,--no-dot-dirs) is specified. Then in the
~/.carcass/flesh file unless the option $(b,--no-user-dir) is
specified.");
`P "The following variables, if undefined by the lookup procedure are
automatically defined by carcass:";
`I ("CARCASS_YEAR",
"Holds the year CE in which the program was started.");
`I ("CARCASS_MATCH_*",
"All variables of this form hold the empty string.");
`P "Depending on the command, remaining undefined variables may be asked
interactively.";
`S "BONE LOOKUP";
`P "If a bone identifier is absolute or starts with './', then the
corresponding file, if it exists, is read as the bone. If the bone
identifier is '-' then it is read from standard input. Otherwise
if the bone identifier is a relative path, the first file matching
the path in the list of carcass directories is taken as the bone.";
`P "For a given bone identifier $(i,BONE_ID) the lookup order is the
following:";
`I ("1. Command line carcass directories", "Starting from the
rightmost one, the file $(i,DIR)/$(i,BONE_ID) if it exists
with $(i,DIR) specified by the $(b,--carcass) option.");
`I ("2. Default carcass directories", "First the .carcass/$(i,BONE_ID)
from the current working directory up to the root path
unless the option $(b,--no-dot-dirs) is specified. Then the the
~/.carcass/$(i,BONE_ID) file unless the option $(b,--no-user-dir) is
specified.");
`S "BODY LOOKUP";
`P "Body lookup works exactly like bone lookup (see above) except that
it can be specified either by $(i,BODY_ID) or $(i,BODY_ID).body.
In the first case the '.body' extension is automatically added
to the requested path identifier before looking up. Note that in
body files, body identifiers must be specified with the extension
otherwise they are taken as being bone identifiers."
] @ Cli.see_also_main_man
let syntax =
("CARCASS-SYNTAX", 5, "", version, carcass_manual),
[ `S "NAME";
`P "carcass-syntax - syntax of carcass files";
`S "DESCRIPTION";
`P "At the lexical level, carcass files are sequences of keywords
and $(b,atoms) separated by $(b,white space) and $(b,comments).";
`P "$(b,variable identifiers) are restricted forms of atoms and
$(b,variable references) are used to refer to the value of
variables. Atoms with variable references are called $(b,patterns).";
`P "We first describe these basic elements before proceding to the
definition of the syntax of $(b,flesh), $(b,bone) and
$(b,body) files.";
`S "CHARACTER STREAM PROCESSING";
`P "Leaving out binary bone files, carcass only interprets valid
UTF-8 \ encoded files.";
`P "If an initial BOM character (U+FEFF) is present it is
discarded. In flesh and body files the newline functions CR
(U+000D), CRLF (<U+000D, U+000A>) and NEL (U+0085) are
normalized to LF (U+000A). The newlines of bone files are however
left untouched.";
`P "The grammar productions below are defined on the resulting
stream of Unicode scalar values.";
`S "WHITE SPACE";
`P "White space is space, horizontal tabulation, line feed, line tabulation
and form feed. White space delineates atoms and keywords.";
`Pre "$(i,white) ::= U+0020 | U+0009 | 0x000A | U+000B | U+000C";
`S "COMMENTS";
`P "Outside quoted atoms (see below) a hash
(#, U+0023) and anything that follows is ignored until the next LF
(\\\\n, U+000A) and treated as white space.";
`Pre "\
$(i,comment) ::= $(i,hash) [^$(i,lf)]* $(i,lf)
$(i,lf) ::= U+000A
$(i,hash) ::= U+0023";
`S "ATOMS";
`P "An atom is either any sequence of characters except white space
or a quoted atom, any sequence sequence of characters
between quotation marks (\", U+0022). For example abc and \"abc\"
are respectively an atom and a quoted atom and represent the same
atom.";
`P "Quoted atoms can be split across lines using a backslash
(\\\\, U+005C); in this case initial spaces (U+0020) or
tabs (U+0009) on the following line are discarded. Quoted atoms can
also contain white space and escape sequences which are started
by a backslash character (\\\\, U+005C). The following
escape sequences are recognized:";
`I ("\\\\\\\\",
"denotes U+005C, a backslash character"); `Noblank;
`I ("\\\\\"",
"denotes U+0022, a double quote character"); `Noblank;
`I ("\\\\ ",
"denotes U+0020, a space character"); `Noblank;
`I ("\\\\n",
"denotes U+000A, a line feed character");
`P "Any other character following a backslash is an illegal sequence
of characters.";
`P "The grammar of atoms is:";
`Pre "\
\ $(i,atom) ::= [^$(i,aend)]+ | $(i,quote) $(i,qachar)* $(i,quote)
$(i,aend) ::= $(i,white) | $(i,quote) | $(i,hash)
$(i,qachar) ::= [^$(i,quote) $(i,bslash)] | $(i,bslash) ($(i,bslash) \
| $(i,quote) | $(i,space) | $(i,n))
$(i,quote) ::= U+0022
$(i,bslash) ::= U+005C
$(i,space) ::= U+0020
$(i,n) ::= U+006E";
`S "VARIABLE IDENTIFIERS";
`P "Variable identifiers are sequences of any US-ASCII letter,
digit or underscore ('_', U+005F). Variable identifiers are case
insensitive with respect to US-ASCII case maps.";
`Pre
"$(i,id) ::= (U+0030-U+0039 | U+0041-U+005A | U+0061-U+007A | U+005F)+";
`S "VARIABLE REFERENCES";
`P "Variables references are of the form \\$(VAR) where VAR is a
$(b,variable identifier). In the context where variable references \
are interpreted a literal \\$ must always be escaped by \\$\\$.";
`P "Variable references can be followed by an optional transform using
the syntax \\$(VAR,transform). The following transforms are defined.";
`I ("\\$(VAR,uncapitalize)", "Uncapitalizes the first letter of VAR's
definition according to US-ASCII case maps.");
`I ("\\$(VAR,capitalize)", "Capitalizes the first letter of VAR's
definition according to US-ASCII case maps.");
`I ("\\$(VAR,lowercase)", "Lowercases the letters of VAR's
definition according to US-ASCII case maps.");
`I ("\\$(VAR,uppercase)", "Uppercases the letters of VAR's
definition according to US-ASCII case maps.");
`I ("\\$(VAR,indent(ATOM))", "Prefixes each line of VAR's
definition with the string ATOM. Lines that result in whitespace
only are collapsed to an empty line.");
`P "In context where variable references need to be recognized they
are according to the following grammar.";
`Pre "\
\ $(i,ref) ::= $(i,dollar) $(i,lpar) $(i,refc) $(i,rpar)
$(i,refc) ::= $(i,id) | $(i,id) $(i,comma) $(i,transform)
$(i,transform) ::= $(i,id) [ $(i,lpar) $(i,atom) $(i,rpar) ]
$(i,dollar) ::= U+0024
$(i,comma) ::= U+002C
$(i,lpar) ::= U+0028
$(i,rpar) ::= U+0029";
`S "PATTERNS";
`P "Patterns are atoms (quoted or not) in which variable references are
recognized";
`Pre "$(i,pat) ::= $(i,atom)";
`S "FLESH FILES";
`P "Flesh files are sequences of variable definitions. A variable
definition is a variable identifier and a pattern defining
the variable value.";
`Pre "\
$(i,flesh) ::= ($(i,id) $(i,pat))*
";
`S "BONE FILES";
`P "Bone files are either UTF-8 encoded files in which variable references
are recognized or binary files (detected by the presence of a NULL
byte) which are arbitrary, uninterpreted, sequence of bytes.";
`S "BODY FILES";
`P "Body files start with a documentation directive, followed
by a sequence of variable documentation directives and end
with a sequence of bind directives.";
`P "The body documentation directive 'doc' specifies a synopsis and
long description for the body.";
`P "A variable documentation directive 'var' specifies documentation
for a variable identifier (used for interactive variable
definition).";
`P "A bind directive 'bind' specifies a relative path as a pattern
and a bone or body identifier to bind to the path's content. Note
that unlike command line tool arguments these identifiers cannot
be absolute or start with ./, and body identifiers have to be
specified with their .body extension otherwise they are taken
to be bone identifiers.";
`Pre "\
$(i,body) ::= $(i,doc) $(i,var)* $(i,bind)*
$(i,doc) ::= \"doc\" $(i,atom) $(i,atom)
$(i,var) ::= \"var\" $(i,id) $(i,atom)
$(i,bind) ::= \"bind\" $(i,pat) $(i,atom)";
] @ Cli.see_also_main_man
let pages =
[ "basics", basics;
"lookup", lookup;
"syntax", syntax; ]
let help man_format topic commands = match topic with
| None -> `Help (man_format, None)
| Some topic ->
let topics = "topics" :: commands @ (List.map fst pages) in
let topics = List.sort compare topics in
let conv, _ = Cmdliner.Arg.enum (List.rev_map (fun s -> (s, s)) topics) in
match conv topic with
| `Error e -> `Error (false, e)
| `Ok t when List.mem t commands -> `Help (man_format, Some t)
| `Ok t when t = "topics" ->
Fmt.pr "@[<v>%a@]@." Fmt.(list string) topics;
`Ok 0
| `Ok t ->
let man = try List.assoc t pages with Not_found -> assert false in
Fmt.pr "%a" (Cmdliner.Manpage.print man_format) man;
`Ok 0
open Cmdliner
let topic =
let doc = "The topic to get help on, `topics' lists the topic." in
Arg.(value & pos 0 (some string) None & info [] ~docv:"TOPIC" ~doc)
let doc = "show help about carcass"
let man =
[ `S "DESCRIPTION";
`P "The $(tname) command shows help about carcass.";
`P "Use `topics' as $(i,TOPIC) to get a list of topics.";
] @ Cli.see_also_main_man
let cmd =
let info = Term.info "help" ~doc ~man in
let t = Term.(ret (const help $ Term.man_format $ topic $
Term.choice_names))
in
(t, info)
---------------------------------------------------------------------------
Copyright ( c ) 2016
Permission to use , copy , modify , and/or distribute this software for any
purpose with or without fee is hereby granted , provided that the above
copyright notice and this permission notice appear in all copies .
THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE .
---------------------------------------------------------------------------
Copyright (c) 2016 Daniel C. Bünzli
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
---------------------------------------------------------------------------*)
|
e61e929591c2e800c8ca499a79776cad52e8b1f11b4b4b4dcafff5090d62bc7e | hjwylde/werewolf | Divine.hs | |
Module : Werewolf . Command . Divine
Description : Options and handler for the divine subcommand .
Copyright : ( c ) , 2016
License : :
Options and handler for the divine subcommand .
Module : Werewolf.Command.Divine
Description : Options and handler for the divine subcommand.
Copyright : (c) Henry J. Wylde, 2016
License : BSD3
Maintainer :
Options and handler for the divine subcommand.
-}
module Werewolf.Command.Divine (
-- * Options
Options(..),
-- * Handle
handle,
) where
import Control.Monad.Except
import Control.Monad.Extra
import Control.Monad.Random
import Control.Monad.State
import Control.Monad.Writer
import Data.Text (Text)
import Game.Werewolf
import Game.Werewolf.Command
import Game.Werewolf.Command.Oracle
import Game.Werewolf.Engine
import Game.Werewolf.Message.Error
import Werewolf.System
data Options = Options
{ argTarget :: Text
} deriving (Eq, Show)
handle :: (MonadIO m, MonadRandom m) => Text -> Text -> Options -> m ()
handle callerName tag (Options targetName) = do
unlessM (doesGameExist tag) $ exitWith failure
{ messages = [noGameRunningMessage callerName]
}
game <- readGame tag
let command = divineCommand callerName targetName
result <- runExceptT . runWriterT $ execStateT (apply command >> checkStage >> checkGameOver) game
case result of
Left errorMessages -> exitWith failure { messages = errorMessages }
Right (game', messages) -> writeOrDeleteGame tag game' >> exitWith success { messages = messages }
| null | https://raw.githubusercontent.com/hjwylde/werewolf/d22a941120a282127fc3e2db52e7c86b5d238344/app/Werewolf/Command/Divine.hs | haskell | * Options
* Handle | |
Module : Werewolf . Command . Divine
Description : Options and handler for the divine subcommand .
Copyright : ( c ) , 2016
License : :
Options and handler for the divine subcommand .
Module : Werewolf.Command.Divine
Description : Options and handler for the divine subcommand.
Copyright : (c) Henry J. Wylde, 2016
License : BSD3
Maintainer :
Options and handler for the divine subcommand.
-}
module Werewolf.Command.Divine (
Options(..),
handle,
) where
import Control.Monad.Except
import Control.Monad.Extra
import Control.Monad.Random
import Control.Monad.State
import Control.Monad.Writer
import Data.Text (Text)
import Game.Werewolf
import Game.Werewolf.Command
import Game.Werewolf.Command.Oracle
import Game.Werewolf.Engine
import Game.Werewolf.Message.Error
import Werewolf.System
data Options = Options
{ argTarget :: Text
} deriving (Eq, Show)
handle :: (MonadIO m, MonadRandom m) => Text -> Text -> Options -> m ()
handle callerName tag (Options targetName) = do
unlessM (doesGameExist tag) $ exitWith failure
{ messages = [noGameRunningMessage callerName]
}
game <- readGame tag
let command = divineCommand callerName targetName
result <- runExceptT . runWriterT $ execStateT (apply command >> checkStage >> checkGameOver) game
case result of
Left errorMessages -> exitWith failure { messages = errorMessages }
Right (game', messages) -> writeOrDeleteGame tag game' >> exitWith success { messages = messages }
|
efdd44fc9be1f867ecc7a928451d09a3ed4aee028b23f91a31ef945d216206df | ngorogiannis/cyclist | ptos.mli | (** Multiset of points-tos. *)
include Lib.OrderedContainer with type elt = Pto.t
val subst : Subst.t -> t -> t
val terms : t -> Term.Set.t
val vars : t -> Term.Set.t
val to_string_list : t -> string list
val subsumed : ?total:bool -> Uf.t -> t -> t -> bool
* [ subsumed eqs ptos ptos ' ] is true iff [ ptos ] can be rewritten using the
equalities [ eqs ] such that it becomes equal to [ ptos ' ] .
If the optional argument [ ~total = true ] is set to [ false ] then
check if rewriting could make the first multiset a sub(multi)set of
the second .
equalities [eqs] such that it becomes equal to [ptos'].
If the optional argument [~total=true] is set to [false] then
check if rewriting could make the first multiset a sub(multi)set of
the second. *)
val unify :
?total:bool
-> ?update_check:Unify.Unidirectional.update_check
-> t Unify.Unidirectional.unifier
* Compute substitution that would make the two multisets equal .
If the optional argument [ ~total = true ] is set to [ false ] then
compute a substitution that would make the first multiset a sub(multi)set of
the second .
If the optional argument [~total=true] is set to [false] then
compute a substitution that would make the first multiset a sub(multi)set of
the second. *)
val biunify :
?total:bool
-> ?update_check:Unify.Bidirectional.update_check
-> t Unify.Bidirectional.unifier
val norm : Uf.t -> t -> t
* Replace all terms with their UF representative . NB this may replace [ nil ]
with a variable .
with a variable. *)
| null | https://raw.githubusercontent.com/ngorogiannis/cyclist/c93a168d586b308ab2a2c730cd1b2375ab263167/src/seplog/ptos.mli | ocaml | * Multiset of points-tos. |
include Lib.OrderedContainer with type elt = Pto.t
val subst : Subst.t -> t -> t
val terms : t -> Term.Set.t
val vars : t -> Term.Set.t
val to_string_list : t -> string list
val subsumed : ?total:bool -> Uf.t -> t -> t -> bool
* [ subsumed eqs ptos ptos ' ] is true iff [ ptos ] can be rewritten using the
equalities [ eqs ] such that it becomes equal to [ ptos ' ] .
If the optional argument [ ~total = true ] is set to [ false ] then
check if rewriting could make the first multiset a sub(multi)set of
the second .
equalities [eqs] such that it becomes equal to [ptos'].
If the optional argument [~total=true] is set to [false] then
check if rewriting could make the first multiset a sub(multi)set of
the second. *)
val unify :
?total:bool
-> ?update_check:Unify.Unidirectional.update_check
-> t Unify.Unidirectional.unifier
* Compute substitution that would make the two multisets equal .
If the optional argument [ ~total = true ] is set to [ false ] then
compute a substitution that would make the first multiset a sub(multi)set of
the second .
If the optional argument [~total=true] is set to [false] then
compute a substitution that would make the first multiset a sub(multi)set of
the second. *)
val biunify :
?total:bool
-> ?update_check:Unify.Bidirectional.update_check
-> t Unify.Bidirectional.unifier
val norm : Uf.t -> t -> t
* Replace all terms with their UF representative . NB this may replace [ nil ]
with a variable .
with a variable. *)
|
c857438887b2bfc12e98914ae14a39f67b1a373d2252db6b63edb82b0a4a6be8 | stan-dev/stanc3 | Pretty.ml | (** Named signatures for types that can be pretty-printed.
*)
module type S = sig
type t
val pp : Format.formatter -> t -> unit
end
module type S1 = sig
type 'a t
val pp : (Format.formatter -> 'a -> unit) -> Format.formatter -> 'a t -> unit
end
module type S2 = sig
type ('a, 'b) t
val pp :
(Format.formatter -> 'a -> unit)
-> (Format.formatter -> 'b -> unit)
-> Format.formatter
-> ('a, 'b) t
-> unit
end
| null | https://raw.githubusercontent.com/stan-dev/stanc3/86267798050f9a24f61263b0825f1d44395040db/src/common/Pretty.ml | ocaml | * Named signatures for types that can be pretty-printed.
|
module type S = sig
type t
val pp : Format.formatter -> t -> unit
end
module type S1 = sig
type 'a t
val pp : (Format.formatter -> 'a -> unit) -> Format.formatter -> 'a t -> unit
end
module type S2 = sig
type ('a, 'b) t
val pp :
(Format.formatter -> 'a -> unit)
-> (Format.formatter -> 'b -> unit)
-> Format.formatter
-> ('a, 'b) t
-> unit
end
|
d8cfc6a1166f571b4219bd606ba6a3da81442ee530203b357335493fd1c1528e | luminus-framework/luminus-template | ajax.cljs | (ns <<project-ns>>.ajax
(:require [ajax.core :as ajax]))
(defn local-uri? [{:keys [uri]}]
(not (re-find #"^\w+?://" uri)))
(defn default-headers [request]
(if (local-uri? request)
(-> request<% if servlet %>
(update :uri #(str js/context %))<% endif %>
(update :headers #(merge {"x-csrf-token" js/csrfToken} %)))
request))
(defn load-interceptors! []
(swap! ajax/default-interceptors
conj
(ajax/to-interceptor {:name "default headers"
:request default-headers})))
| null | https://raw.githubusercontent.com/luminus-framework/luminus-template/3278aa727cef0a173ed3ca722dfd6afa6b4bbc8f/resources/leiningen/new/luminus/hoplon/src/cljs/ajax.cljs | clojure | (ns <<project-ns>>.ajax
(:require [ajax.core :as ajax]))
(defn local-uri? [{:keys [uri]}]
(not (re-find #"^\w+?://" uri)))
(defn default-headers [request]
(if (local-uri? request)
(-> request<% if servlet %>
(update :uri #(str js/context %))<% endif %>
(update :headers #(merge {"x-csrf-token" js/csrfToken} %)))
request))
(defn load-interceptors! []
(swap! ajax/default-interceptors
conj
(ajax/to-interceptor {:name "default headers"
:request default-headers})))
| |
ca942a2a68bf07bb661acbeb80086a8135c8db64e34372345f93a1949ff052c9 | janestreet/memtrace_viewer_with_deps | bin_shape_expand.mli | open Ppxlib
open Deriving
val str_gen : (structure, rec_flag * type_declaration list) Generator.t
val sig_gen : (signature, rec_flag * type_declaration list) Generator.t
val shape_extension : loc:Location.t -> core_type -> expression
val digest_extension : loc:Location.t -> core_type -> expression
| null | https://raw.githubusercontent.com/janestreet/memtrace_viewer_with_deps/5a9e1f927f5f8333e2d71c8d3ca03a45587422c4/vendor/ppx_bin_prot/shape/src/bin_shape_expand.mli | ocaml | open Ppxlib
open Deriving
val str_gen : (structure, rec_flag * type_declaration list) Generator.t
val sig_gen : (signature, rec_flag * type_declaration list) Generator.t
val shape_extension : loc:Location.t -> core_type -> expression
val digest_extension : loc:Location.t -> core_type -> expression
| |
57205ee728739d3adb8fc77d2bbb7f4ecfa0d867072c002e62374f890180408f | nvim-treesitter/nvim-treesitter | injections.scm | ((operation
(command) @_command
(message) @bash)
(#any-of? @_command "exec" "x"))
| null | https://raw.githubusercontent.com/nvim-treesitter/nvim-treesitter/053f88f55622c22cfd5cf8a15ab684a3d484cd8f/queries/git_rebase/injections.scm | scheme | ((operation
(command) @_command
(message) @bash)
(#any-of? @_command "exec" "x"))
| |
bbc632d1e390443c9c129dd21285d555b7e163f60c3afa0f683dc202e96c009f | mransan/raft | raft_helper.mli | (** Helper functions for manipulating Raft types *)
module Configuration : sig
val is_majority : Raft_types.configuration -> int -> bool
(** [is_majority configuration nb] returns true if [nb] is a majority *)
end (* Configuration *)
module Follower : sig
val make :
?log:Raft_log.t ->
?commit_index:int ->
?current_term:int ->
configuration:Raft_types.configuration ->
now:float ->
server_id:int ->
unit ->
Raft_types.state
(** [create ~configuration ~now ~server_id ()] creates an initial
follower state.*)
val become :
?current_leader:int ->
now:float ->
term:int ->
Raft_types.state ->
Raft_types.state
* [ become ~current_leader state term ] return the new follower state .
{ ul
{ li [ voted_for ] is [ None ] }
[ current_leader ] is taken from the function argument }
[ current_term ] is taken from the function argument }
}
{ul
{li [voted_for] is [None]}
{li [current_leader] is taken from the function argument}
{li [current_term] is taken from the function argument}
} *)
end (* Follower *)
module Candidate : sig
val become :
now:float ->
Raft_types.state ->
Raft_types.state
* [ become state now ] returns the new state with Candidate role .
[ current_term ] is incremented and [ vote_count ] initialized to 1 .
( ie we assume the candidate votes for itself .
The [ election_timeout ] is reset to a random number between the boundaries
of the configuration .
[current_term] is incremented and [vote_count] initialized to 1.
(ie we assume the candidate votes for itself.
The [election_timeout] is reset to a random number between the boundaries
of the configuration. *)
val increment_vote_count :
Raft_types.candidate_state ->
Raft_types.candidate_state
* [ increment_vote_count state ] increments the candidate vote count
by 1 .
This function is called upon receiving a successful response to a vote
request to one of the servers .
by 1.
This function is called upon receiving a successful response to a vote
request to one of the servers. *)
end (* Candidate *)
module Leader : sig
val become :
now:float ->
Raft_types.state ->
Raft_types.state
(** [become state] returns the new state with a Leader role.
While only candidate with a majority are allowed by the protocol to
become a leader, this function does not perform any checks but simply
initialize the role of Leader.
The calling application is responsible to ensure that it is correct
to become a leader. *)
val update_follower_last_log_index :
follower_id:int ->
index:int ->
Raft_types.leader_state ->
(Raft_types.leader_state * int)
* [ update_receiver_last_log_index leader_state receiver_id last_log_index ]
updates the leader state with the [ last_log_index ] information received
from a server . ( Both [ next_index ] and [ match_index ] are updated .
The function returns [ ( state , nb_of_replication ) ] . The
[ nb_of_replication ] is useful for the application to determine how many
servers have replicated the log and therefore determine if it can
be considered commited .
updates the leader state with the [last_log_index] information received
from a server. (Both [next_index] and [match_index] are updated.
The function returns [(state, nb_of_replication)]. The
[nb_of_replication] is useful for the application to determine how many
servers have replicated the log and therefore determine if it can
be considered commited. *)
val record_response_received :
follower_id:int ->
Raft_types.leader_state ->
Raft_types.leader_state
(** [record_response_received ~server_id leader_state] keeps track of the
fact that there are no more outstanding request for [server_id].
*)
val decrement_next_index :
follower_last_log_index:int ->
follower_id:int ->
Raft_types.state ->
Raft_types.leader_state ->
Raft_types.leader_state
val min_heartbeat_timout :
now:float ->
Raft_types.leader_state ->
float
(** [min_heartbeat_timout ~now ~leader_state] returns when the next timeout
event should occured based on the last request sent to the
followers *)
end (* Leader *)
module Timeout_event : sig
val next : now:float -> Raft_types.state -> Raft_types.timeout_event
* [ next ~now state ] returns the next timeout event which should happened
unless another RAFT event happened first .
unless another RAFT event happened first. *)
end (* Timeout_event *)
module Diff : sig
val leader_change :
Raft_types.state ->
Raft_types.state ->
Raft_types.leader_change option
* [ notifications before after ] computes the notification between 2 states
*)
val committed_logs :
Raft_types.state ->
Raft_types.state ->
Raft_log.log_entry list
(** [committed_logs before after] returns the newly committed log entries
between [before] and [after] state *)
end (* Diff *)
| null | https://raw.githubusercontent.com/mransan/raft/292f99475183d67e960b3a199ed4fc01b1f183e2/src/raft_helper.mli | ocaml | * Helper functions for manipulating Raft types
* [is_majority configuration nb] returns true if [nb] is a majority
Configuration
* [create ~configuration ~now ~server_id ()] creates an initial
follower state.
Follower
Candidate
* [become state] returns the new state with a Leader role.
While only candidate with a majority are allowed by the protocol to
become a leader, this function does not perform any checks but simply
initialize the role of Leader.
The calling application is responsible to ensure that it is correct
to become a leader.
* [record_response_received ~server_id leader_state] keeps track of the
fact that there are no more outstanding request for [server_id].
* [min_heartbeat_timout ~now ~leader_state] returns when the next timeout
event should occured based on the last request sent to the
followers
Leader
Timeout_event
* [committed_logs before after] returns the newly committed log entries
between [before] and [after] state
Diff |
module Configuration : sig
val is_majority : Raft_types.configuration -> int -> bool
module Follower : sig
val make :
?log:Raft_log.t ->
?commit_index:int ->
?current_term:int ->
configuration:Raft_types.configuration ->
now:float ->
server_id:int ->
unit ->
Raft_types.state
val become :
?current_leader:int ->
now:float ->
term:int ->
Raft_types.state ->
Raft_types.state
* [ become ~current_leader state term ] return the new follower state .
{ ul
{ li [ voted_for ] is [ None ] }
[ current_leader ] is taken from the function argument }
[ current_term ] is taken from the function argument }
}
{ul
{li [voted_for] is [None]}
{li [current_leader] is taken from the function argument}
{li [current_term] is taken from the function argument}
} *)
module Candidate : sig
val become :
now:float ->
Raft_types.state ->
Raft_types.state
* [ become state now ] returns the new state with Candidate role .
[ current_term ] is incremented and [ vote_count ] initialized to 1 .
( ie we assume the candidate votes for itself .
The [ election_timeout ] is reset to a random number between the boundaries
of the configuration .
[current_term] is incremented and [vote_count] initialized to 1.
(ie we assume the candidate votes for itself.
The [election_timeout] is reset to a random number between the boundaries
of the configuration. *)
val increment_vote_count :
Raft_types.candidate_state ->
Raft_types.candidate_state
* [ increment_vote_count state ] increments the candidate vote count
by 1 .
This function is called upon receiving a successful response to a vote
request to one of the servers .
by 1.
This function is called upon receiving a successful response to a vote
request to one of the servers. *)
module Leader : sig
val become :
now:float ->
Raft_types.state ->
Raft_types.state
val update_follower_last_log_index :
follower_id:int ->
index:int ->
Raft_types.leader_state ->
(Raft_types.leader_state * int)
* [ update_receiver_last_log_index leader_state receiver_id last_log_index ]
updates the leader state with the [ last_log_index ] information received
from a server . ( Both [ next_index ] and [ match_index ] are updated .
The function returns [ ( state , nb_of_replication ) ] . The
[ nb_of_replication ] is useful for the application to determine how many
servers have replicated the log and therefore determine if it can
be considered commited .
updates the leader state with the [last_log_index] information received
from a server. (Both [next_index] and [match_index] are updated.
The function returns [(state, nb_of_replication)]. The
[nb_of_replication] is useful for the application to determine how many
servers have replicated the log and therefore determine if it can
be considered commited. *)
val record_response_received :
follower_id:int ->
Raft_types.leader_state ->
Raft_types.leader_state
val decrement_next_index :
follower_last_log_index:int ->
follower_id:int ->
Raft_types.state ->
Raft_types.leader_state ->
Raft_types.leader_state
val min_heartbeat_timout :
now:float ->
Raft_types.leader_state ->
float
module Timeout_event : sig
val next : now:float -> Raft_types.state -> Raft_types.timeout_event
* [ next ~now state ] returns the next timeout event which should happened
unless another RAFT event happened first .
unless another RAFT event happened first. *)
module Diff : sig
val leader_change :
Raft_types.state ->
Raft_types.state ->
Raft_types.leader_change option
* [ notifications before after ] computes the notification between 2 states
*)
val committed_logs :
Raft_types.state ->
Raft_types.state ->
Raft_log.log_entry list
|
6daf92fae0a9197cc5818c573b89bbacc1c4ad3263e355c703b6dcffb1941d03 | input-output-hk/cardano-wallet | StakePools.hs | module Light.StakePools where
import Data.Map
( Map )
import Light.Types
-- | Summary of stake distribution and stake pools obtained from network
data StakePoolsSummary = StakePoolsSummary
^ implementable , see ' '
, pools :: Map PoolId RewardInfoPool -- ^ implementable, See 'RewardInfoPool'
}
-- | Global parameters used for computing rewards
data RewardParams = RewardParams
{ nOpt :: Int -- ^ yes, '_protocolParamsNOpt'
, a0 :: Rational -- ^ yes, '_protocolParamsA0'
, r :: Coin
-- ^ implementable, '_epochInfoFees', '_accountInfoReservesSum'?
, totalStake :: Coin -- ^ yes, '_genesisMaxLovelaceSupply'
}
-- | Information need for the computation of rewards, such as the'
-- stake currently delegated to a pool, or the pool cost and margin.'
data RewardInfoPool = RewardInfoPool
{ stakeRelative :: Rational -- ^ yes, '_poolStakeDistributionAmount'
, ownerPledge :: Coin -- ^ yes, '_poolInfoDeclaredPledge'
, ownerStake :: Coin -- ^ yes (?), '_poolInfoLivePledge'
, ownerStakeRelative :: Rational -- ^ yes, redundant
, cost :: Coin -- ^ yes, '_poolInfoFixedCost'
, margin :: Rational -- ^ yes, '_poolInfoMarginCost'
, performanceEstimate :: Double
^ implementable , ' getPoolHistory ' , ' PoolHistory ' , ' _ poolHistoryBlocks '
}
| null | https://raw.githubusercontent.com/input-output-hk/cardano-wallet/bfacc71ada6b926ee608e5e537e7040d37842eaf/prototypes/light-mode-test/src/Light/StakePools.hs | haskell | | Summary of stake distribution and stake pools obtained from network
^ implementable, See 'RewardInfoPool'
| Global parameters used for computing rewards
^ yes, '_protocolParamsNOpt'
^ yes, '_protocolParamsA0'
^ implementable, '_epochInfoFees', '_accountInfoReservesSum'?
^ yes, '_genesisMaxLovelaceSupply'
| Information need for the computation of rewards, such as the'
stake currently delegated to a pool, or the pool cost and margin.'
^ yes, '_poolStakeDistributionAmount'
^ yes, '_poolInfoDeclaredPledge'
^ yes (?), '_poolInfoLivePledge'
^ yes, redundant
^ yes, '_poolInfoFixedCost'
^ yes, '_poolInfoMarginCost' | module Light.StakePools where
import Data.Map
( Map )
import Light.Types
data StakePoolsSummary = StakePoolsSummary
^ implementable , see ' '
}
data RewardParams = RewardParams
, r :: Coin
}
data RewardInfoPool = RewardInfoPool
, performanceEstimate :: Double
^ implementable , ' getPoolHistory ' , ' PoolHistory ' , ' _ poolHistoryBlocks '
}
|
2de29f3f40642aa1a43c43828a8bdacadacb04c19309184ff2126be734ca07d3 | slyrus/mcclim-old | graphics.lisp | ;;; -*- Mode: Lisp; Package: CLIM-POSTSCRIPT -*-
( c ) copyright 2001 by
( )
;;; Lionel Salabartan ()
( c ) copyright 2002 by
( )
( )
;;; This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation ; either
version 2 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
Library General Public License for more details .
;;;
You should have received a copy of the GNU Library 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 .
;;; TODO:
;;;
;;; - clipping
;;; - - more regions to draw
;;; - (?) blending
;;; - MEDIUM-DRAW-TEXT*
- - : , y )
;;; - - landscape orientation
;;; - - (?) :transform-glyphs
;;; - POSTSCRIPT-ACTUALIZE-GRAPHICS-STATE: fix CLIPPING-REGION reusing logic
;;; - MEDIUM-DRAW-... should not duplicate code from POSTSCRIPT-ADD-PATH
;;; - structure this file
;;; - set miter limit?
(in-package :clim-postscript)
;;; Postscript output utilities
(defun write-number (stream number)
(format stream "~,3F " (coerce number 'single-float)))
(defun write-angle (stream angle)
(write-number stream (* angle (/ 180 pi))))
(defun write-coordinates (stream x y)
(with-transformed-position (*transformation* x y)
(write-number stream x)
(write-number stream y)))
(defun write-transformation* (stream mxx mxy myx myy tx ty)
(write-char #\[ stream)
(dolist (c (list mxx myx mxy myy tx ty))
(write-number stream c))
(write-string "] " stream))
;;; Low level functions
(defstruct postscript-procedure
(name nil :type (or symbol string))
(body "" :type string))
(defvar *dictionary-name* "McCLIMDict")
(defvar *procedures* (make-hash-table))
(defvar *extra-entries* 0)
(defun write-postscript-dictionary (stream)
;;; FIXME: DSC
(format stream "~&%%BeginProlog~%")
(format stream "/~A ~D dict def ~2:*~A begin~%"
*dictionary-name* (+ (hash-table-count *procedures*)
*extra-entries*))
(loop for proc being each hash-value in *procedures*
for name = (postscript-procedure-name proc)
and body = (postscript-procedure-body proc)
do (format stream "/~A { ~A } def~%" name body))
(format stream "end~%")
(dump-reencode stream)
(format stream "%%EndProlog~%"))
(defmacro define-postscript-procedure
((name &key postscript-name postscript-body
(extra-entries 0)) args
&body body)
(check-type name symbol)
(check-type postscript-name (or symbol string))
(check-type postscript-body string)
(check-type extra-entries unsigned-byte)
`(progn
(setf (gethash ',name *procedures*)
(make-postscript-procedure :name ,postscript-name
:body ,postscript-body))
(maxf *extra-entries* ,extra-entries)
(defun ,name ,args ,@body)))
;;;
(define-postscript-procedure
(moveto* :postscript-name "m"
:postscript-body "moveto")
(stream x y)
(write-coordinates stream x y)
(format stream "m~%"))
(define-postscript-procedure
(lineto* :postscript-name "l"
:postscript-body "lineto")
(stream x y)
(write-coordinates stream x y)
(format stream "l~%"))
(define-postscript-procedure
(put-rectangle* :postscript-name "pr"
:postscript-body
"/y2 exch def /x2 exch def /y1 exch def /x1 exch def
x1 y1 moveto x1 y2 lineto x2 y2 lineto x2 y1 lineto x1 y1 lineto"
:extra-entries 4)
(stream x1 y1 x2 y2)
(write-coordinates stream x1 y1)
(write-coordinates stream x2 y2)
(format stream "pr~%"))
(define-postscript-procedure (put-line* :postscript-name "pl"
:postscript-body "moveto lineto")
(stream x1 y1 x2 y2)
(write-coordinates stream x2 y2)
(write-coordinates stream x1 y1)
(format stream "pl~%"))
(define-postscript-procedure
(put-ellipse :postscript-name "pe"
:postscript-body
;; filled end-angle start-angle trans
"matrix currentmatrix 5 1 roll
concat dup rotate sub
1 0 moveto
0 0 1 0 5 -1 roll arc
{ 0 0 lineto 1 0 lineto } {} ifelse
setmatrix")
(stream ellipse filled)
(multiple-value-bind (ndx1 ndy1 ndx2 ndy2) (ellipse-normal-radii* ellipse)
(let* ((center (ellipse-center-point ellipse))
(cx (point-x center))
(cy (point-y center))
(tr (make-transformation ndx2 ndx1 ndy2 ndy1 cx cy))
(circle (untransform-region tr ellipse))
;; we need an extra minus sign because the rotation
;; convention for Postscript differs in chirality from the
abstract CLIM convention ; we do a reflection
;; transformation to move the coordinates to the right
;; handedness, but then the sense of positive rotation is
;; backwards, so we need this reflection for angles. --
CSR , 2005 - 08 - 01
(start-angle (- (or (ellipse-end-angle circle) 0)))
(end-angle (- (or (ellipse-start-angle circle) (* -2 pi)))))
(write-string (if filled "true " "false ") stream)
(write-angle stream (if (< end-angle start-angle)
(+ end-angle (* 2 pi))
end-angle))
(write-angle stream start-angle)
(write-transformation* stream ndx2 ndx1 ndy2 ndy1 cx cy)
(format stream "pe~%"))))
;;;;
(defvar *transformation* nil
"Native transformation")
;;; Postscript output utilities
(defmacro with-graphics-state ((stream) &body body)
`(invoke-with-graphics-state ,stream
(lambda () ,@body)))
(defun postscript-save-graphics-state (stream)
(push (copy-list (first (slot-value stream 'graphics-state-stack)))
(slot-value stream 'graphics-state-stack))
(when (stream-drawing-p stream)
(format (postscript-stream-file-stream stream) "gsave~%")))
(defun postscript-restore-graphics-state (stream)
(pop (slot-value stream 'graphics-state-stack))
(when (stream-drawing-p stream)
(format (postscript-stream-file-stream stream) "grestore~%")))
(defun invoke-with-graphics-state (stream continuation)
(postscript-save-graphics-state stream)
(funcall continuation)
(postscript-restore-graphics-state stream))
;;; Postscript path functions
(defgeneric postscript-add-path (stream region)
(:documentation
"Adds REGION (if it is a path) or its boundary (if it is an area)
to the current path of STREAM."))
(defmethod postscript-add-path (stream (region (eql +nowhere+)))
(declare (ignore stream)))
(defmethod postscript-add-path (stream (region standard-region-union))
(map-over-region-set-regions (lambda (region)
(postscript-add-path stream region))
region))
(defmethod postscript-add-path (stream (region standard-region-intersection))
(format stream "gsave~%")
#+nil (format stream "initclip~%")
(loop for subregion in (region-set-regions region)
do (format stream "newpath~%")
(postscript-add-path stream subregion)
(format stream "clip~%"))
(format stream "clippath false upath~%")
(format stream "grestore~%")
(format stream "uappend~%"))
;;; Primitive paths
(defmethod postscript-add-path (stream (polygon polygon))
(let ((points (polygon-points polygon)))
(moveto* stream (point-x (first points)) (point-y (first points)))
(loop for point in (rest points)
do (lineto* stream (point-x point) (point-y point)))
(format stream "closepath~%")))
(defmethod postscript-add-path (stream (ellipse ellipse))
(let ((ellipse (transform-region *transformation* ellipse)))
(put-ellipse stream ellipse t)))
(defmethod postscript-add-path (stream (rs climi::standard-rectangle-set))
(map-over-region-set-regions
(lambda (r) (postscript-add-path stream r))
rs))
;;; Graphics state
(defgeneric postscript-set-graphics-state (stream medium kind))
(defvar *postscript-graphics-states*
'((:line-style . medium-line-style)
(:color . medium-ink)
(:clipping-region . medium-clipping-region)
(:text-style . medium-text-style)))
(defun postscript-current-state (medium kind)
(funcall (cdr (assoc kind *postscript-graphics-states*))
medium))
(defmacro postscript-saved-state (medium kind)
`(getf (postscript-medium-graphics-state ,medium) ,kind))
(defun postscript-actualize-graphics-state (stream medium &rest kinds)
"Sets graphics parameters named in STATES."
(loop for kind in (cons :clipping-region kinds)
;; every drawing function depends on clipping region
;;
: clipping - region MUST be actualized first due to its
dirty dealing with graphics state . -- APD , 2002 - 02 - 11
unless (eql (postscript-current-state medium kind)
(postscript-saved-state medium kind))
do (postscript-set-graphics-state stream medium kind)
(setf (postscript-saved-state medium kind)
(postscript-current-state medium kind))))
;;; Line style
(defconstant +postscript-line-joints+ '(:miter 0
:round 1
:bevel 2
:none 0))
(defconstant +postscript-line-caps+ '(:butt 0
:round 1
:square 2 ; extended butt caps
:no-end-point 0))
(defconstant +postscript-default-line-dashes+ '(30 30))
(defconstant +normal-line-width+ (/ 2.0 3.0))
(defun line-style-scale (line-style)
(let ((unit (line-style-unit line-style)))
(ecase unit
(:normal +normal-line-width+)
(:point 1)
(:coordinate (error ":COORDINATE line unit is not implemented.")))))
(defmethod line-style-effective-thickness
(line-style (medium postscript-medium))
(* (line-style-thickness line-style)
(line-style-scale line-style)))
(defun medium-line-thickness (medium)
(line-style-effective-thickness (medium-line-style medium) medium))
(defmethod postscript-set-graphics-state (stream medium
(kind (eql :line-style)))
(let* ((line-style (medium-line-style medium))
(scale (line-style-scale line-style)))
(write-number stream (* scale (line-style-thickness line-style)))
(format stream "setlinewidth ~A setlinejoin ~A setlinecap~%"
(getf +postscript-line-joints+
(line-style-joint-shape line-style))
(getf +postscript-line-caps+
(line-style-cap-shape line-style)))
(let ((dashes (line-style-dashes line-style)))
(format stream "[")
(mapc (lambda (l) (write-number stream (* scale l)))
(if (eq dashes 't)
+postscript-default-line-dashes+
dashes))
(format stream "] 0 setdash~%"))))
Color
(defgeneric medium-color-rgb (medium ink))
(defmethod medium-color-rgb (medium (ink (eql +foreground-ink+)))
(medium-color-rgb medium (medium-foreground medium)))
(defmethod medium-color-rgb (medium (ink (eql +background-ink+)))
(medium-color-rgb medium (medium-background medium)))
(defmethod medium-color-rgb (medium (ink color))
(declare (ignore medium))
(color-rgb ink))
(defmethod postscript-set-graphics-state (stream medium (kind (eql :color)))
(multiple-value-bind (r g b)
(medium-color-rgb medium (medium-ink medium))
(write-number stream r)
(write-number stream g)
(write-number stream b)
(format stream "setrgbcolor~%")))
;;; Clipping region
(defgeneric postscript-set-clipping-region (stream region))
(defmethod postscript-set-clipping-region (stream region)
(format stream "newpath~%")
(postscript-add-path stream region)
(format stream "clip~%"))
(defmethod postscript-set-clipping-region (stream (region (eql +everywhere+)))
(declare (ignore stream)))
(defmethod postscript-set-clipping-region (stream (region (eql +nowhere+)))
(format stream "newpath 0 0 moveto closepath clip~%"))
(defmethod postscript-set-graphics-state (stream medium
(kind (eql :clipping-region)))
;; FIXME: There is no way to enlarge clipping path. Current code
does only one level of saving graphics state , so we can restore
and save again GS to obtain an initial CP . It is ugly , but I see
no other way now . -- APD , 2002 - 02 - 11
(postscript-restore-graphics-state (medium-sheet medium))
(postscript-save-graphics-state (medium-sheet medium))
(postscript-set-clipping-region stream
(medium-clipping-region medium)))
;;; Medium drawing functions
;;; FIXME: the following methods should share code with POSTSCRIPT-ADD-PATH
(defmethod medium-draw-point* ((medium postscript-medium) x y)
(let ((stream (postscript-medium-file-stream medium))
(*transformation* (sheet-native-transformation (medium-sheet medium)))
(radius (/ (medium-line-thickness medium) 2)))
(postscript-actualize-graphics-state stream medium :color)
(format stream "newpath~%")
(write-coordinates stream x y)
(write-number stream radius)
(format stream "0 360 arc~%")
(format stream "fill~%")))
(defmethod medium-draw-points* ((medium postscript-medium) coord-seq)
(let ((stream (postscript-medium-file-stream medium))
(*transformation* (sheet-native-transformation (medium-sheet medium)))
(radius (/ (medium-line-thickness medium) 2)))
(postscript-actualize-graphics-state stream medium :color)
(map-repeated-sequence 'nil 2
(lambda (x y)
(format stream "newpath~%")
(write-coordinates stream x y)
(write-number stream radius)
(format stream "0 360 arc~%")
(format stream "fill~%"))
coord-seq)))
(defmethod medium-draw-line* ((medium postscript-medium) x1 y1 x2 y2)
(let ((stream (postscript-medium-file-stream medium))
(*transformation* (sheet-native-transformation (medium-sheet medium))))
(postscript-actualize-graphics-state stream medium :line-style :color)
(format stream "newpath ")
(put-line* stream x1 y1 x2 y2)
(format stream "stroke~%")))
(defmethod medium-draw-lines* ((medium postscript-medium) coord-seq)
(let ((stream (postscript-medium-file-stream medium))
(*transformation* (sheet-native-transformation (medium-sheet medium))))
(postscript-actualize-graphics-state stream medium :line-style :color)
(format stream "newpath~%")
(map-repeated-sequence 'nil 4
(lambda (x1 y1 x2 y2) (put-line* stream x1 y1 x2 y2))
coord-seq)
(format stream "stroke~%")))
(defmethod medium-draw-polygon*
((medium postscript-medium) coord-seq closed filled)
(assert (evenp (length coord-seq)))
(let ((stream (postscript-medium-file-stream medium))
(*transformation* (sheet-native-transformation (medium-sheet medium))))
(postscript-actualize-graphics-state stream medium :line-style :color)
(format stream "newpath~%")
(let ((command "moveto"))
(map-repeated-sequence 'nil 2
(lambda (x y)
(write-coordinates stream x y)
(format stream "~A~%"
command)
(setq command "lineto"))
coord-seq))
(when closed
(format stream "closepath~%"))
(format stream (if filled "fill~%" "stroke~%"))))
(defmethod medium-draw-rectangle*
((medium postscript-medium) x1 y1 x2 y2 filled)
(let ((stream (postscript-medium-file-stream medium))
(*transformation* (sheet-native-transformation (medium-sheet medium))))
(postscript-actualize-graphics-state stream medium :line-style :color)
(format stream "newpath~%")
(put-rectangle* stream x1 y1 x2 y2)
(format stream (if filled "fill~%" "stroke~%"))))
(defmethod medium-draw-rectangles*
((medium postscript-medium) position-seq filled)
(assert (evenp (length position-seq)))
(let ((stream (postscript-medium-file-stream medium))
(*transformation* (sheet-native-transformation (medium-sheet medium))))
(postscript-actualize-graphics-state stream medium :line-style :color)
(format stream "newpath~%")
(map-repeated-sequence 'nil 4
(lambda (x1 y1 x2 y2) (put-rectangle* stream x1 y1 x2 y2))
position-seq)
(format stream (if filled "fill~%" "stroke~%"))))
(defmethod medium-draw-ellipse* ((medium postscript-medium) center-x center-y
radius1-dx radius1-dy radius2-dx radius2-dy
start-angle end-angle filled)
(let* ((stream (postscript-medium-file-stream medium))
(*transformation* (sheet-native-transformation (medium-sheet medium)))
(ellipse (transform-region
*transformation*
(make-ellipse* center-x center-y
radius1-dx radius1-dy radius2-dx radius2-dy
:start-angle start-angle
:end-angle end-angle))))
(postscript-actualize-graphics-state stream medium :line-style :color)
(format stream "newpath~%")
(put-ellipse stream ellipse filled)
(format stream (if filled "fill~%" "stroke~%"))))
(defun medium-font (medium)
(text-style-mapping (port medium) (medium-merged-text-style medium)))
(defmethod postscript-set-graphics-state (stream medium
(kind (eql :text-style)))
(let* ((font-name (medium-font medium))
(font (%font-name-postscript-name font-name))
(size (%font-name-size font-name)))
(pushnew font (slot-value (medium-sheet medium) 'document-fonts)
:test #'string=)
(format stream "/~A findfont ~D scalefont setfont~%"
font
# # # evil hack .
(defun postscript-escape-char (char)
(case char
(#\Linefeed "\\n")
(#\Return "\\r")
(#\Tab "\\t")
(#\Backspace "\\b")
(#\Page "\\f")
(#\\ "\\\\")
(#\( "\\(")
(#\) "\\)")
(t (if (standard-char-p char)
(string char)
(format nil "\\~3,'0O" (char-code char))))))
(defun postscript-escape-string (string)
(apply #'concatenate 'string
(map 'list #'postscript-escape-char string)))
(defmethod medium-draw-text* ((medium postscript-medium) string x y
start end
align-x align-y
toward-x toward-y transform-glyphs)
(setq string (if (characterp string)
(make-string 1 :initial-element string)
(subseq string start end)))
(let ((*transformation* (sheet-native-transformation (medium-sheet medium))))
(let ((file-stream (postscript-medium-file-stream medium)))
(postscript-actualize-graphics-state file-stream medium :color :text-style)
(with-graphics-state ((medium-sheet medium))
#+ignore
(when transform-glyphs
;;
;; Now the harder part is that we also want to transform the glyphs,
;; which is rather painless in Postscript. BUT: the x/y coordinates
;; we get are already transformed coordinates, so what I do is
;; untransform them again and simply tell the postscript interpreter
;; our transformation matrix. --GB
;;
;; This code changes both the form of glyphs and the
;; direction of the text, which does not conform to the
specification . So I 've disabled it . -- APD , 2002 - 06 - 03 .
(multiple-value-setq (x y)
(untransform-position (medium-transformation medium) x y))
(multiple-value-bind (mxx mxy myx myy tx ty)
(get-transformation (medium-transformation medium))
(format file-stream "initmatrix [~A ~A ~A ~A ~A ~A] concat~%"
(format-postscript-number mxx)
(format-postscript-number mxy)
(format-postscript-number myx)
(format-postscript-number myy)
(format-postscript-number tx)
(format-postscript-number ty))))
(multiple-value-bind (total-width total-height
final-x final-y baseline)
(let* ((font-name (medium-font medium))
(font (%font-name-metrics-key font-name))
(size (%font-name-size font-name)))
(text-size-in-font font size string 0 nil))
(declare (ignore final-x final-y))
;; Only one line?
(setq x (ecase align-x
(:left x)
(:center (- x (/ total-width 2)))
(:right (- x total-width))))
(setq y (ecase align-y
(:baseline y)
(:top (+ y baseline))
(:center (- y (- (/ total-height 2)
baseline)))
(:bottom (- y (- total-height baseline)))))
(moveto* file-stream x y))
(format file-stream "(~A) show~%" (postscript-escape-string string))))))
support
(defun %draw-bezier-area (stream area)
(format stream "newpath~%")
(let ((segments (climi::segments area)))
(let ((p0 (slot-value (car segments) 'climi::p0)))
(write-coordinates stream (point-x p0) (point-y p0))
(format stream "moveto~%"))
(loop for segment in segments
do (with-slots (climi::p1 climi::p2 climi::p3) segment
(write-coordinates stream (point-x climi::p1) (point-y climi::p1))
(write-coordinates stream (point-x climi::p2) (point-y climi::p2))
(write-coordinates stream (point-x climi::p3) (point-y climi::p3))
(format stream "curveto~%")))
(format stream "fill~%")))
(defmethod climi::medium-draw-bezier-design*
((medium postscript-medium) (design climi::bezier-area))
(let ((stream (postscript-medium-file-stream medium))
(*transformation* (sheet-native-transformation (medium-sheet medium))))
(postscript-actualize-graphics-state stream medium :color)
(%draw-bezier-area stream design)))
(defmethod climi::medium-draw-bezier-design*
((medium postscript-medium) (design climi::bezier-union))
(let ((stream (postscript-medium-file-stream medium))
(*transformation* (sheet-native-transformation (medium-sheet medium))))
(postscript-actualize-graphics-state stream medium :color)
(let ((tr (climi::transformation design)))
(dolist (area (climi::areas design))
(%draw-bezier-area stream (transform-region tr area))))))
(defmethod climi::medium-draw-bezier-design*
((medium postscript-medium) (design climi::bezier-difference))
(let ((stream (postscript-medium-file-stream medium))
(*transformation* (sheet-native-transformation (medium-sheet medium))))
(postscript-actualize-graphics-state stream medium :color)
(dolist (area (climi::positive-areas design))
(%draw-bezier-area stream area))
(with-drawing-options (medium :ink +background-ink+)
(postscript-actualize-graphics-state stream medium :color)
(dolist (area (climi::negative-areas design))
(%draw-bezier-area stream area)))))
| null | https://raw.githubusercontent.com/slyrus/mcclim-old/354cdf73c1a4c70e619ccd7d390cb2f416b21c1a/Backends/PostScript/graphics.lisp | lisp | -*- Mode: Lisp; Package: CLIM-POSTSCRIPT -*-
Lionel Salabartan ()
This library is free software; you can redistribute it and/or
either
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
License along with this library; if not, write to the
TODO:
- clipping
- - more regions to draw
- (?) blending
- MEDIUM-DRAW-TEXT*
- - landscape orientation
- - (?) :transform-glyphs
- POSTSCRIPT-ACTUALIZE-GRAPHICS-STATE: fix CLIPPING-REGION reusing logic
- MEDIUM-DRAW-... should not duplicate code from POSTSCRIPT-ADD-PATH
- structure this file
- set miter limit?
Postscript output utilities
Low level functions
FIXME: DSC
filled end-angle start-angle trans
we need an extra minus sign because the rotation
convention for Postscript differs in chirality from the
we do a reflection
transformation to move the coordinates to the right
handedness, but then the sense of positive rotation is
backwards, so we need this reflection for angles. --
Postscript output utilities
Postscript path functions
Primitive paths
Graphics state
every drawing function depends on clipping region
Line style
extended butt caps
Clipping region
FIXME: There is no way to enlarge clipping path. Current code
Medium drawing functions
FIXME: the following methods should share code with POSTSCRIPT-ADD-PATH
Now the harder part is that we also want to transform the glyphs,
which is rather painless in Postscript. BUT: the x/y coordinates
we get are already transformed coordinates, so what I do is
untransform them again and simply tell the postscript interpreter
our transformation matrix. --GB
This code changes both the form of glyphs and the
direction of the text, which does not conform to the
Only one line? |
( c ) copyright 2001 by
( )
( c ) copyright 2002 by
( )
( )
modify it under the terms of the GNU Library General Public
version 2 of the License , or ( at your option ) any later version .
Library General Public License for more details .
You should have received a copy of the GNU Library General Public
Free Software Foundation , Inc. , 59 Temple Place - Suite 330 ,
Boston , MA 02111 - 1307 USA .
- - : , y )
(in-package :clim-postscript)
(defun write-number (stream number)
(format stream "~,3F " (coerce number 'single-float)))
(defun write-angle (stream angle)
(write-number stream (* angle (/ 180 pi))))
(defun write-coordinates (stream x y)
(with-transformed-position (*transformation* x y)
(write-number stream x)
(write-number stream y)))
(defun write-transformation* (stream mxx mxy myx myy tx ty)
(write-char #\[ stream)
(dolist (c (list mxx myx mxy myy tx ty))
(write-number stream c))
(write-string "] " stream))
(defstruct postscript-procedure
(name nil :type (or symbol string))
(body "" :type string))
(defvar *dictionary-name* "McCLIMDict")
(defvar *procedures* (make-hash-table))
(defvar *extra-entries* 0)
(defun write-postscript-dictionary (stream)
(format stream "~&%%BeginProlog~%")
(format stream "/~A ~D dict def ~2:*~A begin~%"
*dictionary-name* (+ (hash-table-count *procedures*)
*extra-entries*))
(loop for proc being each hash-value in *procedures*
for name = (postscript-procedure-name proc)
and body = (postscript-procedure-body proc)
do (format stream "/~A { ~A } def~%" name body))
(format stream "end~%")
(dump-reencode stream)
(format stream "%%EndProlog~%"))
(defmacro define-postscript-procedure
((name &key postscript-name postscript-body
(extra-entries 0)) args
&body body)
(check-type name symbol)
(check-type postscript-name (or symbol string))
(check-type postscript-body string)
(check-type extra-entries unsigned-byte)
`(progn
(setf (gethash ',name *procedures*)
(make-postscript-procedure :name ,postscript-name
:body ,postscript-body))
(maxf *extra-entries* ,extra-entries)
(defun ,name ,args ,@body)))
(define-postscript-procedure
(moveto* :postscript-name "m"
:postscript-body "moveto")
(stream x y)
(write-coordinates stream x y)
(format stream "m~%"))
(define-postscript-procedure
(lineto* :postscript-name "l"
:postscript-body "lineto")
(stream x y)
(write-coordinates stream x y)
(format stream "l~%"))
(define-postscript-procedure
(put-rectangle* :postscript-name "pr"
:postscript-body
"/y2 exch def /x2 exch def /y1 exch def /x1 exch def
x1 y1 moveto x1 y2 lineto x2 y2 lineto x2 y1 lineto x1 y1 lineto"
:extra-entries 4)
(stream x1 y1 x2 y2)
(write-coordinates stream x1 y1)
(write-coordinates stream x2 y2)
(format stream "pr~%"))
(define-postscript-procedure (put-line* :postscript-name "pl"
:postscript-body "moveto lineto")
(stream x1 y1 x2 y2)
(write-coordinates stream x2 y2)
(write-coordinates stream x1 y1)
(format stream "pl~%"))
(define-postscript-procedure
(put-ellipse :postscript-name "pe"
:postscript-body
"matrix currentmatrix 5 1 roll
concat dup rotate sub
1 0 moveto
0 0 1 0 5 -1 roll arc
{ 0 0 lineto 1 0 lineto } {} ifelse
setmatrix")
(stream ellipse filled)
(multiple-value-bind (ndx1 ndy1 ndx2 ndy2) (ellipse-normal-radii* ellipse)
(let* ((center (ellipse-center-point ellipse))
(cx (point-x center))
(cy (point-y center))
(tr (make-transformation ndx2 ndx1 ndy2 ndy1 cx cy))
(circle (untransform-region tr ellipse))
CSR , 2005 - 08 - 01
(start-angle (- (or (ellipse-end-angle circle) 0)))
(end-angle (- (or (ellipse-start-angle circle) (* -2 pi)))))
(write-string (if filled "true " "false ") stream)
(write-angle stream (if (< end-angle start-angle)
(+ end-angle (* 2 pi))
end-angle))
(write-angle stream start-angle)
(write-transformation* stream ndx2 ndx1 ndy2 ndy1 cx cy)
(format stream "pe~%"))))
(defvar *transformation* nil
"Native transformation")
(defmacro with-graphics-state ((stream) &body body)
`(invoke-with-graphics-state ,stream
(lambda () ,@body)))
(defun postscript-save-graphics-state (stream)
(push (copy-list (first (slot-value stream 'graphics-state-stack)))
(slot-value stream 'graphics-state-stack))
(when (stream-drawing-p stream)
(format (postscript-stream-file-stream stream) "gsave~%")))
(defun postscript-restore-graphics-state (stream)
(pop (slot-value stream 'graphics-state-stack))
(when (stream-drawing-p stream)
(format (postscript-stream-file-stream stream) "grestore~%")))
(defun invoke-with-graphics-state (stream continuation)
(postscript-save-graphics-state stream)
(funcall continuation)
(postscript-restore-graphics-state stream))
(defgeneric postscript-add-path (stream region)
(:documentation
"Adds REGION (if it is a path) or its boundary (if it is an area)
to the current path of STREAM."))
(defmethod postscript-add-path (stream (region (eql +nowhere+)))
(declare (ignore stream)))
(defmethod postscript-add-path (stream (region standard-region-union))
(map-over-region-set-regions (lambda (region)
(postscript-add-path stream region))
region))
(defmethod postscript-add-path (stream (region standard-region-intersection))
(format stream "gsave~%")
#+nil (format stream "initclip~%")
(loop for subregion in (region-set-regions region)
do (format stream "newpath~%")
(postscript-add-path stream subregion)
(format stream "clip~%"))
(format stream "clippath false upath~%")
(format stream "grestore~%")
(format stream "uappend~%"))
(defmethod postscript-add-path (stream (polygon polygon))
(let ((points (polygon-points polygon)))
(moveto* stream (point-x (first points)) (point-y (first points)))
(loop for point in (rest points)
do (lineto* stream (point-x point) (point-y point)))
(format stream "closepath~%")))
(defmethod postscript-add-path (stream (ellipse ellipse))
(let ((ellipse (transform-region *transformation* ellipse)))
(put-ellipse stream ellipse t)))
(defmethod postscript-add-path (stream (rs climi::standard-rectangle-set))
(map-over-region-set-regions
(lambda (r) (postscript-add-path stream r))
rs))
(defgeneric postscript-set-graphics-state (stream medium kind))
(defvar *postscript-graphics-states*
'((:line-style . medium-line-style)
(:color . medium-ink)
(:clipping-region . medium-clipping-region)
(:text-style . medium-text-style)))
(defun postscript-current-state (medium kind)
(funcall (cdr (assoc kind *postscript-graphics-states*))
medium))
(defmacro postscript-saved-state (medium kind)
`(getf (postscript-medium-graphics-state ,medium) ,kind))
(defun postscript-actualize-graphics-state (stream medium &rest kinds)
"Sets graphics parameters named in STATES."
(loop for kind in (cons :clipping-region kinds)
: clipping - region MUST be actualized first due to its
dirty dealing with graphics state . -- APD , 2002 - 02 - 11
unless (eql (postscript-current-state medium kind)
(postscript-saved-state medium kind))
do (postscript-set-graphics-state stream medium kind)
(setf (postscript-saved-state medium kind)
(postscript-current-state medium kind))))
(defconstant +postscript-line-joints+ '(:miter 0
:round 1
:bevel 2
:none 0))
(defconstant +postscript-line-caps+ '(:butt 0
:round 1
:no-end-point 0))
(defconstant +postscript-default-line-dashes+ '(30 30))
(defconstant +normal-line-width+ (/ 2.0 3.0))
(defun line-style-scale (line-style)
(let ((unit (line-style-unit line-style)))
(ecase unit
(:normal +normal-line-width+)
(:point 1)
(:coordinate (error ":COORDINATE line unit is not implemented.")))))
(defmethod line-style-effective-thickness
(line-style (medium postscript-medium))
(* (line-style-thickness line-style)
(line-style-scale line-style)))
(defun medium-line-thickness (medium)
(line-style-effective-thickness (medium-line-style medium) medium))
(defmethod postscript-set-graphics-state (stream medium
(kind (eql :line-style)))
(let* ((line-style (medium-line-style medium))
(scale (line-style-scale line-style)))
(write-number stream (* scale (line-style-thickness line-style)))
(format stream "setlinewidth ~A setlinejoin ~A setlinecap~%"
(getf +postscript-line-joints+
(line-style-joint-shape line-style))
(getf +postscript-line-caps+
(line-style-cap-shape line-style)))
(let ((dashes (line-style-dashes line-style)))
(format stream "[")
(mapc (lambda (l) (write-number stream (* scale l)))
(if (eq dashes 't)
+postscript-default-line-dashes+
dashes))
(format stream "] 0 setdash~%"))))
Color
(defgeneric medium-color-rgb (medium ink))
(defmethod medium-color-rgb (medium (ink (eql +foreground-ink+)))
(medium-color-rgb medium (medium-foreground medium)))
(defmethod medium-color-rgb (medium (ink (eql +background-ink+)))
(medium-color-rgb medium (medium-background medium)))
(defmethod medium-color-rgb (medium (ink color))
(declare (ignore medium))
(color-rgb ink))
(defmethod postscript-set-graphics-state (stream medium (kind (eql :color)))
(multiple-value-bind (r g b)
(medium-color-rgb medium (medium-ink medium))
(write-number stream r)
(write-number stream g)
(write-number stream b)
(format stream "setrgbcolor~%")))
(defgeneric postscript-set-clipping-region (stream region))
(defmethod postscript-set-clipping-region (stream region)
(format stream "newpath~%")
(postscript-add-path stream region)
(format stream "clip~%"))
(defmethod postscript-set-clipping-region (stream (region (eql +everywhere+)))
(declare (ignore stream)))
(defmethod postscript-set-clipping-region (stream (region (eql +nowhere+)))
(format stream "newpath 0 0 moveto closepath clip~%"))
(defmethod postscript-set-graphics-state (stream medium
(kind (eql :clipping-region)))
does only one level of saving graphics state , so we can restore
and save again GS to obtain an initial CP . It is ugly , but I see
no other way now . -- APD , 2002 - 02 - 11
(postscript-restore-graphics-state (medium-sheet medium))
(postscript-save-graphics-state (medium-sheet medium))
(postscript-set-clipping-region stream
(medium-clipping-region medium)))
(defmethod medium-draw-point* ((medium postscript-medium) x y)
(let ((stream (postscript-medium-file-stream medium))
(*transformation* (sheet-native-transformation (medium-sheet medium)))
(radius (/ (medium-line-thickness medium) 2)))
(postscript-actualize-graphics-state stream medium :color)
(format stream "newpath~%")
(write-coordinates stream x y)
(write-number stream radius)
(format stream "0 360 arc~%")
(format stream "fill~%")))
(defmethod medium-draw-points* ((medium postscript-medium) coord-seq)
(let ((stream (postscript-medium-file-stream medium))
(*transformation* (sheet-native-transformation (medium-sheet medium)))
(radius (/ (medium-line-thickness medium) 2)))
(postscript-actualize-graphics-state stream medium :color)
(map-repeated-sequence 'nil 2
(lambda (x y)
(format stream "newpath~%")
(write-coordinates stream x y)
(write-number stream radius)
(format stream "0 360 arc~%")
(format stream "fill~%"))
coord-seq)))
(defmethod medium-draw-line* ((medium postscript-medium) x1 y1 x2 y2)
(let ((stream (postscript-medium-file-stream medium))
(*transformation* (sheet-native-transformation (medium-sheet medium))))
(postscript-actualize-graphics-state stream medium :line-style :color)
(format stream "newpath ")
(put-line* stream x1 y1 x2 y2)
(format stream "stroke~%")))
(defmethod medium-draw-lines* ((medium postscript-medium) coord-seq)
(let ((stream (postscript-medium-file-stream medium))
(*transformation* (sheet-native-transformation (medium-sheet medium))))
(postscript-actualize-graphics-state stream medium :line-style :color)
(format stream "newpath~%")
(map-repeated-sequence 'nil 4
(lambda (x1 y1 x2 y2) (put-line* stream x1 y1 x2 y2))
coord-seq)
(format stream "stroke~%")))
(defmethod medium-draw-polygon*
((medium postscript-medium) coord-seq closed filled)
(assert (evenp (length coord-seq)))
(let ((stream (postscript-medium-file-stream medium))
(*transformation* (sheet-native-transformation (medium-sheet medium))))
(postscript-actualize-graphics-state stream medium :line-style :color)
(format stream "newpath~%")
(let ((command "moveto"))
(map-repeated-sequence 'nil 2
(lambda (x y)
(write-coordinates stream x y)
(format stream "~A~%"
command)
(setq command "lineto"))
coord-seq))
(when closed
(format stream "closepath~%"))
(format stream (if filled "fill~%" "stroke~%"))))
(defmethod medium-draw-rectangle*
((medium postscript-medium) x1 y1 x2 y2 filled)
(let ((stream (postscript-medium-file-stream medium))
(*transformation* (sheet-native-transformation (medium-sheet medium))))
(postscript-actualize-graphics-state stream medium :line-style :color)
(format stream "newpath~%")
(put-rectangle* stream x1 y1 x2 y2)
(format stream (if filled "fill~%" "stroke~%"))))
(defmethod medium-draw-rectangles*
((medium postscript-medium) position-seq filled)
(assert (evenp (length position-seq)))
(let ((stream (postscript-medium-file-stream medium))
(*transformation* (sheet-native-transformation (medium-sheet medium))))
(postscript-actualize-graphics-state stream medium :line-style :color)
(format stream "newpath~%")
(map-repeated-sequence 'nil 4
(lambda (x1 y1 x2 y2) (put-rectangle* stream x1 y1 x2 y2))
position-seq)
(format stream (if filled "fill~%" "stroke~%"))))
(defmethod medium-draw-ellipse* ((medium postscript-medium) center-x center-y
radius1-dx radius1-dy radius2-dx radius2-dy
start-angle end-angle filled)
(let* ((stream (postscript-medium-file-stream medium))
(*transformation* (sheet-native-transformation (medium-sheet medium)))
(ellipse (transform-region
*transformation*
(make-ellipse* center-x center-y
radius1-dx radius1-dy radius2-dx radius2-dy
:start-angle start-angle
:end-angle end-angle))))
(postscript-actualize-graphics-state stream medium :line-style :color)
(format stream "newpath~%")
(put-ellipse stream ellipse filled)
(format stream (if filled "fill~%" "stroke~%"))))
(defun medium-font (medium)
(text-style-mapping (port medium) (medium-merged-text-style medium)))
(defmethod postscript-set-graphics-state (stream medium
(kind (eql :text-style)))
(let* ((font-name (medium-font medium))
(font (%font-name-postscript-name font-name))
(size (%font-name-size font-name)))
(pushnew font (slot-value (medium-sheet medium) 'document-fonts)
:test #'string=)
(format stream "/~A findfont ~D scalefont setfont~%"
font
# # # evil hack .
(defun postscript-escape-char (char)
(case char
(#\Linefeed "\\n")
(#\Return "\\r")
(#\Tab "\\t")
(#\Backspace "\\b")
(#\Page "\\f")
(#\\ "\\\\")
(#\( "\\(")
(#\) "\\)")
(t (if (standard-char-p char)
(string char)
(format nil "\\~3,'0O" (char-code char))))))
(defun postscript-escape-string (string)
(apply #'concatenate 'string
(map 'list #'postscript-escape-char string)))
(defmethod medium-draw-text* ((medium postscript-medium) string x y
start end
align-x align-y
toward-x toward-y transform-glyphs)
(setq string (if (characterp string)
(make-string 1 :initial-element string)
(subseq string start end)))
(let ((*transformation* (sheet-native-transformation (medium-sheet medium))))
(let ((file-stream (postscript-medium-file-stream medium)))
(postscript-actualize-graphics-state file-stream medium :color :text-style)
(with-graphics-state ((medium-sheet medium))
#+ignore
(when transform-glyphs
specification . So I 've disabled it . -- APD , 2002 - 06 - 03 .
(multiple-value-setq (x y)
(untransform-position (medium-transformation medium) x y))
(multiple-value-bind (mxx mxy myx myy tx ty)
(get-transformation (medium-transformation medium))
(format file-stream "initmatrix [~A ~A ~A ~A ~A ~A] concat~%"
(format-postscript-number mxx)
(format-postscript-number mxy)
(format-postscript-number myx)
(format-postscript-number myy)
(format-postscript-number tx)
(format-postscript-number ty))))
(multiple-value-bind (total-width total-height
final-x final-y baseline)
(let* ((font-name (medium-font medium))
(font (%font-name-metrics-key font-name))
(size (%font-name-size font-name)))
(text-size-in-font font size string 0 nil))
(declare (ignore final-x final-y))
(setq x (ecase align-x
(:left x)
(:center (- x (/ total-width 2)))
(:right (- x total-width))))
(setq y (ecase align-y
(:baseline y)
(:top (+ y baseline))
(:center (- y (- (/ total-height 2)
baseline)))
(:bottom (- y (- total-height baseline)))))
(moveto* file-stream x y))
(format file-stream "(~A) show~%" (postscript-escape-string string))))))
support
(defun %draw-bezier-area (stream area)
(format stream "newpath~%")
(let ((segments (climi::segments area)))
(let ((p0 (slot-value (car segments) 'climi::p0)))
(write-coordinates stream (point-x p0) (point-y p0))
(format stream "moveto~%"))
(loop for segment in segments
do (with-slots (climi::p1 climi::p2 climi::p3) segment
(write-coordinates stream (point-x climi::p1) (point-y climi::p1))
(write-coordinates stream (point-x climi::p2) (point-y climi::p2))
(write-coordinates stream (point-x climi::p3) (point-y climi::p3))
(format stream "curveto~%")))
(format stream "fill~%")))
(defmethod climi::medium-draw-bezier-design*
((medium postscript-medium) (design climi::bezier-area))
(let ((stream (postscript-medium-file-stream medium))
(*transformation* (sheet-native-transformation (medium-sheet medium))))
(postscript-actualize-graphics-state stream medium :color)
(%draw-bezier-area stream design)))
(defmethod climi::medium-draw-bezier-design*
((medium postscript-medium) (design climi::bezier-union))
(let ((stream (postscript-medium-file-stream medium))
(*transformation* (sheet-native-transformation (medium-sheet medium))))
(postscript-actualize-graphics-state stream medium :color)
(let ((tr (climi::transformation design)))
(dolist (area (climi::areas design))
(%draw-bezier-area stream (transform-region tr area))))))
(defmethod climi::medium-draw-bezier-design*
((medium postscript-medium) (design climi::bezier-difference))
(let ((stream (postscript-medium-file-stream medium))
(*transformation* (sheet-native-transformation (medium-sheet medium))))
(postscript-actualize-graphics-state stream medium :color)
(dolist (area (climi::positive-areas design))
(%draw-bezier-area stream area))
(with-drawing-options (medium :ink +background-ink+)
(postscript-actualize-graphics-state stream medium :color)
(dolist (area (climi::negative-areas design))
(%draw-bezier-area stream area)))))
|
026caddb75f3654b2c7788b6be3978df3641b2f8584d3e4d8e85108bc5286cd7 | AndrewRademacher/aeson-casing | Test.hs | # LANGUAGE DeriveGeneric #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE TemplateHaskell #
module Data.Aeson.Casing.Test (tests) where
import Data.Aeson
import GHC.Generics
import Test.Tasty
import Test.Tasty.HUnit
import Test.Tasty.TH
import Data.Aeson.Casing.Internal
tests :: TestTree
tests = $(testGroupGenerator)
case_snake :: Assertion
case_snake = do snakeCase "SampleField" @=? "sample_field"
snakeCase "sampleField" @=? "sample_field"
case_camel :: Assertion
case_camel = do camelCase "SampleField" @=? "sampleField"
camelCase "sampleField" @=? "sampleField"
case_pascal :: Assertion
case_pascal = do pascalCase "SampleField" @=? "SampleField"
pascalCase "sampleField" @=? "SampleField"
case_train :: Assertion
case_train = do trainCase "SampleField" @=? "sample-field"
trainCase "sampleField" @=? "sample-field"
case_prefix :: Assertion
case_prefix = dropFPrefix "extraSampleField" @=? "SampleField"
----
data Person = Person
{ personFirstName :: String
, personLastName :: String
} deriving (Eq, Show, Generic)
data Animal = Animal
{ animalFirstName :: String
, animalBreedName :: String
} deriving (Eq, Show, Generic)
instance ToJSON Person where
toJSON = genericToJSON $ aesonPrefix snakeCase
instance FromJSON Person where
parseJSON = genericParseJSON $ aesonPrefix snakeCase
instance ToJSON Animal where
toJSON = genericToJSON $ aesonPrefix trainCase
instance FromJSON Animal where
parseJSON = genericParseJSON $ aesonPrefix trainCase
johnDoe = Person "John" "Doe"
johnDoeJSON = "{\"first_name\":\"John\",\"last_name\":\"Doe\"}"
persianEgypt = Animal "Toffee" "Persian Cat"
persianEgyptJSON = "{\"breed-name\":\"Persian Cat\",\"first-name\":\"Toffee\"}"
case_encode_snake :: Assertion
case_encode_snake = do
let b = encode johnDoe
b @=? johnDoeJSON
case_decode_snake :: Assertion
case_decode_snake = do
let p = decode johnDoeJSON :: Maybe Person
p @=? Just johnDoe
case_encode_train :: Assertion
case_encode_train = do
let b = encode persianEgypt
b @=? persianEgyptJSON
case_decode_train :: Assertion
case_decode_train = do
let p = decode persianEgyptJSON :: Maybe Animal
p @=? Just persianEgypt
| null | https://raw.githubusercontent.com/AndrewRademacher/aeson-casing/a6acbc40f6cffce7692cab5022d98732dc7a68b3/test/Data/Aeson/Casing/Test.hs | haskell | # LANGUAGE OverloadedStrings #
-- | # LANGUAGE DeriveGeneric #
# LANGUAGE TemplateHaskell #
module Data.Aeson.Casing.Test (tests) where
import Data.Aeson
import GHC.Generics
import Test.Tasty
import Test.Tasty.HUnit
import Test.Tasty.TH
import Data.Aeson.Casing.Internal
tests :: TestTree
tests = $(testGroupGenerator)
case_snake :: Assertion
case_snake = do snakeCase "SampleField" @=? "sample_field"
snakeCase "sampleField" @=? "sample_field"
case_camel :: Assertion
case_camel = do camelCase "SampleField" @=? "sampleField"
camelCase "sampleField" @=? "sampleField"
case_pascal :: Assertion
case_pascal = do pascalCase "SampleField" @=? "SampleField"
pascalCase "sampleField" @=? "SampleField"
case_train :: Assertion
case_train = do trainCase "SampleField" @=? "sample-field"
trainCase "sampleField" @=? "sample-field"
case_prefix :: Assertion
case_prefix = dropFPrefix "extraSampleField" @=? "SampleField"
data Person = Person
{ personFirstName :: String
, personLastName :: String
} deriving (Eq, Show, Generic)
data Animal = Animal
{ animalFirstName :: String
, animalBreedName :: String
} deriving (Eq, Show, Generic)
instance ToJSON Person where
toJSON = genericToJSON $ aesonPrefix snakeCase
instance FromJSON Person where
parseJSON = genericParseJSON $ aesonPrefix snakeCase
instance ToJSON Animal where
toJSON = genericToJSON $ aesonPrefix trainCase
instance FromJSON Animal where
parseJSON = genericParseJSON $ aesonPrefix trainCase
johnDoe = Person "John" "Doe"
johnDoeJSON = "{\"first_name\":\"John\",\"last_name\":\"Doe\"}"
persianEgypt = Animal "Toffee" "Persian Cat"
persianEgyptJSON = "{\"breed-name\":\"Persian Cat\",\"first-name\":\"Toffee\"}"
case_encode_snake :: Assertion
case_encode_snake = do
let b = encode johnDoe
b @=? johnDoeJSON
case_decode_snake :: Assertion
case_decode_snake = do
let p = decode johnDoeJSON :: Maybe Person
p @=? Just johnDoe
case_encode_train :: Assertion
case_encode_train = do
let b = encode persianEgypt
b @=? persianEgyptJSON
case_decode_train :: Assertion
case_decode_train = do
let p = decode persianEgyptJSON :: Maybe Animal
p @=? Just persianEgypt
|
06794c30b5562bf72b85951cf61c5053d94834470832efbfa2342adf67a02e0b | mbutterick/pollen | test-langs.rkt | #lang at-exp racket/base
(require rackunit
racket/port
racket/system
racket/runtime-path
compiler/find-exe
pollen/render
pollen/unstable/convert
txexpr)
(module test-default pollen
"hello world")
(require (prefix-in default: 'test-default))
(check-equal? default:doc "hello world")
(module test-pre pollen/pre
"hello world"
(void))
(require (prefix-in pre: 'test-pre))
(check-equal? pre:doc "hello world")
(module test-markup pollen/markup
"hello world"
(void))
(require (prefix-in markup: 'test-markup))
(check-equal? markup:doc '(root "hello world"))
(module test-markdown pollen/markdown
"hello world"
(void))
(require (prefix-in markdown: 'test-markdown))
(check-equal? markdown:doc '(root (p "hello world")))
(module test-ptree pollen/ptree
'(index (brother sister)))
(require (prefix-in ptree: 'test-ptree))
(check-equal? ptree:doc '(pagetree-root (index (brother sister))))
;; define-runtime-path only allowed at top level
(define-runtime-path test.ptree "data/test.ptree")
(define-runtime-path test.html.pm "data/test.html.pm")
(define-runtime-path test-import.html.pm "data/test-import.html.pm")
(define-runtime-path test.html.pmd "data/test.html.pmd")
(define-runtime-path test.html.pp "data/test.html.pp")
(define-runtime-path test.no-ext "data/test.no-ext")
(define-runtime-path test.pp "data/test.pp")
(define-runtime-path test.pm "data/test.pm")
;; `find-exe` avoids reliance on $PATH of the host system
(define racket-path (find-exe))
(when racket-path
(define (run path)
(define cmd-string (format "'~a' ~a" racket-path path))
(with-output-to-string (λ () (system cmd-string))))
(check-equal? (run test.ptree) "'(pagetree-root test ====)")
(check-equal? (run test.html.pm) @string-append{'(root "test" "\n" "====")})
(check-equal? (run test-import.html.pm) @string-append{'(root "test" "\n" "====" "\n" (root "This is sample 01."))})
(check-equal? (run test.html.pmd) "'(root (h1 ((id \"test\")) \"test\"))")
(check-equal? (run test.html.pp) "test\n====")
(check-equal? (run test.no-ext) "test\n====")
(check-equal? (run test.pm) "'(root \"test\" \"\\n\" \"====\")")
(check-equal? (run test.pp) "test\n====")
(check-txexprs-equal? (html->xexpr (render test.html.pm)) (html->xexpr "<html><head><meta charset=\"UTF-8\"/></head><body><root>test\n====</root></body></html>"))
(check-txexprs-equal? (html->xexpr (render test.html.pmd)) (html->xexpr "<html><head><meta charset=\"UTF-8\"/></head><body><root><h1 id=\"test\">test</h1></root></body></html>"))
(check-txexprs-equal? (render test.html.pp) "test\n====")
(check-txexprs-equal? (html->xexpr (render test.pm)) (html->xexpr "<html><head><meta charset=\"UTF-8\"/></head><body><root>test\n====</root></body></html>"))
(check-txexprs-equal? (render test.pp) "test\n===="))
| null | https://raw.githubusercontent.com/mbutterick/pollen/a4910a86dc62d1147f3aad94b56cecd6499d7aa6/pollen/test/test-langs.rkt | racket | define-runtime-path only allowed at top level
`find-exe` avoids reliance on $PATH of the host system | #lang at-exp racket/base
(require rackunit
racket/port
racket/system
racket/runtime-path
compiler/find-exe
pollen/render
pollen/unstable/convert
txexpr)
(module test-default pollen
"hello world")
(require (prefix-in default: 'test-default))
(check-equal? default:doc "hello world")
(module test-pre pollen/pre
"hello world"
(void))
(require (prefix-in pre: 'test-pre))
(check-equal? pre:doc "hello world")
(module test-markup pollen/markup
"hello world"
(void))
(require (prefix-in markup: 'test-markup))
(check-equal? markup:doc '(root "hello world"))
(module test-markdown pollen/markdown
"hello world"
(void))
(require (prefix-in markdown: 'test-markdown))
(check-equal? markdown:doc '(root (p "hello world")))
(module test-ptree pollen/ptree
'(index (brother sister)))
(require (prefix-in ptree: 'test-ptree))
(check-equal? ptree:doc '(pagetree-root (index (brother sister))))
(define-runtime-path test.ptree "data/test.ptree")
(define-runtime-path test.html.pm "data/test.html.pm")
(define-runtime-path test-import.html.pm "data/test-import.html.pm")
(define-runtime-path test.html.pmd "data/test.html.pmd")
(define-runtime-path test.html.pp "data/test.html.pp")
(define-runtime-path test.no-ext "data/test.no-ext")
(define-runtime-path test.pp "data/test.pp")
(define-runtime-path test.pm "data/test.pm")
(define racket-path (find-exe))
(when racket-path
(define (run path)
(define cmd-string (format "'~a' ~a" racket-path path))
(with-output-to-string (λ () (system cmd-string))))
(check-equal? (run test.ptree) "'(pagetree-root test ====)")
(check-equal? (run test.html.pm) @string-append{'(root "test" "\n" "====")})
(check-equal? (run test-import.html.pm) @string-append{'(root "test" "\n" "====" "\n" (root "This is sample 01."))})
(check-equal? (run test.html.pmd) "'(root (h1 ((id \"test\")) \"test\"))")
(check-equal? (run test.html.pp) "test\n====")
(check-equal? (run test.no-ext) "test\n====")
(check-equal? (run test.pm) "'(root \"test\" \"\\n\" \"====\")")
(check-equal? (run test.pp) "test\n====")
(check-txexprs-equal? (html->xexpr (render test.html.pm)) (html->xexpr "<html><head><meta charset=\"UTF-8\"/></head><body><root>test\n====</root></body></html>"))
(check-txexprs-equal? (html->xexpr (render test.html.pmd)) (html->xexpr "<html><head><meta charset=\"UTF-8\"/></head><body><root><h1 id=\"test\">test</h1></root></body></html>"))
(check-txexprs-equal? (render test.html.pp) "test\n====")
(check-txexprs-equal? (html->xexpr (render test.pm)) (html->xexpr "<html><head><meta charset=\"UTF-8\"/></head><body><root>test\n====</root></body></html>"))
(check-txexprs-equal? (render test.pp) "test\n===="))
|
c14685be109812d47c33c5047b2f60d4088530c5a38bcf131628912e746a854e | jamshidh/ethereum-client-haskell | Display.hs |
module Blockchain.Display (
addPingCount,
setPeers,
displayMessage
) where
import Control.Monad.IO.Class
import Control.Monad.Trans.State
import qualified Blockchain.Colors as CL
import Blockchain.Context
import Blockchain.Data.Peer
import Blockchain.Format
import Blockchain.Data.Wire
setTitle::String->IO()
setTitle value = do
putStr $ "\ESC]0;" ++ value ++ "\007"
updateStatus::ContextM ()
updateStatus = do
cxt <- get
liftIO $ setTitle $
"pingCount = " ++ show (pingCount cxt)
++ ", peer count=" ++ show (length $ peers cxt)
++ ", hashes requested=" ++ show (length $ neededBlockHashes cxt)
addPingCount::ContextM ()
addPingCount = do
cxt <- get
put cxt{pingCount = pingCount cxt + 1}
updateStatus
setPeers::[Peer]->ContextM ()
setPeers p = do
cxt <- get
put cxt{peers = p}
updateStatus
prefix::Bool->String
prefix True = CL.green "msg>>>>>: "
prefix False = CL.cyan "msg<<<<: "
displayMessage::Bool->Message->ContextM ()
displayMessage _ Ping = return ()
displayMessage _ Pong = return ()
displayMessage _ GetPeers = return ()
displayMessage _ (Peers _) = return ()
displayMessage outbound (GetBlocks blocks) = do
liftIO $ putStrLn $ prefix outbound ++ CL.blue "GetBlocks: " ++ "(Requesting " ++ show (length blocks) ++ " blocks)"
displayMessage _ QqqqPacket = return ()
displayMessage outbound (BlockHashes shas) = do
liftIO $ putStrLn $ prefix outbound ++ CL.blue "BlockHashes: " ++ "(" ++ show (length shas) ++ " new hashes)"
updateStatus
displayMessage outbound (Blocks blocks) = do
liftIO $ putStrLn $ prefix outbound ++ CL.blue "Blocks: " ++ "(" ++ show (length blocks) ++ " new blocks)"
updateStatus
displayMessage outbound msg =
liftIO $ putStrLn $ (prefix outbound) ++ format msg
| null | https://raw.githubusercontent.com/jamshidh/ethereum-client-haskell/6f02781ff661b6a9687fd6fe0f3e0d99d1eacc6b/src/Blockchain/Display.hs | haskell |
module Blockchain.Display (
addPingCount,
setPeers,
displayMessage
) where
import Control.Monad.IO.Class
import Control.Monad.Trans.State
import qualified Blockchain.Colors as CL
import Blockchain.Context
import Blockchain.Data.Peer
import Blockchain.Format
import Blockchain.Data.Wire
setTitle::String->IO()
setTitle value = do
putStr $ "\ESC]0;" ++ value ++ "\007"
updateStatus::ContextM ()
updateStatus = do
cxt <- get
liftIO $ setTitle $
"pingCount = " ++ show (pingCount cxt)
++ ", peer count=" ++ show (length $ peers cxt)
++ ", hashes requested=" ++ show (length $ neededBlockHashes cxt)
addPingCount::ContextM ()
addPingCount = do
cxt <- get
put cxt{pingCount = pingCount cxt + 1}
updateStatus
setPeers::[Peer]->ContextM ()
setPeers p = do
cxt <- get
put cxt{peers = p}
updateStatus
prefix::Bool->String
prefix True = CL.green "msg>>>>>: "
prefix False = CL.cyan "msg<<<<: "
displayMessage::Bool->Message->ContextM ()
displayMessage _ Ping = return ()
displayMessage _ Pong = return ()
displayMessage _ GetPeers = return ()
displayMessage _ (Peers _) = return ()
displayMessage outbound (GetBlocks blocks) = do
liftIO $ putStrLn $ prefix outbound ++ CL.blue "GetBlocks: " ++ "(Requesting " ++ show (length blocks) ++ " blocks)"
displayMessage _ QqqqPacket = return ()
displayMessage outbound (BlockHashes shas) = do
liftIO $ putStrLn $ prefix outbound ++ CL.blue "BlockHashes: " ++ "(" ++ show (length shas) ++ " new hashes)"
updateStatus
displayMessage outbound (Blocks blocks) = do
liftIO $ putStrLn $ prefix outbound ++ CL.blue "Blocks: " ++ "(" ++ show (length blocks) ++ " new blocks)"
updateStatus
displayMessage outbound msg =
liftIO $ putStrLn $ (prefix outbound) ++ format msg
| |
4c5d013fa1949dba92dd4e764a9d5439c075a8e8410941a68aa063b79cff54e3 | theodormoroianu/SecondYearCourses | LambdaChurch_20210415171024.hs | module LambdaChurch where
import Data.Char (isLetter)
import Data.List ( nub )
class ShowNice a where
showNice :: a -> String
class ReadNice a where
readNice :: String -> (a, String)
data Variable
= Variable
{ name :: String
, count :: Int
}
deriving (Show, Eq, Ord)
var :: String -> Variable
var x = Variable x 0
instance ShowNice Variable where
showNice (Variable x 0) = x
showNice (Variable x cnt) = x <> "_" <> show cnt
instance ReadNice Variable where
readNice s
| null x = error $ "expected variable but found " <> s
| otherwise = (var x, s')
where
(x, s') = span isLetter s
freshVariable :: Variable -> [Variable] -> Variable
freshVariable var vars = Variable x (cnt + 1)
where
x = name var
varsWithName = filter ((== x) . name) vars
Variable _ cnt = maximum (var : varsWithName)
data Term
= V Variable
| App Term Term
| Lam Variable Term
deriving (Show)
-- alpha-equivalence
aEq :: Term -> Term -> Bool
aEq (V x) (V x') = x == x'
aEq (App t1 t2) (App t1' t2') = aEq t1 t1' && aEq t2 t2'
aEq (Lam x t) (Lam x' t')
| x == x' = aEq t t'
| otherwise = aEq (subst (V y) x t) (subst (V y) x' t')
where
fvT = freeVars t
fvT' = freeVars t'
allFV = nub ([x, x'] ++ fvT ++ fvT')
y = freshVariable x allFV
aEq _ _ = False
v :: String -> Term
v x = V (var x)
lam :: String -> Term -> Term
lam x = Lam (var x)
lams :: [String] -> Term -> Term
lams xs t = foldr lam t xs
($$) :: Term -> Term -> Term
($$) = App
infixl 9 $$
instance ShowNice Term where
showNice (V var) = showNice var
showNice (App t1 t2) = "(" <> showNice t1 <> " " <> showNice t2 <> ")"
showNice (Lam var t) = "(" <> "\\" <> showNice var <> "." <> showNice t <> ")"
instance ReadNice Term where
readNice [] = error "Nothing to read"
readNice ('(' : '\\' : s) = (Lam var t, s'')
where
(var, '.' : s') = readNice s
(t, ')' : s'') = readNice s'
readNice ('(' : s) = (App t1 t2, s'')
where
(t1, ' ' : s') = readNice s
(t2, ')' : s'') = readNice s'
readNice s = (V var, s')
where
(var, s') = readNice s
freeVars :: Term -> [Variable]
freeVars (V var) = [var]
freeVars (App t1 t2) = nub $ freeVars t1 ++ freeVars t2
freeVars (Lam var t) = filter (/= var) (freeVars t)
-- subst u x t defines [u/x]t, i.e., substituting u for x in t
for example [ 3 / x](x + x ) = = 3 + 3
-- This substitution avoids variable captures so it is safe to be used when
-- reducing terms with free variables (e.g., if evaluating inside lambda abstractions)
subst
:: Term -- ^ substitution term
-> Variable -- ^ variable to be substitutes
-> Term -- ^ term in which the substitution occurs
-> Term
subst u x (V y)
| x == y = u
| otherwise = V y
subst u x (App t1 t2) = App (subst u x t1) (subst u x t2)
subst u x (Lam y t)
| x == y = Lam y t
| y `notElem` fvU = Lam y (subst u x t)
| x `notElem` fvT = Lam y t
| otherwise = Lam y' (subst u x (subst (V y') y t))
where
fvT = freeVars t
fvU = freeVars u
allFV = nub ([x] ++ fvU ++ fvT)
y' = freshVariable y allFV
-- Normal order reduction
-- - like call by name
-- - but also reduce under lambda abstractions if no application is possible
-- - guarantees reaching a normal form if it exists
normalReduceStep :: Term -> Maybe Term
normalReduceStep (App (Lam v t) t2) = Just $ subst t2 v t
normalReduceStep (App t1 t2)
| Just t1' <- normalReduceStep t1 = Just $ App t1' t2
| Just t2' <- normalReduceStep t2 = Just $ App t1 t2'
normalReduceStep (Lam x t)
| Just t' <- normalReduceStep t = Just $ Lam x t'
normalReduceStep _ = Nothing
normalReduce :: Term -> Term
normalReduce t
| Just t' <- normalReduceStep t = normalReduce t'
| otherwise = t
reduce :: Term -> Term
reduce = normalReduce
-- alpha-beta equivalence (for strongly normalizing terms) is obtained by
-- fully evaluating the terms using beta-reduction, then checking their
-- alpha-equivalence.
abEq :: Term -> Term -> Bool
abEq t1 t2 = aEq (reduce t1) (reduce t2)
evaluate :: String -> String
evaluate s = showNice (reduce t)
where
(t, "") = readNice s
-- Church Encodings in Lambda
------------
--BOOLEANS--
------------
A boolean is any way to choose between two alternatives ( t - > t - > t )
The boolean constant true always chooses the first alternative
cTrue :: Term
cTrue = undefined
The boolean constant false always chooses the second alternative
cFalse :: Term
cFalse = undefined
--If is not really needed because we can use the booleans themselves, but...
cIf :: Term
cIf = undefined
--The boolean negation switches the alternatives
cNot :: Term
cNot = undefined
--The boolean conjunction can be built as a conditional
cAnd :: Term
cAnd = undefined
--The boolean disjunction can be built as a conditional
cOr :: Term
cOr = undefined
---------
PAIRS--
---------
-- a pair with components of type a and b is a way to compute something based
-- on the values contained within the pair (a -> b -> c) -> c
builds a pair out of two values as an object which , when given
--a function to be applied on the values, it will apply it on them.
cPair :: Term
cPair = undefined
first projection uses the function selecting first component on a pair
cFst :: Term
cFst = undefined
second projection
cSnd :: Term
cSnd = undefined
-------------------
--NATURAL NUMBERS--
-------------------
-- A natural number is any way to iterate a function s a number of times
-- over an initial value z ( (t -> t) -> t -> t )
--0 will iterate the function s 0 times over z, producing z
c0 :: Term
c0 = undefined
1 is the the function s iterated 1 times over z , that is , z
c1 :: Term
c1 = undefined
--Successor n either
- applies s one more time in addition to what n does
-- - iterates s n times over (s z)
cS :: Term
cS = undefined
Transform a value into a CNat ( should yield c0 for nums < = 0 )
cNat :: (Ord p, Num p) -> Term
cNat = undefined
--Addition of m and n can be done by composing n s with m s
cPlus :: Term
cPlus = undefined
--Multiplication of m and n can be done by composing n and m
cMul :: Term
cMul = undefined
--Exponentiation of m and n can be done by applying n to m
cPow :: Term
cPow = undefined
--Testing whether a value is 0 can be done through iteration
-- using a function constantly false and an initial value true
cIs0 :: Term
cIs0 = undefined
Predecessor ( evaluating to 0 for 0 ) can be defined iterating
over pairs , starting from an initial value ( 0 , 0 )
cPred :: Term
cPred = undefined
substraction from m n ( evaluating to 0 if m < n ) is repeated application
-- of the predeccesor function
cSub :: Term
cSub = undefined
-- m is less than (or equal to) n if when substracting n from m we get 0
cLte :: Term
cLte = undefined
cGte :: Term
cGte = undefined
cLt :: Term
cLt = undefined
cGt :: Term
cGt = undefined
-- equality on naturals can be defined my means of comparisons
cEq :: Term
cEq = undefined
--Fun with arithmetic and pairs
--Define factorial. You can iterate over a pair to contain the current index and so far factorial
cFactorial :: Term
cFactorial = undefined
Define Fibonacci . You can iterate over a pair to contain two consecutive numbers in the sequence
cFibonacci :: Term
cFibonacci = undefined
--Given m and n, compute q and r satisfying m = q * n + r. If n is not 0 then r should be less than n.
--hint iterate over a pair, initially (0, m),
incrementing the first and substracting n from the second if it is smaller than n
--for at most m times
cDivMod :: Term
cDivMod = undefined
---------
LISTS--
---------
-- a list with elements of type a is a way to aggregate a sequence of elements of type a
-- given an aggregation function and an initial value ( (a -> b -> b) -> b -> b )
-- The empty list is that which when aggregated it will always produce the initial value
cNil :: Term
cNil = undefined
-- Adding an element to a list means that, when aggregating the list, the newly added
-- element will be aggregated with the result obtained by aggregating the remainder of the list
cCons :: Term
cCons = undefined
we can obtain a CList from a regular list of terms by folding the list
cList :: [Term] -> Term
cList = undefined
-- builds a encoded list of encodings of natural numbers corresponding to a list of Integers
cNatList :: [Integer] -> Term
cNatList = undefined
-- sums the elements in the list
cSum :: Term
cSum = undefined
-- checks whether a list is nil (similar to cIs0)
cIsNil :: Term
cIsNil = undefined
-- gets the head of the list (or the default specified value if the list is empty)
cHead :: Term
cHead = undefined
-- gets the tail of the list (empty if the list is empty) --- similar to cPred
cTail :: Term
cTail = undefined
--The Y combinator
fix :: Term
fix = undefined
-- a recursive definition for
cDivMod' :: Term
cDivMod' = lams ["m", "n"]
(cIs0 $$ v "n"
$$ (cPair $$ c0 $$ v "m")
$$ (fix
$$ lams ["f", "p"]
(lam "x"
(cIs0 $$ v "x"
$$ (cLte $$ v "n" $$ (cSnd $$ v "p")
$$ (cPair $$ (cS $$ (cFst $$ v "p")) $$ c0)
$$ v "p"
)
$$ (v "f" $$ (cPair $$ (cS $$ (cFst $$ v "p")) $$ v "x"))
)
$$ (cSub $$ (cSnd $$ v "p") $$ v "n")
)
$$ (cPair $$ c0 $$ v "m")
)
)
cSudan :: Term
cSudan = fix $$ lam "f" (lams ["n", "x", "y"]
(cIs0 $$ v "n"
$$ (cPlus $$ v "x" $$ v "y")
$$ (cIs0 $$ v "y"
$$ v "x"
$$ (lam "fnpy"
(v "f" $$ (cPred $$ v "n")
$$ v "fnpy"
$$ (cPlus $$ v "fnpy" $$ v "y")
)
$$ (v "f" $$ v "n" $$ v "x" $$ (cPred $$ v "y"))
)
)
))
cAckermann :: Term
cAckermann = fix $$ lam "A" (lams ["m", "n"]
(cIs0 $$ v "m"
$$ (cS $$ v "n")
$$ (cIs0 $$ v "n"
$$ (v "A" $$ (cPred $$ v "m") $$ c1)
$$ (v "A" $$ (cPred $$ v "m")
$$ (v "A" $$ v "m" $$ (cPred $$ v "n")))
)
))
| null | https://raw.githubusercontent.com/theodormoroianu/SecondYearCourses/5e359e6a7cf588a527d27209bf53b4ce6b8d5e83/FLP/Laboratoare/Lab%209/.history/LambdaChurch_20210415171024.hs | haskell | alpha-equivalence
subst u x t defines [u/x]t, i.e., substituting u for x in t
This substitution avoids variable captures so it is safe to be used when
reducing terms with free variables (e.g., if evaluating inside lambda abstractions)
^ substitution term
^ variable to be substitutes
^ term in which the substitution occurs
Normal order reduction
- like call by name
- but also reduce under lambda abstractions if no application is possible
- guarantees reaching a normal form if it exists
alpha-beta equivalence (for strongly normalizing terms) is obtained by
fully evaluating the terms using beta-reduction, then checking their
alpha-equivalence.
Church Encodings in Lambda
----------
BOOLEANS--
----------
If is not really needed because we can use the booleans themselves, but...
The boolean negation switches the alternatives
The boolean conjunction can be built as a conditional
The boolean disjunction can be built as a conditional
-------
-------
a pair with components of type a and b is a way to compute something based
on the values contained within the pair (a -> b -> c) -> c
a function to be applied on the values, it will apply it on them.
-----------------
NATURAL NUMBERS--
-----------------
A natural number is any way to iterate a function s a number of times
over an initial value z ( (t -> t) -> t -> t )
0 will iterate the function s 0 times over z, producing z
Successor n either
- iterates s n times over (s z)
Addition of m and n can be done by composing n s with m s
Multiplication of m and n can be done by composing n and m
Exponentiation of m and n can be done by applying n to m
Testing whether a value is 0 can be done through iteration
using a function constantly false and an initial value true
of the predeccesor function
m is less than (or equal to) n if when substracting n from m we get 0
equality on naturals can be defined my means of comparisons
Fun with arithmetic and pairs
Define factorial. You can iterate over a pair to contain the current index and so far factorial
Given m and n, compute q and r satisfying m = q * n + r. If n is not 0 then r should be less than n.
hint iterate over a pair, initially (0, m),
for at most m times
-------
-------
a list with elements of type a is a way to aggregate a sequence of elements of type a
given an aggregation function and an initial value ( (a -> b -> b) -> b -> b )
The empty list is that which when aggregated it will always produce the initial value
Adding an element to a list means that, when aggregating the list, the newly added
element will be aggregated with the result obtained by aggregating the remainder of the list
builds a encoded list of encodings of natural numbers corresponding to a list of Integers
sums the elements in the list
checks whether a list is nil (similar to cIs0)
gets the head of the list (or the default specified value if the list is empty)
gets the tail of the list (empty if the list is empty) --- similar to cPred
The Y combinator
a recursive definition for | module LambdaChurch where
import Data.Char (isLetter)
import Data.List ( nub )
class ShowNice a where
showNice :: a -> String
class ReadNice a where
readNice :: String -> (a, String)
data Variable
= Variable
{ name :: String
, count :: Int
}
deriving (Show, Eq, Ord)
var :: String -> Variable
var x = Variable x 0
instance ShowNice Variable where
showNice (Variable x 0) = x
showNice (Variable x cnt) = x <> "_" <> show cnt
instance ReadNice Variable where
readNice s
| null x = error $ "expected variable but found " <> s
| otherwise = (var x, s')
where
(x, s') = span isLetter s
freshVariable :: Variable -> [Variable] -> Variable
freshVariable var vars = Variable x (cnt + 1)
where
x = name var
varsWithName = filter ((== x) . name) vars
Variable _ cnt = maximum (var : varsWithName)
data Term
= V Variable
| App Term Term
| Lam Variable Term
deriving (Show)
aEq :: Term -> Term -> Bool
aEq (V x) (V x') = x == x'
aEq (App t1 t2) (App t1' t2') = aEq t1 t1' && aEq t2 t2'
aEq (Lam x t) (Lam x' t')
| x == x' = aEq t t'
| otherwise = aEq (subst (V y) x t) (subst (V y) x' t')
where
fvT = freeVars t
fvT' = freeVars t'
allFV = nub ([x, x'] ++ fvT ++ fvT')
y = freshVariable x allFV
aEq _ _ = False
v :: String -> Term
v x = V (var x)
lam :: String -> Term -> Term
lam x = Lam (var x)
lams :: [String] -> Term -> Term
lams xs t = foldr lam t xs
($$) :: Term -> Term -> Term
($$) = App
infixl 9 $$
instance ShowNice Term where
showNice (V var) = showNice var
showNice (App t1 t2) = "(" <> showNice t1 <> " " <> showNice t2 <> ")"
showNice (Lam var t) = "(" <> "\\" <> showNice var <> "." <> showNice t <> ")"
instance ReadNice Term where
readNice [] = error "Nothing to read"
readNice ('(' : '\\' : s) = (Lam var t, s'')
where
(var, '.' : s') = readNice s
(t, ')' : s'') = readNice s'
readNice ('(' : s) = (App t1 t2, s'')
where
(t1, ' ' : s') = readNice s
(t2, ')' : s'') = readNice s'
readNice s = (V var, s')
where
(var, s') = readNice s
freeVars :: Term -> [Variable]
freeVars (V var) = [var]
freeVars (App t1 t2) = nub $ freeVars t1 ++ freeVars t2
freeVars (Lam var t) = filter (/= var) (freeVars t)
for example [ 3 / x](x + x ) = = 3 + 3
subst
-> Term
subst u x (V y)
| x == y = u
| otherwise = V y
subst u x (App t1 t2) = App (subst u x t1) (subst u x t2)
subst u x (Lam y t)
| x == y = Lam y t
| y `notElem` fvU = Lam y (subst u x t)
| x `notElem` fvT = Lam y t
| otherwise = Lam y' (subst u x (subst (V y') y t))
where
fvT = freeVars t
fvU = freeVars u
allFV = nub ([x] ++ fvU ++ fvT)
y' = freshVariable y allFV
normalReduceStep :: Term -> Maybe Term
normalReduceStep (App (Lam v t) t2) = Just $ subst t2 v t
normalReduceStep (App t1 t2)
| Just t1' <- normalReduceStep t1 = Just $ App t1' t2
| Just t2' <- normalReduceStep t2 = Just $ App t1 t2'
normalReduceStep (Lam x t)
| Just t' <- normalReduceStep t = Just $ Lam x t'
normalReduceStep _ = Nothing
normalReduce :: Term -> Term
normalReduce t
| Just t' <- normalReduceStep t = normalReduce t'
| otherwise = t
reduce :: Term -> Term
reduce = normalReduce
abEq :: Term -> Term -> Bool
abEq t1 t2 = aEq (reduce t1) (reduce t2)
evaluate :: String -> String
evaluate s = showNice (reduce t)
where
(t, "") = readNice s
A boolean is any way to choose between two alternatives ( t - > t - > t )
The boolean constant true always chooses the first alternative
cTrue :: Term
cTrue = undefined
The boolean constant false always chooses the second alternative
cFalse :: Term
cFalse = undefined
cIf :: Term
cIf = undefined
cNot :: Term
cNot = undefined
cAnd :: Term
cAnd = undefined
cOr :: Term
cOr = undefined
builds a pair out of two values as an object which , when given
cPair :: Term
cPair = undefined
first projection uses the function selecting first component on a pair
cFst :: Term
cFst = undefined
second projection
cSnd :: Term
cSnd = undefined
c0 :: Term
c0 = undefined
1 is the the function s iterated 1 times over z , that is , z
c1 :: Term
c1 = undefined
- applies s one more time in addition to what n does
cS :: Term
cS = undefined
Transform a value into a CNat ( should yield c0 for nums < = 0 )
cNat :: (Ord p, Num p) -> Term
cNat = undefined
cPlus :: Term
cPlus = undefined
cMul :: Term
cMul = undefined
cPow :: Term
cPow = undefined
cIs0 :: Term
cIs0 = undefined
Predecessor ( evaluating to 0 for 0 ) can be defined iterating
over pairs , starting from an initial value ( 0 , 0 )
cPred :: Term
cPred = undefined
substraction from m n ( evaluating to 0 if m < n ) is repeated application
cSub :: Term
cSub = undefined
cLte :: Term
cLte = undefined
cGte :: Term
cGte = undefined
cLt :: Term
cLt = undefined
cGt :: Term
cGt = undefined
cEq :: Term
cEq = undefined
cFactorial :: Term
cFactorial = undefined
Define Fibonacci . You can iterate over a pair to contain two consecutive numbers in the sequence
cFibonacci :: Term
cFibonacci = undefined
incrementing the first and substracting n from the second if it is smaller than n
cDivMod :: Term
cDivMod = undefined
cNil :: Term
cNil = undefined
cCons :: Term
cCons = undefined
we can obtain a CList from a regular list of terms by folding the list
cList :: [Term] -> Term
cList = undefined
cNatList :: [Integer] -> Term
cNatList = undefined
cSum :: Term
cSum = undefined
cIsNil :: Term
cIsNil = undefined
cHead :: Term
cHead = undefined
cTail :: Term
cTail = undefined
fix :: Term
fix = undefined
cDivMod' :: Term
cDivMod' = lams ["m", "n"]
(cIs0 $$ v "n"
$$ (cPair $$ c0 $$ v "m")
$$ (fix
$$ lams ["f", "p"]
(lam "x"
(cIs0 $$ v "x"
$$ (cLte $$ v "n" $$ (cSnd $$ v "p")
$$ (cPair $$ (cS $$ (cFst $$ v "p")) $$ c0)
$$ v "p"
)
$$ (v "f" $$ (cPair $$ (cS $$ (cFst $$ v "p")) $$ v "x"))
)
$$ (cSub $$ (cSnd $$ v "p") $$ v "n")
)
$$ (cPair $$ c0 $$ v "m")
)
)
cSudan :: Term
cSudan = fix $$ lam "f" (lams ["n", "x", "y"]
(cIs0 $$ v "n"
$$ (cPlus $$ v "x" $$ v "y")
$$ (cIs0 $$ v "y"
$$ v "x"
$$ (lam "fnpy"
(v "f" $$ (cPred $$ v "n")
$$ v "fnpy"
$$ (cPlus $$ v "fnpy" $$ v "y")
)
$$ (v "f" $$ v "n" $$ v "x" $$ (cPred $$ v "y"))
)
)
))
cAckermann :: Term
cAckermann = fix $$ lam "A" (lams ["m", "n"]
(cIs0 $$ v "m"
$$ (cS $$ v "n")
$$ (cIs0 $$ v "n"
$$ (v "A" $$ (cPred $$ v "m") $$ c1)
$$ (v "A" $$ (cPred $$ v "m")
$$ (v "A" $$ v "m" $$ (cPred $$ v "n")))
)
))
|
a72e78665980f8cbab7aabdcbcdd5fc7c7cf7484feaf547dea4d7e8c0ac8180e | pascal-knodel/haskell-craft | E'6'52.hs | --
--
--
-----------------
Exercise 6.52 .
-----------------
--
--
--
module E'6'52 where
import B'C'6
(
TillType
, Database
, BarCode
, Name
, lineLength
)
import E'6'44 ( formatTitle )
import E'6'45 ( look )
import Data.List ( concat )
import GHC.List ( elem )
type Sales = Int
makeSalesReport :: TillType -> Database -> String
makeSalesReport barCodes database
= (formatTitle title) -- formatTitle, see ex. 6.44.
++ (formatLines'' nameSalesPairs)
where
title :: String
title = "Sales"
barCodesOnce :: [BarCode]
barCodesOnce = removeReplicatives barCodes
barCodesOnceCountings :: [BarCode]
barCodesOnceCountings = [ countReplicatives barCode barCodes | barCode <- barCodesOnce ]
totalSales :: [(BarCode, Sales)]
totalSales = zip barCodesOnce barCodesOnceCountings
nameSalesPairs :: [ (Name, Sales) ]
nameSalesPairs = [ ( fst (look database barCode) , sales ) | (barCode , sales) <- totalSales ]
removeReplicatives :: Eq t => [t] -> [t] -- Naive.
removeReplicatives [] = []
removeReplicatives (firstItem : remainingItems)
| isReplicative firstItem remainingItems = removeReplicatives remainingItems
| otherwise = firstItem : removeReplicatives remainingItems
where
isReplicative :: Eq t => t -> [t] -> Bool -- Naive.
isReplicative item list
= item `elem` list
countReplicatives :: Eq t => t -> [t] -> Int
countReplicatives item [] = 0
countReplicatives item (comparisonItem : remainingComparisonItems)
| item == comparisonItem = 1 + countReplicatives item remainingComparisonItems
| otherwise = countReplicatives item remainingComparisonItems
formatLine'' :: (Name, Sales) -> String
formatLine'' (name, sales)
= name ++ fillCharacters ++ sales' ++ "\n"
where
nonFillCharacterCount :: Int
nonFillCharacterCount = (length name) + (length sales') -- Definition: "\n" (white space) doesn't count.
numberOfFillCharacters :: Int
lineLength , see ex . 6.39 .
fillCharacters :: String
fillCharacters = replicate numberOfFillCharacters ' '
sales' :: String
sales' = show sales
formatLines'' :: [ (Name, Sales) ] -> String
formatLines'' nameSalesPairs
= concat (map formatLine'' nameSalesPairs)
exampleDatabase :: Database
exampleDatabase
= [
( 1 , "Hs. Reference Book" , 100 ) ,
( 2 , "Hs. Reference Cards" , 100 ) ,
( 3 , "Hs. Reference Poster" , 100 ) ,
( 4 , "Hs. Learning Book LB1" , 10000 ) ,
( 5 , "Hs. LB1 Solutions" , 100 ) ,
( 6 , "Hs. Learning Book LB2" , 1000 ) ,
( 7 , "Hs. Learning Cards" , 100 ) ,
( 8 , "Hs. Editor" , 100 ) ,
( 9 , "Hs. IDE" , 1000 ) ,
( 10 , "Hs. Expression Evaluator" , 100 ) ,
( 11 , "Hs. Calculator" , 100 ) ,
( 12 , "Hs. to C Converter" , 100 ) ,
( 13 , "Hs. Sorting Library" , 100 ) ,
( 14 , "Functional Processor FP1" , 1000 ) ,
( 15 , "Functional Processor FP2" , 10000 ) ,
( 16 , "Functional Processor FP3" , 100000 )
]
GHCi >
: {
putStr (
makeSalesReport [
-- Known items :
4 , 4 ,
5 , 5 ,
7 ,
8 ,
10
]
exampleDatabase
)
:}
:{
putStr (
makeSalesReport [
-- Known items:
4, 4,
5, 5,
7,
8,
10
]
exampleDatabase
)
:}
-}
--
-- Sales
--
Hs . Learning Book LB1 2
Hs . LB1 Solutions 2
Hs . Learning Cards 1
Hs . Editor 1
Hs . Expression Evaluator 1
GHCi >
: {
putStr (
makeSalesReport [
-- Unknown items :
-1 ,
-2 ,
-3
]
[ ]
)
:}
:{
putStr (
makeSalesReport [
-- Unknown items:
-1,
-2,
-3
]
[]
)
:}
-}
--
-- Sales
--
Unknown Item 1
Unknown Item 1
Unknown Item 1
| null | https://raw.githubusercontent.com/pascal-knodel/haskell-craft/c03d6eb857abd8b4785b6de075b094ec3653c968/Chapter%206/E'6'52.hs | haskell |
---------------
---------------
formatTitle, see ex. 6.44.
Naive.
Naive.
Definition: "\n" (white space) doesn't count.
Known items :
Known items:
Sales
Unknown items :
Unknown items:
Sales
| Exercise 6.52 .
module E'6'52 where
import B'C'6
(
TillType
, Database
, BarCode
, Name
, lineLength
)
import E'6'44 ( formatTitle )
import E'6'45 ( look )
import Data.List ( concat )
import GHC.List ( elem )
type Sales = Int
makeSalesReport :: TillType -> Database -> String
makeSalesReport barCodes database
++ (formatLines'' nameSalesPairs)
where
title :: String
title = "Sales"
barCodesOnce :: [BarCode]
barCodesOnce = removeReplicatives barCodes
barCodesOnceCountings :: [BarCode]
barCodesOnceCountings = [ countReplicatives barCode barCodes | barCode <- barCodesOnce ]
totalSales :: [(BarCode, Sales)]
totalSales = zip barCodesOnce barCodesOnceCountings
nameSalesPairs :: [ (Name, Sales) ]
nameSalesPairs = [ ( fst (look database barCode) , sales ) | (barCode , sales) <- totalSales ]
removeReplicatives [] = []
removeReplicatives (firstItem : remainingItems)
| isReplicative firstItem remainingItems = removeReplicatives remainingItems
| otherwise = firstItem : removeReplicatives remainingItems
where
isReplicative item list
= item `elem` list
countReplicatives :: Eq t => t -> [t] -> Int
countReplicatives item [] = 0
countReplicatives item (comparisonItem : remainingComparisonItems)
| item == comparisonItem = 1 + countReplicatives item remainingComparisonItems
| otherwise = countReplicatives item remainingComparisonItems
formatLine'' :: (Name, Sales) -> String
formatLine'' (name, sales)
= name ++ fillCharacters ++ sales' ++ "\n"
where
nonFillCharacterCount :: Int
numberOfFillCharacters :: Int
lineLength , see ex . 6.39 .
fillCharacters :: String
fillCharacters = replicate numberOfFillCharacters ' '
sales' :: String
sales' = show sales
formatLines'' :: [ (Name, Sales) ] -> String
formatLines'' nameSalesPairs
= concat (map formatLine'' nameSalesPairs)
exampleDatabase :: Database
exampleDatabase
= [
( 1 , "Hs. Reference Book" , 100 ) ,
( 2 , "Hs. Reference Cards" , 100 ) ,
( 3 , "Hs. Reference Poster" , 100 ) ,
( 4 , "Hs. Learning Book LB1" , 10000 ) ,
( 5 , "Hs. LB1 Solutions" , 100 ) ,
( 6 , "Hs. Learning Book LB2" , 1000 ) ,
( 7 , "Hs. Learning Cards" , 100 ) ,
( 8 , "Hs. Editor" , 100 ) ,
( 9 , "Hs. IDE" , 1000 ) ,
( 10 , "Hs. Expression Evaluator" , 100 ) ,
( 11 , "Hs. Calculator" , 100 ) ,
( 12 , "Hs. to C Converter" , 100 ) ,
( 13 , "Hs. Sorting Library" , 100 ) ,
( 14 , "Functional Processor FP1" , 1000 ) ,
( 15 , "Functional Processor FP2" , 10000 ) ,
( 16 , "Functional Processor FP3" , 100000 )
]
GHCi >
: {
putStr (
makeSalesReport [
4 , 4 ,
5 , 5 ,
7 ,
8 ,
10
]
exampleDatabase
)
:}
:{
putStr (
makeSalesReport [
4, 4,
5, 5,
7,
8,
10
]
exampleDatabase
)
:}
-}
Hs . Learning Book LB1 2
Hs . LB1 Solutions 2
Hs . Learning Cards 1
Hs . Editor 1
Hs . Expression Evaluator 1
GHCi >
: {
putStr (
makeSalesReport [
-1 ,
-2 ,
-3
]
[ ]
)
:}
:{
putStr (
makeSalesReport [
-1,
-2,
-3
]
[]
)
:}
-}
Unknown Item 1
Unknown Item 1
Unknown Item 1
|
44bc100581f21c3eb50feac56c748f7366f10de05b931ead18cec5ddb59f6ffc | kappelmann/engaging-large-scale-functional-programming | Exercise01.hs | module Exercise01 where
contestTeams :: (Integer, Integer) -> (Integer, Integer, Integer, Integer)
contestTeams (n, k) = (nEins, nEins*k, nEins*(k*k), nEins*(k*k*k))
where
kges = 1 + k + (k*k) + (k*k*k)
nEins = div n kges
| null | https://raw.githubusercontent.com/kappelmann/engaging-large-scale-functional-programming/8ed2c056fbd611f1531230648497cb5436d489e4/resources/contest/example_data/01/uploads/ghzi/Exercise01.hs | haskell | module Exercise01 where
contestTeams :: (Integer, Integer) -> (Integer, Integer, Integer, Integer)
contestTeams (n, k) = (nEins, nEins*k, nEins*(k*k), nEins*(k*k*k))
where
kges = 1 + k + (k*k) + (k*k*k)
nEins = div n kges
| |
c2e0d8f60b0043fd94ff5e5c81d89982a925124610dc73cf15121aceda352821 | rohitjha/ProjectEuler | PE002.hs |
Author :
File : PE002.hs
July 5 , 2013
Problem 2 :
Each new term in the Fibonacci sequence is generated by adding the previous
two terms . By starting with 1 and 2 , the first 10 terms will be :
1 , 2 , 3 , 5 , 8 , 13 , 21 , 34 , 55 , 89 , ...
By considering the terms in the Fibonacci sequence whose values do not exceed
four million , find the sum of the even - valued terms .
Author: Rohit Jha
File: PE002.hs
July 5, 2013
Problem 2:
Each new term in the Fibonacci sequence is generated by adding the previous
two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed
four million, find the sum of the even-valued terms.
-}
main = putStrLn $ show $ sum [ x | x <- takeWhile (<= 4000000) fibs, even x]
where
fibs = 1 : 2 : zipWith (+) fibs (tail fibs)
4613732
real 0m0.003s
user 0m0.000s
sys 0m0.000s
4613732
real 0m0.003s
user 0m0.000s
sys 0m0.000s
-}
| null | https://raw.githubusercontent.com/rohitjha/ProjectEuler/2f0a46bb1547b06a373c30966bba7a001b932bf4/Haskell/PE002.hs | haskell |
Author :
File : PE002.hs
July 5 , 2013
Problem 2 :
Each new term in the Fibonacci sequence is generated by adding the previous
two terms . By starting with 1 and 2 , the first 10 terms will be :
1 , 2 , 3 , 5 , 8 , 13 , 21 , 34 , 55 , 89 , ...
By considering the terms in the Fibonacci sequence whose values do not exceed
four million , find the sum of the even - valued terms .
Author: Rohit Jha
File: PE002.hs
July 5, 2013
Problem 2:
Each new term in the Fibonacci sequence is generated by adding the previous
two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed
four million, find the sum of the even-valued terms.
-}
main = putStrLn $ show $ sum [ x | x <- takeWhile (<= 4000000) fibs, even x]
where
fibs = 1 : 2 : zipWith (+) fibs (tail fibs)
4613732
real 0m0.003s
user 0m0.000s
sys 0m0.000s
4613732
real 0m0.003s
user 0m0.000s
sys 0m0.000s
-}
| |
2d511bef42215d102084f6f13b71e4c175629a1d103926eaeccb2d4521ed2ebd | hunt-framework/hunt | Files.hs | {-# LANGUAGE BangPatterns #-}
module Hunt.IO.Files (
AppendFile
, withAppendFile
, append
, RandomAccessFile
, openRandomAccessFile
, closeRandomAccessFile
, readRandomAccessFile
, seekRandomAccessFile
) where
import Control.Exception
import Data.ByteString.Internal (ByteString (PS))
import qualified Data.ByteString.Internal as ByteString
import Data.Word
import Foreign.Ptr
import qualified GHC.IO.Device as FD
import qualified GHC.IO.FD as FD
import qualified System.IO as IO
newtype RandomAccessFile = MkRAF FD.FD
openRandomAccessFile :: FilePath -> IO RandomAccessFile
openRandomAccessFile fp = do
(fd, _) <- FD.openFile fp IO.ReadMode True
return (MkRAF fd)
closeRandomAccessFile :: RandomAccessFile -> IO ()
closeRandomAccessFile (MkRAF fd) = FD.close fd
readRandomAccessFile :: Int -> RandomAccessFile -> IO ByteString
readRandomAccessFile n (MkRAF fd) =
ByteString.createAndTrim n $ \buf -> FD.read fd buf n
seekRandomAccessFile :: Word64 -> RandomAccessFile -> IO ()
seekRandomAccessFile off (MkRAF fd) =
FD.seek fd IO.AbsoluteSeek (fromIntegral off)
newtype AppendFile = MkAF FD.FD
openAppendFile :: FilePath -> IO AppendFile
openAppendFile fp = do
(fd, _) <- FD.openFile fp IO.AppendMode True
return (MkAF fd)
append :: AppendFile -> Ptr Word8 -> Int -> IO Int
append (MkAF fd) op sz = do
FD.write fd op sz
return (fromIntegral sz)
closeAppendFile :: AppendFile -> IO ()
closeAppendFile (MkAF fd) = FD.close fd
withAppendFile :: FilePath -> (AppendFile -> IO a) -> IO a
withAppendFile fp = bracket (openAppendFile fp) closeAppendFile
| null | https://raw.githubusercontent.com/hunt-framework/hunt/d692aae756b7bdfb4c99f5a3951aec12893649a8/hunt-searchengine/src/Hunt/IO/Files.hs | haskell | # LANGUAGE BangPatterns # | module Hunt.IO.Files (
AppendFile
, withAppendFile
, append
, RandomAccessFile
, openRandomAccessFile
, closeRandomAccessFile
, readRandomAccessFile
, seekRandomAccessFile
) where
import Control.Exception
import Data.ByteString.Internal (ByteString (PS))
import qualified Data.ByteString.Internal as ByteString
import Data.Word
import Foreign.Ptr
import qualified GHC.IO.Device as FD
import qualified GHC.IO.FD as FD
import qualified System.IO as IO
newtype RandomAccessFile = MkRAF FD.FD
openRandomAccessFile :: FilePath -> IO RandomAccessFile
openRandomAccessFile fp = do
(fd, _) <- FD.openFile fp IO.ReadMode True
return (MkRAF fd)
closeRandomAccessFile :: RandomAccessFile -> IO ()
closeRandomAccessFile (MkRAF fd) = FD.close fd
readRandomAccessFile :: Int -> RandomAccessFile -> IO ByteString
readRandomAccessFile n (MkRAF fd) =
ByteString.createAndTrim n $ \buf -> FD.read fd buf n
seekRandomAccessFile :: Word64 -> RandomAccessFile -> IO ()
seekRandomAccessFile off (MkRAF fd) =
FD.seek fd IO.AbsoluteSeek (fromIntegral off)
newtype AppendFile = MkAF FD.FD
openAppendFile :: FilePath -> IO AppendFile
openAppendFile fp = do
(fd, _) <- FD.openFile fp IO.AppendMode True
return (MkAF fd)
append :: AppendFile -> Ptr Word8 -> Int -> IO Int
append (MkAF fd) op sz = do
FD.write fd op sz
return (fromIntegral sz)
closeAppendFile :: AppendFile -> IO ()
closeAppendFile (MkAF fd) = FD.close fd
withAppendFile :: FilePath -> (AppendFile -> IO a) -> IO a
withAppendFile fp = bracket (openAppendFile fp) closeAppendFile
|
524c72374e3e6cd580028ae582c5e22583035604d2d009cb9ef08a04ec5e4556 | fhur/eaml | scope_test.clj | (ns eaml.scope-test
(:require [eaml.scope :refer :all]
[eaml.parser :refer [parse-str]]
[eaml.parser :refer [parse-str]]
[presto.core :refer :all]
[clojure.test :refer :all]))
(def nodes (parse-str "color red: #f00;
color main_color: red;
integer foo: 5;
string name: 'a name';
string my_name: name;
string other_name: my_name;
mixin RedText {
android:textColor: red;
}
style Foo < Bar {
android:textColor: main_color;
android:foo: foo;
android:text: my_name;
}"))
(def scope (create nodes))
(expected-when "obtain-type returns the resolved type of an expression
in the current scope" #(obtain-type % scope)
when ["red"] = :color
when ["main_color"] = :color
when ["foo"] = :integer
when ["name"] = :string
when ["my_name"] = :string
when ["other_name"] = :string
when ["5"] = :integer
when ["5123"] = :integer
when ["true"] = :bool
when ["false"] = :bool
when ["'foo'"] = :string
when ["\"\""] = :string
when ["@string/foo"] = :string
when ["@bool/foo"] = :bool
when ["''"] = :string)
(expected-when "resolve-expr obtains the value of an expression in the
current scope" #(resolve-expr :any % scope)
when ["#f00"] = "#f00"
when ["true"] = "true"
when ["false"] = "false"
when ["'foo'"] = "foo"
when ["12sp"] = "12sp"
when ["1234"] = "1234"
when ["red"] = "@color/red"
when ["main_color"] = "@color/main_color"
when ["foo"] = "@integer/foo"
when ["my_name"] = "@string/my_name")
(expected-when "include? returns true iff the scope contains
the given id" #(include? scope %)
when ["red"] = true
when ["main_color"] = true
when ["RedText"] = true
when ["Foo"] = true
when ["other_name"] = true
when ["akaljsdhf"] = false)
(deftest obtain-type-throws-when-not-found
(is (thrown? IllegalStateException (obtain-type "asdf" scope)))
(is (thrown? IllegalStateException (obtain-type "a%1234" scope)))
(is (thrown? IllegalStateException (obtain-type "#" scope)))
(is (thrown? IllegalStateException (resolve-expr :string "main_color" scope)))
(is (thrown? IllegalStateException (create (parse-str "integer foo: 1; color foo: #f00;")))))
| null | https://raw.githubusercontent.com/fhur/eaml/ee398417d4ec76966f3b88b61ffc9332741eeb28/test/eaml/scope_test.clj | clojure | (ns eaml.scope-test
(:require [eaml.scope :refer :all]
[eaml.parser :refer [parse-str]]
[eaml.parser :refer [parse-str]]
[presto.core :refer :all]
[clojure.test :refer :all]))
mixin RedText {
}
style Foo < Bar {
}"))
(def scope (create nodes))
(expected-when "obtain-type returns the resolved type of an expression
in the current scope" #(obtain-type % scope)
when ["red"] = :color
when ["main_color"] = :color
when ["foo"] = :integer
when ["name"] = :string
when ["my_name"] = :string
when ["other_name"] = :string
when ["5"] = :integer
when ["5123"] = :integer
when ["true"] = :bool
when ["false"] = :bool
when ["'foo'"] = :string
when ["\"\""] = :string
when ["@string/foo"] = :string
when ["@bool/foo"] = :bool
when ["''"] = :string)
(expected-when "resolve-expr obtains the value of an expression in the
current scope" #(resolve-expr :any % scope)
when ["#f00"] = "#f00"
when ["true"] = "true"
when ["false"] = "false"
when ["'foo'"] = "foo"
when ["12sp"] = "12sp"
when ["1234"] = "1234"
when ["red"] = "@color/red"
when ["main_color"] = "@color/main_color"
when ["foo"] = "@integer/foo"
when ["my_name"] = "@string/my_name")
(expected-when "include? returns true iff the scope contains
the given id" #(include? scope %)
when ["red"] = true
when ["main_color"] = true
when ["RedText"] = true
when ["Foo"] = true
when ["other_name"] = true
when ["akaljsdhf"] = false)
(deftest obtain-type-throws-when-not-found
(is (thrown? IllegalStateException (obtain-type "asdf" scope)))
(is (thrown? IllegalStateException (obtain-type "a%1234" scope)))
(is (thrown? IllegalStateException (obtain-type "#" scope)))
(is (thrown? IllegalStateException (resolve-expr :string "main_color" scope)))
(is (thrown? IllegalStateException (create (parse-str "integer foo: 1; color foo: #f00;")))))
| |
ffe4af5577c7a8bda36e6c660a6ea23f984c915bfba7f8c0d1d2f0ab34297bb9 | billstclair/trubanc-lisp | test.lisp | (defpackage :rfc2388.test
(:use :common-lisp))
(in-package :rfc2388.test)
(defconstant +crlf+ (format nil "~C~C" #\return #\linefeed))
(defun generate-test-strings (parts)
(flet ((prepend (left list)
(mapcar (lambda (right)
(format nil "~A~A" left right))
list))
(postpend (right list)
(mapcar (lambda (left)
(format nil "~A~A" left right))
list)))
(cond ((null parts)
nil)
((null (cdr parts))
(list (format nil "~A" (first parts))))
(t
(list* (format nil "~A" (first parts))
(nconc (prepend (first parts) (rest parts))
(postpend (first parts) (rest parts))
(generate-test-strings (cdr parts))))))))
(defparameter *strings* (generate-test-strings `("X" " " "-" "--" "---" ,+crlf+ #\return #\linefeed)))
(defparameter *boundaries* '("x" "-x" "--x"))
(defun sanitize-test-string (string)
(with-output-to-string (out)
(loop for char across string
do (case char
(#\return (write-string "[CR]" out))
(#\linefeed (write-string "[LF]" out))
(t (write-char char out))))))
(defun test-string (string &optional (boundary "boundary"))
(with-input-from-string (stream string)
(handler-bind ((simple-warning (lambda (condition)
(declare (ignore condition))
(format t "~&Testing: ~S (boundary ~S)~%"
(sanitize-test-string string)
boundary))))
(rfc2388::read-until-next-boundary stream boundary))))
(defun test ()
(declare (optimize debug))
(flet ((last-char (string)
(declare (type simple-string string))
(schar string (1- (length string))))
(test (test expected boundary)
(multiple-value-bind (result more-p)
(test-string test boundary)
(unless (or (string= result expected)
more-p)
(format t "~%String: ~S (Boundary: ~S)~%Expected: ~S~%Got: ~S~%More: ~S~%"
(sanitize-test-string test)
boundary
(sanitize-test-string expected)
(sanitize-test-string result)
more-p)
(finish-output t)))))
(dolist (string *strings*)
(dolist (boundary *boundaries*)
(dolist (trailing-separator '("--" ""))
(test (concatenate 'string string +crlf+ "--" boundary trailing-separator +crlf+)
string
boundary)
(unless (char= #\- (last-char string))
(test (concatenate 'string string "--" boundary trailing-separator +crlf+)
(let ((end (- (length string) 2)))
(if (and (<= 0 end)
(string= string +crlf+ :start1 end))
(subseq string 0 end)
string))
boundary))))))
t)
| null | https://raw.githubusercontent.com/billstclair/trubanc-lisp/5436d2eca5b1ed10bc47eec7080f6cb90f98ca65/systems/rfc2388/test.lisp | lisp | (defpackage :rfc2388.test
(:use :common-lisp))
(in-package :rfc2388.test)
(defconstant +crlf+ (format nil "~C~C" #\return #\linefeed))
(defun generate-test-strings (parts)
(flet ((prepend (left list)
(mapcar (lambda (right)
(format nil "~A~A" left right))
list))
(postpend (right list)
(mapcar (lambda (left)
(format nil "~A~A" left right))
list)))
(cond ((null parts)
nil)
((null (cdr parts))
(list (format nil "~A" (first parts))))
(t
(list* (format nil "~A" (first parts))
(nconc (prepend (first parts) (rest parts))
(postpend (first parts) (rest parts))
(generate-test-strings (cdr parts))))))))
(defparameter *strings* (generate-test-strings `("X" " " "-" "--" "---" ,+crlf+ #\return #\linefeed)))
(defparameter *boundaries* '("x" "-x" "--x"))
(defun sanitize-test-string (string)
(with-output-to-string (out)
(loop for char across string
do (case char
(#\return (write-string "[CR]" out))
(#\linefeed (write-string "[LF]" out))
(t (write-char char out))))))
(defun test-string (string &optional (boundary "boundary"))
(with-input-from-string (stream string)
(handler-bind ((simple-warning (lambda (condition)
(declare (ignore condition))
(format t "~&Testing: ~S (boundary ~S)~%"
(sanitize-test-string string)
boundary))))
(rfc2388::read-until-next-boundary stream boundary))))
(defun test ()
(declare (optimize debug))
(flet ((last-char (string)
(declare (type simple-string string))
(schar string (1- (length string))))
(test (test expected boundary)
(multiple-value-bind (result more-p)
(test-string test boundary)
(unless (or (string= result expected)
more-p)
(format t "~%String: ~S (Boundary: ~S)~%Expected: ~S~%Got: ~S~%More: ~S~%"
(sanitize-test-string test)
boundary
(sanitize-test-string expected)
(sanitize-test-string result)
more-p)
(finish-output t)))))
(dolist (string *strings*)
(dolist (boundary *boundaries*)
(dolist (trailing-separator '("--" ""))
(test (concatenate 'string string +crlf+ "--" boundary trailing-separator +crlf+)
string
boundary)
(unless (char= #\- (last-char string))
(test (concatenate 'string string "--" boundary trailing-separator +crlf+)
(let ((end (- (length string) 2)))
(if (and (<= 0 end)
(string= string +crlf+ :start1 end))
(subseq string 0 end)
string))
boundary))))))
t)
| |
087703573559b58e7f3eebd74d997bd2e87ae10ccc3b87c51b48d3cf6ef81a3a | matterandvoid-space/subscriptions | reagent_ratom.cljs | (ns space.matterandvoid.subscriptions.impl.reagent-ratom
(:require-macros [space.matterandvoid.subscriptions.impl.reagent-ratom])
(:refer-clojure :exclude [atom])
(:require [reagent.ratom]))
;; Make sure the Google Closure compiler sees this as a boolean constant,
otherwise Dead Code Elimination wo n't happen in ` : advanced ` builds .
;; Type hints have been liberally sprinkled.
;; -for-compiler
(def ^boolean debug-enabled? "@define {boolean}" ^boolean goog/DEBUG)
(defn ratom? [x]
^:js suppresses externs inference warnings by forcing the compiler to
generate proper externs . Although not strictly required as
reagent.ratom/IReactiveAtom is not JS interop it appears to be harmless .
;; See -cljs.github.io/docs/UsersGuide.html#infer-externs
(satisfies? reagent.ratom/IReactiveAtom ^js x))
(def atom reagent.ratom/atom)
(defn deref? [x] (satisfies? IDeref x))
(defn make-reaction [f] (reagent.ratom/make-reaction f))
(defn run-in-reaction
"Evaluates `f` and returns the result. If `f` calls `deref` on any ratoms,
creates a new Reaction that watches those atoms and calls `run` whenever
any of those watched ratoms change. Also, the new reaction is added to
list of 'watches' of each of the ratoms. The `run` parameter is a function
that should expect one argument. It is passed `obj` when run. The `opts`
are any options accepted by a Reaction and will be set on the newly created
Reaction. Sets the newly created Reaction to the `key` on `obj`."
[f obj key run opts] (reagent.ratom/run-in-reaction f obj key run opts))
(defn add-on-dispose! [a-ratom f] (reagent.ratom/add-on-dispose! a-ratom f))
(defn reaction? [r] (instance? reagent.ratom/Reaction r))
(defn cursor? [r] (instance? reagent.ratom/RCursor r))
(defn dispose! [^clj a-ratom]
(if (cursor? a-ratom)
(if (.-on-dispose a-ratom)
(.on-dispose a-ratom)
(when (.-reaction a-ratom)
(reagent.ratom/dispose! (.-reaction a-ratom))))
(reagent.ratom/dispose! a-ratom)))
(defn ^boolean reactive-context? [] (reagent.ratom/reactive?))
(defn reagent-id
"Produces an id for reactive Reagent values
e.g. reactions, ratoms, cursors."
[reactive-val]
^:js suppresses externs inference warnings by forcing the compiler to
generate proper externs . Although not strictly required as
reagent.ratom/IReactiveAtom is not JS interop it appears to be harmless .
;; See -cljs.github.io/docs/UsersGuide.html#infer-externs
(when (implements? reagent.ratom/IReactiveAtom ^js reactive-val)
(str (condp instance? reactive-val
reagent.ratom/RAtom "ra"
reagent.ratom/Reaction "rx"
reagent.ratom/Track "tr"
"other")
(hash reactive-val))))
;; copied from reagent to allow setting an on-destroy callback to cleanup the cursor in the subscription cache.
(defn cached-reaction [f ^clj ratom k ^clj obj destroy]
(let [m (.-reagReactionCache ratom)
m (if (nil? m) {} m)
reaction (reagent.ratom/make-reaction
f :on-dispose (fn [x]
(as-> (.-reagReactionCache ratom) _
(dissoc _ k)
(set! (.-reagReactionCache ratom) _))
(when (some? obj) (set! (.-reaction obj) nil))
(when (some? (.-on-dispose obj)) (.on-dispose obj))))]
(set! (.-reagReactionCache ratom) (assoc m k reaction))
(when (some? obj)
(set! (.-reaction obj) reaction))))
(defn cursor [^clj ratom path]
(let [cursor (reagent.ratom/->RCursor ratom path nil nil nil)
f (fn [] (get-in @ratom path))]
(cached-reaction f ratom path cursor nil)
cursor))
| null | https://raw.githubusercontent.com/matterandvoid-space/subscriptions/a7e3a93cc94152a6b9098a4766b8796eae6b498d/src/main/space/matterandvoid/subscriptions/impl/reagent_ratom.cljs | clojure | Make sure the Google Closure compiler sees this as a boolean constant,
Type hints have been liberally sprinkled.
-for-compiler
See -cljs.github.io/docs/UsersGuide.html#infer-externs
See -cljs.github.io/docs/UsersGuide.html#infer-externs
copied from reagent to allow setting an on-destroy callback to cleanup the cursor in the subscription cache. | (ns space.matterandvoid.subscriptions.impl.reagent-ratom
(:require-macros [space.matterandvoid.subscriptions.impl.reagent-ratom])
(:refer-clojure :exclude [atom])
(:require [reagent.ratom]))
otherwise Dead Code Elimination wo n't happen in ` : advanced ` builds .
(def ^boolean debug-enabled? "@define {boolean}" ^boolean goog/DEBUG)
(defn ratom? [x]
^:js suppresses externs inference warnings by forcing the compiler to
generate proper externs . Although not strictly required as
reagent.ratom/IReactiveAtom is not JS interop it appears to be harmless .
(satisfies? reagent.ratom/IReactiveAtom ^js x))
(def atom reagent.ratom/atom)
(defn deref? [x] (satisfies? IDeref x))
(defn make-reaction [f] (reagent.ratom/make-reaction f))
(defn run-in-reaction
"Evaluates `f` and returns the result. If `f` calls `deref` on any ratoms,
creates a new Reaction that watches those atoms and calls `run` whenever
any of those watched ratoms change. Also, the new reaction is added to
list of 'watches' of each of the ratoms. The `run` parameter is a function
that should expect one argument. It is passed `obj` when run. The `opts`
are any options accepted by a Reaction and will be set on the newly created
Reaction. Sets the newly created Reaction to the `key` on `obj`."
[f obj key run opts] (reagent.ratom/run-in-reaction f obj key run opts))
(defn add-on-dispose! [a-ratom f] (reagent.ratom/add-on-dispose! a-ratom f))
(defn reaction? [r] (instance? reagent.ratom/Reaction r))
(defn cursor? [r] (instance? reagent.ratom/RCursor r))
(defn dispose! [^clj a-ratom]
(if (cursor? a-ratom)
(if (.-on-dispose a-ratom)
(.on-dispose a-ratom)
(when (.-reaction a-ratom)
(reagent.ratom/dispose! (.-reaction a-ratom))))
(reagent.ratom/dispose! a-ratom)))
(defn ^boolean reactive-context? [] (reagent.ratom/reactive?))
(defn reagent-id
"Produces an id for reactive Reagent values
e.g. reactions, ratoms, cursors."
[reactive-val]
^:js suppresses externs inference warnings by forcing the compiler to
generate proper externs . Although not strictly required as
reagent.ratom/IReactiveAtom is not JS interop it appears to be harmless .
(when (implements? reagent.ratom/IReactiveAtom ^js reactive-val)
(str (condp instance? reactive-val
reagent.ratom/RAtom "ra"
reagent.ratom/Reaction "rx"
reagent.ratom/Track "tr"
"other")
(hash reactive-val))))
(defn cached-reaction [f ^clj ratom k ^clj obj destroy]
(let [m (.-reagReactionCache ratom)
m (if (nil? m) {} m)
reaction (reagent.ratom/make-reaction
f :on-dispose (fn [x]
(as-> (.-reagReactionCache ratom) _
(dissoc _ k)
(set! (.-reagReactionCache ratom) _))
(when (some? obj) (set! (.-reaction obj) nil))
(when (some? (.-on-dispose obj)) (.on-dispose obj))))]
(set! (.-reagReactionCache ratom) (assoc m k reaction))
(when (some? obj)
(set! (.-reaction obj) reaction))))
(defn cursor [^clj ratom path]
(let [cursor (reagent.ratom/->RCursor ratom path nil nil nil)
f (fn [] (get-in @ratom path))]
(cached-reaction f ratom path cursor nil)
cursor))
|
b157a1c6373453fe1e3605d79d5037764a932b067c1674d64b54244da73f7109 | jrm-code-project/LISP-Machine | demo.lisp | -*- Mode : LISP ; Package : AUSCOM ; ; : CL -*-
DRIVER FOR THE AUSCOM MODEL 8600
MULTIBUS CHANNEL INTERFACE
;;; 6/18/86 16:32:31 - DEMO:
;;; - GEORGE CARRETTE
the system 38 side of this demo :
;;; A line is read from the terminal, then written to the channel.
;;; then he does a READ and displays that to the terminal.
;;; My side.
(defvar *result-string* "nothing here yet.....")
(defun demo-write-data-function (string length)
(string-translate-in-place *ebcdic->lispm* string 0 length)
(format terminal-io "~&FROM SYSTEM-38: ~S~%" (substring string 0 length))
(setq *result-string* (demo-evaluate string length))
(format terminal-io "~&TO SYSTEM-38: ~S~%" *result-string*)
(string-translate-in-place *lispm->ebcdic* *result-string*))
(defun demo-read-data-function ()
(values *result-string* (length *result-string*)))
;;; idea, if read is chained to write, then hold off on device-end (after the write)
;;; until the read buffer is ready.
(defun demo-on ()
(setq *chwrite-data-function* 'demo-write-data-function)
(setq *chread-data-function* 'demo-read-data-function))
(defun demo-off ()
(setq *chwrite-data-function* nil)
(setq *chread-data-function* nil))
(defun read-expression ()
(global:read))
(defun print-expression (exp)
(prin1 exp))
(defun demo-evaluate (string &optional (length (length string)))
(let ((*package* (find-package "USER"))
(base 10)
(ibase 10)
(*readtable* (si:find-readtable-named "CL")))
(with-output-to-string (out)
(with-input-from-string (in string :end length)
(let ((standard-output out)
(error-output out)
(standard-input in))
(catch-error (print-expression (si:eval-special-ok (read-expression)))))))))
| null | https://raw.githubusercontent.com/jrm-code-project/LISP-Machine/0a448d27f40761fafabe5775ffc550637be537b2/lambda/gjcx/auscom/demo.lisp | lisp | Package : AUSCOM ; ; : CL -*-
6/18/86 16:32:31 - DEMO:
- GEORGE CARRETTE
A line is read from the terminal, then written to the channel.
then he does a READ and displays that to the terminal.
My side.
idea, if read is chained to write, then hold off on device-end (after the write)
until the read buffer is ready. |
DRIVER FOR THE AUSCOM MODEL 8600
MULTIBUS CHANNEL INTERFACE
the system 38 side of this demo :
(defvar *result-string* "nothing here yet.....")
(defun demo-write-data-function (string length)
(string-translate-in-place *ebcdic->lispm* string 0 length)
(format terminal-io "~&FROM SYSTEM-38: ~S~%" (substring string 0 length))
(setq *result-string* (demo-evaluate string length))
(format terminal-io "~&TO SYSTEM-38: ~S~%" *result-string*)
(string-translate-in-place *lispm->ebcdic* *result-string*))
(defun demo-read-data-function ()
(values *result-string* (length *result-string*)))
(defun demo-on ()
(setq *chwrite-data-function* 'demo-write-data-function)
(setq *chread-data-function* 'demo-read-data-function))
(defun demo-off ()
(setq *chwrite-data-function* nil)
(setq *chread-data-function* nil))
(defun read-expression ()
(global:read))
(defun print-expression (exp)
(prin1 exp))
(defun demo-evaluate (string &optional (length (length string)))
(let ((*package* (find-package "USER"))
(base 10)
(ibase 10)
(*readtable* (si:find-readtable-named "CL")))
(with-output-to-string (out)
(with-input-from-string (in string :end length)
(let ((standard-output out)
(error-output out)
(standard-input in))
(catch-error (print-expression (si:eval-special-ok (read-expression)))))))))
|
e327bc26ba1f3baf45023d6d9667fab9ef57fe5d95c824b522f71fdc0c0a10bc | nmattia/makefile | Internal.hs | # LANGUAGE LambdaCase #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE ViewPatterns #
module Data.Makefile.Parse.Internal where
import Control.Monad
import Data.Foldable
import Data.Attoparsec.Text
import Data.Makefile
import Data.Monoid
import Control.Applicative
import qualified Data.Attoparsec.Text as Atto
import qualified Data.Text as T
import qualified Data.Text.IO as T
-- $setup
-- >>> :set -XOverloadedStrings
-- | Parse makefile.
--
-- Tries to open and parse a file name @Makefile@ in the current directory.
parseMakefile :: IO (Either String Makefile)
parseMakefile = Atto.parseOnly makefile <$> T.readFile "Makefile"
-- | Parse the specified file as a makefile.
parseAsMakefile :: FilePath -> IO (Either String Makefile)
parseAsMakefile f = Atto.parseOnly makefile <$> T.readFile f
parseMakefileContents :: T.Text -> Either String Makefile
parseMakefileContents = Atto.parseOnly makefile
-- | Similar to 'Atto.parseOnly' but fails if all input has not been consumed.
parseAll :: Parser a -> T.Text -> Either String a
parseAll p = Atto.parseOnly (p <* Atto.endOfInput)
--------------------------------------------------------------------------------
Parsers
-- | Parser for a makefile
makefile :: Parser Makefile
makefile = Makefile <$> many' entry
-- | Parser for a makefile entry (either a rule or a variable assignment)
entry :: Parser Entry
entry = assignment <|> rule <|> otherLine
-- | Parser of variable assignment (see 'Assignment'). Note that leading and
-- trailing whitespaces will be stripped both from the variable name and
-- assigned value.
--
-- Note that this tries to follow GNU make's (crazy) behavior when it comes to
-- variable names and assignment operators.
--
-- >>> parseAll assignment "foo = bar "
-- Right (Assignment RecursiveAssign "foo" "bar")
--
-- >>> parseAll assignment "foo := bar "
-- Right (Assignment SimpleAssign "foo" "bar")
--
-- >>> parseAll assignment "foo ::= bar "
-- Right (Assignment SimplePosixAssign "foo" "bar")
--
-- >>> parseAll assignment "foo?= bar "
-- Right (Assignment ConditionalAssign "foo" "bar")
--
-- >>> parseAll assignment "foo??= bar "
-- Right (Assignment ConditionalAssign "foo?" "bar")
--
-- >>> parseAll assignment "foo!?!= bar "
-- Right (Assignment ShellAssign "foo!?" "bar")
assignment :: Parser Entry
assignment = do
varName <- variableName
assType <- assignmentType
varVal <- toEscapedLineEnd
return (Assignment assType varName varVal)
| Read chars while some ( ' ' , monadic ) predicate is ' True ' .
--
-- XXX: extremely inefficient.
takeWhileM :: (Char -> Parser Bool) -> Parser T.Text
takeWhileM a = (T.pack . reverse) <$> go []
where
go cs = do
c <- Atto.anyChar
True <- a c
go (c:cs) <|> pure (c:cs)
-- | Parse a variable name, not consuming any of the assignment operator. See
-- also 'assignment'.
--
-- >>> Atto.parseOnly variableName "foo!?!= bar "
-- Right "foo!?"
variableName :: Parser T.Text
variableName = stripped $ takeWhileM go
where
go '+' = Atto.peekChar' >>= \case
'=' -> return False
_c -> return True
go '?' = Atto.peekChar' >>= \case
'=' -> return False
_c -> return True
go '!' = Atto.peekChar' >>= \case
'=' -> return False
_c -> return True
-- those chars are not allowed in variable names
go ':' = return False
go '#' = return False
go '=' = return False
go (Atto.isEndOfLine -> True) = return False
go _c = return True
-- | Parse an assignment type, not consuming any of the assigned value. See
-- also 'assignment'.
--
-- >>> Atto.parseOnly assignmentType "!= bar "
-- Right ShellAssign
assignmentType :: Parser AssignmentType
assignmentType =
("=" *> pure RecursiveAssign)
<|> ("+=" *> pure AppendAssign)
<|> ("?=" *> pure ConditionalAssign)
<|> ("!=" *> pure ShellAssign)
<|> (":=" *> pure SimpleAssign)
<|> ("::=" *> pure SimplePosixAssign)
-- | Parser for an entire rule
rule :: Parser Entry
rule =
Rule
<$> target
<*> (many' dependency <* (Atto.takeWhile (not.Atto.isEndOfLine) <* endOfLine'))
<*> many' command
-- | Succeeds on 'Atto.endOfLine' (line end) or if the end of input is reached.
endOfLine' :: Parser ()
endOfLine' =
Atto.endOfLine <|> (Atto.atEnd >>= check)
where
check True = pure ()
check False = mzero
-- | Parser for a command
command :: Parser Command
command = Command <$> recipeLine
recipeLine :: Parser T.Text
recipeLine =
Atto.char '\t' *> recipeLineContents ""
where
recipeLineContents pre = do
cur <- Atto.takeWhile $ \c ->
c /= '\\' && not (Atto.isEndOfLine c)
asum
[ -- Multi-line
Atto.char '\\'
*> Atto.endOfLine
*> (void (Atto.char '\t') <|> pure ())
*> recipeLineContents (pre <> cur <> "\\\n")
Just EOL or EOF
endOfLine' *> pure (pre <> cur)
, -- It was just a backslash within a recipe line, we're not doing
-- anything particular
Atto.char '\\' *> recipeLineContents (pre <> cur <> "\\")
]
-- | Parser for a (rule) target
target :: Parser Target
target = Target <$> (go $ stripped (Atto.takeWhile (/= ':') <* Atto.char ':'))
where
-- takes care of some makefile target quirks
go :: Parser a -> Parser a
go p =
Atto.takeWhile (liftA2 (||) (== ' ') (== '\t'))
*> (Atto.peekChar >>= \case
Just '#' -> mzero
Just '\n' -> mzero
_ -> p)
-- | Parser for a (rule) dependency
dependency :: Parser Dependency
dependency = Dependency <$> (sameLine <|> newLine)
where
sameLine =
Atto.takeWhile (== ' ')
*> Atto.takeWhile1 (`notElem` [' ', '\n', '#', '\\'])
newLine =
Atto.takeWhile (== ' ')
*> Atto.char '\\'
*> Atto.char '\n'
*> (sameLine <|> newLine)
-- | Catch all, used for
-- * comments, empty lines
-- * lines that failed to parse
--
> > > parseAll otherLine " # I AM A COMMENT\n "
Right ( OtherLine " # I AM A COMMENT " )
--
-- Ensure all 'Entry's consume the end of line:
-- >>> parseAll otherLine "\n"
Right ( OtherLine " " )
--
otherLine :: Parser Entry
otherLine = OtherLine <$> go
where
go = asum
[ -- Typical case of empty line
Atto.endOfLine *> pure ""
, -- Either a line of spaces and/or comment, or a line that we failed to
-- parse
Atto.takeWhile1 (not . Atto.isEndOfLine) <* Atto.endOfLine
]
toLineEnd :: Parser T.Text
toLineEnd = Atto.takeWhile (`notElem` ['\n', '#'])
-- | Get the contents until the end of the (potentially multi) line. Multiple
-- lines are separated by a @\\@ char and individual lines will be stripped and
-- spaces will be interspersed.
--
The final character is consumed .
--
-- >>> Atto.parseOnly toEscapedLineEnd "foo bar \\\n baz"
-- Right "foo bar baz"
--
-- >>> Atto.parseOnly toEscapedLineEnd "foo \t\\\n bar \\\n baz \\\n \t"
-- Right "foo bar baz"
toEscapedLineEnd :: Parser T.Text
toEscapedLineEnd = (T.unwords . filter (not . T.null)) <$> go
where
go = do
l <- toLineEnd <* (void (Atto.char '\n') <|> pure ())
case T.stripSuffix "\\" l of
Nothing -> return [T.strip l]
Just l' -> (T.strip l':) <$> go
-------------------------------------------------------------------------------
-- Helpers
-------------------------------------------------------------------------------
stripped :: Parser T.Text -> Parser T.Text
stripped = fmap T.strip
| null | https://raw.githubusercontent.com/nmattia/makefile/dbc21465c5195e32922aa5d0786fd1ffadb75a0d/src/Data/Makefile/Parse/Internal.hs | haskell | # LANGUAGE OverloadedStrings #
$setup
>>> :set -XOverloadedStrings
| Parse makefile.
Tries to open and parse a file name @Makefile@ in the current directory.
| Parse the specified file as a makefile.
| Similar to 'Atto.parseOnly' but fails if all input has not been consumed.
------------------------------------------------------------------------------
| Parser for a makefile
| Parser for a makefile entry (either a rule or a variable assignment)
| Parser of variable assignment (see 'Assignment'). Note that leading and
trailing whitespaces will be stripped both from the variable name and
assigned value.
Note that this tries to follow GNU make's (crazy) behavior when it comes to
variable names and assignment operators.
>>> parseAll assignment "foo = bar "
Right (Assignment RecursiveAssign "foo" "bar")
>>> parseAll assignment "foo := bar "
Right (Assignment SimpleAssign "foo" "bar")
>>> parseAll assignment "foo ::= bar "
Right (Assignment SimplePosixAssign "foo" "bar")
>>> parseAll assignment "foo?= bar "
Right (Assignment ConditionalAssign "foo" "bar")
>>> parseAll assignment "foo??= bar "
Right (Assignment ConditionalAssign "foo?" "bar")
>>> parseAll assignment "foo!?!= bar "
Right (Assignment ShellAssign "foo!?" "bar")
XXX: extremely inefficient.
| Parse a variable name, not consuming any of the assignment operator. See
also 'assignment'.
>>> Atto.parseOnly variableName "foo!?!= bar "
Right "foo!?"
those chars are not allowed in variable names
| Parse an assignment type, not consuming any of the assigned value. See
also 'assignment'.
>>> Atto.parseOnly assignmentType "!= bar "
Right ShellAssign
| Parser for an entire rule
| Succeeds on 'Atto.endOfLine' (line end) or if the end of input is reached.
| Parser for a command
Multi-line
It was just a backslash within a recipe line, we're not doing
anything particular
| Parser for a (rule) target
takes care of some makefile target quirks
| Parser for a (rule) dependency
| Catch all, used for
* comments, empty lines
* lines that failed to parse
Ensure all 'Entry's consume the end of line:
>>> parseAll otherLine "\n"
Typical case of empty line
Either a line of spaces and/or comment, or a line that we failed to
parse
| Get the contents until the end of the (potentially multi) line. Multiple
lines are separated by a @\\@ char and individual lines will be stripped and
spaces will be interspersed.
>>> Atto.parseOnly toEscapedLineEnd "foo bar \\\n baz"
Right "foo bar baz"
>>> Atto.parseOnly toEscapedLineEnd "foo \t\\\n bar \\\n baz \\\n \t"
Right "foo bar baz"
-----------------------------------------------------------------------------
Helpers
----------------------------------------------------------------------------- | # LANGUAGE LambdaCase #
# LANGUAGE ViewPatterns #
module Data.Makefile.Parse.Internal where
import Control.Monad
import Data.Foldable
import Data.Attoparsec.Text
import Data.Makefile
import Data.Monoid
import Control.Applicative
import qualified Data.Attoparsec.Text as Atto
import qualified Data.Text as T
import qualified Data.Text.IO as T
parseMakefile :: IO (Either String Makefile)
parseMakefile = Atto.parseOnly makefile <$> T.readFile "Makefile"
parseAsMakefile :: FilePath -> IO (Either String Makefile)
parseAsMakefile f = Atto.parseOnly makefile <$> T.readFile f
parseMakefileContents :: T.Text -> Either String Makefile
parseMakefileContents = Atto.parseOnly makefile
parseAll :: Parser a -> T.Text -> Either String a
parseAll p = Atto.parseOnly (p <* Atto.endOfInput)
Parsers
makefile :: Parser Makefile
makefile = Makefile <$> many' entry
entry :: Parser Entry
entry = assignment <|> rule <|> otherLine
assignment :: Parser Entry
assignment = do
varName <- variableName
assType <- assignmentType
varVal <- toEscapedLineEnd
return (Assignment assType varName varVal)
| Read chars while some ( ' ' , monadic ) predicate is ' True ' .
takeWhileM :: (Char -> Parser Bool) -> Parser T.Text
takeWhileM a = (T.pack . reverse) <$> go []
where
go cs = do
c <- Atto.anyChar
True <- a c
go (c:cs) <|> pure (c:cs)
variableName :: Parser T.Text
variableName = stripped $ takeWhileM go
where
go '+' = Atto.peekChar' >>= \case
'=' -> return False
_c -> return True
go '?' = Atto.peekChar' >>= \case
'=' -> return False
_c -> return True
go '!' = Atto.peekChar' >>= \case
'=' -> return False
_c -> return True
go ':' = return False
go '#' = return False
go '=' = return False
go (Atto.isEndOfLine -> True) = return False
go _c = return True
assignmentType :: Parser AssignmentType
assignmentType =
("=" *> pure RecursiveAssign)
<|> ("+=" *> pure AppendAssign)
<|> ("?=" *> pure ConditionalAssign)
<|> ("!=" *> pure ShellAssign)
<|> (":=" *> pure SimpleAssign)
<|> ("::=" *> pure SimplePosixAssign)
rule :: Parser Entry
rule =
Rule
<$> target
<*> (many' dependency <* (Atto.takeWhile (not.Atto.isEndOfLine) <* endOfLine'))
<*> many' command
endOfLine' :: Parser ()
endOfLine' =
Atto.endOfLine <|> (Atto.atEnd >>= check)
where
check True = pure ()
check False = mzero
command :: Parser Command
command = Command <$> recipeLine
recipeLine :: Parser T.Text
recipeLine =
Atto.char '\t' *> recipeLineContents ""
where
recipeLineContents pre = do
cur <- Atto.takeWhile $ \c ->
c /= '\\' && not (Atto.isEndOfLine c)
asum
Atto.char '\\'
*> Atto.endOfLine
*> (void (Atto.char '\t') <|> pure ())
*> recipeLineContents (pre <> cur <> "\\\n")
Just EOL or EOF
endOfLine' *> pure (pre <> cur)
Atto.char '\\' *> recipeLineContents (pre <> cur <> "\\")
]
target :: Parser Target
target = Target <$> (go $ stripped (Atto.takeWhile (/= ':') <* Atto.char ':'))
where
go :: Parser a -> Parser a
go p =
Atto.takeWhile (liftA2 (||) (== ' ') (== '\t'))
*> (Atto.peekChar >>= \case
Just '#' -> mzero
Just '\n' -> mzero
_ -> p)
dependency :: Parser Dependency
dependency = Dependency <$> (sameLine <|> newLine)
where
sameLine =
Atto.takeWhile (== ' ')
*> Atto.takeWhile1 (`notElem` [' ', '\n', '#', '\\'])
newLine =
Atto.takeWhile (== ' ')
*> Atto.char '\\'
*> Atto.char '\n'
*> (sameLine <|> newLine)
> > > parseAll otherLine " # I AM A COMMENT\n "
Right ( OtherLine " # I AM A COMMENT " )
Right ( OtherLine " " )
otherLine :: Parser Entry
otherLine = OtherLine <$> go
where
go = asum
Atto.endOfLine *> pure ""
Atto.takeWhile1 (not . Atto.isEndOfLine) <* Atto.endOfLine
]
toLineEnd :: Parser T.Text
toLineEnd = Atto.takeWhile (`notElem` ['\n', '#'])
The final character is consumed .
toEscapedLineEnd :: Parser T.Text
toEscapedLineEnd = (T.unwords . filter (not . T.null)) <$> go
where
go = do
l <- toLineEnd <* (void (Atto.char '\n') <|> pure ())
case T.stripSuffix "\\" l of
Nothing -> return [T.strip l]
Just l' -> (T.strip l':) <$> go
stripped :: Parser T.Text -> Parser T.Text
stripped = fmap T.strip
|
a94537a080f5ff89942f1337c730844b0bba888a7d7f781e553896ad113f1f84 | derui/okeyfum | okeyfum_time.ml | open Ctypes
open Foreign
module Types = Okeyfum_types
module Inner = struct
let gettimeofday = foreign "gettimeofday" ~check_errno:true
(ptr Types.Timeval.t @-> Types.Timezone.t @-> returning int)
end
(* Get time when execute this function *)
let now () =
let time = {
Types.Timeval.tv_sec = PosixTypes.Time.of_int 0;
tv_usec = 0L;
} in
let time = Types.Timeval.of_ocaml time in
gettimeofday 's timezone should give null
Inner.gettimeofday (addr time) (coerce (ptr void) Types.Timezone.t null) |> ignore;
Types.Timeval.to_ocaml time
| null | https://raw.githubusercontent.com/derui/okeyfum/bc47c0bea35c00d720dcde0200256a3f2e1312bd/src/okeyfum_time.ml | ocaml | Get time when execute this function | open Ctypes
open Foreign
module Types = Okeyfum_types
module Inner = struct
let gettimeofday = foreign "gettimeofday" ~check_errno:true
(ptr Types.Timeval.t @-> Types.Timezone.t @-> returning int)
end
let now () =
let time = {
Types.Timeval.tv_sec = PosixTypes.Time.of_int 0;
tv_usec = 0L;
} in
let time = Types.Timeval.of_ocaml time in
gettimeofday 's timezone should give null
Inner.gettimeofday (addr time) (coerce (ptr void) Types.Timezone.t null) |> ignore;
Types.Timeval.to_ocaml time
|
a86a6f01a2f80a7587da37eb24fe1989cbc58323336361e9e1227c6a1b6a4577 | amnh/poy5 | pdffun.mli | (** Parsing and Evaluating PDF functions *)
type calculator =
| If of calculator list
| IfElse of calculator list * calculator list
| Bool of bool
| Float of float
| Int of int32
| Abs
| Add
| Atan
| Ceiling
| Cos
| Cvi
| Cvr
| Div
| Exp
| Floor
| Idiv
| Ln
| Log
| Mod
| Mul
| Neg
| Round
| Sin
| Sqrt
| Sub
| Truncate
| And
| Bitshift
| Eq
| Ge
| Gt
| Le
| Lt
| Ne
| Not
| Or
| Xor
| Copy
| Exch
| Pop
| Dup
| Index
| Roll
type sampled =
{size : int list;
order : int;
encode : float list;
decode : float list;
bps : int;
samples : int32 array}
and interpolation =
{c0 : float list;
c1 : float list;
n : float}
and stitching =
{functions : pdf_fun list;
bounds : float list;
stitch_encode : float list}
and pdf_fun_kind =
| Interpolation of interpolation
| Stitching of stitching
| Sampled of sampled
| Calculator of calculator list
and pdf_fun =
{func : pdf_fun_kind;
domain : float list;
range : float list option}
(** The type of functions. *)
val parse_function : Pdf.pdfdoc -> Pdf.pdfobject -> pdf_fun
(** Raised from [eval_function] (see below) in the case of inputs which don't
match the evaluation *)
exception BadFunctionEvaluation of string
(** Evaluate a function given a list of inputs. *)
val eval_function : pdf_fun -> float list -> float list
(**/**)
val print_function : pdf_fun -> unit
| null | https://raw.githubusercontent.com/amnh/poy5/da563a2339d3fa9c0110ae86cc35fad576f728ab/src/camlpdf-0.3/pdffun.mli | ocaml | * Parsing and Evaluating PDF functions
* The type of functions.
* Raised from [eval_function] (see below) in the case of inputs which don't
match the evaluation
* Evaluate a function given a list of inputs.
*/* | type calculator =
| If of calculator list
| IfElse of calculator list * calculator list
| Bool of bool
| Float of float
| Int of int32
| Abs
| Add
| Atan
| Ceiling
| Cos
| Cvi
| Cvr
| Div
| Exp
| Floor
| Idiv
| Ln
| Log
| Mod
| Mul
| Neg
| Round
| Sin
| Sqrt
| Sub
| Truncate
| And
| Bitshift
| Eq
| Ge
| Gt
| Le
| Lt
| Ne
| Not
| Or
| Xor
| Copy
| Exch
| Pop
| Dup
| Index
| Roll
type sampled =
{size : int list;
order : int;
encode : float list;
decode : float list;
bps : int;
samples : int32 array}
and interpolation =
{c0 : float list;
c1 : float list;
n : float}
and stitching =
{functions : pdf_fun list;
bounds : float list;
stitch_encode : float list}
and pdf_fun_kind =
| Interpolation of interpolation
| Stitching of stitching
| Sampled of sampled
| Calculator of calculator list
and pdf_fun =
{func : pdf_fun_kind;
domain : float list;
range : float list option}
val parse_function : Pdf.pdfdoc -> Pdf.pdfobject -> pdf_fun
exception BadFunctionEvaluation of string
val eval_function : pdf_fun -> float list -> float list
val print_function : pdf_fun -> unit
|
20114ca84ea211044a3d384bae53fb46e1bc86a7b72547457c4c63c61b294f1f | mbj/stratosphere | Rule.hs | module Stratosphere.WAFRegional.Rule (
module Exports, Rule(..), mkRule
) where
import qualified Data.Aeson as JSON
import qualified Stratosphere.Prelude as Prelude
import Stratosphere.Property
import {-# SOURCE #-} Stratosphere.WAFRegional.Rule.PredicateProperty as Exports
import Stratosphere.ResourceProperties
import Stratosphere.Value
data Rule
= Rule {metricName :: (Value Prelude.Text),
name :: (Value Prelude.Text),
predicates :: (Prelude.Maybe [PredicateProperty])}
mkRule :: Value Prelude.Text -> Value Prelude.Text -> Rule
mkRule metricName name
= Rule
{metricName = metricName, name = name,
predicates = Prelude.Nothing}
instance ToResourceProperties Rule where
toResourceProperties Rule {..}
= ResourceProperties
{awsType = "AWS::WAFRegional::Rule", supportsTags = Prelude.False,
properties = Prelude.fromList
((Prelude.<>)
["MetricName" JSON..= metricName, "Name" JSON..= name]
(Prelude.catMaybes
[(JSON..=) "Predicates" Prelude.<$> predicates]))}
instance JSON.ToJSON Rule where
toJSON Rule {..}
= JSON.object
(Prelude.fromList
((Prelude.<>)
["MetricName" JSON..= metricName, "Name" JSON..= name]
(Prelude.catMaybes
[(JSON..=) "Predicates" Prelude.<$> predicates])))
instance Property "MetricName" Rule where
type PropertyType "MetricName" Rule = Value Prelude.Text
set newValue Rule {..} = Rule {metricName = newValue, ..}
instance Property "Name" Rule where
type PropertyType "Name" Rule = Value Prelude.Text
set newValue Rule {..} = Rule {name = newValue, ..}
instance Property "Predicates" Rule where
type PropertyType "Predicates" Rule = [PredicateProperty]
set newValue Rule {..}
= Rule {predicates = Prelude.pure newValue, ..} | null | https://raw.githubusercontent.com/mbj/stratosphere/c70f301715425247efcda29af4f3fcf7ec04aa2f/services/wafregional/gen/Stratosphere/WAFRegional/Rule.hs | haskell | # SOURCE # | module Stratosphere.WAFRegional.Rule (
module Exports, Rule(..), mkRule
) where
import qualified Data.Aeson as JSON
import qualified Stratosphere.Prelude as Prelude
import Stratosphere.Property
import Stratosphere.ResourceProperties
import Stratosphere.Value
data Rule
= Rule {metricName :: (Value Prelude.Text),
name :: (Value Prelude.Text),
predicates :: (Prelude.Maybe [PredicateProperty])}
mkRule :: Value Prelude.Text -> Value Prelude.Text -> Rule
mkRule metricName name
= Rule
{metricName = metricName, name = name,
predicates = Prelude.Nothing}
instance ToResourceProperties Rule where
toResourceProperties Rule {..}
= ResourceProperties
{awsType = "AWS::WAFRegional::Rule", supportsTags = Prelude.False,
properties = Prelude.fromList
((Prelude.<>)
["MetricName" JSON..= metricName, "Name" JSON..= name]
(Prelude.catMaybes
[(JSON..=) "Predicates" Prelude.<$> predicates]))}
instance JSON.ToJSON Rule where
toJSON Rule {..}
= JSON.object
(Prelude.fromList
((Prelude.<>)
["MetricName" JSON..= metricName, "Name" JSON..= name]
(Prelude.catMaybes
[(JSON..=) "Predicates" Prelude.<$> predicates])))
instance Property "MetricName" Rule where
type PropertyType "MetricName" Rule = Value Prelude.Text
set newValue Rule {..} = Rule {metricName = newValue, ..}
instance Property "Name" Rule where
type PropertyType "Name" Rule = Value Prelude.Text
set newValue Rule {..} = Rule {name = newValue, ..}
instance Property "Predicates" Rule where
type PropertyType "Predicates" Rule = [PredicateProperty]
set newValue Rule {..}
= Rule {predicates = Prelude.pure newValue, ..} |
25bef5eac23fa793cd9e128940e5e0fe704d98e4f0fccffc0d9b2495c1c74394 | sansarip/owlbear | tag_open.cljs | (ns owlbear.lexer.html.tag-open
(:require [owlbear.lexer.html.token-types :as html-tknt]))
(defn tag-open-bracket-ctx?
"Given a context,
returns true if the context is an HTML tag open angular bracket e.g. <"
[ctx]
(and (some? ctx) (html-tknt/token-type? ctx :tag-open)))
(defn tag-open-bracket-ctx
"Given a context,
returns the context if the tag is an HTML opening tag"
[ctx]
(when (tag-open-bracket-ctx? ctx)
ctx))
| null | https://raw.githubusercontent.com/sansarip/owlbear/b25d46e3f401f5fee739889e5bc604f6b9c00c41/src/cljs/owlbear/lexer/html/tag_open.cljs | clojure | (ns owlbear.lexer.html.tag-open
(:require [owlbear.lexer.html.token-types :as html-tknt]))
(defn tag-open-bracket-ctx?
"Given a context,
returns true if the context is an HTML tag open angular bracket e.g. <"
[ctx]
(and (some? ctx) (html-tknt/token-type? ctx :tag-open)))
(defn tag-open-bracket-ctx
"Given a context,
returns the context if the tag is an HTML opening tag"
[ctx]
(when (tag-open-bracket-ctx? ctx)
ctx))
| |
a8ec4a921262672e1c30f7d6a65b8cc2475ddd3bf3a28e93c350d59609139627 | Kappa-Dev/KappaTools | graph_loggers.mli | *
* graph_loggers.mli
*
* a module for * , projet Antique , INRIA Paris
*
* * , Université Paris - Diderot , CNRS
*
* Creation : 23/05/2016
* Last modification : 25/05/2016
* *
*
*
* Copyright 2016 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
* graph_loggers.mli
*
* a module for KaSim
* Jérôme Feret, projet Antique, INRIA Paris
*
* KaSim
* Jean Krivine, Université Paris-Diderot, CNRS
*
* Creation: 23/05/2016
* Last modification: 25/05/2016
* *
*
*
* Copyright 2016 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 *)
val dot_color_encoding: Graph_loggers_sig.color -> string
val shape_in_dot: Graph_loggers_sig.shape -> string
val print_graph_preamble:
Graph_loggers_sig.t ->
?filter_in:Loggers.encoding list option ->
?filter_out:Loggers.encoding list ->
?header:string list ->
string ->
unit
val print_graph_foot: Graph_loggers_sig.t -> unit
val print_comment:
Graph_loggers_sig.t ->
?filter_in:Loggers.encoding list option ->
?filter_out:Loggers.encoding list ->
string ->
unit
val open_asso: Graph_loggers_sig.t -> unit
val close_asso: Graph_loggers_sig.t -> unit
val print_asso: Graph_loggers_sig.t -> string -> string -> unit
val print_node: Graph_loggers_sig.t -> ?directives:Graph_loggers_sig.options list -> string -> unit
val print_edge: Graph_loggers_sig.t -> ?directives:Graph_loggers_sig.options list -> ?prefix:string -> string -> string -> unit
val print_one_to_n_relation: Graph_loggers_sig.t -> ?directives:Graph_loggers_sig.options list -> ?style_one:Graph_loggers_sig.linestyle -> ?style_n:Graph_loggers_sig.linestyle -> string -> string list -> unit
| null | https://raw.githubusercontent.com/Kappa-Dev/KappaTools/eef2337e8688018eda47ccc838aea809cae68de7/core/classical_graphs/graph_loggers.mli | ocaml | *
* graph_loggers.mli
*
* a module for * , projet Antique , INRIA Paris
*
* * , Université Paris - Diderot , CNRS
*
* Creation : 23/05/2016
* Last modification : 25/05/2016
* *
*
*
* Copyright 2016 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
* graph_loggers.mli
*
* a module for KaSim
* Jérôme Feret, projet Antique, INRIA Paris
*
* KaSim
* Jean Krivine, Université Paris-Diderot, CNRS
*
* Creation: 23/05/2016
* Last modification: 25/05/2016
* *
*
*
* Copyright 2016 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 *)
val dot_color_encoding: Graph_loggers_sig.color -> string
val shape_in_dot: Graph_loggers_sig.shape -> string
val print_graph_preamble:
Graph_loggers_sig.t ->
?filter_in:Loggers.encoding list option ->
?filter_out:Loggers.encoding list ->
?header:string list ->
string ->
unit
val print_graph_foot: Graph_loggers_sig.t -> unit
val print_comment:
Graph_loggers_sig.t ->
?filter_in:Loggers.encoding list option ->
?filter_out:Loggers.encoding list ->
string ->
unit
val open_asso: Graph_loggers_sig.t -> unit
val close_asso: Graph_loggers_sig.t -> unit
val print_asso: Graph_loggers_sig.t -> string -> string -> unit
val print_node: Graph_loggers_sig.t -> ?directives:Graph_loggers_sig.options list -> string -> unit
val print_edge: Graph_loggers_sig.t -> ?directives:Graph_loggers_sig.options list -> ?prefix:string -> string -> string -> unit
val print_one_to_n_relation: Graph_loggers_sig.t -> ?directives:Graph_loggers_sig.options list -> ?style_one:Graph_loggers_sig.linestyle -> ?style_n:Graph_loggers_sig.linestyle -> string -> string list -> unit
| |
2de886c1dc6cddaedf0a695901a87a8ad071882f869cf2e1385cb022f4770e8c | haskell-suite/haskell-src-exts | EmptyList.hs | module EmptyList where
eAttrs = []
| null | https://raw.githubusercontent.com/haskell-suite/haskell-src-exts/84a4930e0e5c051b7d9efd20ef7c822d5fc1c33b/tests/examples/EmptyList.hs | haskell | module EmptyList where
eAttrs = []
| |
b73b4cefadbac172395122f8493e7db37acda71e8d0b81bf069fd7b4d663b735 | coq/coq | stmargs.ml | (************************************************************************)
(* * The Coq Proof Assistant / The Coq Development Team *)
v * Copyright INRIA , CNRS and contributors
< O _ _ _ , , * ( see version control and CREDITS file for authors & dates )
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
(* // * This file is distributed under the terms of the *)
* GNU Lesser General Public License Version 2.1
(* * (see LICENSE file for the text of the license) *)
(************************************************************************)
let fatal_error exn =
Topfmt.(in_phase ~phase:ParsingCommandLine print_err_exn exn);
let exit_code = if (CErrors.is_anomaly exn) then 129 else 1 in
exit exit_code
let set_worker_id opt s =
assert (s <> "master");
Flags.async_proofs_worker_id := s
let get_host_port opt s =
match String.split_on_char ':' s with
| [host; portr; portw] ->
Some (Spawned.Socket(host, int_of_string portr, int_of_string portw))
| ["stdfds"] -> Some Spawned.AnonPipe
| _ ->
Coqargs.error_wrong_arg ("Error: host:portr:portw or stdfds expected after option "^opt)
let get_error_resilience opt = function
| "on" | "all" | "yes" -> Stm.AsyncOpts.FAll
| "off" | "no" -> Stm.AsyncOpts.FNone
| s -> Stm.AsyncOpts.FOnly (String.split_on_char ',' s)
let get_priority opt s =
try CoqworkmgrApi.priority_of_string s
with Invalid_argument _ ->
Coqargs.error_wrong_arg ("Error: low/high expected after "^opt)
let get_async_proofs_mode opt = let open Stm.AsyncOpts in function
| "no" | "off" -> APoff
| "yes" | "on" -> APon
| "lazy" -> APonLazy
| _ ->
Coqargs.error_wrong_arg ("Error: on/off/lazy expected after "^opt)
let get_cache opt = function
| "force" -> Some Stm.AsyncOpts.Force
| _ ->
Coqargs.error_wrong_arg ("Error: force expected after "^opt)
let parse_args ~init arglist : Stm.AsyncOpts.stm_opt * string list =
let args = ref arglist in
let extras = ref [] in
let rec parse oval = match !args with
| [] ->
(oval, List.rev !extras)
| opt :: rem ->
args := rem;
let next () = match !args with
| x::rem -> args := rem; x
| [] -> Coqargs.error_missing_arg opt
in
let noval = begin match opt with
|"-async-proofs" ->
{ oval with
Stm.AsyncOpts.async_proofs_mode = get_async_proofs_mode opt (next())
}
|"-async-proofs-j" ->
{ oval with
Stm.AsyncOpts.async_proofs_n_workers = (Coqargs.get_int ~opt (next ()))
}
|"-async-proofs-cache" ->
{ oval with
Stm.AsyncOpts.async_proofs_cache = get_cache opt (next ())
}
|"-async-proofs-tac-j" ->
let j = Coqargs.get_int ~opt (next ()) in
if j < 0 then begin
Coqargs.error_wrong_arg ("Error: -async-proofs-tac-j only accepts values greater than or equal to 0")
end;
{ oval with
Stm.AsyncOpts.async_proofs_n_tacworkers = j
}
|"-async-proofs-worker-priority" ->
{ oval with
Stm.AsyncOpts.async_proofs_worker_priority = get_priority opt (next ())
}
|"-async-proofs-private-flags" ->
{ oval with
Stm.AsyncOpts.async_proofs_private_flags = Some (next ());
}
|"-async-proofs-tactic-error-resilience" ->
{ oval with
Stm.AsyncOpts.async_proofs_tac_error_resilience = get_error_resilience opt (next ())
}
|"-async-proofs-command-error-resilience" ->
{ oval with
Stm.AsyncOpts.async_proofs_cmd_error_resilience = Coqargs.get_bool ~opt (next ())
}
|"-async-proofs-delegation-threshold" ->
{ oval with
Stm.AsyncOpts.async_proofs_delegation_threshold = Coqargs.get_float ~opt (next ())
}
|"-worker-id" -> set_worker_id opt (next ()); oval
|"-main-channel" ->
Spawned.main_channel := get_host_port opt (next()); oval
|"-control-channel" ->
Spawned.control_channel := get_host_port opt (next()); oval
Options with zero arg
|"-async-queries-always-delegate"
|"-async-proofs-always-delegate"
|"-async-proofs-never-reopen-branch" ->
{ oval with
Stm.AsyncOpts.async_proofs_never_reopen_branch = true
}
|"-stm-debug" -> Stm.stm_debug := true; oval
(* Unknown option *)
| s ->
extras := s :: !extras;
oval
end in
parse noval
in
try
parse init
with any -> fatal_error any
let usage = "\
\n -stm-debug STM debug mode (will trace every transaction)\
"
| null | https://raw.githubusercontent.com/coq/coq/be73f2503157561b67d97d264e3820ce9caa73f2/stm/stmargs.ml | ocaml | **********************************************************************
* The Coq Proof Assistant / The Coq Development Team
// * This file is distributed under the terms of the
* (see LICENSE file for the text of the license)
**********************************************************************
Unknown option | v * Copyright INRIA , CNRS and contributors
< O _ _ _ , , * ( see version control and CREDITS file for authors & dates )
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* GNU Lesser General Public License Version 2.1
let fatal_error exn =
Topfmt.(in_phase ~phase:ParsingCommandLine print_err_exn exn);
let exit_code = if (CErrors.is_anomaly exn) then 129 else 1 in
exit exit_code
let set_worker_id opt s =
assert (s <> "master");
Flags.async_proofs_worker_id := s
let get_host_port opt s =
match String.split_on_char ':' s with
| [host; portr; portw] ->
Some (Spawned.Socket(host, int_of_string portr, int_of_string portw))
| ["stdfds"] -> Some Spawned.AnonPipe
| _ ->
Coqargs.error_wrong_arg ("Error: host:portr:portw or stdfds expected after option "^opt)
let get_error_resilience opt = function
| "on" | "all" | "yes" -> Stm.AsyncOpts.FAll
| "off" | "no" -> Stm.AsyncOpts.FNone
| s -> Stm.AsyncOpts.FOnly (String.split_on_char ',' s)
let get_priority opt s =
try CoqworkmgrApi.priority_of_string s
with Invalid_argument _ ->
Coqargs.error_wrong_arg ("Error: low/high expected after "^opt)
let get_async_proofs_mode opt = let open Stm.AsyncOpts in function
| "no" | "off" -> APoff
| "yes" | "on" -> APon
| "lazy" -> APonLazy
| _ ->
Coqargs.error_wrong_arg ("Error: on/off/lazy expected after "^opt)
let get_cache opt = function
| "force" -> Some Stm.AsyncOpts.Force
| _ ->
Coqargs.error_wrong_arg ("Error: force expected after "^opt)
let parse_args ~init arglist : Stm.AsyncOpts.stm_opt * string list =
let args = ref arglist in
let extras = ref [] in
let rec parse oval = match !args with
| [] ->
(oval, List.rev !extras)
| opt :: rem ->
args := rem;
let next () = match !args with
| x::rem -> args := rem; x
| [] -> Coqargs.error_missing_arg opt
in
let noval = begin match opt with
|"-async-proofs" ->
{ oval with
Stm.AsyncOpts.async_proofs_mode = get_async_proofs_mode opt (next())
}
|"-async-proofs-j" ->
{ oval with
Stm.AsyncOpts.async_proofs_n_workers = (Coqargs.get_int ~opt (next ()))
}
|"-async-proofs-cache" ->
{ oval with
Stm.AsyncOpts.async_proofs_cache = get_cache opt (next ())
}
|"-async-proofs-tac-j" ->
let j = Coqargs.get_int ~opt (next ()) in
if j < 0 then begin
Coqargs.error_wrong_arg ("Error: -async-proofs-tac-j only accepts values greater than or equal to 0")
end;
{ oval with
Stm.AsyncOpts.async_proofs_n_tacworkers = j
}
|"-async-proofs-worker-priority" ->
{ oval with
Stm.AsyncOpts.async_proofs_worker_priority = get_priority opt (next ())
}
|"-async-proofs-private-flags" ->
{ oval with
Stm.AsyncOpts.async_proofs_private_flags = Some (next ());
}
|"-async-proofs-tactic-error-resilience" ->
{ oval with
Stm.AsyncOpts.async_proofs_tac_error_resilience = get_error_resilience opt (next ())
}
|"-async-proofs-command-error-resilience" ->
{ oval with
Stm.AsyncOpts.async_proofs_cmd_error_resilience = Coqargs.get_bool ~opt (next ())
}
|"-async-proofs-delegation-threshold" ->
{ oval with
Stm.AsyncOpts.async_proofs_delegation_threshold = Coqargs.get_float ~opt (next ())
}
|"-worker-id" -> set_worker_id opt (next ()); oval
|"-main-channel" ->
Spawned.main_channel := get_host_port opt (next()); oval
|"-control-channel" ->
Spawned.control_channel := get_host_port opt (next()); oval
Options with zero arg
|"-async-queries-always-delegate"
|"-async-proofs-always-delegate"
|"-async-proofs-never-reopen-branch" ->
{ oval with
Stm.AsyncOpts.async_proofs_never_reopen_branch = true
}
|"-stm-debug" -> Stm.stm_debug := true; oval
| s ->
extras := s :: !extras;
oval
end in
parse noval
in
try
parse init
with any -> fatal_error any
let usage = "\
\n -stm-debug STM debug mode (will trace every transaction)\
"
|
d629d1bbdd2d0e8a628aeda93d46d6354e4fb678a077370e953b8634099807ba | Frechmatz/cl-synthesizer | profile-phase-waveform-converter.lisp | (defpackage :cl-synthesizer-profiling-waveform-converter
(:use :cl))
(in-package :cl-synthesizer-profiling-waveform-converter)
;;
;; The tests add a bit overhead to prevent compiler from optimizations
;;
(defun run-sine (&key duration-seconds phi)
(let ((result 0.0))
(dotimes (i (* 44100 duration-seconds))
(setf result (+ result (cl-synthesizer-util:phase-sine-converter phi 0.0)))
(setf phi (+ 0.01 phi)))
result))
(defun run-square (&key duration-seconds phi)
(let ((result 0.0))
(dotimes (i (* 44100 duration-seconds))
(setf result (+ result (cl-synthesizer-util:phase-square-converter phi 0.0 0.5)))
(setf phi (+ 0.01 phi)))
result))
(defun run-triangle (&key duration-seconds phi)
(let ((result 0.0))
(dotimes (i (* 44100 duration-seconds))
(setf result (+ result (cl-synthesizer-util:phase-triangle-converter phi 0.0)))
(setf phi (+ 0.01 phi)))
result))
(defun run-saw (&key duration-seconds phi)
(let ((result 0.0))
(dotimes (i (* 44100 duration-seconds))
(setf result (+ result (cl-synthesizer-util:phase-saw-converter phi 0.0)))
(setf phi (+ 0.01 phi)))
result))
| null | https://raw.githubusercontent.com/Frechmatz/cl-synthesizer/7490d12f0f1e744fa1f71e014627551ebc4388c7/profiling/profile-phase-waveform-converter.lisp | lisp |
The tests add a bit overhead to prevent compiler from optimizations
| (defpackage :cl-synthesizer-profiling-waveform-converter
(:use :cl))
(in-package :cl-synthesizer-profiling-waveform-converter)
(defun run-sine (&key duration-seconds phi)
(let ((result 0.0))
(dotimes (i (* 44100 duration-seconds))
(setf result (+ result (cl-synthesizer-util:phase-sine-converter phi 0.0)))
(setf phi (+ 0.01 phi)))
result))
(defun run-square (&key duration-seconds phi)
(let ((result 0.0))
(dotimes (i (* 44100 duration-seconds))
(setf result (+ result (cl-synthesizer-util:phase-square-converter phi 0.0 0.5)))
(setf phi (+ 0.01 phi)))
result))
(defun run-triangle (&key duration-seconds phi)
(let ((result 0.0))
(dotimes (i (* 44100 duration-seconds))
(setf result (+ result (cl-synthesizer-util:phase-triangle-converter phi 0.0)))
(setf phi (+ 0.01 phi)))
result))
(defun run-saw (&key duration-seconds phi)
(let ((result 0.0))
(dotimes (i (* 44100 duration-seconds))
(setf result (+ result (cl-synthesizer-util:phase-saw-converter phi 0.0)))
(setf phi (+ 0.01 phi)))
result))
|
b3af41a9ad26b841b6d81bf8651f0a5e4d8356b6fccf0650e8b9aafbd4053368 | hasktorch/ffi-experimental | ParseDerivatives.hs |
{-# LANGUAGE DeriveAnyClass #-}
# LANGUAGE DeriveGeneric #
{-# LANGUAGE OverloadedStrings #-}
module ParseDerivatives where
import GHC.Generics
import Data.Yaml
import qualified Data.Yaml as Y
import Text.Show.Prettyprint (prettyPrint)
{- derivatives.yaml -}
data Derivative = Derivative {
name :: String
, self :: Maybe String
, other :: Maybe String
, tensor1 :: Maybe String
, tensor2 :: Maybe String
, tensors :: Maybe String
, mat1 :: Maybe String
, mat2 :: Maybe String
, vec :: Maybe String
, batch1 :: Maybe String
, batch2 :: Maybe String
, output_differentiability :: Maybe [Bool]
, value :: Maybe String
, exponent :: Maybe String
, src :: Maybe String
, grad_output :: Maybe String
, weight :: Maybe String
, bias :: Maybe String
, input :: Maybe String
, input2 :: Maybe String
, input3 :: Maybe String
, input_gates :: Maybe String
, input_bias :: Maybe String
, hidden_gates :: Maybe String
, hidden_bias :: Maybe String
, cx :: Maybe String
, hx :: Maybe String
, save_mean :: Maybe String
, save_var :: Maybe String
, grid :: Maybe String
, i1 :: Maybe String
, i2 :: Maybe String
, i3 :: Maybe String
} deriving (Show, Generic)
instance FromJSON Derivative
decodeAndPrint :: String -> IO ()
decodeAndPrint fileName = do
file <- Y.decodeFileEither fileName :: IO (Either ParseException [Derivative])
prettyPrint file
| null | https://raw.githubusercontent.com/hasktorch/ffi-experimental/54192297742221c4d50398586ba8d187451f9ee0/codegen/src/ParseDerivatives.hs | haskell | # LANGUAGE DeriveAnyClass #
# LANGUAGE OverloadedStrings #
derivatives.yaml |
# LANGUAGE DeriveGeneric #
module ParseDerivatives where
import GHC.Generics
import Data.Yaml
import qualified Data.Yaml as Y
import Text.Show.Prettyprint (prettyPrint)
data Derivative = Derivative {
name :: String
, self :: Maybe String
, other :: Maybe String
, tensor1 :: Maybe String
, tensor2 :: Maybe String
, tensors :: Maybe String
, mat1 :: Maybe String
, mat2 :: Maybe String
, vec :: Maybe String
, batch1 :: Maybe String
, batch2 :: Maybe String
, output_differentiability :: Maybe [Bool]
, value :: Maybe String
, exponent :: Maybe String
, src :: Maybe String
, grad_output :: Maybe String
, weight :: Maybe String
, bias :: Maybe String
, input :: Maybe String
, input2 :: Maybe String
, input3 :: Maybe String
, input_gates :: Maybe String
, input_bias :: Maybe String
, hidden_gates :: Maybe String
, hidden_bias :: Maybe String
, cx :: Maybe String
, hx :: Maybe String
, save_mean :: Maybe String
, save_var :: Maybe String
, grid :: Maybe String
, i1 :: Maybe String
, i2 :: Maybe String
, i3 :: Maybe String
} deriving (Show, Generic)
instance FromJSON Derivative
decodeAndPrint :: String -> IO ()
decodeAndPrint fileName = do
file <- Y.decodeFileEither fileName :: IO (Either ParseException [Derivative])
prettyPrint file
|
0411d3cfbf7613ce84d629d85aad8af78359151f167c2cb6169d5b8b6bcff4d3 | imrehg/ypsilon | container.scm | #!nobacktrace
Ypsilon Scheme System
Copyright ( c ) 2004 - 2009 Y.FUJITA / LittleWing Company Limited .
See license.txt for terms and conditions of use .
(library (ypsilon gtk container)
(export gtk_container_add
gtk_container_add_with_properties
gtk_container_check_resize
gtk_container_child_get
gtk_container_child_get_property
gtk_container_child_get_valist
gtk_container_child_set
gtk_container_child_set_property
gtk_container_child_set_valist
gtk_container_child_type
gtk_container_class_find_child_property
gtk_container_class_install_child_property
gtk_container_class_list_child_properties
gtk_container_forall
gtk_container_foreach
gtk_container_get_border_width
gtk_container_get_children
gtk_container_get_focus_chain
gtk_container_get_focus_child
gtk_container_get_focus_hadjustment
gtk_container_get_focus_vadjustment
gtk_container_get_resize_mode
gtk_container_get_type
gtk_container_propagate_expose
gtk_container_remove
gtk_container_resize_children
gtk_container_set_border_width
gtk_container_set_focus_chain
gtk_container_set_focus_child
gtk_container_set_focus_hadjustment
gtk_container_set_focus_vadjustment
gtk_container_set_reallocate_redraws
gtk_container_set_resize_mode
gtk_container_unset_focus_chain)
(import (rnrs) (ypsilon ffi))
(define lib-name
(cond (on-linux "libgtk-x11-2.0.so.0")
(on-sunos "libgtk-x11-2.0.so.0")
(on-freebsd "libgtk-x11-2.0.so.0")
(on-openbsd "libgtk-x11-2.0.so.0")
(on-darwin "Gtk.framework/Gtk")
(on-windows "libgtk-win32-2.0-0.dll")
(else
(assertion-violation #f "can not locate GTK library, unknown operating system"))))
(define lib (load-shared-object lib-name))
(define-syntax define-function
(syntax-rules ()
((_ ret name args)
(define name (c-function lib lib-name ret name args)))))
(define-syntax define-function/va_list
(syntax-rules ()
((_ ret name args)
(define name (lambda x (assertion-violation 'name "va_list argument not supported"))))))
void gtk_container_add ( GtkContainer * container , GtkWidget * widget )
(define-function void gtk_container_add (void* void*))
void ( GtkContainer * container , GtkWidget * widget , const gchar * first_prop_name , ... )
(define-function void gtk_container_add_with_properties (void* void* char* ...))
void gtk_container_check_resize ( GtkContainer * container )
(define-function void gtk_container_check_resize (void*))
void gtk_container_child_get ( GtkContainer * container , GtkWidget * child , const gchar * first_prop_name , ... )
(define-function void gtk_container_child_get (void* void* char* ...))
void gtk_container_child_get_property ( GtkContainer * container , GtkWidget * child , const gchar * property_name , GValue * value )
(define-function void gtk_container_child_get_property (void* void* char* void*))
void gtk_container_child_get_valist ( GtkContainer * container , GtkWidget * child , const gchar * first_property_name , va_list )
(define-function/va_list void gtk_container_child_get_valist (void* void* char* va_list))
void gtk_container_child_set ( GtkContainer * container , GtkWidget * child , const gchar * first_prop_name , ... )
(define-function void gtk_container_child_set (void* void* char* ...))
void gtk_container_child_set_property ( GtkContainer * container , GtkWidget * child , const gchar * property_name , const GValue * value )
(define-function void gtk_container_child_set_property (void* void* char* void*))
void gtk_container_child_set_valist ( GtkContainer * container , GtkWidget * child , const gchar * first_property_name , va_list )
(define-function/va_list void gtk_container_child_set_valist (void* void* char* va_list))
GType gtk_container_child_type ( GtkContainer * container )
(define-function unsigned-long gtk_container_child_type (void*))
GParamSpec * gtk_container_class_find_child_property ( GObjectClass * cclass , const gchar * property_name )
(define-function void* gtk_container_class_find_child_property (void* char*))
void gtk_container_class_install_child_property ( GtkContainerClass * cclass , guint property_id , GParamSpec * )
(define-function void gtk_container_class_install_child_property (void* unsigned-int void*))
GParamSpec * * gtk_container_class_list_child_properties ( GObjectClass * cclass , guint * n_properties )
(define-function void* gtk_container_class_list_child_properties (void* void*))
void gtk_container_forall ( GtkContainer * container , GtkCallback callback , )
(define-function void gtk_container_forall (void* (c-callback void (void* void*)) void*))
void ( GtkContainer * container , GtkCallback callback , )
(define-function void gtk_container_foreach (void* (c-callback void (void* void*)) void*))
guint gtk_container_get_border_width ( GtkContainer * container )
(define-function unsigned-int gtk_container_get_border_width (void*))
GList * ( GtkContainer * container )
(define-function void* gtk_container_get_children (void*))
gboolean gtk_container_get_focus_chain ( GtkContainer * container , GList * * focusable_widgets )
(define-function int gtk_container_get_focus_chain (void* void*))
GtkWidget * gtk_container_get_focus_child ( GtkContainer * container )
(define-function void* gtk_container_get_focus_child (void*))
GtkAdjustment * gtk_container_get_focus_hadjustment ( GtkContainer * container )
(define-function void* gtk_container_get_focus_hadjustment (void*))
GtkAdjustment * gtk_container_get_focus_vadjustment ( GtkContainer * container )
(define-function void* gtk_container_get_focus_vadjustment (void*))
GtkResizeMode gtk_container_get_resize_mode ( GtkContainer * container )
(define-function int gtk_container_get_resize_mode (void*))
GType gtk_container_get_type ( void )
(define-function unsigned-long gtk_container_get_type ())
void gtk_container_propagate_expose ( GtkContainer * container , GtkWidget * child , * event )
(define-function void gtk_container_propagate_expose (void* void* void*))
void gtk_container_remove ( GtkContainer * container , GtkWidget * widget )
(define-function void gtk_container_remove (void* void*))
void gtk_container_resize_children ( GtkContainer * container )
(define-function void gtk_container_resize_children (void*))
void gtk_container_set_border_width ( GtkContainer * container , )
(define-function void gtk_container_set_border_width (void* unsigned-int))
void gtk_container_set_focus_chain ( GtkContainer * container , GList * focusable_widgets )
(define-function void gtk_container_set_focus_chain (void* void*))
void gtk_container_set_focus_child ( GtkContainer * container , GtkWidget * child )
(define-function void gtk_container_set_focus_child (void* void*))
void gtk_container_set_focus_hadjustment ( GtkContainer * container , GtkAdjustment * adjustment )
(define-function void gtk_container_set_focus_hadjustment (void* void*))
void gtk_container_set_focus_vadjustment ( GtkContainer * container , GtkAdjustment * adjustment )
(define-function void gtk_container_set_focus_vadjustment (void* void*))
void gtk_container_set_reallocate_redraws ( GtkContainer * container , )
(define-function void gtk_container_set_reallocate_redraws (void* int))
void gtk_container_set_resize_mode ( GtkContainer * container , GtkResizeMode resize_mode )
(define-function void gtk_container_set_resize_mode (void* int))
void gtk_container_unset_focus_chain ( GtkContainer * container )
(define-function void gtk_container_unset_focus_chain (void*))
) ;[end]
| null | https://raw.githubusercontent.com/imrehg/ypsilon/e57a06ef5c66c1a88905b2be2fa791fa29848514/sitelib/ypsilon/gtk/container.scm | scheme | [end] | #!nobacktrace
Ypsilon Scheme System
Copyright ( c ) 2004 - 2009 Y.FUJITA / LittleWing Company Limited .
See license.txt for terms and conditions of use .
(library (ypsilon gtk container)
(export gtk_container_add
gtk_container_add_with_properties
gtk_container_check_resize
gtk_container_child_get
gtk_container_child_get_property
gtk_container_child_get_valist
gtk_container_child_set
gtk_container_child_set_property
gtk_container_child_set_valist
gtk_container_child_type
gtk_container_class_find_child_property
gtk_container_class_install_child_property
gtk_container_class_list_child_properties
gtk_container_forall
gtk_container_foreach
gtk_container_get_border_width
gtk_container_get_children
gtk_container_get_focus_chain
gtk_container_get_focus_child
gtk_container_get_focus_hadjustment
gtk_container_get_focus_vadjustment
gtk_container_get_resize_mode
gtk_container_get_type
gtk_container_propagate_expose
gtk_container_remove
gtk_container_resize_children
gtk_container_set_border_width
gtk_container_set_focus_chain
gtk_container_set_focus_child
gtk_container_set_focus_hadjustment
gtk_container_set_focus_vadjustment
gtk_container_set_reallocate_redraws
gtk_container_set_resize_mode
gtk_container_unset_focus_chain)
(import (rnrs) (ypsilon ffi))
(define lib-name
(cond (on-linux "libgtk-x11-2.0.so.0")
(on-sunos "libgtk-x11-2.0.so.0")
(on-freebsd "libgtk-x11-2.0.so.0")
(on-openbsd "libgtk-x11-2.0.so.0")
(on-darwin "Gtk.framework/Gtk")
(on-windows "libgtk-win32-2.0-0.dll")
(else
(assertion-violation #f "can not locate GTK library, unknown operating system"))))
(define lib (load-shared-object lib-name))
(define-syntax define-function
(syntax-rules ()
((_ ret name args)
(define name (c-function lib lib-name ret name args)))))
(define-syntax define-function/va_list
(syntax-rules ()
((_ ret name args)
(define name (lambda x (assertion-violation 'name "va_list argument not supported"))))))
void gtk_container_add ( GtkContainer * container , GtkWidget * widget )
(define-function void gtk_container_add (void* void*))
void ( GtkContainer * container , GtkWidget * widget , const gchar * first_prop_name , ... )
(define-function void gtk_container_add_with_properties (void* void* char* ...))
void gtk_container_check_resize ( GtkContainer * container )
(define-function void gtk_container_check_resize (void*))
void gtk_container_child_get ( GtkContainer * container , GtkWidget * child , const gchar * first_prop_name , ... )
(define-function void gtk_container_child_get (void* void* char* ...))
void gtk_container_child_get_property ( GtkContainer * container , GtkWidget * child , const gchar * property_name , GValue * value )
(define-function void gtk_container_child_get_property (void* void* char* void*))
void gtk_container_child_get_valist ( GtkContainer * container , GtkWidget * child , const gchar * first_property_name , va_list )
(define-function/va_list void gtk_container_child_get_valist (void* void* char* va_list))
void gtk_container_child_set ( GtkContainer * container , GtkWidget * child , const gchar * first_prop_name , ... )
(define-function void gtk_container_child_set (void* void* char* ...))
void gtk_container_child_set_property ( GtkContainer * container , GtkWidget * child , const gchar * property_name , const GValue * value )
(define-function void gtk_container_child_set_property (void* void* char* void*))
void gtk_container_child_set_valist ( GtkContainer * container , GtkWidget * child , const gchar * first_property_name , va_list )
(define-function/va_list void gtk_container_child_set_valist (void* void* char* va_list))
GType gtk_container_child_type ( GtkContainer * container )
(define-function unsigned-long gtk_container_child_type (void*))
GParamSpec * gtk_container_class_find_child_property ( GObjectClass * cclass , const gchar * property_name )
(define-function void* gtk_container_class_find_child_property (void* char*))
void gtk_container_class_install_child_property ( GtkContainerClass * cclass , guint property_id , GParamSpec * )
(define-function void gtk_container_class_install_child_property (void* unsigned-int void*))
GParamSpec * * gtk_container_class_list_child_properties ( GObjectClass * cclass , guint * n_properties )
(define-function void* gtk_container_class_list_child_properties (void* void*))
void gtk_container_forall ( GtkContainer * container , GtkCallback callback , )
(define-function void gtk_container_forall (void* (c-callback void (void* void*)) void*))
void ( GtkContainer * container , GtkCallback callback , )
(define-function void gtk_container_foreach (void* (c-callback void (void* void*)) void*))
guint gtk_container_get_border_width ( GtkContainer * container )
(define-function unsigned-int gtk_container_get_border_width (void*))
GList * ( GtkContainer * container )
(define-function void* gtk_container_get_children (void*))
gboolean gtk_container_get_focus_chain ( GtkContainer * container , GList * * focusable_widgets )
(define-function int gtk_container_get_focus_chain (void* void*))
GtkWidget * gtk_container_get_focus_child ( GtkContainer * container )
(define-function void* gtk_container_get_focus_child (void*))
GtkAdjustment * gtk_container_get_focus_hadjustment ( GtkContainer * container )
(define-function void* gtk_container_get_focus_hadjustment (void*))
GtkAdjustment * gtk_container_get_focus_vadjustment ( GtkContainer * container )
(define-function void* gtk_container_get_focus_vadjustment (void*))
GtkResizeMode gtk_container_get_resize_mode ( GtkContainer * container )
(define-function int gtk_container_get_resize_mode (void*))
GType gtk_container_get_type ( void )
(define-function unsigned-long gtk_container_get_type ())
void gtk_container_propagate_expose ( GtkContainer * container , GtkWidget * child , * event )
(define-function void gtk_container_propagate_expose (void* void* void*))
void gtk_container_remove ( GtkContainer * container , GtkWidget * widget )
(define-function void gtk_container_remove (void* void*))
void gtk_container_resize_children ( GtkContainer * container )
(define-function void gtk_container_resize_children (void*))
void gtk_container_set_border_width ( GtkContainer * container , )
(define-function void gtk_container_set_border_width (void* unsigned-int))
void gtk_container_set_focus_chain ( GtkContainer * container , GList * focusable_widgets )
(define-function void gtk_container_set_focus_chain (void* void*))
void gtk_container_set_focus_child ( GtkContainer * container , GtkWidget * child )
(define-function void gtk_container_set_focus_child (void* void*))
void gtk_container_set_focus_hadjustment ( GtkContainer * container , GtkAdjustment * adjustment )
(define-function void gtk_container_set_focus_hadjustment (void* void*))
void gtk_container_set_focus_vadjustment ( GtkContainer * container , GtkAdjustment * adjustment )
(define-function void gtk_container_set_focus_vadjustment (void* void*))
void gtk_container_set_reallocate_redraws ( GtkContainer * container , )
(define-function void gtk_container_set_reallocate_redraws (void* int))
void gtk_container_set_resize_mode ( GtkContainer * container , GtkResizeMode resize_mode )
(define-function void gtk_container_set_resize_mode (void* int))
void gtk_container_unset_focus_chain ( GtkContainer * container )
(define-function void gtk_container_unset_focus_chain (void*))
|
78f9bdec27a98d65a0eecea96c9beb11bb3498ed188e78ad0c48d8b60360c247 | tezos/tezos-mirror | binaries.ml | (*****************************************************************************)
(* *)
(* Open Source License *)
Copyright ( c ) 2021 Nomadic Labs < >
(* *)
(* Permission is hereby granted, free of charge, to any person obtaining a *)
(* copy of this software and associated documentation files (the "Software"),*)
to deal in the Software without restriction , including without limitation
(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)
and/or sell copies of the Software , and to permit persons to whom the
(* Software is furnished to do so, subject to the following conditions: *)
(* *)
(* The above copyright notice and this permission notice shall be included *)
(* in all copies or substantial portions of the Software. *)
(* *)
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)
(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)
(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING
(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)
(* DEALINGS IN THE SOFTWARE. *)
(* *)
(*****************************************************************************)
Testing
-------
Component : Released and Experimental binaries
Invocation : dune exec / tests / main.exe -- --file binaries.ml
Subject : Perform global coherence tests across released and experimental binaries .
-------
Component: Released and Experimental binaries
Invocation: dune exec tezt/tests/main.exe -- --file binaries.ml
Subject: Perform global coherence tests across released and experimental binaries.
*)
TODO : tezos / tezos#4769
We should be able to get the Version flag string from the Node
module , e.g. by exporting make_argument .
We should be able to get the Version flag string from the Node
module, e.g. by exporting make_argument. *)
let version_flag = "--version"
TODO : tezos / tezos#4804
Should we implement this via Component.run commands when possible ?
Should we implement this via Component.run commands when possible?
*)
let spawn_command path =
Process.run_and_read_stdout ("./" ^ path) [version_flag]
let test_versions path =
let node = Node.create [] in
(* We remove octez-node as it will be checked separately. It is the
binary whose version we assume to be canonical. *)
let* node_version = Node.get_version node in
let commands =
Base.read_file path |> String.split_on_char '\n'
|> List.filter @@ fun str ->
(not (String.equal str String.empty))
&& not (String.equal str "octez-node")
in
let loop cmd =
Log.info
"Check that %s supports %s as version flag, and returns version %s."
cmd
version_flag
node_version ;
let* result = spawn_command cmd in
let error_msg = "%s: expected version %L, got version %R" in
Check.((node_version = String.trim result) ~__LOC__ string ~error_msg) ;
unit
in
Lwt_list.iter_s loop commands
Test that all released binaries support the --version flag , and
that they report the same version value as the node .
that they report the same version value as the Octez node. *)
let test_released_versions () =
Test.register
~__FILE__
~title:"Released binaries: report consistent version"
~tags:["binaries"; "released"; "node"; "baker"; "version"]
@@ fun () -> test_versions Constant.released_executables
Test that all experimental binaries support the --version flag , and
that they report the same version value as the node .
that they report the same version value as the Octez node. *)
let test_experimental_versions () =
Test.register
~__FILE__
~title:"Experimental binaries: report consistent version"
~tags:["binaries"; "experimental"; "version"]
@@ fun () -> test_versions Constant.experimental_executables
let register_protocol_independent () =
test_released_versions () ;
test_experimental_versions ()
| null | https://raw.githubusercontent.com/tezos/tezos-mirror/774792023ac622e1c3a298a040060621c0dd2f50/tezt/tests/binaries.ml | ocaml | ***************************************************************************
Open Source License
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
the rights to use, copy, modify, merge, publish, distribute, sublicense,
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
***************************************************************************
We remove octez-node as it will be checked separately. It is the
binary whose version we assume to be canonical. | Copyright ( c ) 2021 Nomadic Labs < >
to deal in the Software without restriction , including without limitation
and/or sell copies of the Software , and to permit persons to whom the
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING
Testing
-------
Component : Released and Experimental binaries
Invocation : dune exec / tests / main.exe -- --file binaries.ml
Subject : Perform global coherence tests across released and experimental binaries .
-------
Component: Released and Experimental binaries
Invocation: dune exec tezt/tests/main.exe -- --file binaries.ml
Subject: Perform global coherence tests across released and experimental binaries.
*)
TODO : tezos / tezos#4769
We should be able to get the Version flag string from the Node
module , e.g. by exporting make_argument .
We should be able to get the Version flag string from the Node
module, e.g. by exporting make_argument. *)
let version_flag = "--version"
TODO : tezos / tezos#4804
Should we implement this via Component.run commands when possible ?
Should we implement this via Component.run commands when possible?
*)
let spawn_command path =
Process.run_and_read_stdout ("./" ^ path) [version_flag]
let test_versions path =
let node = Node.create [] in
let* node_version = Node.get_version node in
let commands =
Base.read_file path |> String.split_on_char '\n'
|> List.filter @@ fun str ->
(not (String.equal str String.empty))
&& not (String.equal str "octez-node")
in
let loop cmd =
Log.info
"Check that %s supports %s as version flag, and returns version %s."
cmd
version_flag
node_version ;
let* result = spawn_command cmd in
let error_msg = "%s: expected version %L, got version %R" in
Check.((node_version = String.trim result) ~__LOC__ string ~error_msg) ;
unit
in
Lwt_list.iter_s loop commands
Test that all released binaries support the --version flag , and
that they report the same version value as the node .
that they report the same version value as the Octez node. *)
let test_released_versions () =
Test.register
~__FILE__
~title:"Released binaries: report consistent version"
~tags:["binaries"; "released"; "node"; "baker"; "version"]
@@ fun () -> test_versions Constant.released_executables
Test that all experimental binaries support the --version flag , and
that they report the same version value as the node .
that they report the same version value as the Octez node. *)
let test_experimental_versions () =
Test.register
~__FILE__
~title:"Experimental binaries: report consistent version"
~tags:["binaries"; "experimental"; "version"]
@@ fun () -> test_versions Constant.experimental_executables
let register_protocol_independent () =
test_released_versions () ;
test_experimental_versions ()
|
d767358ded8a1e2fa87003183204014339458ce0b29fbe50922f9e540f344663 | tmattio/gettext | utils.ml | (**************************************************************************)
(* ocaml-gettext: a library to translate messages *)
(* *)
Copyright ( C ) 2003 - 2008 < >
(* *)
(* This library is free software; you can redistribute it and/or *)
(* modify it under the terms of the GNU Lesser General Public *)
License as published by the Free Software Foundation ; either
version 2.1 of the License , or ( at your option ) any later version ;
(* with the OCaml static compilation exception. *)
(* *)
(* This library is distributed in the hope that it will be useful, *)
(* but WITHOUT ANY WARRANTY; without even the implied warranty of *)
(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 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
(**************************************************************************)
* @author
open Types
open Exn
type translation = Types.translation
type filepos = Types.filepos
type special = Types.special
type commented_translation = Types.commented_translation
type translations = Types.translations
type t = content
let empty = { no_domain = String_map.empty; domain = String_map.empty }
See GettextPo for details concerning merge of the translation
let add_translation_aux map commented_translation =
let translation = commented_translation.comment_translation in
let is_lst_empty lst =
List.for_all (fun lst -> String.concat "" lst = "") lst
in
let is_lst_same lst1 lst2 =
try not (List.exists2 (fun a b -> a <> b) lst1 lst2)
with Invalid_argument _ -> false
in
let string_of_list lst =
let lst_escaped =
List.map (fun s -> Printf.sprintf "%S" (String.concat "" s)) lst
in
Printf.sprintf "[ %a ]" (fun () lst -> String.concat ";" lst) lst_escaped
in
let str_id =
match translation with
| Singular (str_lst, _) | Plural (str_lst, _, _) -> str_lst
in
let new_commented_translation =
try
let previous_commented_translation =
String_map.find (String.concat "" str_id) map
in
let previous_location_lst =
previous_commented_translation.comment_filepos
in
let previous_translation =
previous_commented_translation.comment_translation
in
let location_lst = commented_translation.comment_filepos in
let merged_translation =
match (previous_translation, translation) with
| Singular (_, str1), Singular (_, str2) when is_lst_same str1 str2 ->
Singular (str_id, str1)
| Singular (_, [ "" ]), Singular (_, str2) -> Singular (str_id, str2)
| Singular (_, str1), Singular (_, [ "" ]) -> Singular (str_id, str1)
| Singular (_, str1), Singular (_, str2) ->
raise
(Inconsistent_merge (String.concat "" str1, String.concat "" str2))
| Plural (_, str1, lst1), Plural (_, str2, lst2)
when is_lst_same str1 str2 && is_lst_empty lst1 ->
Plural (str_id, str2, lst2)
| Plural (_, str1, lst1), Plural (_, str2, lst2)
when is_lst_same str1 str2 && is_lst_empty lst2 ->
Plural (str_id, str1, lst1)
| Plural (_, str1, lst1), Plural (_, str2, lst2)
when is_lst_same str1 str2 && is_lst_same lst1 lst2 ->
Plural (str_id, str1, lst1)
| Plural (_, str1, lst1), Plural (_, str2, lst2)
when is_lst_same str1 str2 ->
raise
(Inconsistent_merge (string_of_list lst1, string_of_list lst2))
| Plural (_, str1, _), Plural (_, str2, _) ->
raise
(Inconsistent_merge (String.concat "" str1, String.concat "" str2))
| Singular (_, str), Plural (_, str_plural, lst)
| Plural (_, str_plural, lst), Singular (_, str) -> (
match lst with
| x :: tl when String.concat "" x = "" ->
Plural (str_id, str_plural, str :: tl)
| [] -> Plural (str_id, str_plural, [ str ])
| _ ->
raise
(Inconsistent_merge (String.concat "" str, string_of_list lst))
)
in
(* TODO: merge comment_special and use fuzzy when merging *)
{
comment_special =
previous_commented_translation.comment_special
@ commented_translation.comment_special;
comment_filepos = location_lst @ previous_location_lst;
comment_translation = merged_translation;
}
with Not_found -> commented_translation
in
String_map.add (String.concat "" str_id) new_commented_translation map
let add_translation_no_domain po translation =
{ po with no_domain = add_translation_aux po.no_domain translation }
let add_translation_domain domain po translation =
{
po with
domain =
(let map_domain =
try String_map.find domain po.domain
with Not_found -> String_map.empty
in
let map_domain = add_translation_aux map_domain translation in
String_map.add domain map_domain po.domain);
}
| null | https://raw.githubusercontent.com/tmattio/gettext/edafb76a1e9c7c760634eef93b2c53aac80a2b82/lib/po/utils.ml | ocaml | ************************************************************************
ocaml-gettext: a library to translate messages
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
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.
************************************************************************
TODO: merge comment_special and use fuzzy when merging | Copyright ( C ) 2003 - 2008 < >
License as published by the Free Software Foundation ; either
version 2.1 of the License , or ( at your option ) any later version ;
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
* @author
open Types
open Exn
type translation = Types.translation
type filepos = Types.filepos
type special = Types.special
type commented_translation = Types.commented_translation
type translations = Types.translations
type t = content
let empty = { no_domain = String_map.empty; domain = String_map.empty }
See GettextPo for details concerning merge of the translation
let add_translation_aux map commented_translation =
let translation = commented_translation.comment_translation in
let is_lst_empty lst =
List.for_all (fun lst -> String.concat "" lst = "") lst
in
let is_lst_same lst1 lst2 =
try not (List.exists2 (fun a b -> a <> b) lst1 lst2)
with Invalid_argument _ -> false
in
let string_of_list lst =
let lst_escaped =
List.map (fun s -> Printf.sprintf "%S" (String.concat "" s)) lst
in
Printf.sprintf "[ %a ]" (fun () lst -> String.concat ";" lst) lst_escaped
in
let str_id =
match translation with
| Singular (str_lst, _) | Plural (str_lst, _, _) -> str_lst
in
let new_commented_translation =
try
let previous_commented_translation =
String_map.find (String.concat "" str_id) map
in
let previous_location_lst =
previous_commented_translation.comment_filepos
in
let previous_translation =
previous_commented_translation.comment_translation
in
let location_lst = commented_translation.comment_filepos in
let merged_translation =
match (previous_translation, translation) with
| Singular (_, str1), Singular (_, str2) when is_lst_same str1 str2 ->
Singular (str_id, str1)
| Singular (_, [ "" ]), Singular (_, str2) -> Singular (str_id, str2)
| Singular (_, str1), Singular (_, [ "" ]) -> Singular (str_id, str1)
| Singular (_, str1), Singular (_, str2) ->
raise
(Inconsistent_merge (String.concat "" str1, String.concat "" str2))
| Plural (_, str1, lst1), Plural (_, str2, lst2)
when is_lst_same str1 str2 && is_lst_empty lst1 ->
Plural (str_id, str2, lst2)
| Plural (_, str1, lst1), Plural (_, str2, lst2)
when is_lst_same str1 str2 && is_lst_empty lst2 ->
Plural (str_id, str1, lst1)
| Plural (_, str1, lst1), Plural (_, str2, lst2)
when is_lst_same str1 str2 && is_lst_same lst1 lst2 ->
Plural (str_id, str1, lst1)
| Plural (_, str1, lst1), Plural (_, str2, lst2)
when is_lst_same str1 str2 ->
raise
(Inconsistent_merge (string_of_list lst1, string_of_list lst2))
| Plural (_, str1, _), Plural (_, str2, _) ->
raise
(Inconsistent_merge (String.concat "" str1, String.concat "" str2))
| Singular (_, str), Plural (_, str_plural, lst)
| Plural (_, str_plural, lst), Singular (_, str) -> (
match lst with
| x :: tl when String.concat "" x = "" ->
Plural (str_id, str_plural, str :: tl)
| [] -> Plural (str_id, str_plural, [ str ])
| _ ->
raise
(Inconsistent_merge (String.concat "" str, string_of_list lst))
)
in
{
comment_special =
previous_commented_translation.comment_special
@ commented_translation.comment_special;
comment_filepos = location_lst @ previous_location_lst;
comment_translation = merged_translation;
}
with Not_found -> commented_translation
in
String_map.add (String.concat "" str_id) new_commented_translation map
let add_translation_no_domain po translation =
{ po with no_domain = add_translation_aux po.no_domain translation }
let add_translation_domain domain po translation =
{
po with
domain =
(let map_domain =
try String_map.find domain po.domain
with Not_found -> String_map.empty
in
let map_domain = add_translation_aux map_domain translation in
String_map.add domain map_domain po.domain);
}
|
aae922f916659ef868cf94f1d28cb7c43bef281d821522e6c6b60af0da504215 | chunsj/TH | backprop.lisp | (declaim (optimize (speed 3) (debug 1) (safety 0)))
(in-package :th)
(defgeneric $parameter (object) (:documentation "Returns a wrapped, differentiable object."))
(defgeneric $parameters (object) (:documentation "Returns parameters."))
(defgeneric $parameterp (object) (:documentation "Returns whether object is a parameter or not."))
(defgeneric $gradient (node) (:documentation "Returns gradient value."))
(defgeneric $attr (node key &optional default) (:documentation "An attribute for key in node."))
(defgeneric $cg! (node) (:documentation "Clear gradient value."))
(defgeneric $reset! (node) (:documentation "Clear gradient value and attributes."))
(defclass node ()
((nm :initform :parameter :accessor $name)
(data :initform nil :accessor $data)
(fns :initform nil :accessor $fns)
(gradientv :initform nil :accessor $gradientv)
(gradientp :initform nil :accessor $gradientp)
(attrs :initform #{} :accessor $attrs))
(:documentation "Represents a computational node for differentiable parameter."))
(defmethod $data ((n T)) n)
(defmethod print-object ((node node) stream)
(format stream "[~A] ~A" ($name node) ($data node)))
(defun $pfn! (node f) (push f ($fns node)))
(defun node (data &key (name :parameter) link)
(let ((n (make-instance 'node)))
(setf ($data n) data)
(setf ($name n) name)
(cond (($tensorp data) (setf ($gradientv n) ($zero data)))
((numberp data) (setf ($gradientv n) 0D0)))
(when link (funcall link n))
n))
(defun $gs! (node &optional gradientv)
"Set gradient seed value."
(when ($fns node) (setf ($fns node) nil))
(setf ($gradientp node) T)
(if gradientv
(setf ($gradientv node) gradientv)
(cond (($tensorp ($gradientv node)) ($one! ($gradientv node)))
((numberp ($gradientv node)) (setf ($gradientv node) 1D0)))))
(defun accumulate-effects (node)
(loop :for f :in ($fns node)
:for fv = (funcall f)
:do (cond (($tensorp ($gradientv node)) ($add! ($gradientv node) fv))
((numberp ($gradientv node)) (incf ($gradientv node) ($scalar fv)))
(T (error "unknown gradient value ~A" ($gradientv node))))))
(defun compute-gradient (node)
(if ($fns node)
(progn
(accumulate-effects node)
(setf ($fns node) nil)
(setf ($gradientp node) T))
($gs! node))
($gradientv node))
(defmethod $gradient ((node node))
(if ($gradientp node)
($gradientv node)
(compute-gradient node)))
(defmethod $cg! ((node node))
(setf ($fns node) nil
($gradientp node) nil)
(cond (($tensorp ($gradientv node)) ($zero! ($gradientv node)))
((numberp ($gradientv node)) (setf ($gradientv node) 0D0))))
(defmethod $reset! ((node node))
($cg! node)
(setf ($attrs node) #{}))
(defmethod $parameter ((node node)) (node ($data node)))
(defmethod $parameter ((data list)) (node (tensor data)))
(defmethod $parameter ((data t)) (node data))
(defmethod $parameterp ((node node)) T)
(defmethod $parameterp ((object T)) nil)
(defmethod $tensorp ((node node)) ($tensorp ($data node)))
(defmethod $zero ((x node)) (node ($zero ($data x))))
(defmethod $one ((x node)) (node ($one ($data x))))
(defmethod $fill ((x node) value) (node ($fill ($data x) value)))
(defmethod $ndim ((x node)) ($ndim ($data x)))
(defmethod $count ((x node)) ($count ($data x)))
(defmethod $zero! ((x node))
($zero! ($data x))
x)
(defmethod $one! ((x node))
($one! ($data x))
x)
(defmethod $fill! ((x node) value)
($fill! ($data x) value)
x)
(defmethod $empty ((node node)) ($parameter ($empty ($data node))))
(defmethod $clear ((node node)) ($parameter ($clear ($data node))))
(defmethod $storage ((node node)) ($storage ($data node)))
(defmethod $offset ((node node)) ($offset ($data node)))
(defmethod $size ((node node) &optional dimension) ($size ($data node) dimension))
(defmethod $stride ((node node) &optional dimension) ($stride ($data node) dimension))
(defmethod $attr ((node node) key &optional default)
(let ((v ($ ($attrs node) key nil)))
(when (and (null v) default)
(setf ($ ($attrs node) key) default)
(setf v default))
v))
(defmethod (setf $attr) (value (node node) key)
(setf ($ ($attrs node) key) value)
value)
(defclass parameters () ((parameters :initform nil :accessor $parameters)))
(defun parameters () (make-instance 'parameters))
(defgeneric $push (parameters parameter) (:documentation "Group the parameter."))
(defmethod $push ((parameters parameters) (node node))
(push node ($parameters parameters))
node)
(defmethod $push ((parameters parameters) (data t))
(let ((v ($parameter data)))
(push v ($parameters parameters))
v))
(defmethod $cg! ((parameters list))
(loop :for p :in parameters :do ($cg! p)))
(defmethod $reset! ((parameters list))
(loop :for p :in parameters :do ($reset! p)))
(defmethod $cg! ((parameters parameters))
(loop :for p :in ($parameters parameters) :do ($cg! p)))
(defmethod $reset! ((parameters parameters))
(loop :for p :in ($parameters parameters) :do ($reset! p)))
(defmacro with-node ((self) &body body)
`(lambda ()
(let ((dv ($data ,self))
(gv ($gradient ,self)))
(declare (ignorable dv gv))
,@body)))
(defmacro to (target &body body) `($pfn! ,target (with-node (self) ,@body)))
(defmacro link (&body body) `(lambda (self) ,@body))
| null | https://raw.githubusercontent.com/chunsj/TH/890f05ab81148d9fe558be3979c30c303b448480/bp/backprop.lisp | lisp | (declaim (optimize (speed 3) (debug 1) (safety 0)))
(in-package :th)
(defgeneric $parameter (object) (:documentation "Returns a wrapped, differentiable object."))
(defgeneric $parameters (object) (:documentation "Returns parameters."))
(defgeneric $parameterp (object) (:documentation "Returns whether object is a parameter or not."))
(defgeneric $gradient (node) (:documentation "Returns gradient value."))
(defgeneric $attr (node key &optional default) (:documentation "An attribute for key in node."))
(defgeneric $cg! (node) (:documentation "Clear gradient value."))
(defgeneric $reset! (node) (:documentation "Clear gradient value and attributes."))
(defclass node ()
((nm :initform :parameter :accessor $name)
(data :initform nil :accessor $data)
(fns :initform nil :accessor $fns)
(gradientv :initform nil :accessor $gradientv)
(gradientp :initform nil :accessor $gradientp)
(attrs :initform #{} :accessor $attrs))
(:documentation "Represents a computational node for differentiable parameter."))
(defmethod $data ((n T)) n)
(defmethod print-object ((node node) stream)
(format stream "[~A] ~A" ($name node) ($data node)))
(defun $pfn! (node f) (push f ($fns node)))
(defun node (data &key (name :parameter) link)
(let ((n (make-instance 'node)))
(setf ($data n) data)
(setf ($name n) name)
(cond (($tensorp data) (setf ($gradientv n) ($zero data)))
((numberp data) (setf ($gradientv n) 0D0)))
(when link (funcall link n))
n))
(defun $gs! (node &optional gradientv)
"Set gradient seed value."
(when ($fns node) (setf ($fns node) nil))
(setf ($gradientp node) T)
(if gradientv
(setf ($gradientv node) gradientv)
(cond (($tensorp ($gradientv node)) ($one! ($gradientv node)))
((numberp ($gradientv node)) (setf ($gradientv node) 1D0)))))
(defun accumulate-effects (node)
(loop :for f :in ($fns node)
:for fv = (funcall f)
:do (cond (($tensorp ($gradientv node)) ($add! ($gradientv node) fv))
((numberp ($gradientv node)) (incf ($gradientv node) ($scalar fv)))
(T (error "unknown gradient value ~A" ($gradientv node))))))
(defun compute-gradient (node)
(if ($fns node)
(progn
(accumulate-effects node)
(setf ($fns node) nil)
(setf ($gradientp node) T))
($gs! node))
($gradientv node))
(defmethod $gradient ((node node))
(if ($gradientp node)
($gradientv node)
(compute-gradient node)))
(defmethod $cg! ((node node))
(setf ($fns node) nil
($gradientp node) nil)
(cond (($tensorp ($gradientv node)) ($zero! ($gradientv node)))
((numberp ($gradientv node)) (setf ($gradientv node) 0D0))))
(defmethod $reset! ((node node))
($cg! node)
(setf ($attrs node) #{}))
(defmethod $parameter ((node node)) (node ($data node)))
(defmethod $parameter ((data list)) (node (tensor data)))
(defmethod $parameter ((data t)) (node data))
(defmethod $parameterp ((node node)) T)
(defmethod $parameterp ((object T)) nil)
(defmethod $tensorp ((node node)) ($tensorp ($data node)))
(defmethod $zero ((x node)) (node ($zero ($data x))))
(defmethod $one ((x node)) (node ($one ($data x))))
(defmethod $fill ((x node) value) (node ($fill ($data x) value)))
(defmethod $ndim ((x node)) ($ndim ($data x)))
(defmethod $count ((x node)) ($count ($data x)))
(defmethod $zero! ((x node))
($zero! ($data x))
x)
(defmethod $one! ((x node))
($one! ($data x))
x)
(defmethod $fill! ((x node) value)
($fill! ($data x) value)
x)
(defmethod $empty ((node node)) ($parameter ($empty ($data node))))
(defmethod $clear ((node node)) ($parameter ($clear ($data node))))
(defmethod $storage ((node node)) ($storage ($data node)))
(defmethod $offset ((node node)) ($offset ($data node)))
(defmethod $size ((node node) &optional dimension) ($size ($data node) dimension))
(defmethod $stride ((node node) &optional dimension) ($stride ($data node) dimension))
(defmethod $attr ((node node) key &optional default)
(let ((v ($ ($attrs node) key nil)))
(when (and (null v) default)
(setf ($ ($attrs node) key) default)
(setf v default))
v))
(defmethod (setf $attr) (value (node node) key)
(setf ($ ($attrs node) key) value)
value)
(defclass parameters () ((parameters :initform nil :accessor $parameters)))
(defun parameters () (make-instance 'parameters))
(defgeneric $push (parameters parameter) (:documentation "Group the parameter."))
(defmethod $push ((parameters parameters) (node node))
(push node ($parameters parameters))
node)
(defmethod $push ((parameters parameters) (data t))
(let ((v ($parameter data)))
(push v ($parameters parameters))
v))
(defmethod $cg! ((parameters list))
(loop :for p :in parameters :do ($cg! p)))
(defmethod $reset! ((parameters list))
(loop :for p :in parameters :do ($reset! p)))
(defmethod $cg! ((parameters parameters))
(loop :for p :in ($parameters parameters) :do ($cg! p)))
(defmethod $reset! ((parameters parameters))
(loop :for p :in ($parameters parameters) :do ($reset! p)))
(defmacro with-node ((self) &body body)
`(lambda ()
(let ((dv ($data ,self))
(gv ($gradient ,self)))
(declare (ignorable dv gv))
,@body)))
(defmacro to (target &body body) `($pfn! ,target (with-node (self) ,@body)))
(defmacro link (&body body) `(lambda (self) ,@body))
| |
575104abcf545e4508a1d9d8321258686dd385edac647fe5d18063b230029a89 | jrh13/hol-light | Custom_inference_rules.ml | let near_ring_axioms =
`(!x. 0 + x = x) /\
(!x. neg x + x = 0) /\
(!x y z. (x + y) + z = x + y + z) /\
(!x y z. (x * y) * z = x * y * z) /\
(!x y z. (x + y) * z = (x * z) + (y * z))`;;
* * * Works eventually but takes a very long time
[ ]
` ( ! x. 0 + x = x ) /\
( ! x. neg x + x = 0 ) /\
( ! x ( x + y ) + z = x + y + z ) /\
( ! x ( x * y ) * z = x * y * z ) /\
( ! x ( x + y ) * z = ( x * z ) + ( y * z ) )
= = > ! a. 0 * a = 0 ` ; ;
* * *
MESON[]
`(!x. 0 + x = x) /\
(!x. neg x + x = 0) /\
(!x y z. (x + y) + z = x + y + z) /\
(!x y z. (x * y) * z = x * y * z) /\
(!x y z. (x + y) * z = (x * z) + (y * z))
==> !a. 0 * a = 0`;;
****)
let is_realvar w x = is_var x && not(mem x w);;
let rec real_strip w tm =
if mem tm w then tm,[] else
let l,r = dest_comb tm in
let f,args = real_strip w l in f,args@[r];;
let weight lis (f,n) (g,m) =
let i = index f lis and j = index g lis in
i > j || i = j && n > m;;
let rec lexord ord l1 l2 =
match (l1,l2) with
(h1::t1,h2::t2) -> if ord h1 h2 then length t1 = length t2
else h1 = h2 && lexord ord t1 t2
| _ -> false;;
let rec lpo_gt w s t =
if is_realvar w t then not(s = t) && mem t (frees s)
else if is_realvar w s || is_abs s || is_abs t then false else
let f,fargs = real_strip w s and g,gargs = real_strip w t in
exists (fun si -> lpo_ge w si t) fargs ||
forall (lpo_gt w s) gargs &&
(f = g && lexord (lpo_gt w) fargs gargs ||
weight w (f,length fargs) (g,length gargs))
and lpo_ge w s t = (s = t) || lpo_gt w s t;;
let rec istriv w env x t =
if is_realvar w t then t = x || defined env t && istriv w env x (apply env t)
else if is_const t then false else
let f,args = strip_comb t in
exists (istriv w env x) args && failwith "cyclic";;
let rec unify w env tp =
match tp with
((Var(_,_) as x),t) | (t,(Var(_,_) as x)) when not(mem x w) ->
if defined env x then unify w env (apply env x,t)
else if istriv w env x t then env else (x|->t) env
| (Comb(f,x),Comb(g,y)) -> unify w (unify w env (x,y)) (f,g)
| (s,t) -> if s = t then env else failwith "unify: not unifiable";;
let fullunify w (s,t) =
let env = unify w undefined (s,t) in
let th = map (fun (x,t) -> (t,x)) (graph env) in
let rec subs t =
let t' = vsubst th t in
if t' = t then t else subs t' in
map (fun (t,x) -> (subs t,x)) th;;
let rec listcases fn rfn lis acc =
match lis with
[] -> acc
| h::t -> fn h (fun i h' -> rfn i (h'::map REFL t)) @
listcases fn (fun i t' -> rfn i (REFL h::t')) t acc;;
let LIST_MK_COMB f ths = rev_itlist (fun s t -> MK_COMB(t,s)) ths (REFL f);;
let rec overlaps w th tm rfn =
let l,r = dest_eq(concl th) in
if not (is_comb tm) then [] else
let f,args = strip_comb tm in
listcases (overlaps w th) (fun i a -> rfn i (LIST_MK_COMB f a)) args
(try [rfn (fullunify w (l,tm)) th] with Failure _ -> []);;
let crit1 w eq1 eq2 =
let l1,r1 = dest_eq(concl eq1)
and l2,r2 = dest_eq(concl eq2) in
overlaps w eq1 l2 (fun i th -> TRANS (SYM(INST i th)) (INST i eq2));;
let fixvariables s th =
let fvs = subtract (frees(concl th)) (freesl(hyp th)) in
let gvs = map2 (fun v n -> mk_var(s^string_of_int n,type_of v))
fvs (1--length fvs) in
INST (zip gvs fvs) th;;
let renamepair (th1,th2) = fixvariables "x" th1,fixvariables "y" th2;;
let critical_pairs w tha thb =
let th1,th2 = renamepair (tha,thb) in crit1 w th1 th2 @ crit1 w th2 th1;;
let normalize_and_orient w eqs th =
let th' = GEN_REWRITE_RULE TOP_DEPTH_CONV eqs th in
let s',t' = dest_eq(concl th') in
if lpo_ge w s' t' then th' else if lpo_ge w t' s' then SYM th'
else failwith "Can't orient equation";;
let status(eqs,crs) eqs0 =
if eqs = eqs0 && (length crs) mod 1000 <> 0 then () else
(print_string(string_of_int(length eqs)^" equations and "^
string_of_int(length crs)^" pending critical pairs");
print_newline());;
let left_reducible eqs eq =
can (CHANGED_CONV(GEN_REWRITE_CONV (LAND_CONV o ONCE_DEPTH_CONV) eqs))
(concl eq);;
let rec complete w (eqs,crits) =
match crits with
(eq::ocrits) ->
let trip =
try let eq' = normalize_and_orient w eqs eq in
let s',t' = dest_eq(concl eq') in
if s' = t' then (eqs,ocrits) else
let crits',eqs' = partition(left_reducible [eq']) eqs in
let eqs'' = eq'::eqs' in
eqs'',
ocrits @ crits' @ itlist ((@) o critical_pairs w eq') eqs'' []
with Failure _ ->
if exists (can (normalize_and_orient w eqs)) ocrits
then (eqs,ocrits@[eq])
else failwith "complete: no orientable equations" in
status trip eqs; complete w trip
| [] -> eqs;;
let complete_equations wts eqs =
let eqs' = map (normalize_and_orient wts []) eqs in
complete wts ([],eqs');;
complete_equations [`1`; `( * ):num->num->num`; `i:num->num`]
[SPEC_ALL(ASSUME `!a b. i(a) * a * b = b`)];;
complete_equations [`c:A`; `f:A->A`]
(map SPEC_ALL (CONJUNCTS (ASSUME
`((f(f(f(f(f c))))) = c:A) /\ (f(f(f c)) = c)`)));;
let eqs = map SPEC_ALL (CONJUNCTS (ASSUME
`(!x. 1 * x = x) /\ (!x. i(x) * x = 1) /\
(!x y z. (x * y) * z = x * y * z)`)) in
map concl (complete_equations [`1`; `( * ):num->num->num`; `i:num->num`] eqs);;
let COMPLETE_TAC w th =
let eqs = map SPEC_ALL (CONJUNCTS(SPEC_ALL th)) in
let eqs' = complete_equations w eqs in
MAP_EVERY (ASSUME_TAC o GEN_ALL) eqs';;
g `(!x. 1 * x = x) /\
(!x. i(x) * x = 1) /\
(!x y z. (x * y) * z = x * y * z)
==> !x y. i(y) * i(i(i(x * i(y)))) * x = 1`;;
e (DISCH_THEN(COMPLETE_TAC [`1`; `( * ):num->num->num`; `i:num->num`]));;
e(ASM_REWRITE_TAC[]);;
g `(!x. 0 + x = x) /\
(!x. neg x + x = 0) /\
(!x y z. (x + y) + z = x + y + z) /\
(!x y z. (x * y) * z = x * y * z) /\
(!x y z. (x + y) * z = (x * z) + (y * z))
==> (neg 0 * (x * y + z + neg(neg(w + z))) + neg(neg b + neg a) =
a + b)`;;
e (DISCH_THEN(COMPLETE_TAC
[`0`; `(+):num->num->num`; `neg:num->num`; `( * ):num->num->num`]));;
e(ASM_REWRITE_TAC[]);;
* * * Could have done this instead
e ( DISCH_THEN(COMPLETE_TAC
[ ` 0 ` ; ` ( + ): num->num->num ` ; ` ( * ): num->num->num ` ; ` neg : num->num ` ] ) ) ; ;
* * *
e (DISCH_THEN(COMPLETE_TAC
[`0`; `(+):num->num->num`; `( * ):num->num->num`; `neg:num->num`]));;
****)
| null | https://raw.githubusercontent.com/jrh13/hol-light/d125b0ae73e546a63ed458a7891f4e14ae0409e2/Tutorial/Custom_inference_rules.ml | ocaml | let near_ring_axioms =
`(!x. 0 + x = x) /\
(!x. neg x + x = 0) /\
(!x y z. (x + y) + z = x + y + z) /\
(!x y z. (x * y) * z = x * y * z) /\
(!x y z. (x + y) * z = (x * z) + (y * z))`;;
* * * Works eventually but takes a very long time
[ ]
` ( ! x. 0 + x = x ) /\
( ! x. neg x + x = 0 ) /\
( ! x ( x + y ) + z = x + y + z ) /\
( ! x ( x * y ) * z = x * y * z ) /\
( ! x ( x + y ) * z = ( x * z ) + ( y * z ) )
= = > ! a. 0 * a = 0 ` ; ;
* * *
MESON[]
`(!x. 0 + x = x) /\
(!x. neg x + x = 0) /\
(!x y z. (x + y) + z = x + y + z) /\
(!x y z. (x * y) * z = x * y * z) /\
(!x y z. (x + y) * z = (x * z) + (y * z))
==> !a. 0 * a = 0`;;
****)
let is_realvar w x = is_var x && not(mem x w);;
let rec real_strip w tm =
if mem tm w then tm,[] else
let l,r = dest_comb tm in
let f,args = real_strip w l in f,args@[r];;
let weight lis (f,n) (g,m) =
let i = index f lis and j = index g lis in
i > j || i = j && n > m;;
let rec lexord ord l1 l2 =
match (l1,l2) with
(h1::t1,h2::t2) -> if ord h1 h2 then length t1 = length t2
else h1 = h2 && lexord ord t1 t2
| _ -> false;;
let rec lpo_gt w s t =
if is_realvar w t then not(s = t) && mem t (frees s)
else if is_realvar w s || is_abs s || is_abs t then false else
let f,fargs = real_strip w s and g,gargs = real_strip w t in
exists (fun si -> lpo_ge w si t) fargs ||
forall (lpo_gt w s) gargs &&
(f = g && lexord (lpo_gt w) fargs gargs ||
weight w (f,length fargs) (g,length gargs))
and lpo_ge w s t = (s = t) || lpo_gt w s t;;
let rec istriv w env x t =
if is_realvar w t then t = x || defined env t && istriv w env x (apply env t)
else if is_const t then false else
let f,args = strip_comb t in
exists (istriv w env x) args && failwith "cyclic";;
let rec unify w env tp =
match tp with
((Var(_,_) as x),t) | (t,(Var(_,_) as x)) when not(mem x w) ->
if defined env x then unify w env (apply env x,t)
else if istriv w env x t then env else (x|->t) env
| (Comb(f,x),Comb(g,y)) -> unify w (unify w env (x,y)) (f,g)
| (s,t) -> if s = t then env else failwith "unify: not unifiable";;
let fullunify w (s,t) =
let env = unify w undefined (s,t) in
let th = map (fun (x,t) -> (t,x)) (graph env) in
let rec subs t =
let t' = vsubst th t in
if t' = t then t else subs t' in
map (fun (t,x) -> (subs t,x)) th;;
let rec listcases fn rfn lis acc =
match lis with
[] -> acc
| h::t -> fn h (fun i h' -> rfn i (h'::map REFL t)) @
listcases fn (fun i t' -> rfn i (REFL h::t')) t acc;;
let LIST_MK_COMB f ths = rev_itlist (fun s t -> MK_COMB(t,s)) ths (REFL f);;
let rec overlaps w th tm rfn =
let l,r = dest_eq(concl th) in
if not (is_comb tm) then [] else
let f,args = strip_comb tm in
listcases (overlaps w th) (fun i a -> rfn i (LIST_MK_COMB f a)) args
(try [rfn (fullunify w (l,tm)) th] with Failure _ -> []);;
let crit1 w eq1 eq2 =
let l1,r1 = dest_eq(concl eq1)
and l2,r2 = dest_eq(concl eq2) in
overlaps w eq1 l2 (fun i th -> TRANS (SYM(INST i th)) (INST i eq2));;
let fixvariables s th =
let fvs = subtract (frees(concl th)) (freesl(hyp th)) in
let gvs = map2 (fun v n -> mk_var(s^string_of_int n,type_of v))
fvs (1--length fvs) in
INST (zip gvs fvs) th;;
let renamepair (th1,th2) = fixvariables "x" th1,fixvariables "y" th2;;
let critical_pairs w tha thb =
let th1,th2 = renamepair (tha,thb) in crit1 w th1 th2 @ crit1 w th2 th1;;
let normalize_and_orient w eqs th =
let th' = GEN_REWRITE_RULE TOP_DEPTH_CONV eqs th in
let s',t' = dest_eq(concl th') in
if lpo_ge w s' t' then th' else if lpo_ge w t' s' then SYM th'
else failwith "Can't orient equation";;
let status(eqs,crs) eqs0 =
if eqs = eqs0 && (length crs) mod 1000 <> 0 then () else
(print_string(string_of_int(length eqs)^" equations and "^
string_of_int(length crs)^" pending critical pairs");
print_newline());;
let left_reducible eqs eq =
can (CHANGED_CONV(GEN_REWRITE_CONV (LAND_CONV o ONCE_DEPTH_CONV) eqs))
(concl eq);;
let rec complete w (eqs,crits) =
match crits with
(eq::ocrits) ->
let trip =
try let eq' = normalize_and_orient w eqs eq in
let s',t' = dest_eq(concl eq') in
if s' = t' then (eqs,ocrits) else
let crits',eqs' = partition(left_reducible [eq']) eqs in
let eqs'' = eq'::eqs' in
eqs'',
ocrits @ crits' @ itlist ((@) o critical_pairs w eq') eqs'' []
with Failure _ ->
if exists (can (normalize_and_orient w eqs)) ocrits
then (eqs,ocrits@[eq])
else failwith "complete: no orientable equations" in
status trip eqs; complete w trip
| [] -> eqs;;
let complete_equations wts eqs =
let eqs' = map (normalize_and_orient wts []) eqs in
complete wts ([],eqs');;
complete_equations [`1`; `( * ):num->num->num`; `i:num->num`]
[SPEC_ALL(ASSUME `!a b. i(a) * a * b = b`)];;
complete_equations [`c:A`; `f:A->A`]
(map SPEC_ALL (CONJUNCTS (ASSUME
`((f(f(f(f(f c))))) = c:A) /\ (f(f(f c)) = c)`)));;
let eqs = map SPEC_ALL (CONJUNCTS (ASSUME
`(!x. 1 * x = x) /\ (!x. i(x) * x = 1) /\
(!x y z. (x * y) * z = x * y * z)`)) in
map concl (complete_equations [`1`; `( * ):num->num->num`; `i:num->num`] eqs);;
let COMPLETE_TAC w th =
let eqs = map SPEC_ALL (CONJUNCTS(SPEC_ALL th)) in
let eqs' = complete_equations w eqs in
MAP_EVERY (ASSUME_TAC o GEN_ALL) eqs';;
g `(!x. 1 * x = x) /\
(!x. i(x) * x = 1) /\
(!x y z. (x * y) * z = x * y * z)
==> !x y. i(y) * i(i(i(x * i(y)))) * x = 1`;;
e (DISCH_THEN(COMPLETE_TAC [`1`; `( * ):num->num->num`; `i:num->num`]));;
e(ASM_REWRITE_TAC[]);;
g `(!x. 0 + x = x) /\
(!x. neg x + x = 0) /\
(!x y z. (x + y) + z = x + y + z) /\
(!x y z. (x * y) * z = x * y * z) /\
(!x y z. (x + y) * z = (x * z) + (y * z))
==> (neg 0 * (x * y + z + neg(neg(w + z))) + neg(neg b + neg a) =
a + b)`;;
e (DISCH_THEN(COMPLETE_TAC
[`0`; `(+):num->num->num`; `neg:num->num`; `( * ):num->num->num`]));;
e(ASM_REWRITE_TAC[]);;
* * * Could have done this instead
e ( DISCH_THEN(COMPLETE_TAC
[ ` 0 ` ; ` ( + ): num->num->num ` ; ` ( * ): num->num->num ` ; ` neg : num->num ` ] ) ) ; ;
* * *
e (DISCH_THEN(COMPLETE_TAC
[`0`; `(+):num->num->num`; `( * ):num->num->num`; `neg:num->num`]));;
****)
| |
2d6db66003bb97c7cec9d00a6940b78e54c70f1f0e9f3ab1eeb5ac8987fc7667 | well-typed-lightbulbs/ocaml-esp32 | reg_availability_set.ml | (**************************************************************************)
(* *)
(* OCaml *)
(* *)
, Jane Street Europe
(* *)
Copyright 2016 - -2017 Jane Street Group LLC
(* *)
(* All rights reserved. This file is distributed under the terms of *)
the GNU Lesser General Public License version 2.1 , with the
(* special exception on linking described in the file LICENSE. *)
(* *)
(**************************************************************************)
[@@@ocaml.warning "+a-4-9-30-40-41-42"]
module RD = Reg_with_debug_info
module V = Backend_var
type t =
| Ok of RD.Set.t
| Unreachable
let inter regs1 regs2 =
match regs1, regs2 with
| Unreachable, _ -> regs2
| _, Unreachable -> regs1
| Ok avail1, Ok avail2 ->
let result =
RD.Set.fold (fun reg1 result ->
match RD.Set.find_reg_exn avail2 (RD.reg reg1) with
| exception Not_found -> result
| reg2 ->
let debug_info1 = RD.debug_info reg1 in
let debug_info2 = RD.debug_info reg2 in
let debug_info =
match debug_info1, debug_info2 with
| None, None -> None
Example for this next case : the value of a mutable variable x
is copied into another variable y ; then there is a conditional
where on one branch x is assigned and on the other branch it
is not . This means that on the former branch we have
forgotten about y holding the value of x ; but we have not on
the latter . At the join point we must have forgotten the
information .
is copied into another variable y; then there is a conditional
where on one branch x is assigned and on the other branch it
is not. This means that on the former branch we have
forgotten about y holding the value of x; but we have not on
the latter. At the join point we must have forgotten the
information. *)
| None, Some _ | Some _, None -> None
| Some debug_info1, Some debug_info2 ->
if RD.Debug_info.compare debug_info1 debug_info2 = 0 then
Some debug_info1
else
None
in
let reg =
RD.create_with_debug_info ~reg:(RD.reg reg1)
~debug_info
in
RD.Set.add reg result)
avail1
RD.Set.empty
in
Ok result
let equal t1 t2 =
match t1, t2 with
| Unreachable, Unreachable -> true
| Unreachable, Ok _ | Ok _, Unreachable -> false
| Ok regs1, Ok regs2 -> RD.Set.equal regs1 regs2
let canonicalise availability =
match availability with
| Unreachable -> Unreachable
| Ok availability ->
let regs_by_ident = V.Tbl.create 42 in
RD.Set.iter (fun reg ->
match RD.debug_info reg with
| None -> ()
| Some debug_info ->
let name = RD.Debug_info.holds_value_of debug_info in
if not (V.persistent name) then begin
match V.Tbl.find regs_by_ident name with
| exception Not_found -> V.Tbl.add regs_by_ident name reg
| (reg' : RD.t) ->
(* We prefer registers that are assigned to the stack since
they probably give longer available ranges (less likely to
be clobbered). *)
match RD.location reg, RD.location reg' with
| Reg _, Stack _
| Reg _, Reg _
| Stack _, Stack _
| _, Unknown
| Unknown, _ -> ()
| Stack _, Reg _ ->
V.Tbl.remove regs_by_ident name;
V.Tbl.add regs_by_ident name reg
end)
availability;
let result =
V.Tbl.fold (fun _ident reg availability ->
RD.Set.add reg availability)
regs_by_ident
RD.Set.empty
in
Ok result
let print ~print_reg ppf = function
| Unreachable -> Format.fprintf ppf "<unreachable>"
| Ok availability ->
Format.fprintf ppf "{%a}"
(Format.pp_print_list ~pp_sep:(fun ppf () -> Format.fprintf ppf ",@ ")
(Reg_with_debug_info.print ~print_reg))
(RD.Set.elements availability)
| null | https://raw.githubusercontent.com/well-typed-lightbulbs/ocaml-esp32/c24fcbfbee0e3aa6bb71c9b467c60c6bac326cc7/asmcomp/debug/reg_availability_set.ml | ocaml | ************************************************************************
OCaml
All rights reserved. This file is distributed under the terms of
special exception on linking described in the file LICENSE.
************************************************************************
We prefer registers that are assigned to the stack since
they probably give longer available ranges (less likely to
be clobbered). | , Jane Street Europe
Copyright 2016 - -2017 Jane Street Group LLC
the GNU Lesser General Public License version 2.1 , with the
[@@@ocaml.warning "+a-4-9-30-40-41-42"]
module RD = Reg_with_debug_info
module V = Backend_var
type t =
| Ok of RD.Set.t
| Unreachable
let inter regs1 regs2 =
match regs1, regs2 with
| Unreachable, _ -> regs2
| _, Unreachable -> regs1
| Ok avail1, Ok avail2 ->
let result =
RD.Set.fold (fun reg1 result ->
match RD.Set.find_reg_exn avail2 (RD.reg reg1) with
| exception Not_found -> result
| reg2 ->
let debug_info1 = RD.debug_info reg1 in
let debug_info2 = RD.debug_info reg2 in
let debug_info =
match debug_info1, debug_info2 with
| None, None -> None
Example for this next case : the value of a mutable variable x
is copied into another variable y ; then there is a conditional
where on one branch x is assigned and on the other branch it
is not . This means that on the former branch we have
forgotten about y holding the value of x ; but we have not on
the latter . At the join point we must have forgotten the
information .
is copied into another variable y; then there is a conditional
where on one branch x is assigned and on the other branch it
is not. This means that on the former branch we have
forgotten about y holding the value of x; but we have not on
the latter. At the join point we must have forgotten the
information. *)
| None, Some _ | Some _, None -> None
| Some debug_info1, Some debug_info2 ->
if RD.Debug_info.compare debug_info1 debug_info2 = 0 then
Some debug_info1
else
None
in
let reg =
RD.create_with_debug_info ~reg:(RD.reg reg1)
~debug_info
in
RD.Set.add reg result)
avail1
RD.Set.empty
in
Ok result
let equal t1 t2 =
match t1, t2 with
| Unreachable, Unreachable -> true
| Unreachable, Ok _ | Ok _, Unreachable -> false
| Ok regs1, Ok regs2 -> RD.Set.equal regs1 regs2
let canonicalise availability =
match availability with
| Unreachable -> Unreachable
| Ok availability ->
let regs_by_ident = V.Tbl.create 42 in
RD.Set.iter (fun reg ->
match RD.debug_info reg with
| None -> ()
| Some debug_info ->
let name = RD.Debug_info.holds_value_of debug_info in
if not (V.persistent name) then begin
match V.Tbl.find regs_by_ident name with
| exception Not_found -> V.Tbl.add regs_by_ident name reg
| (reg' : RD.t) ->
match RD.location reg, RD.location reg' with
| Reg _, Stack _
| Reg _, Reg _
| Stack _, Stack _
| _, Unknown
| Unknown, _ -> ()
| Stack _, Reg _ ->
V.Tbl.remove regs_by_ident name;
V.Tbl.add regs_by_ident name reg
end)
availability;
let result =
V.Tbl.fold (fun _ident reg availability ->
RD.Set.add reg availability)
regs_by_ident
RD.Set.empty
in
Ok result
let print ~print_reg ppf = function
| Unreachable -> Format.fprintf ppf "<unreachable>"
| Ok availability ->
Format.fprintf ppf "{%a}"
(Format.pp_print_list ~pp_sep:(fun ppf () -> Format.fprintf ppf ",@ ")
(Reg_with_debug_info.print ~print_reg))
(RD.Set.elements availability)
|
69a3756d5963b022f896f97b686b4680cdd04273e687b531f13bdd6792d10875 | dhammikamare/Learn-OCaml | max_depth.ml | type 'a binarytree =
| Empty
| Node of 'a * 'a binarytree * 'a binarytree ;;
let max_depth tr =
let rec loop t md =
match t with
| Empty -> -1
| Node(value, Empty, Empty) -> md
| Node(value, left, right) ->
let lmax = loop left (md+1) in
let rmax = loop right (md+1) in
max lmax rmax in
(* if lmax >= rmax then lmax else rmax in *)
loop tr 0;;
(* test *)
let bt1 = Node(6,
Node(3,
Node(2, Empty, Empty),
Node(4, Empty, Empty)),
Node(8,
Node(7, Empty, Empty),
Node(9,
Empty,
Node(10, Empty, Empty))));;
let be = Empty;;
let b1 = Node(2, Empty, Empty);;
max_depth bt1;;
max_depth be;;
max_depth b1;;
| null | https://raw.githubusercontent.com/dhammikamare/Learn-OCaml/2d4e3da38ee86cd7477964ffb8756a8483260322/lab10%20Binary%20Tree/max_depth.ml | ocaml | if lmax >= rmax then lmax else rmax in
test | type 'a binarytree =
| Empty
| Node of 'a * 'a binarytree * 'a binarytree ;;
let max_depth tr =
let rec loop t md =
match t with
| Empty -> -1
| Node(value, Empty, Empty) -> md
| Node(value, left, right) ->
let lmax = loop left (md+1) in
let rmax = loop right (md+1) in
max lmax rmax in
loop tr 0;;
let bt1 = Node(6,
Node(3,
Node(2, Empty, Empty),
Node(4, Empty, Empty)),
Node(8,
Node(7, Empty, Empty),
Node(9,
Empty,
Node(10, Empty, Empty))));;
let be = Empty;;
let b1 = Node(2, Empty, Empty);;
max_depth bt1;;
max_depth be;;
max_depth b1;;
|
ba4e360d7adc51d6e9cb85d3a898719763e89d401a8a1aa029fe8cbf25a88955 | omcljs/om | core.cljs | (ns examples.mixins.core
(:require [om.core :as om :include-macros true]
[om.dom :as dom :include-macros true])
(:import [goog.ui IdGenerator]))
(enable-console-print!)
(def TestMixin
#js {:componentWillMount
(fn []
(println "TextMixin componentWillMount"))})
(def MyComponent
(let [obj (om/specify-state-methods! (clj->js om/pure-methods))]
(aset obj "mixins" #js [TestMixin])
(js/React.createClass obj)))
(om/root
(fn [app owner]
(om/component
(MyComponent. nil
(dom/div nil "Hello world!"))))
{}
{:target (.getElementById js/document "app")})
| null | https://raw.githubusercontent.com/omcljs/om/3a1fbe9c0e282646fc58550139b491ff9869f96d/examples/mixins/src/core.cljs | clojure | (ns examples.mixins.core
(:require [om.core :as om :include-macros true]
[om.dom :as dom :include-macros true])
(:import [goog.ui IdGenerator]))
(enable-console-print!)
(def TestMixin
#js {:componentWillMount
(fn []
(println "TextMixin componentWillMount"))})
(def MyComponent
(let [obj (om/specify-state-methods! (clj->js om/pure-methods))]
(aset obj "mixins" #js [TestMixin])
(js/React.createClass obj)))
(om/root
(fn [app owner]
(om/component
(MyComponent. nil
(dom/div nil "Hello world!"))))
{}
{:target (.getElementById js/document "app")})
| |
b22af9f67823a13f5bd47109aabec9c0b269f21cc9d57f0025131cdb3abcb8b0 | katcipis/sicp | numbers.rkt | #lang racket
(require "stream.rkt")
(define (ones)
(kstream 1 ones))
(define (naturals-from i)
(kstream i (lambda () (naturals-from (+ i 1)))))
(define (naturals) (naturals-from 0))
(provide ones naturals naturals-from) | null | https://raw.githubusercontent.com/katcipis/sicp/d365de58e106d54f83d0ca236ea5ea666253da89/stream/numbers.rkt | racket | #lang racket
(require "stream.rkt")
(define (ones)
(kstream 1 ones))
(define (naturals-from i)
(kstream i (lambda () (naturals-from (+ i 1)))))
(define (naturals) (naturals-from 0))
(provide ones naturals naturals-from) | |
fe17b7ab0e673b06877ee3b20ae90534c58d830e0c45ef0ea8746504a546e906 | liqd/thentos | Missing.hs | module LIO.Missing
where
import LIO.Core (MonadLIO, liftLIO, taint, guardWrite)
import LIO.Error (AnyLabelError)
import LIO.Label (Label)
import LIO.DCLabel (DCLabel, (%%))
import qualified LIO.Exception as LE
tryTaint :: (MonadLIO l m, Label l) => l -> m r -> (AnyLabelError -> m r) -> m r
tryTaint label onSuccess onFailure = do
result <- liftLIO $ LE.try (taint label)
case result of
Left e -> onFailure e
Right () -> onSuccess
tryGuardWrite :: (MonadLIO l m, Label l) => l -> m r -> (AnyLabelError -> m r) -> m r
tryGuardWrite label onSuccess onFailure = do
result <- liftLIO $ LE.try (guardWrite label)
case result of
Left e -> onFailure e
Right () -> onSuccess
-- | Test whether guard-write against a given label violates current clearance. In other words:
-- whether given label can flow to clearance.
guardWriteOk :: MonadLIO l m => l -> m Bool
guardWriteOk l = tryGuardWrite l (pure True) (\_ -> pure False)
dcBottom :: DCLabel
dcBottom = True %% False
dcTop :: DCLabel
dcTop = False %% True
| null | https://raw.githubusercontent.com/liqd/thentos/f7d53d8e9d11956d2cc83efb5f5149876109b098/thentos-core/src/LIO/Missing.hs | haskell | | Test whether guard-write against a given label violates current clearance. In other words:
whether given label can flow to clearance. | module LIO.Missing
where
import LIO.Core (MonadLIO, liftLIO, taint, guardWrite)
import LIO.Error (AnyLabelError)
import LIO.Label (Label)
import LIO.DCLabel (DCLabel, (%%))
import qualified LIO.Exception as LE
tryTaint :: (MonadLIO l m, Label l) => l -> m r -> (AnyLabelError -> m r) -> m r
tryTaint label onSuccess onFailure = do
result <- liftLIO $ LE.try (taint label)
case result of
Left e -> onFailure e
Right () -> onSuccess
tryGuardWrite :: (MonadLIO l m, Label l) => l -> m r -> (AnyLabelError -> m r) -> m r
tryGuardWrite label onSuccess onFailure = do
result <- liftLIO $ LE.try (guardWrite label)
case result of
Left e -> onFailure e
Right () -> onSuccess
guardWriteOk :: MonadLIO l m => l -> m Bool
guardWriteOk l = tryGuardWrite l (pure True) (\_ -> pure False)
dcBottom :: DCLabel
dcBottom = True %% False
dcTop :: DCLabel
dcTop = False %% True
|
97dd38fba2042cabc05122728ba55fca802d6cdade8d652053793119313a31f7 | artyom-poptsov/metabash | tee.scm | tee.scm -- Tee implementation for .
Copyright ( C ) 2020 < >
;;
;; This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation , either version 3 of the License , or
;; (at your option) any later version.
;;
;; The program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;;
You should have received a copy of the GNU General Public License
;; along with the program. If not, see </>.
;;; Commentary:
;; This file contains implementation of a tee that can connect an input port to
two output ports effectively copying the output to two ports simultaneously ,
;; akin to the Unix 'tee' command.
;;; Code:
(define-module (metabash core plumbing tee)
#:use-module (oop goops)
#:use-module (metabash core plumbing pipe)
#:export (<tee>
tee-side-branch-port))
;;; Tee implementation.
This class describes a tee that can send a data from an INPUT - PORT to both an
;; OUTPUT-PORT and a SIDE-BRANCH-PORT.
(define-class <tee> (<pipe>)
(side-branch-port #:accessor tee-side-branch-port
#:init-value #f
#:init-keyword #:side-branch-port))
;;; Default tee callbacks.
(define (%default-tee-on-disconnect-callback! tee)
"Default callback to be called when a PIPE is closed."
(close (pipe-input-port tee))
(close (pipe-output-port tee))
(close (tee-side-branch-port tee)))
;;; The <tee> constructor.
(define-method (initialize (tee <tee>) initargs)
(next-method)
(unless (memq #:on-disconnect initargs)
(slot-set! tee 'on-disconnect-callback
%default-tee-on-disconnect-callback!)))
;; Overloaded methods to display a <tee> instance.
;; TODO: Make the format less cumbersome.
(define-method (display (tee <tee>) (port <port>))
(format port "#<tee [~a] ~a> [~a], [~a] tx: ~a ~a>"
(object->naked-string (pipe-input-port tee))
(if (pipe-thread tee)
"="
"x")
(object->naked-string (tee-side-branch-port tee))
(object->naked-string (pipe-output-port tee))
(pipe-tx tee)
(number->string (object-address tee) 16)))
(define-method (write (tee <tee>) (port <tee>))
(display tee port))
(define-method (display (tee <tee>))
(next-method)
(display tee (current-output-port)))
(define-method (write (tee <tee>))
(next-method)
(display tee (current-output-port)))
Redirect data from INPUT - PORT to OUTPUT - PORT and BRANCH - OUTPUT - PORT .
(define-method (pipe-connect! (tee <tee>))
(let ((input-port (pipe-input-port tee))
(output-port (pipe-output-port tee))
(branch-port (tee-side-branch-port tee)))
(when (pipe-closed? tee)
(error "One of the ports is closed."
input-port output-port branch-port))
(slot-set! tee 'thread
(begin-thread
(let loop ((data (get-bytevector-some input-port)))
(unless (eof-object? data)
(slot-set! tee 'tx (+ (pipe-tx tee) (bytevector-length data)))
(put-bytevector branch-port data)
(put-bytevector output-port data)
(loop (get-bytevector-some input-port))))))))
Close a specified TEE by stopping the thread and closing the ports .
(define-method (pipe-close! (tee <tee>))
(pipe-disconnect! tee)
(close (pipe-input-port tee))
(close (tee-side-branch-port tee))
(close (pipe-output-port tee)))
Check if a TEE is closed . The tee is considered as closed if any of its
;; ports is closed.
(define-method (pipe-closed? (tee <tee>))
(or (port-closed? (pipe-input-port tee))
(port-closed? (pipe-output-port tee))
(port-closed? (tee-side-branch-port tee))))
;;; tee.scm ends here.
| null | https://raw.githubusercontent.com/artyom-poptsov/metabash/8a0979ca1a1d411f0d15916e0affca8989094679/modules/metabash/core/plumbing/tee.scm | scheme |
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
The program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
along with the program. If not, see </>.
Commentary:
This file contains implementation of a tee that can connect an input port to
akin to the Unix 'tee' command.
Code:
Tee implementation.
OUTPUT-PORT and a SIDE-BRANCH-PORT.
Default tee callbacks.
The <tee> constructor.
Overloaded methods to display a <tee> instance.
TODO: Make the format less cumbersome.
ports is closed.
tee.scm ends here. | tee.scm -- Tee implementation for .
Copyright ( C ) 2020 < >
it under the terms of the GNU General Public License as published by
the Free Software Foundation , either version 3 of the License , or
You should have received a copy of the GNU General Public License
two output ports effectively copying the output to two ports simultaneously ,
(define-module (metabash core plumbing tee)
#:use-module (oop goops)
#:use-module (metabash core plumbing pipe)
#:export (<tee>
tee-side-branch-port))
This class describes a tee that can send a data from an INPUT - PORT to both an
(define-class <tee> (<pipe>)
(side-branch-port #:accessor tee-side-branch-port
#:init-value #f
#:init-keyword #:side-branch-port))
(define (%default-tee-on-disconnect-callback! tee)
"Default callback to be called when a PIPE is closed."
(close (pipe-input-port tee))
(close (pipe-output-port tee))
(close (tee-side-branch-port tee)))
(define-method (initialize (tee <tee>) initargs)
(next-method)
(unless (memq #:on-disconnect initargs)
(slot-set! tee 'on-disconnect-callback
%default-tee-on-disconnect-callback!)))
(define-method (display (tee <tee>) (port <port>))
(format port "#<tee [~a] ~a> [~a], [~a] tx: ~a ~a>"
(object->naked-string (pipe-input-port tee))
(if (pipe-thread tee)
"="
"x")
(object->naked-string (tee-side-branch-port tee))
(object->naked-string (pipe-output-port tee))
(pipe-tx tee)
(number->string (object-address tee) 16)))
(define-method (write (tee <tee>) (port <tee>))
(display tee port))
(define-method (display (tee <tee>))
(next-method)
(display tee (current-output-port)))
(define-method (write (tee <tee>))
(next-method)
(display tee (current-output-port)))
Redirect data from INPUT - PORT to OUTPUT - PORT and BRANCH - OUTPUT - PORT .
(define-method (pipe-connect! (tee <tee>))
(let ((input-port (pipe-input-port tee))
(output-port (pipe-output-port tee))
(branch-port (tee-side-branch-port tee)))
(when (pipe-closed? tee)
(error "One of the ports is closed."
input-port output-port branch-port))
(slot-set! tee 'thread
(begin-thread
(let loop ((data (get-bytevector-some input-port)))
(unless (eof-object? data)
(slot-set! tee 'tx (+ (pipe-tx tee) (bytevector-length data)))
(put-bytevector branch-port data)
(put-bytevector output-port data)
(loop (get-bytevector-some input-port))))))))
Close a specified TEE by stopping the thread and closing the ports .
(define-method (pipe-close! (tee <tee>))
(pipe-disconnect! tee)
(close (pipe-input-port tee))
(close (tee-side-branch-port tee))
(close (pipe-output-port tee)))
Check if a TEE is closed . The tee is considered as closed if any of its
(define-method (pipe-closed? (tee <tee>))
(or (port-closed? (pipe-input-port tee))
(port-closed? (pipe-output-port tee))
(port-closed? (tee-side-branch-port tee))))
|
928f1f2615c2146e7fe28122a5e2f6e37db83597a474923943629a0fdd5d52eb | eslick/cl-registry | ilr-surveys.lisp | ;;; -*- Mode:Lisp; tab-width:2; indent-tabs-mode:nil -*-
Copyright ( c ) 2008 - 2010 , Massachusetts Institute of;Technology . All rights reserved .
Copyright ( c ) 2008 - 2010 , LAM Treatment Alliance . All rights reserved .
;;; Released under a BSD-style license: -license.php
;;; See LICENSE file
(in-package :registry)
(define-plugin ilr-surveys ()
)
;;; UI macros
(defmacro dropdown-options (var &rest args &key (help t) &allow-other-keys)
(remf args ':help)
`(list :data-type :choice :view-type :dropdown
,@(if help '(:help "Please choose one"))
:choices ,var ,@args))
(defmacro multi-choices-options (var &rest args &key (help t) &allow-other-keys)
(remf args ':help)
`(list :data-type :multichoice
,@(if help '(:help "Please choose all that apply"))
:choices ,var ,@args))
(defmacro checkbox-options (&rest args &key (help t) &allow-other-keys)
(remf args ':help)
`(list :data-type :boolean :view-type :checkbox
,@(if help '(:help "Select if applicable"))
,@args))
(defmacro radio-options (var &rest args &key (help t) &allow-other-keys)
(remf args ':help)
`(list :data-type :choice :view-type :radio
,@(if help '(:help "Please choose one"))
:choices ,var ,@args))
(defmacro choices-options-numbered (labels &key (start 1.))
(let ((countsym (gensym)))
`(let ((,countsym ,start))
(loop for item in ,labels
collect
(prog1
(cons
(format nil "(~D) ~A" ,countsym item)
,countsym)
(incf ,countsym))))))
(defvar *choices-alist-yes-no '(("Yes" . "Yes") ("No" . "No")))
(defmacro choices-options-yes-no (&key (help t))
`(radio-options *choices-alist-yes-no ,@(if help '(:help "Answer yes or no"))))
(defvar *choices-alist-yes-no-unknown '(("Yes" . "Yes") ("No" . "No") ("Unknown" . "Unknown")))
(defmacro choices-options-yes-no-unknown (&key (help t))
`(radio-options *choices-alist-yes-no-unknown ,@(if help '(:help "Answer yes or no or unknown"))))
(defmacro choices-mirror-alist (choices)
`(loop for str in ,choices
collect (cons str str)))
(defmacro choices-breaks-alist (choices)
`(loop for thing in ,choices
collect
(multiple-value-bind (car cdr)
(if (atom thing)
(values thing thing)
(values (car thing) (cdr thing)))
;; Returns
(cons (concatenate 'string car "<BR>") cdr))))
(defun formatted-question-number (num &optional stream)
(and num (format stream "<SUP>~D</SUP>" num)))
(defun group-section-name-and-number (survey name &optional (num t))
(format nil "~A Section~@[ ~D~]"
name
(cond
((null num) nil)
((numberp num) num)
((eq num t) (1+ (length (survey-groups survey)))))))
(defun make-survey-group-named (survey name &rest args)
(let* ((groups (survey-groups survey))
(group
(apply #'make-instance 'survey-group
:owner (owner survey)
:name name
args)))
;;(format t "~&Add group ~S to groups ~S" group groups)
(if groups
(setf (survey-groups survey) (append groups (list group)))
(setf (survey-groups survey) (list group)))
;; Returns
group))
(defun make-survey-group-named-and-numbered (survey name num &rest args)
(apply #'make-survey-group-named survey (group-section-name-and-number survey name num) args))
(defun make-survey-sub-group-named (group name &rest args)
(setq name (or name (gensym)))
(apply #'make-instance 'survey-group
:name (format nil "~A ~A" (group-name group) name)
:owner (owner group) args))
(defmethod survey-name-append ((survey-name string) string2)
(format nil "~A - ~A" survey-name string2))
(defmethod survey-name-append ((inst survey) str)
(survey-name-append (name inst) str))
| null | https://raw.githubusercontent.com/eslick/cl-registry/d4015c400dc6abf0eeaf908ed9056aac956eee82/src/plugins/ilr-surveys/ilr-surveys.lisp | lisp | -*- Mode:Lisp; tab-width:2; indent-tabs-mode:nil -*-
Technology . All rights reserved .
Released under a BSD-style license: -license.php
See LICENSE file
UI macros
Returns
(format t "~&Add group ~S to groups ~S" group groups)
Returns |
Copyright ( c ) 2008 - 2010 , LAM Treatment Alliance . All rights reserved .
(in-package :registry)
(define-plugin ilr-surveys ()
)
(defmacro dropdown-options (var &rest args &key (help t) &allow-other-keys)
(remf args ':help)
`(list :data-type :choice :view-type :dropdown
,@(if help '(:help "Please choose one"))
:choices ,var ,@args))
(defmacro multi-choices-options (var &rest args &key (help t) &allow-other-keys)
(remf args ':help)
`(list :data-type :multichoice
,@(if help '(:help "Please choose all that apply"))
:choices ,var ,@args))
(defmacro checkbox-options (&rest args &key (help t) &allow-other-keys)
(remf args ':help)
`(list :data-type :boolean :view-type :checkbox
,@(if help '(:help "Select if applicable"))
,@args))
(defmacro radio-options (var &rest args &key (help t) &allow-other-keys)
(remf args ':help)
`(list :data-type :choice :view-type :radio
,@(if help '(:help "Please choose one"))
:choices ,var ,@args))
(defmacro choices-options-numbered (labels &key (start 1.))
(let ((countsym (gensym)))
`(let ((,countsym ,start))
(loop for item in ,labels
collect
(prog1
(cons
(format nil "(~D) ~A" ,countsym item)
,countsym)
(incf ,countsym))))))
(defvar *choices-alist-yes-no '(("Yes" . "Yes") ("No" . "No")))
(defmacro choices-options-yes-no (&key (help t))
`(radio-options *choices-alist-yes-no ,@(if help '(:help "Answer yes or no"))))
(defvar *choices-alist-yes-no-unknown '(("Yes" . "Yes") ("No" . "No") ("Unknown" . "Unknown")))
(defmacro choices-options-yes-no-unknown (&key (help t))
`(radio-options *choices-alist-yes-no-unknown ,@(if help '(:help "Answer yes or no or unknown"))))
(defmacro choices-mirror-alist (choices)
`(loop for str in ,choices
collect (cons str str)))
(defmacro choices-breaks-alist (choices)
`(loop for thing in ,choices
collect
(multiple-value-bind (car cdr)
(if (atom thing)
(values thing thing)
(values (car thing) (cdr thing)))
(cons (concatenate 'string car "<BR>") cdr))))
(defun formatted-question-number (num &optional stream)
(and num (format stream "<SUP>~D</SUP>" num)))
(defun group-section-name-and-number (survey name &optional (num t))
(format nil "~A Section~@[ ~D~]"
name
(cond
((null num) nil)
((numberp num) num)
((eq num t) (1+ (length (survey-groups survey)))))))
(defun make-survey-group-named (survey name &rest args)
(let* ((groups (survey-groups survey))
(group
(apply #'make-instance 'survey-group
:owner (owner survey)
:name name
args)))
(if groups
(setf (survey-groups survey) (append groups (list group)))
(setf (survey-groups survey) (list group)))
group))
(defun make-survey-group-named-and-numbered (survey name num &rest args)
(apply #'make-survey-group-named survey (group-section-name-and-number survey name num) args))
(defun make-survey-sub-group-named (group name &rest args)
(setq name (or name (gensym)))
(apply #'make-instance 'survey-group
:name (format nil "~A ~A" (group-name group) name)
:owner (owner group) args))
(defmethod survey-name-append ((survey-name string) string2)
(format nil "~A - ~A" survey-name string2))
(defmethod survey-name-append ((inst survey) str)
(survey-name-append (name inst) str))
|
b7048460081e2cda41015e98978f984f573cc5f6b188f9ffffcdd336428263d7 | christian-marie/oauth2-server | Token.hs | --
Copyright © 2013 - 2015 Anchor Systems , Pty Ltd and Others
--
-- The code in this file, and the program it is a part of, is
-- made available to you by its authors as open source software:
-- you can redistribute it and/or modify it under the terms of
the 3 - clause BSD licence .
--
{-# LANGUAGE DeriveDataTypeable #-}
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE MultiParamTypeClasses #
{-# LANGUAGE OverloadedStrings #-}
-- | Description: Internal representation of OAuth2 tokens, token identifiers and token types
--
Internal representation of OAuth2 tokens , token identifiers and token types
--
-- Relevant syntax specific things
--
Access / Bearer tokens : #appendix-A.12
-- Refresh tokens: #appendix-A.17
module Network.OAuth2.Server.Types.Token (
-- * Types
Token,
TokenType(..),
TokenID,
-- * ByteString Encoding and Decoding
token
) where
import Control.Applicative ((<|>))
import Control.Arrow (first)
import Control.Lens.Fold ((^?))
import Control.Lens.Operators ((^.))
import Control.Lens.Prism (Prism', prism')
import Control.Lens.Review (re, review)
import Control.Monad (guard)
import Data.Aeson (FromJSON (..),
ToJSON (..),
Value (String),
withText)
import Data.ByteString (ByteString)
import qualified Data.ByteString as B (all, null)
import Data.Monoid ((<>))
import qualified Data.Text as T (pack, toLower,
unpack)
import qualified Data.Text.Encoding as T (decodeUtf8,
encodeUtf8)
import Data.Typeable (Typeable)
import Data.UUID (UUID)
import qualified Data.UUID as U (fromASCIIBytes,
fromString,
toASCIIBytes)
import Database.PostgreSQL.Simple.FromField
import Database.PostgreSQL.Simple.ToField
import Text.Blaze.Html5 (ToValue, toValue)
import Yesod.Core (PathPiece (..))
import Network.OAuth2.Server.Types.Common
--------------------------------------------------------------------------------
-- * Types
-- | A token is a unique piece of text, opaque to users.
--
-- There are access and refresh tokens, but with respect to
-- internal representation they are identical.
newtype Token = Token { unToken :: ByteString }
deriving (Eq, Ord, Typeable)
-- | Tokens can be either access/bearer tokens or refresh tokens
--
-- #section-7.1
data TokenType
= Bearer
| Refresh
deriving (Eq, Typeable)
-- | Unique identifier for a token. Identifiers are only useful for revocation
requests , and so when such actions are exposed to users , TokenIDs are used
-- over actual tokens
newtype TokenID = TokenID { unTokenID :: UUID }
deriving (Eq, Ord, ToField, FromField)
--------------------------------------------------------------------------------
-- * ByteString Encoding and Decoding
-- | Token ByteString encode/decode prism
--
access - token = 1*VSCHAR
--
refresh - token = 1*VSCHAR
token :: Prism' ByteString Token
token = prism' t2b b2t
where
t2b :: Token -> ByteString
t2b t = unToken t
b2t :: ByteString -> Maybe Token
b2t b = do
guard . not $ B.null b
guard $ B.all vschar b
return (Token b)
--------------------------------------------------------------------------------
String Encoding and Decoding
instance Show Token where
show = show . review token
instance Show TokenType where
show Bearer = "bearer"
show Refresh = "refresh"
instance Show TokenID where
show (TokenID x) = show x
instance Read TokenID where
readsPrec n x = map (first TokenID) $ readsPrec n x
--------------------------------------------------------------------------------
-- Servant Encoding and Decoding
instance PathPiece TokenID where
fromPathPiece t = (fmap TokenID) $
(U.fromASCIIBytes $ T.encodeUtf8 t)
<|> (U.fromString $ T.unpack t)
toPathPiece = T.decodeUtf8 . U.toASCIIBytes . unTokenID
--------------------------------------------------------------------------------
-- Postgres Encoding and Decoding
instance ToField Token where
toField tok = toField $ tok ^.re token
instance FromField Token where
fromField f bs = do
rawToken <- fromField f bs
case rawToken ^? token of
Nothing -> returnError ConversionFailed f "Invalid Token"
Just t -> return t
instance ToField TokenType where
toField = toField . T.pack . show
instance FromField TokenType where
fromField f bs = do
x <- fromField f bs
case T.toLower x of
"bearer" -> return Bearer
"refresh" -> return Refresh
t -> returnError ConversionFailed f $ "Invalid TokenType: " <> show t
--------------------------------------------------------------------------------
-- JSON/Aeson Encoding and Decoding
instance ToJSON Token where
toJSON t = String . T.decodeUtf8 $ t ^.re token
instance FromJSON Token where
parseJSON = withText "Token" $ \t ->
case T.encodeUtf8 t ^? token of
Nothing -> fail $ T.unpack t <> " is not a valid Token."
Just s -> return s
instance ToJSON TokenType where
toJSON = String . T.pack . show
instance FromJSON TokenType where
parseJSON = withText "TokenType" $ \t -> do
case T.toLower t of
"bearer" -> return Bearer
"refresh" -> return Refresh
_ -> fail $ "Invalid TokenType: " <> show t
--------------------------------------------------------------------------------
Blaze Encoding
instance ToValue TokenID where
toValue = toValue . show . unTokenID
--------------------------------------------------------------------------------
| null | https://raw.githubusercontent.com/christian-marie/oauth2-server/ebb75be9d05dd52d478a6e069d32461d4e54544e/lib/Network/OAuth2/Server/Types/Token.hs | haskell |
The code in this file, and the program it is a part of, is
made available to you by its authors as open source software:
you can redistribute it and/or modify it under the terms of
# LANGUAGE DeriveDataTypeable #
# LANGUAGE OverloadedStrings #
| Description: Internal representation of OAuth2 tokens, token identifiers and token types
Relevant syntax specific things
Refresh tokens: #appendix-A.17
* Types
* ByteString Encoding and Decoding
------------------------------------------------------------------------------
* Types
| A token is a unique piece of text, opaque to users.
There are access and refresh tokens, but with respect to
internal representation they are identical.
| Tokens can be either access/bearer tokens or refresh tokens
#section-7.1
| Unique identifier for a token. Identifiers are only useful for revocation
over actual tokens
------------------------------------------------------------------------------
* ByteString Encoding and Decoding
| Token ByteString encode/decode prism
------------------------------------------------------------------------------
------------------------------------------------------------------------------
Servant Encoding and Decoding
------------------------------------------------------------------------------
Postgres Encoding and Decoding
------------------------------------------------------------------------------
JSON/Aeson Encoding and Decoding
------------------------------------------------------------------------------
------------------------------------------------------------------------------ | Copyright © 2013 - 2015 Anchor Systems , Pty Ltd and Others
the 3 - clause BSD licence .
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE MultiParamTypeClasses #
Internal representation of OAuth2 tokens , token identifiers and token types
Access / Bearer tokens : #appendix-A.12
module Network.OAuth2.Server.Types.Token (
Token,
TokenType(..),
TokenID,
token
) where
import Control.Applicative ((<|>))
import Control.Arrow (first)
import Control.Lens.Fold ((^?))
import Control.Lens.Operators ((^.))
import Control.Lens.Prism (Prism', prism')
import Control.Lens.Review (re, review)
import Control.Monad (guard)
import Data.Aeson (FromJSON (..),
ToJSON (..),
Value (String),
withText)
import Data.ByteString (ByteString)
import qualified Data.ByteString as B (all, null)
import Data.Monoid ((<>))
import qualified Data.Text as T (pack, toLower,
unpack)
import qualified Data.Text.Encoding as T (decodeUtf8,
encodeUtf8)
import Data.Typeable (Typeable)
import Data.UUID (UUID)
import qualified Data.UUID as U (fromASCIIBytes,
fromString,
toASCIIBytes)
import Database.PostgreSQL.Simple.FromField
import Database.PostgreSQL.Simple.ToField
import Text.Blaze.Html5 (ToValue, toValue)
import Yesod.Core (PathPiece (..))
import Network.OAuth2.Server.Types.Common
newtype Token = Token { unToken :: ByteString }
deriving (Eq, Ord, Typeable)
data TokenType
= Bearer
| Refresh
deriving (Eq, Typeable)
requests , and so when such actions are exposed to users , TokenIDs are used
newtype TokenID = TokenID { unTokenID :: UUID }
deriving (Eq, Ord, ToField, FromField)
access - token = 1*VSCHAR
refresh - token = 1*VSCHAR
token :: Prism' ByteString Token
token = prism' t2b b2t
where
t2b :: Token -> ByteString
t2b t = unToken t
b2t :: ByteString -> Maybe Token
b2t b = do
guard . not $ B.null b
guard $ B.all vschar b
return (Token b)
String Encoding and Decoding
instance Show Token where
show = show . review token
instance Show TokenType where
show Bearer = "bearer"
show Refresh = "refresh"
instance Show TokenID where
show (TokenID x) = show x
instance Read TokenID where
readsPrec n x = map (first TokenID) $ readsPrec n x
instance PathPiece TokenID where
fromPathPiece t = (fmap TokenID) $
(U.fromASCIIBytes $ T.encodeUtf8 t)
<|> (U.fromString $ T.unpack t)
toPathPiece = T.decodeUtf8 . U.toASCIIBytes . unTokenID
instance ToField Token where
toField tok = toField $ tok ^.re token
instance FromField Token where
fromField f bs = do
rawToken <- fromField f bs
case rawToken ^? token of
Nothing -> returnError ConversionFailed f "Invalid Token"
Just t -> return t
instance ToField TokenType where
toField = toField . T.pack . show
instance FromField TokenType where
fromField f bs = do
x <- fromField f bs
case T.toLower x of
"bearer" -> return Bearer
"refresh" -> return Refresh
t -> returnError ConversionFailed f $ "Invalid TokenType: " <> show t
instance ToJSON Token where
toJSON t = String . T.decodeUtf8 $ t ^.re token
instance FromJSON Token where
parseJSON = withText "Token" $ \t ->
case T.encodeUtf8 t ^? token of
Nothing -> fail $ T.unpack t <> " is not a valid Token."
Just s -> return s
instance ToJSON TokenType where
toJSON = String . T.pack . show
instance FromJSON TokenType where
parseJSON = withText "TokenType" $ \t -> do
case T.toLower t of
"bearer" -> return Bearer
"refresh" -> return Refresh
_ -> fail $ "Invalid TokenType: " <> show t
Blaze Encoding
instance ToValue TokenID where
toValue = toValue . show . unTokenID
|
6c335ace33273a9c93d8f31ca00e872380a2d0cda14513f84fd72e97a8a61bf2 | heidihoward/ocaml-raft | test_spl_wrapper.ml | open Core_kernel.Std
open OUnit
open RaftMonitorWrapper
let apply x y = tick y x
let test_general2 _ =
let monitor = init () in
apply `Startup monitor
|> apply `StartElection
|> apply `WinElection
|> apply `RestartElection
|> (fun _ -> ())
let test_general1 _ =
let monitor = init () in
apply `Recover monitor
|> apply `StartElection
|> apply `RestartElection
|> apply `RestartElection
|> apply `WinElection
|> apply `StepDown_from_Leader
|> (fun _ -> () )
let suite = "SPL Test" >:::
["general_succcessful" >:: test_general1;
"general_failure" >:: test_general2;
]
let _ =
run_test_tt_main suite
| null | https://raw.githubusercontent.com/heidihoward/ocaml-raft/b1502ebf8c19be28270d11994abac68e5a6418be/test/test_spl_wrapper.ml | ocaml | open Core_kernel.Std
open OUnit
open RaftMonitorWrapper
let apply x y = tick y x
let test_general2 _ =
let monitor = init () in
apply `Startup monitor
|> apply `StartElection
|> apply `WinElection
|> apply `RestartElection
|> (fun _ -> ())
let test_general1 _ =
let monitor = init () in
apply `Recover monitor
|> apply `StartElection
|> apply `RestartElection
|> apply `RestartElection
|> apply `WinElection
|> apply `StepDown_from_Leader
|> (fun _ -> () )
let suite = "SPL Test" >:::
["general_succcessful" >:: test_general1;
"general_failure" >:: test_general2;
]
let _ =
run_test_tt_main suite
| |
a0ae2178142cd5a2338ee095aa8aa4901ce4b91eae365a7107d33109610b623f | facebook/duckling | Corpus.hs | Copyright ( c ) 2016 - present , Facebook , Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree.
{-# LANGUAGE OverloadedStrings #-}
module Duckling.Time.PT.Corpus
( corpus
, negativeCorpus
) where
import Data.String
import Prelude
import Duckling.Locale
import Duckling.Resolve
import Duckling.Testing.Types hiding (examples)
import Duckling.Time.Corpus
import Duckling.Time.Types hiding (Month)
import Duckling.TimeGrain.Types hiding (add)
corpus :: Corpus
corpus = (testContext {locale = makeLocale PT Nothing}, testOptions, allExamples)
negativeCorpus :: NegativeCorpus
negativeCorpus = (testContext {locale = makeLocale PT Nothing}, testOptions, examples)
where
examples =
[ "no 987"
, "um"
, "um dos"
, "um dos minutos"
, "ter"
]
allExamples :: [Example]
allExamples = concat
[ examples (datetime (2013, 2, 12, 4, 30, 0) Second)
[ "agora"
, "já"
, "ja"
, "nesse instante"
, "neste instante"
]
, examples (datetime (2013, 2, 12, 0, 0, 0) Day)
[ "hoje"
, "nesse momento"
, "neste momento"
]
, examples (datetime (2013, 2, 11, 0, 0, 0) Day)
[ "ontem"
]
, examples (datetime (2013, 2, 10, 0, 0, 0) Day)
[ "antes de ontem"
, "anteontem"
]
, examples (datetime (2013, 2, 13, 0, 0, 0) Day)
[ "amanhã"
, "amanha"
]
, examples (datetime (2013, 2, 14, 0, 0, 0) Day)
[ "depois de amanhã"
, "depois de amanha"
]
, examples (datetime (2013, 2, 18, 0, 0, 0) Day)
[ "segunda-feira"
, "segunda feira"
, "segunda"
, "seg."
, "seg"
, "essa segunda-feira"
, "essa segunda feira"
, "essa segunda"
]
, examples (datetime (2013, 2, 18, 0, 0, 0) Day)
[ "segunda, 18 de fevereiro"
]
, examples (datetime (2013, 2, 19, 0, 0, 0) Day)
[ "terça-feira"
, "terça feira"
, "terça"
, "terca-feira"
, "terca feira"
, "terca"
, "ter."
]
, examples (datetime (2013, 2, 13, 0, 0, 0) Day)
[ "quarta-feira"
, "quarta feira"
, "quarta"
, "qua."
, "qua"
]
, examples (datetime (2013, 2, 14, 0, 0, 0) Day)
[ "quinta-feira"
, "quinta feira"
, "quinta"
, "qui."
, "qui"
]
, examples (datetime (2013, 2, 15, 0, 0, 0) Day)
[ "sexta-feira"
, "sexta feira"
, "sexta"
, "sex."
, "sex"
]
, examples (datetime (2013, 2, 16, 0, 0, 0) Day)
[ "sábado"
, "sabado"
, "sáb."
, "sáb"
, "sab."
, "sab"
]
, examples (datetime (2013, 2, 17, 0, 0, 0) Day)
[ "domingo"
, "dom."
, "dom"
]
, examples (datetime (2013, 5, 5, 0, 0, 0) Day)
[ "5 de maio"
, "5 maio"
, "05 maio"
, "cinco de maio"
, "cinco maio"
, "maio 5"
, "maio cinco"
]
, examples (datetime (2013, 5, 5, 0, 0, 0) Day)
[ "cinco de maio de 2013"
, "5 de maio de 2013"
, "5 maio de 2013"
, "5 de maio 2013"
, "5 maio 2013"
, "5/5"
, "5/5/2013"
]
, examples (datetime (2013, 7, 4, 0, 0, 0) Day)
[ "4 de julho"
, "04 de julho"
, "04 julho"
, "quatro de julho"
, "quatro julho"
, "julho 4"
, "julho quatro"
, "4/7"
, "4/7/2013"
]
, examples (datetime (2013, 3, 3, 0, 0, 0) Day)
[ "3 de março"
, "três de março"
, "tres de março"
, "3/3"
, "3/3/2013"
]
, examples (datetime (2013, 4, 5, 0, 0, 0) Day)
[ "5 de abril"
, "cinco de abril"
]
, examples (datetime (2013, 3, 1, 0, 0, 0) Day)
[ "1 de março"
, "primeiro de março"
, "um de março"
, "1o de março"
]
, examples (datetime (2013, 3, 1, 0, 0, 0) Day)
[ "1-3-2013"
, "1.3.2013"
, "1/3/2013"
]
, examples (datetime (2013, 2, 16, 0, 0, 0) Day)
[ "essa dia 16"
, "16 de fevereiro"
]
, examples (datetime (2013, 2, 17, 0, 0, 0) Day)
[ "este dia 17"
, "17 de fevereiro"
, "17/2"
, "no domingo"
, "no dia 17"
, "dia 17"
]
, examples (datetime (2013, 2, 20, 0, 0, 0) Day)
[ "esse dia 20"
, "20 de fevereiro"
, "20/2"
]
, examples (datetime (1974, 10, 31, 0, 0, 0) Day)
[ "31/10/1974"
, "31/10/74"
]
, examples (datetime (2013, 2, 19, 0, 0, 0) Day)
[ "próxima terça-feira"
, "próxima terça feira"
, "próxima terça"
, "proxima terça-feira"
, "proxima terça feira"
, "proxima terça"
]
, examples (datetime (2013, 2, 20, 0, 0, 0) Day)
[ "quarta que vem"
, "quarta da semana que vem"
, "quarta da próxima semana"
]
, examples (datetime (2013, 2, 12, 0, 0, 0) Day)
[ "terça desta semana"
, "terça dessa semana"
, "terça agora"
]
, examples (datetime (2013, 2, 11, 0, 0, 0) Week)
[ "esta semana"
]
, examples (datetime (2013, 2, 4, 0, 0, 0) Week)
[ "semana passada"
, "semana anterior"
, "passada semana"
, "anterior semana"
, "última semana"
, "ultima semana"
]
, examples (datetime (2013, 2, 18, 0, 0, 0) Week)
[ "semana que vem"
, "proxima semana"
]
, examples (datetime (2013, 1, 0, 0, 0, 0) Month)
[ "mês passado"
]
, examples (datetime (2013, 3, 0, 0, 0, 0) Month)
[ "mes que vem"
, "próximo mês"
]
, examples (datetime (2012, 0, 0, 0, 0, 0) Year)
[ "ano passado"
]
, examples (datetime (2013, 0, 0, 0, 0, 0) Year)
[ "este ano"
]
, examples (datetime (2014, 0, 0, 0, 0, 0) Year)
[ "ano que vem"
, "proximo ano"
]
, examples (datetime (2013, 2, 10, 0, 0, 0) Day)
[ "domingo passado"
, "domingo da semana passada"
]
, examples (datetime (2013, 2, 5, 0, 0, 0) Day)
[ "terça passada"
]
, examples (datetime (2013, 2, 12, 15, 0, 0) Hour)
[ "às tres da tarde"
, "às tres"
, "às 3 pm"
, "às 15 horas"
]
, examples (datetime (2013, 2, 12, 20, 0, 0) Hour)
[ "às oito da noite"
]
, examples (datetime (2013, 2, 13, 20, 0, 0) Hour)
[ "amanhã às oito da noite"
]
, examples (datetime (2013, 2, 15, 18, 0, 0) Hour)
[ "no dia 15 às 18"
, "dia 15 às 18"
, "dia 15 às 18 horas"
, "dia 15 às dezoito"
, "dia quinze às dezoito"
]
, examples (datetime (2013, 2, 14, 18, 0, 0) Hour)
[ "quinta-feira às 18 horas"
, "quinta às 18"
]
, examples (datetime (2013, 2, 15, 18, 15, 0) Minute)
[ "dia 15 de Fevereiro às 18:15"
, "dia 15 às 18:15"
]
, examples (datetime (2013, 2, 12, 15, 0, 0) Minute)
[ "15:00"
, "15.00"
, "às 15:00"
, "às 15.00"
]
, examples (datetime (2013, 2, 13, 0, 0, 0) Hour)
[ "meianoite"
, "meia noite"
]
, examples (datetime (2013, 2, 12, 12, 0, 0) Hour)
[ "meio dia"
, "meiodia"
]
, examples (datetime (2013, 2, 12, 12, 15, 0) Minute)
[ "meio dia e quinze"
]
, examples (datetime (2013, 2, 12, 11, 55, 0) Minute)
[ "5 para meio dia"
]
, examples (datetime (2013, 2, 12, 12, 30, 0) Minute)
[ "meio dia e meia"
]
, examples (datetime (2013, 2, 12, 6, 0, 0) Hour)
[ "as seis da manha"
, "as seis pela manha"
]
, examples (datetime (2013, 2, 12, 15, 15, 0) Minute)
[ "às tres e quinze"
, "às tres e quinze da tarde"
, "às tres e quinze pela tarde"
, "15:15"
, "15.15"
]
, examples (datetime (2013, 2, 12, 15, 30, 0) Minute)
[ "às tres e meia"
, "às 3 e trinta"
, "às tres e meia da tarde"
, "às 3 e trinta da tarde"
, "15:30"
, "15.30"
]
, examples (datetime (2013, 2, 12, 11, 45, 0) Minute)
[ "quinze para meio dia"
, "quinze para o meio dia"
, "11:45"
, "as onze e quarenta e cinco"
, "hoje quinze para o meio dia"
, "hoje às onze e quarenta e cinco"
]
, examples (datetime (2013, 2, 12, 5, 15, 0) Minute)
[ "5 e quinze"
]
, examples (datetime (2013, 2, 12, 6, 0, 0) Hour)
[ "6 da manhã"
]
, examples (datetime (2013, 2, 13, 11, 0, 0) Hour)
[ "quarta às onze da manhã"
]
, examples (datetime (2014, 9, 12, 0, 0, 0) Day)
[ "sexta, 12 de setembro de 2014"
, "sexta feira, 12 de setembro de 2014"
, "12 de setembro de 2014, sexta"
, "12 de setembro de 2014 sexta feira"
, "sexta feira 12 de setembro de 2014"
]
, examples (datetime (2013, 2, 12, 4, 30, 1) Second)
[ "em um segundo"
]
, examples (datetime (2013, 2, 12, 4, 31, 0) Second)
[ "em um minuto"
, "em 1 min"
]
, examples (datetime (2013, 2, 12, 4, 32, 0) Second)
[ "em 2 minutos"
, "em dois minutos"
]
, examples (datetime (2013, 2, 12, 5, 30, 0) Second)
[ "em 60 minutos"
]
, examples (datetime (2013, 2, 12, 5, 30, 0) Minute)
[ "em uma hora"
]
, examples (datetime (2013, 2, 12, 2, 30, 0) Minute)
[ "fazem duas horas"
]
, examples (datetime (2013, 2, 13, 4, 30, 0) Minute)
[ "em 24 horas"
, "em vinte e quatro horas"
]
, examples (datetime (2013, 2, 13, 4, 0, 0) Hour)
[ "em um dia"
]
, examples (datetime (2013, 2, 19, 4, 0, 0) Hour)
[ "em 7 dias"
]
, examples (datetime (2013, 2, 19, 0, 0, 0) Day)
[ "em uma semana"
]
, examples (datetime (2013, 1, 22, 0, 0, 0) Day)
[ "faz tres semanas"
, "faz três semanas"
]
, examples (datetime (2013, 4, 12, 0, 0, 0) Day)
[ "em dois meses"
]
, examples (datetime (2012, 11, 12, 0, 0, 0) Day)
[ "faz tres meses"
]
, examples (datetime (2014, 2, 0, 0, 0, 0) Month)
[ "em um ano"
, "em 1 ano"
]
, examples (datetime (2011, 2, 0, 0, 0, 0) Month)
[ "faz dois anos"
]
, examples (datetimeInterval ((2013, 6, 21, 0, 0, 0), (2013, 9, 24, 0, 0, 0)) Day)
[ "este verão"
, "este verao"
]
, examples (datetimeInterval ((2012, 12, 21, 0, 0, 0), (2013, 3, 21, 0, 0, 0)) Day)
[ "este inverno"
]
, examples (datetime (2013, 12, 25, 0, 0, 0) Day)
[ "Natal"
]
, examples (datetime (2013, 12, 31, 0, 0, 0) Day)
[ "véspera de ano novo"
]
, examples (datetime (2014, 1, 1, 0, 0, 0) Day)
[ "ano novo"
, "reveillon"
, "Reveillon"
]
, examples (datetimeInterval ((2013, 2, 12, 18, 0, 0), (2013, 2, 13, 0, 0, 0)) Hour)
[ "esta noite"
, "essa noite"
]
, examples (datetimeInterval ((2013, 2, 13, 18, 0, 0), (2013, 2, 14, 0, 0, 0)) Hour)
[ "amanhã a noite"
, "amanhã à noite"
]
, examples (datetimeInterval ((2013, 2, 11, 18, 0, 0), (2013, 2, 12, 0, 0, 0)) Hour)
[ "ontem a noite"
, "ontem à noite"
]
, examples (datetimeInterval ((2013, 2, 13, 12, 0, 0), (2013, 2, 13, 19, 0, 0)) Hour)
[ "amanhã a tarde"
, "amanhã à tarde"
]
, examples (datetimeInterval ((2013, 2, 11, 12, 0, 0), (2013, 2, 11, 19, 0, 0)) Hour)
[ "ontem a tarde"
, "ontem à tarde"
]
, examples (datetimeInterval ((2013, 2, 15, 18, 0, 0), (2013, 2, 18, 0, 0, 0)) Hour)
[ "este final de semana"
, "este fim de semana"
]
, examples (datetimeInterval ((2013, 2, 18, 4, 0, 0), (2013, 2, 18, 12, 0, 0)) Hour)
[ "segunda de manhã"
]
, examples (datetimeInterval ((2013, 2, 15, 4, 0, 0), (2013, 2, 15, 12, 0, 0)) Hour)
[ "dia 15 de fevereiro pela manhã"
, "dia 15 de fevereiro de manhã"
]
, examples (datetime (2013, 2, 12, 20, 0, 0) Hour)
[ "às 8 da noite"
]
, examples (datetimeInterval ((2013, 2, 12, 4, 29, 58), (2013, 2, 12, 4, 30, 0)) Second)
[ "2 segundos atras"
]
, examples (datetimeInterval ((2013, 2, 12, 4, 30, 1), (2013, 2, 12, 4, 30, 4)) Second)
[ "proximos 3 segundos"
]
, examples (datetimeInterval ((2013, 2, 12, 4, 28, 0), (2013, 2, 12, 4, 30, 0)) Minute)
[ "2 minutos atrás"
]
, examples (datetimeInterval ((2013, 2, 12, 4, 31, 0), (2013, 2, 12, 4, 34, 0)) Minute)
[ "proximos 3 minutos"
]
, examples (datetimeInterval ((2013, 2, 12, 5, 0, 0), (2013, 2, 12, 8, 0, 0)) Hour)
[ "proximas 3 horas"
]
, examples (datetimeInterval ((2013, 2, 10, 0, 0, 0), (2013, 2, 12, 0, 0, 0)) Day)
[ "passados 2 dias"
]
, examples (datetimeInterval ((2013, 2, 13, 0, 0, 0), (2013, 2, 16, 0, 0, 0)) Day)
[ "proximos 3 dias"
]
, examples (datetimeInterval ((2013, 1, 28, 0, 0, 0), (2013, 2, 11, 0, 0, 0)) Week)
[ "duas semanas atras"
]
, examples (datetimeInterval ((2013, 2, 18, 0, 0, 0), (2013, 3, 11, 0, 0, 0)) Week)
[ "3 proximas semanas"
, "3 semanas que vem"
]
, examples (datetimeInterval ((2012, 12, 0, 0, 0, 0), (2013, 2, 0, 0, 0, 0)) Month)
[ "passados 2 meses"
, "últimos 2 meses"
, "2 meses anteriores"
, "2 últimos meses"
, "2 anteriores meses"
]
, examples (datetimeInterval ((2013, 3, 0, 0, 0, 0), (2013, 6, 0, 0, 0, 0)) Month)
[ "3 próximos meses"
, "proximos tres meses"
, "tres meses que vem"
]
, examples (datetimeInterval ((2011, 0, 0, 0, 0, 0), (2013, 0, 0, 0, 0, 0)) Year)
[ "passados 2 anos"
, "últimos 2 anos"
, "2 anos anteriores"
, "2 últimos anos"
, "2 anteriores anos"
]
, examples (datetimeInterval ((2014, 0, 0, 0, 0, 0), (2017, 0, 0, 0, 0, 0)) Year)
[ "3 próximos anos"
, "proximo tres anos"
, "3 anos que vem"
]
, examples (datetimeInterval ((2013, 7, 13, 0, 0, 0), (2013, 7, 16, 0, 0, 0)) Day)
[ "13 a 15 de julho"
, "13 - 15 de julho de 2013"
]
, examples (datetimeInterval ((2013, 2, 12, 9, 30, 0), (2013, 2, 12, 11, 1, 0)) Minute)
[ "9:30 - 11:00"
]
, examples (datetimeInterval ((2013, 12, 21, 0, 0, 0), (2014, 1, 7, 0, 0, 0)) Day)
[ "21 de Dez. a 6 de Jan"
]
, examples (datetimeInterval ((2013, 2, 12, 4, 30, 0), (2013, 2, 12, 7, 30, 0)) Second)
[ "dentro de tres horas"
]
, examples (datetime (2013, 2, 12, 16, 0, 0) Hour)
[ "as quatro da tarde"
]
, examples (datetime (2013, 2, 12, 13, 0, 0) Minute)
[ "as quatro CET"
]
, examples (datetimeOpenInterval After (2013, 2, 12, 12, 0, 0) Hour)
[ "após ao meio dia"
, "depois do meio dia"
]
, examples (datetimeOpenInterval Before (2013, 2, 12, 12, 0, 0) Hour)
[ "antes do meio dia"
, "não mais que meio dia"
]
, examples (datetimeOpenInterval After (2013, 2, 13, 15, 0, 0) Hour)
[ "amanhã depois das 15hs"
, "amanha após as quinze horas"
]
, examples (datetimeOpenInterval Before (2013, 2, 13, 0, 0, 0) Hour)
[ "antes da meia noite"
, "até a meia noite"
]
,examples (datetime (2013, 2, 12, 3, 0, 0) Hour)
[ "última hora"
, "hora anterior"
, "hora passada"
]
, examples (datetime (2013, 1, 1, 0, 0, 0) Quarter)
[ "este trimestre"
, "trimestre actual"
, "trimestre atual"
]
, examples (datetime (2013, 1, 1, 0, 0, 0) Month)
[ "primeiro mês de 2013"
, "primeiro mês 2013"
]
, examples (datetime (2013, 4, 1, 0, 0, 0) Quarter)
[ "próximo trimestre"
, "segundo trimestre de 2013"
, "segundo trimestre"
]
, examples (datetime (2013, 7, 1, 0, 0, 0) Quarter)
[ "terceiro trimestre"
]
, examples (datetime (2018, 10, 1, 0, 0, 0) Quarter)
[ "quarto trimestre de 2018"
, "quarto trimestre 2018"
]
, examples (datetime (2012, 10, 1, 0, 0, 0) Quarter)
[ "trimestre passado"
, "trimestre anterior"
, "último trimestre"
, "ultimo trimestre"
]
, examples (datetime (2013, 12, 1, 0, 0, 0) Month)
[ "décimo segundo mês de 2013"
, "último mês de 2013"
, "último mês 2013"
]
, examples (datetime (2015, 10, 1, 0, 0, 0) Quarter)
[ "último trimestre de 2015"
, "último trimestre 2015"
]
, examples (datetimeInterval ((2013, 7, 13, 0, 0, 0), (2013, 7, 16, 0, 0, 0)) Day)
[ "desde 13 a 15 de Julho"
, "a partir de 13 até 15 de Julho"
, "desde 13 até 15 de Julho"
, "13-15 de Julho"
, "13 até 15 de Julho"
, "13 a 15 de Julho"
, "desde 13 a 15 Julho"
, "a partir de 13 até 15 Julho"
, "desde 13 até 15 Julho"
, "13-15 Julho"
, "13 até 15 Julho"
, "13 a 15 Julho"
]
, examples (datetimeInterval ((2017, 1, 1, 0, 0, 0), (2017, 10, 1, 0, 0, 0)) Quarter)
[ "de primeiro trimestre de 2017 até terceiro trimestre de 2017"
, "de primeiro trimestre de 2017 até ao terceiro trimestre de 2017"
, "do primeiro trimestre de 2017 até terceiro trimestre de 2017"
, "do primeiro trimestre de 2017 até ao terceiro trimestre de 2017"
, "desde primeiro trimestre de 2017 até terceiro trimestre de 2017"
, "desde primeiro trimestre de 2017 até ao terceiro trimestre de 2017"
, "a partir do primeiro trimestre de 2017 até terceiro trimestre de 2017"
, "a partir do primeiro trimestre de 2017 até ao terceiro trimestre de 2017"
, "a partir de primeiro trimestre de 2017 até terceiro trimestre de 2017"
, "a partir de primeiro trimestre de 2017 até ao terceiro trimestre de 2017"
, "primeiro trimestre de 2017 a terceiro trimestre de 2017"
, "primeiro trimestre de 2017 ao terceiro trimestre de 2017"
, "primeiro trimestre de 2017 - terceiro trimestre de 2017"
, "entre primeiro trimestre de 2017 e terceiro trimestre de 2017"
, "entre o primeiro trimestre de 2017 e terceiro trimestre de 2017"
, "primeiro trimestre de 2017 até terceiro trimestre de 2017"
, "primeiro trimestre de 2017 até ao terceiro trimestre de 2017"
, "primeiro trimestre 2017 a terceiro trimestre 2017"
, "primeiro trimestre 2017 ao terceiro trimestre 2017"
, "primeiro trimestre 2017 - terceiro trimestre 2017"
, "primeiro trimestre 2017 até terceiro trimestre 2017"
, "primeiro trimestre 2017 até ao terceiro trimestre 2017"
, "entre primeiro trimestre 2017 e terceiro trimestre 2017"
, "entre o primeiro trimestre 2017 e terceiro trimestre 2017"
]
, examples (datetimeInterval ((2017, 3, 1, 0, 0, 0), (2017, 10, 1, 0, 0, 0)) Month)
[ "de terceiro mês de 2017 até nono mês de 2017"
, "de terceiro mês de 2017 até ao nono mês de 2017"
, "do terceiro mês de 2017 até nono mês de 2017"
, "do terceiro mês de 2017 até ao nono mês de 2017"
, "desde terceiro mês de 2017 até nono mês de 2017"
, "desde terceiro mês de 2017 até ao nono mês de 2017"
, "a partir do terceiro mês de 2017 até nono mês de 2017"
, "a partir do terceiro mês de 2017 até ao nono mês de 2017"
, "a partir de terceiro mês de 2017 até nono mês de 2017"
, "a partir de terceiro mês de 2017 até ao nono mês de 2017"
, "terceiro mês de 2017 a nono mês de 2017"
, "terceiro mês de 2017 ao nono mês de 2017"
, "terceiro mês de 2017 - nono mês de 2017"
, "entre terceiro mês de 2017 e nono mês de 2017"
, "entre o terceiro mês de 2017 e nono mês de 2017"
, "terceiro mês de 2017 até nono mês de 2017"
, "terceiro mês de 2017 até ao nono mês de 2017"
, "terceiro mês 2017 a nono mês 2017"
, "terceiro mês 2017 ao nono mês 2017"
, "terceiro mês 2017 - nono mês 2017"
, "terceiro mês 2017 até nono mês 2017"
, "terceiro mês 2017 até ao nono mês 2017"
, "entre terceiro mês 2017 e nono mês 2017"
, "entre o terceiro mês 2017 e nono mês 2017"
]
]
| null | https://raw.githubusercontent.com/facebook/duckling/72f45e8e2c7385f41f2f8b1f063e7b5daa6dca94/Duckling/Time/PT/Corpus.hs | haskell | All rights reserved.
This source code is licensed under the BSD-style license found in the
LICENSE file in the root directory of this source tree.
# LANGUAGE OverloadedStrings # | Copyright ( c ) 2016 - present , Facebook , Inc.
module Duckling.Time.PT.Corpus
( corpus
, negativeCorpus
) where
import Data.String
import Prelude
import Duckling.Locale
import Duckling.Resolve
import Duckling.Testing.Types hiding (examples)
import Duckling.Time.Corpus
import Duckling.Time.Types hiding (Month)
import Duckling.TimeGrain.Types hiding (add)
corpus :: Corpus
corpus = (testContext {locale = makeLocale PT Nothing}, testOptions, allExamples)
negativeCorpus :: NegativeCorpus
negativeCorpus = (testContext {locale = makeLocale PT Nothing}, testOptions, examples)
where
examples =
[ "no 987"
, "um"
, "um dos"
, "um dos minutos"
, "ter"
]
allExamples :: [Example]
allExamples = concat
[ examples (datetime (2013, 2, 12, 4, 30, 0) Second)
[ "agora"
, "já"
, "ja"
, "nesse instante"
, "neste instante"
]
, examples (datetime (2013, 2, 12, 0, 0, 0) Day)
[ "hoje"
, "nesse momento"
, "neste momento"
]
, examples (datetime (2013, 2, 11, 0, 0, 0) Day)
[ "ontem"
]
, examples (datetime (2013, 2, 10, 0, 0, 0) Day)
[ "antes de ontem"
, "anteontem"
]
, examples (datetime (2013, 2, 13, 0, 0, 0) Day)
[ "amanhã"
, "amanha"
]
, examples (datetime (2013, 2, 14, 0, 0, 0) Day)
[ "depois de amanhã"
, "depois de amanha"
]
, examples (datetime (2013, 2, 18, 0, 0, 0) Day)
[ "segunda-feira"
, "segunda feira"
, "segunda"
, "seg."
, "seg"
, "essa segunda-feira"
, "essa segunda feira"
, "essa segunda"
]
, examples (datetime (2013, 2, 18, 0, 0, 0) Day)
[ "segunda, 18 de fevereiro"
]
, examples (datetime (2013, 2, 19, 0, 0, 0) Day)
[ "terça-feira"
, "terça feira"
, "terça"
, "terca-feira"
, "terca feira"
, "terca"
, "ter."
]
, examples (datetime (2013, 2, 13, 0, 0, 0) Day)
[ "quarta-feira"
, "quarta feira"
, "quarta"
, "qua."
, "qua"
]
, examples (datetime (2013, 2, 14, 0, 0, 0) Day)
[ "quinta-feira"
, "quinta feira"
, "quinta"
, "qui."
, "qui"
]
, examples (datetime (2013, 2, 15, 0, 0, 0) Day)
[ "sexta-feira"
, "sexta feira"
, "sexta"
, "sex."
, "sex"
]
, examples (datetime (2013, 2, 16, 0, 0, 0) Day)
[ "sábado"
, "sabado"
, "sáb."
, "sáb"
, "sab."
, "sab"
]
, examples (datetime (2013, 2, 17, 0, 0, 0) Day)
[ "domingo"
, "dom."
, "dom"
]
, examples (datetime (2013, 5, 5, 0, 0, 0) Day)
[ "5 de maio"
, "5 maio"
, "05 maio"
, "cinco de maio"
, "cinco maio"
, "maio 5"
, "maio cinco"
]
, examples (datetime (2013, 5, 5, 0, 0, 0) Day)
[ "cinco de maio de 2013"
, "5 de maio de 2013"
, "5 maio de 2013"
, "5 de maio 2013"
, "5 maio 2013"
, "5/5"
, "5/5/2013"
]
, examples (datetime (2013, 7, 4, 0, 0, 0) Day)
[ "4 de julho"
, "04 de julho"
, "04 julho"
, "quatro de julho"
, "quatro julho"
, "julho 4"
, "julho quatro"
, "4/7"
, "4/7/2013"
]
, examples (datetime (2013, 3, 3, 0, 0, 0) Day)
[ "3 de março"
, "três de março"
, "tres de março"
, "3/3"
, "3/3/2013"
]
, examples (datetime (2013, 4, 5, 0, 0, 0) Day)
[ "5 de abril"
, "cinco de abril"
]
, examples (datetime (2013, 3, 1, 0, 0, 0) Day)
[ "1 de março"
, "primeiro de março"
, "um de março"
, "1o de março"
]
, examples (datetime (2013, 3, 1, 0, 0, 0) Day)
[ "1-3-2013"
, "1.3.2013"
, "1/3/2013"
]
, examples (datetime (2013, 2, 16, 0, 0, 0) Day)
[ "essa dia 16"
, "16 de fevereiro"
]
, examples (datetime (2013, 2, 17, 0, 0, 0) Day)
[ "este dia 17"
, "17 de fevereiro"
, "17/2"
, "no domingo"
, "no dia 17"
, "dia 17"
]
, examples (datetime (2013, 2, 20, 0, 0, 0) Day)
[ "esse dia 20"
, "20 de fevereiro"
, "20/2"
]
, examples (datetime (1974, 10, 31, 0, 0, 0) Day)
[ "31/10/1974"
, "31/10/74"
]
, examples (datetime (2013, 2, 19, 0, 0, 0) Day)
[ "próxima terça-feira"
, "próxima terça feira"
, "próxima terça"
, "proxima terça-feira"
, "proxima terça feira"
, "proxima terça"
]
, examples (datetime (2013, 2, 20, 0, 0, 0) Day)
[ "quarta que vem"
, "quarta da semana que vem"
, "quarta da próxima semana"
]
, examples (datetime (2013, 2, 12, 0, 0, 0) Day)
[ "terça desta semana"
, "terça dessa semana"
, "terça agora"
]
, examples (datetime (2013, 2, 11, 0, 0, 0) Week)
[ "esta semana"
]
, examples (datetime (2013, 2, 4, 0, 0, 0) Week)
[ "semana passada"
, "semana anterior"
, "passada semana"
, "anterior semana"
, "última semana"
, "ultima semana"
]
, examples (datetime (2013, 2, 18, 0, 0, 0) Week)
[ "semana que vem"
, "proxima semana"
]
, examples (datetime (2013, 1, 0, 0, 0, 0) Month)
[ "mês passado"
]
, examples (datetime (2013, 3, 0, 0, 0, 0) Month)
[ "mes que vem"
, "próximo mês"
]
, examples (datetime (2012, 0, 0, 0, 0, 0) Year)
[ "ano passado"
]
, examples (datetime (2013, 0, 0, 0, 0, 0) Year)
[ "este ano"
]
, examples (datetime (2014, 0, 0, 0, 0, 0) Year)
[ "ano que vem"
, "proximo ano"
]
, examples (datetime (2013, 2, 10, 0, 0, 0) Day)
[ "domingo passado"
, "domingo da semana passada"
]
, examples (datetime (2013, 2, 5, 0, 0, 0) Day)
[ "terça passada"
]
, examples (datetime (2013, 2, 12, 15, 0, 0) Hour)
[ "às tres da tarde"
, "às tres"
, "às 3 pm"
, "às 15 horas"
]
, examples (datetime (2013, 2, 12, 20, 0, 0) Hour)
[ "às oito da noite"
]
, examples (datetime (2013, 2, 13, 20, 0, 0) Hour)
[ "amanhã às oito da noite"
]
, examples (datetime (2013, 2, 15, 18, 0, 0) Hour)
[ "no dia 15 às 18"
, "dia 15 às 18"
, "dia 15 às 18 horas"
, "dia 15 às dezoito"
, "dia quinze às dezoito"
]
, examples (datetime (2013, 2, 14, 18, 0, 0) Hour)
[ "quinta-feira às 18 horas"
, "quinta às 18"
]
, examples (datetime (2013, 2, 15, 18, 15, 0) Minute)
[ "dia 15 de Fevereiro às 18:15"
, "dia 15 às 18:15"
]
, examples (datetime (2013, 2, 12, 15, 0, 0) Minute)
[ "15:00"
, "15.00"
, "às 15:00"
, "às 15.00"
]
, examples (datetime (2013, 2, 13, 0, 0, 0) Hour)
[ "meianoite"
, "meia noite"
]
, examples (datetime (2013, 2, 12, 12, 0, 0) Hour)
[ "meio dia"
, "meiodia"
]
, examples (datetime (2013, 2, 12, 12, 15, 0) Minute)
[ "meio dia e quinze"
]
, examples (datetime (2013, 2, 12, 11, 55, 0) Minute)
[ "5 para meio dia"
]
, examples (datetime (2013, 2, 12, 12, 30, 0) Minute)
[ "meio dia e meia"
]
, examples (datetime (2013, 2, 12, 6, 0, 0) Hour)
[ "as seis da manha"
, "as seis pela manha"
]
, examples (datetime (2013, 2, 12, 15, 15, 0) Minute)
[ "às tres e quinze"
, "às tres e quinze da tarde"
, "às tres e quinze pela tarde"
, "15:15"
, "15.15"
]
, examples (datetime (2013, 2, 12, 15, 30, 0) Minute)
[ "às tres e meia"
, "às 3 e trinta"
, "às tres e meia da tarde"
, "às 3 e trinta da tarde"
, "15:30"
, "15.30"
]
, examples (datetime (2013, 2, 12, 11, 45, 0) Minute)
[ "quinze para meio dia"
, "quinze para o meio dia"
, "11:45"
, "as onze e quarenta e cinco"
, "hoje quinze para o meio dia"
, "hoje às onze e quarenta e cinco"
]
, examples (datetime (2013, 2, 12, 5, 15, 0) Minute)
[ "5 e quinze"
]
, examples (datetime (2013, 2, 12, 6, 0, 0) Hour)
[ "6 da manhã"
]
, examples (datetime (2013, 2, 13, 11, 0, 0) Hour)
[ "quarta às onze da manhã"
]
, examples (datetime (2014, 9, 12, 0, 0, 0) Day)
[ "sexta, 12 de setembro de 2014"
, "sexta feira, 12 de setembro de 2014"
, "12 de setembro de 2014, sexta"
, "12 de setembro de 2014 sexta feira"
, "sexta feira 12 de setembro de 2014"
]
, examples (datetime (2013, 2, 12, 4, 30, 1) Second)
[ "em um segundo"
]
, examples (datetime (2013, 2, 12, 4, 31, 0) Second)
[ "em um minuto"
, "em 1 min"
]
, examples (datetime (2013, 2, 12, 4, 32, 0) Second)
[ "em 2 minutos"
, "em dois minutos"
]
, examples (datetime (2013, 2, 12, 5, 30, 0) Second)
[ "em 60 minutos"
]
, examples (datetime (2013, 2, 12, 5, 30, 0) Minute)
[ "em uma hora"
]
, examples (datetime (2013, 2, 12, 2, 30, 0) Minute)
[ "fazem duas horas"
]
, examples (datetime (2013, 2, 13, 4, 30, 0) Minute)
[ "em 24 horas"
, "em vinte e quatro horas"
]
, examples (datetime (2013, 2, 13, 4, 0, 0) Hour)
[ "em um dia"
]
, examples (datetime (2013, 2, 19, 4, 0, 0) Hour)
[ "em 7 dias"
]
, examples (datetime (2013, 2, 19, 0, 0, 0) Day)
[ "em uma semana"
]
, examples (datetime (2013, 1, 22, 0, 0, 0) Day)
[ "faz tres semanas"
, "faz três semanas"
]
, examples (datetime (2013, 4, 12, 0, 0, 0) Day)
[ "em dois meses"
]
, examples (datetime (2012, 11, 12, 0, 0, 0) Day)
[ "faz tres meses"
]
, examples (datetime (2014, 2, 0, 0, 0, 0) Month)
[ "em um ano"
, "em 1 ano"
]
, examples (datetime (2011, 2, 0, 0, 0, 0) Month)
[ "faz dois anos"
]
, examples (datetimeInterval ((2013, 6, 21, 0, 0, 0), (2013, 9, 24, 0, 0, 0)) Day)
[ "este verão"
, "este verao"
]
, examples (datetimeInterval ((2012, 12, 21, 0, 0, 0), (2013, 3, 21, 0, 0, 0)) Day)
[ "este inverno"
]
, examples (datetime (2013, 12, 25, 0, 0, 0) Day)
[ "Natal"
]
, examples (datetime (2013, 12, 31, 0, 0, 0) Day)
[ "véspera de ano novo"
]
, examples (datetime (2014, 1, 1, 0, 0, 0) Day)
[ "ano novo"
, "reveillon"
, "Reveillon"
]
, examples (datetimeInterval ((2013, 2, 12, 18, 0, 0), (2013, 2, 13, 0, 0, 0)) Hour)
[ "esta noite"
, "essa noite"
]
, examples (datetimeInterval ((2013, 2, 13, 18, 0, 0), (2013, 2, 14, 0, 0, 0)) Hour)
[ "amanhã a noite"
, "amanhã à noite"
]
, examples (datetimeInterval ((2013, 2, 11, 18, 0, 0), (2013, 2, 12, 0, 0, 0)) Hour)
[ "ontem a noite"
, "ontem à noite"
]
, examples (datetimeInterval ((2013, 2, 13, 12, 0, 0), (2013, 2, 13, 19, 0, 0)) Hour)
[ "amanhã a tarde"
, "amanhã à tarde"
]
, examples (datetimeInterval ((2013, 2, 11, 12, 0, 0), (2013, 2, 11, 19, 0, 0)) Hour)
[ "ontem a tarde"
, "ontem à tarde"
]
, examples (datetimeInterval ((2013, 2, 15, 18, 0, 0), (2013, 2, 18, 0, 0, 0)) Hour)
[ "este final de semana"
, "este fim de semana"
]
, examples (datetimeInterval ((2013, 2, 18, 4, 0, 0), (2013, 2, 18, 12, 0, 0)) Hour)
[ "segunda de manhã"
]
, examples (datetimeInterval ((2013, 2, 15, 4, 0, 0), (2013, 2, 15, 12, 0, 0)) Hour)
[ "dia 15 de fevereiro pela manhã"
, "dia 15 de fevereiro de manhã"
]
, examples (datetime (2013, 2, 12, 20, 0, 0) Hour)
[ "às 8 da noite"
]
, examples (datetimeInterval ((2013, 2, 12, 4, 29, 58), (2013, 2, 12, 4, 30, 0)) Second)
[ "2 segundos atras"
]
, examples (datetimeInterval ((2013, 2, 12, 4, 30, 1), (2013, 2, 12, 4, 30, 4)) Second)
[ "proximos 3 segundos"
]
, examples (datetimeInterval ((2013, 2, 12, 4, 28, 0), (2013, 2, 12, 4, 30, 0)) Minute)
[ "2 minutos atrás"
]
, examples (datetimeInterval ((2013, 2, 12, 4, 31, 0), (2013, 2, 12, 4, 34, 0)) Minute)
[ "proximos 3 minutos"
]
, examples (datetimeInterval ((2013, 2, 12, 5, 0, 0), (2013, 2, 12, 8, 0, 0)) Hour)
[ "proximas 3 horas"
]
, examples (datetimeInterval ((2013, 2, 10, 0, 0, 0), (2013, 2, 12, 0, 0, 0)) Day)
[ "passados 2 dias"
]
, examples (datetimeInterval ((2013, 2, 13, 0, 0, 0), (2013, 2, 16, 0, 0, 0)) Day)
[ "proximos 3 dias"
]
, examples (datetimeInterval ((2013, 1, 28, 0, 0, 0), (2013, 2, 11, 0, 0, 0)) Week)
[ "duas semanas atras"
]
, examples (datetimeInterval ((2013, 2, 18, 0, 0, 0), (2013, 3, 11, 0, 0, 0)) Week)
[ "3 proximas semanas"
, "3 semanas que vem"
]
, examples (datetimeInterval ((2012, 12, 0, 0, 0, 0), (2013, 2, 0, 0, 0, 0)) Month)
[ "passados 2 meses"
, "últimos 2 meses"
, "2 meses anteriores"
, "2 últimos meses"
, "2 anteriores meses"
]
, examples (datetimeInterval ((2013, 3, 0, 0, 0, 0), (2013, 6, 0, 0, 0, 0)) Month)
[ "3 próximos meses"
, "proximos tres meses"
, "tres meses que vem"
]
, examples (datetimeInterval ((2011, 0, 0, 0, 0, 0), (2013, 0, 0, 0, 0, 0)) Year)
[ "passados 2 anos"
, "últimos 2 anos"
, "2 anos anteriores"
, "2 últimos anos"
, "2 anteriores anos"
]
, examples (datetimeInterval ((2014, 0, 0, 0, 0, 0), (2017, 0, 0, 0, 0, 0)) Year)
[ "3 próximos anos"
, "proximo tres anos"
, "3 anos que vem"
]
, examples (datetimeInterval ((2013, 7, 13, 0, 0, 0), (2013, 7, 16, 0, 0, 0)) Day)
[ "13 a 15 de julho"
, "13 - 15 de julho de 2013"
]
, examples (datetimeInterval ((2013, 2, 12, 9, 30, 0), (2013, 2, 12, 11, 1, 0)) Minute)
[ "9:30 - 11:00"
]
, examples (datetimeInterval ((2013, 12, 21, 0, 0, 0), (2014, 1, 7, 0, 0, 0)) Day)
[ "21 de Dez. a 6 de Jan"
]
, examples (datetimeInterval ((2013, 2, 12, 4, 30, 0), (2013, 2, 12, 7, 30, 0)) Second)
[ "dentro de tres horas"
]
, examples (datetime (2013, 2, 12, 16, 0, 0) Hour)
[ "as quatro da tarde"
]
, examples (datetime (2013, 2, 12, 13, 0, 0) Minute)
[ "as quatro CET"
]
, examples (datetimeOpenInterval After (2013, 2, 12, 12, 0, 0) Hour)
[ "após ao meio dia"
, "depois do meio dia"
]
, examples (datetimeOpenInterval Before (2013, 2, 12, 12, 0, 0) Hour)
[ "antes do meio dia"
, "não mais que meio dia"
]
, examples (datetimeOpenInterval After (2013, 2, 13, 15, 0, 0) Hour)
[ "amanhã depois das 15hs"
, "amanha após as quinze horas"
]
, examples (datetimeOpenInterval Before (2013, 2, 13, 0, 0, 0) Hour)
[ "antes da meia noite"
, "até a meia noite"
]
,examples (datetime (2013, 2, 12, 3, 0, 0) Hour)
[ "última hora"
, "hora anterior"
, "hora passada"
]
, examples (datetime (2013, 1, 1, 0, 0, 0) Quarter)
[ "este trimestre"
, "trimestre actual"
, "trimestre atual"
]
, examples (datetime (2013, 1, 1, 0, 0, 0) Month)
[ "primeiro mês de 2013"
, "primeiro mês 2013"
]
, examples (datetime (2013, 4, 1, 0, 0, 0) Quarter)
[ "próximo trimestre"
, "segundo trimestre de 2013"
, "segundo trimestre"
]
, examples (datetime (2013, 7, 1, 0, 0, 0) Quarter)
[ "terceiro trimestre"
]
, examples (datetime (2018, 10, 1, 0, 0, 0) Quarter)
[ "quarto trimestre de 2018"
, "quarto trimestre 2018"
]
, examples (datetime (2012, 10, 1, 0, 0, 0) Quarter)
[ "trimestre passado"
, "trimestre anterior"
, "último trimestre"
, "ultimo trimestre"
]
, examples (datetime (2013, 12, 1, 0, 0, 0) Month)
[ "décimo segundo mês de 2013"
, "último mês de 2013"
, "último mês 2013"
]
, examples (datetime (2015, 10, 1, 0, 0, 0) Quarter)
[ "último trimestre de 2015"
, "último trimestre 2015"
]
, examples (datetimeInterval ((2013, 7, 13, 0, 0, 0), (2013, 7, 16, 0, 0, 0)) Day)
[ "desde 13 a 15 de Julho"
, "a partir de 13 até 15 de Julho"
, "desde 13 até 15 de Julho"
, "13-15 de Julho"
, "13 até 15 de Julho"
, "13 a 15 de Julho"
, "desde 13 a 15 Julho"
, "a partir de 13 até 15 Julho"
, "desde 13 até 15 Julho"
, "13-15 Julho"
, "13 até 15 Julho"
, "13 a 15 Julho"
]
, examples (datetimeInterval ((2017, 1, 1, 0, 0, 0), (2017, 10, 1, 0, 0, 0)) Quarter)
[ "de primeiro trimestre de 2017 até terceiro trimestre de 2017"
, "de primeiro trimestre de 2017 até ao terceiro trimestre de 2017"
, "do primeiro trimestre de 2017 até terceiro trimestre de 2017"
, "do primeiro trimestre de 2017 até ao terceiro trimestre de 2017"
, "desde primeiro trimestre de 2017 até terceiro trimestre de 2017"
, "desde primeiro trimestre de 2017 até ao terceiro trimestre de 2017"
, "a partir do primeiro trimestre de 2017 até terceiro trimestre de 2017"
, "a partir do primeiro trimestre de 2017 até ao terceiro trimestre de 2017"
, "a partir de primeiro trimestre de 2017 até terceiro trimestre de 2017"
, "a partir de primeiro trimestre de 2017 até ao terceiro trimestre de 2017"
, "primeiro trimestre de 2017 a terceiro trimestre de 2017"
, "primeiro trimestre de 2017 ao terceiro trimestre de 2017"
, "primeiro trimestre de 2017 - terceiro trimestre de 2017"
, "entre primeiro trimestre de 2017 e terceiro trimestre de 2017"
, "entre o primeiro trimestre de 2017 e terceiro trimestre de 2017"
, "primeiro trimestre de 2017 até terceiro trimestre de 2017"
, "primeiro trimestre de 2017 até ao terceiro trimestre de 2017"
, "primeiro trimestre 2017 a terceiro trimestre 2017"
, "primeiro trimestre 2017 ao terceiro trimestre 2017"
, "primeiro trimestre 2017 - terceiro trimestre 2017"
, "primeiro trimestre 2017 até terceiro trimestre 2017"
, "primeiro trimestre 2017 até ao terceiro trimestre 2017"
, "entre primeiro trimestre 2017 e terceiro trimestre 2017"
, "entre o primeiro trimestre 2017 e terceiro trimestre 2017"
]
, examples (datetimeInterval ((2017, 3, 1, 0, 0, 0), (2017, 10, 1, 0, 0, 0)) Month)
[ "de terceiro mês de 2017 até nono mês de 2017"
, "de terceiro mês de 2017 até ao nono mês de 2017"
, "do terceiro mês de 2017 até nono mês de 2017"
, "do terceiro mês de 2017 até ao nono mês de 2017"
, "desde terceiro mês de 2017 até nono mês de 2017"
, "desde terceiro mês de 2017 até ao nono mês de 2017"
, "a partir do terceiro mês de 2017 até nono mês de 2017"
, "a partir do terceiro mês de 2017 até ao nono mês de 2017"
, "a partir de terceiro mês de 2017 até nono mês de 2017"
, "a partir de terceiro mês de 2017 até ao nono mês de 2017"
, "terceiro mês de 2017 a nono mês de 2017"
, "terceiro mês de 2017 ao nono mês de 2017"
, "terceiro mês de 2017 - nono mês de 2017"
, "entre terceiro mês de 2017 e nono mês de 2017"
, "entre o terceiro mês de 2017 e nono mês de 2017"
, "terceiro mês de 2017 até nono mês de 2017"
, "terceiro mês de 2017 até ao nono mês de 2017"
, "terceiro mês 2017 a nono mês 2017"
, "terceiro mês 2017 ao nono mês 2017"
, "terceiro mês 2017 - nono mês 2017"
, "terceiro mês 2017 até nono mês 2017"
, "terceiro mês 2017 até ao nono mês 2017"
, "entre terceiro mês 2017 e nono mês 2017"
, "entre o terceiro mês 2017 e nono mês 2017"
]
]
|
d910e3fad5a60930febf7657e48cba88447c3c82f2502bf96e7d0b8c967c8191 | ucsd-progsys/mist | mochi-l-isort.hs | undefined as rforall a. a
undefined = 0
assert as {safe:Bool | safe == True} -> Int
assert = 0
makePair as rforall a, b. fst:a -> snd:b -> Pair >a >b
makePair = undefined
fst as rforall a, b. pair:(Pair >a >b) -> a
fst = undefined
snd as rforall a, b. pair:(Pair >a >b) -> b
snd = undefined
nil :: Pair >Int >({v:Int | False} -> Int)
nil = makePair 0 (\i -> assert False)
cons :: x:Int -> (Pair >Int >(Int -> Int)) -> Pair >Int >(i:Int -> {v:Int | (i = 0) => (v = x)})
cons = \x xs ->
makePair ((fst xs) + 1) (\i -> if i = 0 then x else (snd xs) (i - 1))
-- hd :: out:Int ~> (Pair >Int >(i:Int -> {v:Int | (i = 0) => (v = out)})) -> {v:Int | v = out}
hd :: (Pair >Int >(Int -> Int)) -> Int
hd = \p -> (snd p) 0
tl :: (Pair >Int >(Int -> Int)) -> Pair >Int >(Int -> Int)
tl = \p -> makePair ((fst p) - 1) (\i -> (snd p) (i + 1))
isNil :: (Pair >Int >(Int -> Int)) -> {v:Bool | v = (len = 0)}
isNil = \p -> (fst p) == 0
insert :: x:Int -> (Pair >Int >(Int -> Int)) -> Pair >Int >(Int -> Int)
insert = \x ys ->
if isNil ys then
cons x nil
else
if x <= (hd ys) then
cons x ys
else
cons (hd ys) (insert x (tl ys))
forAll : : s:(Set > Int ) ~ > n : Int ~ > ( { v : Int | v ∈ s } - > { v : | v } ) - > ( Pair > { v : Int | v = n } > ( { v : Int | v < n } - > { v : Int | v ∈ s } ) ) - > { v : | v }
-- forAll = \f xs ->
-- if isNil xs then
-- True
-- else
-- (f (hd xs)) /\ (forAll f (tl xs))
-- main :: Int -> Unit
main = \len - > assert ( forAll ( \x - > x < = len ) ( makePair len ( \i - > len - i ) ) )
| null | https://raw.githubusercontent.com/ucsd-progsys/mist/0a9345e73dc53ff8e8adb8bed78d0e3e0cdc6af0/tests/Tests/Integration/todo/mochi-l-isort.hs | haskell | hd :: out:Int ~> (Pair >Int >(i:Int -> {v:Int | (i = 0) => (v = out)})) -> {v:Int | v = out}
forAll = \f xs ->
if isNil xs then
True
else
(f (hd xs)) /\ (forAll f (tl xs))
main :: Int -> Unit | undefined as rforall a. a
undefined = 0
assert as {safe:Bool | safe == True} -> Int
assert = 0
makePair as rforall a, b. fst:a -> snd:b -> Pair >a >b
makePair = undefined
fst as rforall a, b. pair:(Pair >a >b) -> a
fst = undefined
snd as rforall a, b. pair:(Pair >a >b) -> b
snd = undefined
nil :: Pair >Int >({v:Int | False} -> Int)
nil = makePair 0 (\i -> assert False)
cons :: x:Int -> (Pair >Int >(Int -> Int)) -> Pair >Int >(i:Int -> {v:Int | (i = 0) => (v = x)})
cons = \x xs ->
makePair ((fst xs) + 1) (\i -> if i = 0 then x else (snd xs) (i - 1))
hd :: (Pair >Int >(Int -> Int)) -> Int
hd = \p -> (snd p) 0
tl :: (Pair >Int >(Int -> Int)) -> Pair >Int >(Int -> Int)
tl = \p -> makePair ((fst p) - 1) (\i -> (snd p) (i + 1))
isNil :: (Pair >Int >(Int -> Int)) -> {v:Bool | v = (len = 0)}
isNil = \p -> (fst p) == 0
insert :: x:Int -> (Pair >Int >(Int -> Int)) -> Pair >Int >(Int -> Int)
insert = \x ys ->
if isNil ys then
cons x nil
else
if x <= (hd ys) then
cons x ys
else
cons (hd ys) (insert x (tl ys))
forAll : : s:(Set > Int ) ~ > n : Int ~ > ( { v : Int | v ∈ s } - > { v : | v } ) - > ( Pair > { v : Int | v = n } > ( { v : Int | v < n } - > { v : Int | v ∈ s } ) ) - > { v : | v }
main = \len - > assert ( forAll ( \x - > x < = len ) ( makePair len ( \i - > len - i ) ) )
|
95c9149433fad51d1575544f45a35eec5a5c5296fc043b84f7d551e649a91bc2 | TheClimateCorporation/lemur | sample-jobdef.clj | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Sample
;;; This job does nothing
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; The symbols of lemur.core and lemur.command-line are
; automatically refer'ed in and the following namespaces are required for you:
; clojure.java.io :as io
; clojure.string :as s
; clojure.tools.logging :as log
; com.climate.shell :as sh
; lemur.util :as util
com.climate.services.aws.emr : as
; com.climate.services.aws.s3 :as s3
; com.climate.services.aws.ec2 :as ec2
(comment ***
Run "lemur help" for an overview and description of the concepts and
syntax in this file.
***)
;;; Set the defaults
Essentially , this does a Clojure ( use ) , so all symbols from each base are automatically
; referred into your jobdef's namespace. If this causes name collisions or you want more
control , you can use require or other standard Clojure constructs ( e.g. : only ) .
(use-base
; optional, lemur.base is always included automatically
'your.org.base)
;;; Command line processing
;;; Catch args
; Additional command line options to accept. You DO NOT need to specify
; options that ONLY your hadoop job expects-- use args.passthrough to let those
; options (i.e. :remaining) pass on to your hadoop job. However, you may want to
; specify a fn to validate (:remaining eopts) before the hadoop job is triggered
; (see Custom options validation below).
; Each argument is either
;
; 1) a vector [:option-name doc-string default-value?]
; where option-name is a keyword. If the option is a boolean flag, it's name
; should end with '?', and then no value will be expected on the command line,
; default-value is optional; or
;
; 2) a pair of values, :option-name doc-string
;
;(catch-args
; [:dummy "do nothing with this value" "dummy-default"]
; :foo? "the foo flag"
; [:bar "bar help text" (fn [eopts] (:dummy eopts))])
;
The --bar example uses a fn for the default . When the command line help is printed ,
; the fn value is not very helpful to the user. As an alternative, you can supply some
; text that should be used to document the default value. This can be done be putting
: default - doc metadata on the function . Here are two ways to do that :
;
1 . [: bar " bar help text " ( with - meta ( fn [ eopts ] (: dummy eopts ) ) { : default - doc " same as dummy " } ) ]
; or
2 . ( defn ^{:default - doc " same as dummy " } barfn
; []
; (:dummy eopts))
; and in (catch-args)
[: bar " bar help text " ( ) ]
In the last line , pddd is necessary , b / c defn puts that metadat on the var , rather than the fn itself .
;
Also note that you can specify default values in ( see
" Defaults for command line options " ) . A default in defcluster or a base will
; take precedence over a default in catch-args. BUT this default will NOT appear
; in the help documentation printed for "lemur help path/to/jobdef.clj"
;
; Also note that args defined in your defstep are automatically added to catch-args
;;; Profiles
; Enable the profile :foo, which means that values in the nested map :foo will
; override other entries. Generally, profiles would be enabled on the command
; line, but it is possible to do it in the jobdef like this.
;(add-profiles [:foo])
;;; Custom options validation
; OPTIONAL. A set of functions that are run before your job is started to validate the
; command line options, environment or anything else you like.
;
Each function is either a 0 - arg function or a 1 - arg function . In the latter case , eopts
is passed in . eopts includes all your values in defcluster , the command line options ,
; defaults, values from bases, etc). The function returns a String, vector of Strings
; or false on failure (the strings will be output as the failure message). On success
; the fn should return nil or true or '().
;
; You can write your own functions for arbitrary checks (consider using the helper
; functions: lemur.core/lfn, and/or lemur.common/mk-validator). However, for many common
; cases, you can use lemur.common/val-opts and lemur.common/val-remaining; which provide
; a declarative method for specifying validations.
;
; RECOMMENDED defining validators can save time by avoiding a cluster launch that fails
; because of missing/bad options. In particular, remember to write a validator
; to check :remaining. Any options that are not caught are left in remaining,
; so if someone mis-types an option it could show up here.
;
; EXAMPLES
;(add-validators
( lfn [ dataset ]
; (if-not
( contains ? # { " ahps " " stage_iv " } dataset )
" --dataset must be specified as ' ahps ' or ' stage_iv ' " ) )
( - opts : file : days - file )
( - opts : required : numeric : num - days ) )
;;; Hooks (actions)
While you can include arbitrary Clojure code anywhere , use hooks for a more
; structured approach to executing actions as part of your job.
;(add-hooks
; [optional-boolean-expr] function-to-execute
; ...
; )
;;; Define cluster
; See note above on map values
(defcluster sample-cluster
DEFAULT values
; The defaults from (base) are shown. If you include other files in (use-base)
; then they might change the defaults. However, if the option has no default
; (as noted below), then an example is shown.
; A symbolic name for this job.
The default is the cluster name specified as the first arg to
;:app "${jobdef-file}"
; The name of the cluster (aka jobflow), visible in AWS console or elastic-mapreduce listings
;:emr-name "${run-id}"
; Enable this feature, to save the details of the job (options, bootstrap-actions,
; steps with their args, uploads, args, etc) to "${base-uri}/METAJOB.yml".
: - file true
; The bucket name in s3 where emr logs, data, scripts, etc will be stored.
;:bucket "com.your-co.${env}.hadoop"
; A local path where your jar exists. If specified, it will be uploaded to S3 automatically.
; REQUIRED.
;:jar-src-path "build/your-hadoop-java.jar"
;:ec2 {:jar-src-path "/location/of/your/deployed/hadoop-java.jar"}
; An s3 path for the hadoop job jar. Takes precedence over jar-src-path.
; NO DEFAULT
;:runtime-jar "s3-co.${env}.hadoop/marc/my-hadoop-java.jar"
; Number of instances (including the master)
: num - instances 1
; Instance type for slaves
;:slave-instance-type "m1.large"
; Instance type for master
;:master-instance-type "m1.large"
; Provide a comma-separated list of key=value pairs, which will be used to
create tags for instances in your cluster . Read more at
; -plan-tags.html
;:tags "fake:project=fightingcrime,fake:group=ateam"
; Uncomment to attempt to get additional nodes via the spot market
This example requests up to 30 additional m1.xlarge nodes , and we are willing to
pay up to 80 % of the difference between the reserve price and the demand price .
NO DEFAULT . Example :
;:spot-task-group "m1.xlarge,80%,30"
; To keep the cluster alive after running the job steps, change this to true.
; In particular, if your job is failing, and you want to debug on the live cluster,
; set this option to true.
;:keep-alive? false
; The keypair file to use (this is just a short name, not a pathname)
; EXAMPLE
;:keypair "your-keypair"
; Set true to enable debugging, which simply indexes the log files
so they can be accessed from the AWS console . No impact on performance .
;:enable-debugging? true
To enable ec2 monitoring ( basic stats are collected and viewable in the AWS console ) , set to true
;:enable-ec2-monitoring false
; The location of the bootstrap action scripts (a local path). All scripts in this
; directory will be uploaded to S3.
; REQUIRED
;:scripts-src-path "location/of/your/bootstrap-scripts"
;:ec2 {:scripts-src-path "/deployed/location/of/your/bootstrap-scripts"}
; run-path is used to determine the base-uri
;:run-path "${run-id}"
; To use the same paths every time, try this:
;:run-path "${app}/shared-data"
; The base-uri is the S3 root path for all things associated with the current run.
;:base-uri "s3://${bucket}/runs/${run-path}"
;:local {:base-uri "/${ENV.HOME}/lemur/${run-path}"}
; The S3 location where the cluster logs will be stored (AFTER CLUSTER SHUTDOWN)
;:log-uri "${base-uri}/emr-logs"
; The S3 prefix where data should be stored. If :args.data-uri is true, this path will be passed
; as an argument to your hadoop job. It is intended to be the output path for any generated data
; that should be persistent.
;:data-uri "${base-uri}/data"
; The location under base-uri where your uploaded bootstrap-action scripts will be saved.
; REQUIRED
;:std-scripts-prefix "runs/${run-id}/emr-bootstrap"
; Uploads
Specify files that should be uploaded from your local fs to s3 ( or s3 to s3 , or local to local ) .
; Each file can be absolute or relative, and can name a file or a directory (directories are processed
; recursively). The default destination is ${data-uri} (also note that this works in local mode,
; since $(data-uri} is automatically set to a local path in that case). If you want to specify a different
; destination, follow your source path by :to and then another string which is the dest. Again, this dest
; string can be relative or absolute, and can be a local path or an s3 path. If it is not an absolute
; path, than it is considered relative to ${data-uri} (i.e. "the remote working directory").
NO DEFAULT . Examples :
: upload [ " file1 " " /tmp / " ]
; Results in
- file1 from your CWD uploaded to $ { data - uri}/file1
- /tmp / uploaded to $ { data - uri}/file2
;:upload ["file"
; "bar/file" :to "COUNTIES"
; ;in the next line, the / at the end of cropy is significant, see below
; "/tmp/input-dir" :to "cropy/"
; Next one is [src dest]. Useful if you're constructing the structure from a function
[ " ./foo.txt " " data.txt " ]
; "/tmp/input-dir" :to "s3://${bucket}/foo"]
; Results in
- file from your CWD uploaded to $ { data - uri}/file
- bar / file from your CWD uploaded to $ { data - uri}/COUNTIES
; - /tmp/input-dir uploaded to ${data-uri}/cropy/input-dir
; input-dir is copied under cropy b/c of the trailing slash above
; - ./foo.txt uploaded to ${data-uri}/data.txt
; - /tmp/input-dir uploaded to "s3://${bucket}/foo"
; Enable this feature, so that uploads to S3 will display an ascii progress bar during
; the transfer to give you an indication of how long the upload will take.
;:show-progress? true
; Additional bootstrap actions can be added by using a key of the form
; :bootstrap-action.N
; Where N is a unique integer which indicates the order in which the scripts should
be executed . Use " lemur dry - run " to display the that are currently set .
; The value can be (literally or as the result of a fn) any of:
; - nil
; do nothing (maybe as the result of a fn with a conditional; or as a way to
; skip a bootstrap-action defined in a base)
; - [ba-name script-name-or-path args]
; ba-name is an arbitrary string used to label the script when it is run
; script-name-or-path is either a simple name like "my-config.sh" or a full path
; starting with "s3://". If you supply a name only, it will be looked for under
; :std-scripts-prefix of the :bucket. See :scripts-src-path above, generally
; anything in that location can just be referred to by name.
args is a vector of string arguments for the BA script
; - [ba-name script-name-or-path]
; as above, but no arguments for the script
; - [script-name-or-path]
; as above, but ba-name will be "Custom Config"
; Example:
;:bootstrap-action.N "s3"
; Modify the hadoop configuration. Any key starting with ":hadoop-config." is
; concatenated to the default config (see :hadoop-config.* in
; lemur.base/update-base). The part of the key following the dot is ignored,
; but serves to avoid overlap with hadoop-config keys from any included base.
; Use "lemur dry-run <job-def.clj>" to see the current hadoop-config. keys.
;
The value is a collection of strings , which are the args passed to Amazon 's hadoop
; bootstrap-action script:
"
In short , the config consists of pairs : the first entry is -c , -m or -h and indicates the
; hadoop config file that should be modified.
; "-c" => "/home/hadoop/conf/core-site.xml"
; "-h" => "/home/hadoop/conf/hdfs-site.xml"
; "-m" => "/home/hadoop/conf/mapred-site.xml"
And the second is a name = value to add to the file .
;
NOTE : since this is implemented via a Bootstrap Action , it has no impact in local mode .
;
For example , the entry below sets the max map tasks to 7 .
: hadoop-config.custom [ " -m " " mapred.tasktracker.map.tasks.maximum=7 " ]
For local mode only , to set ENVIRONMENT VARIABLES for Hadoop , you can
; specify a Map of name value like this.
; EXAMPLE
: local { : hadoop - env { " HADOOP_HEAPSIZE " " 2048 " } }
; To run cluster in non default region, specify AWS API endpoint
; (list of endpoints #emr_region)
;:endpoint "elasticmapreduce.eu-west-1.amazonaws.com"
; To run cluster in VPC subnet, specify subnet's id
;:subnet-id "subnet-b35104f5"
)
Define one or more steps
(defstep sample-step
REQUIRED The classname for the class with the main function , i.e. the Hadoop
; job entry point
:main-class "com.your-co.some.Class"
; A symbolic name given to the step. This is what is displayed in a jobflow
listing and the AWS console .
DEFAULT is the name given to defstep minus ' -step ' suffix if it exists .
;:step-name "some other name"
; The jar to use for this step.
DEFAULT the jar specified in : runtime - jar or : jar - src - path , but this JAR is
; not copied under the base-uri path.
: step - jar " s3 / foo / bar.jar "
; Defaults for command line options
Same as for ( but limited in scope to the step )
; See the docs on "JOB ARGS" in help.txt
; :args.data-uri is RECOMMENDED. data-uri is important if you use local
; mode, as the value of :data-uri is adjusted for that purpose.
; Also note that args like :foo and :bar? below would be automatically added
; to (catch-args):
;:args.foo "some value"
;:args.bar false
;:args.positional ["foo" "bar"]
:args.passthrough true
:args.data-uri true
)
;;; Fire! (i.e. start the cluster and run the steps)
; fire! returns right away. The jobflow-id is saved (context-get :jobflow-id).
; (fire! cluster steps)
; steps is a list (in-line or collection) of steps to run, or a "fn of eopts",
which returns a step ( created by defstep or a StepConfig object ) or a collection of steps .
; cluster is defined by a previous defcluster, or a fn that returns a single cluster.
(fire! sample-cluster sample-step)
If you want to block on cluster startup , where < stage > is one of
; :provisioned
; :accepted
; :ready
;(wait <stage>)
; If you want to block on step completion use wait-on-step as below;
; returns a map with information on how the job completed. If the timeout expires it might look like
; {:timeout true, :success false}
; if the job completes before the timeout expires it might look like
; {:success true}
; Read the function documentation for more details.
;
( wait - on - step step timeout - seconds )
| null | https://raw.githubusercontent.com/TheClimateCorporation/lemur/00eb21b6f534ceefe354ab89042826188d156991/examples/sample-jobdef.clj | clojure |
Sample
This job does nothing
The symbols of lemur.core and lemur.command-line are
automatically refer'ed in and the following namespaces are required for you:
clojure.java.io :as io
clojure.string :as s
clojure.tools.logging :as log
com.climate.shell :as sh
lemur.util :as util
com.climate.services.aws.s3 :as s3
com.climate.services.aws.ec2 :as ec2
Set the defaults
referred into your jobdef's namespace. If this causes name collisions or you want more
optional, lemur.base is always included automatically
Command line processing
Catch args
Additional command line options to accept. You DO NOT need to specify
options that ONLY your hadoop job expects-- use args.passthrough to let those
options (i.e. :remaining) pass on to your hadoop job. However, you may want to
specify a fn to validate (:remaining eopts) before the hadoop job is triggered
(see Custom options validation below).
Each argument is either
1) a vector [:option-name doc-string default-value?]
where option-name is a keyword. If the option is a boolean flag, it's name
should end with '?', and then no value will be expected on the command line,
default-value is optional; or
2) a pair of values, :option-name doc-string
(catch-args
[:dummy "do nothing with this value" "dummy-default"]
:foo? "the foo flag"
[:bar "bar help text" (fn [eopts] (:dummy eopts))])
the fn value is not very helpful to the user. As an alternative, you can supply some
text that should be used to document the default value. This can be done be putting
or
[]
(:dummy eopts))
and in (catch-args)
take precedence over a default in catch-args. BUT this default will NOT appear
in the help documentation printed for "lemur help path/to/jobdef.clj"
Also note that args defined in your defstep are automatically added to catch-args
Profiles
Enable the profile :foo, which means that values in the nested map :foo will
override other entries. Generally, profiles would be enabled on the command
line, but it is possible to do it in the jobdef like this.
(add-profiles [:foo])
Custom options validation
OPTIONAL. A set of functions that are run before your job is started to validate the
command line options, environment or anything else you like.
defaults, values from bases, etc). The function returns a String, vector of Strings
or false on failure (the strings will be output as the failure message). On success
the fn should return nil or true or '().
You can write your own functions for arbitrary checks (consider using the helper
functions: lemur.core/lfn, and/or lemur.common/mk-validator). However, for many common
cases, you can use lemur.common/val-opts and lemur.common/val-remaining; which provide
a declarative method for specifying validations.
RECOMMENDED defining validators can save time by avoiding a cluster launch that fails
because of missing/bad options. In particular, remember to write a validator
to check :remaining. Any options that are not caught are left in remaining,
so if someone mis-types an option it could show up here.
EXAMPLES
(add-validators
(if-not
Hooks (actions)
structured approach to executing actions as part of your job.
(add-hooks
[optional-boolean-expr] function-to-execute
...
)
Define cluster
See note above on map values
The defaults from (base) are shown. If you include other files in (use-base)
then they might change the defaults. However, if the option has no default
(as noted below), then an example is shown.
A symbolic name for this job.
:app "${jobdef-file}"
The name of the cluster (aka jobflow), visible in AWS console or elastic-mapreduce listings
:emr-name "${run-id}"
Enable this feature, to save the details of the job (options, bootstrap-actions,
steps with their args, uploads, args, etc) to "${base-uri}/METAJOB.yml".
The bucket name in s3 where emr logs, data, scripts, etc will be stored.
:bucket "com.your-co.${env}.hadoop"
A local path where your jar exists. If specified, it will be uploaded to S3 automatically.
REQUIRED.
:jar-src-path "build/your-hadoop-java.jar"
:ec2 {:jar-src-path "/location/of/your/deployed/hadoop-java.jar"}
An s3 path for the hadoop job jar. Takes precedence over jar-src-path.
NO DEFAULT
:runtime-jar "s3-co.${env}.hadoop/marc/my-hadoop-java.jar"
Number of instances (including the master)
Instance type for slaves
:slave-instance-type "m1.large"
Instance type for master
:master-instance-type "m1.large"
Provide a comma-separated list of key=value pairs, which will be used to
-plan-tags.html
:tags "fake:project=fightingcrime,fake:group=ateam"
Uncomment to attempt to get additional nodes via the spot market
:spot-task-group "m1.xlarge,80%,30"
To keep the cluster alive after running the job steps, change this to true.
In particular, if your job is failing, and you want to debug on the live cluster,
set this option to true.
:keep-alive? false
The keypair file to use (this is just a short name, not a pathname)
EXAMPLE
:keypair "your-keypair"
Set true to enable debugging, which simply indexes the log files
:enable-debugging? true
:enable-ec2-monitoring false
The location of the bootstrap action scripts (a local path). All scripts in this
directory will be uploaded to S3.
REQUIRED
:scripts-src-path "location/of/your/bootstrap-scripts"
:ec2 {:scripts-src-path "/deployed/location/of/your/bootstrap-scripts"}
run-path is used to determine the base-uri
:run-path "${run-id}"
To use the same paths every time, try this:
:run-path "${app}/shared-data"
The base-uri is the S3 root path for all things associated with the current run.
:base-uri "s3://${bucket}/runs/${run-path}"
:local {:base-uri "/${ENV.HOME}/lemur/${run-path}"}
The S3 location where the cluster logs will be stored (AFTER CLUSTER SHUTDOWN)
:log-uri "${base-uri}/emr-logs"
The S3 prefix where data should be stored. If :args.data-uri is true, this path will be passed
as an argument to your hadoop job. It is intended to be the output path for any generated data
that should be persistent.
:data-uri "${base-uri}/data"
The location under base-uri where your uploaded bootstrap-action scripts will be saved.
REQUIRED
:std-scripts-prefix "runs/${run-id}/emr-bootstrap"
Uploads
Each file can be absolute or relative, and can name a file or a directory (directories are processed
recursively). The default destination is ${data-uri} (also note that this works in local mode,
since $(data-uri} is automatically set to a local path in that case). If you want to specify a different
destination, follow your source path by :to and then another string which is the dest. Again, this dest
string can be relative or absolute, and can be a local path or an s3 path. If it is not an absolute
path, than it is considered relative to ${data-uri} (i.e. "the remote working directory").
Results in
:upload ["file"
"bar/file" :to "COUNTIES"
;in the next line, the / at the end of cropy is significant, see below
"/tmp/input-dir" :to "cropy/"
Next one is [src dest]. Useful if you're constructing the structure from a function
"/tmp/input-dir" :to "s3://${bucket}/foo"]
Results in
- /tmp/input-dir uploaded to ${data-uri}/cropy/input-dir
input-dir is copied under cropy b/c of the trailing slash above
- ./foo.txt uploaded to ${data-uri}/data.txt
- /tmp/input-dir uploaded to "s3://${bucket}/foo"
Enable this feature, so that uploads to S3 will display an ascii progress bar during
the transfer to give you an indication of how long the upload will take.
:show-progress? true
Additional bootstrap actions can be added by using a key of the form
:bootstrap-action.N
Where N is a unique integer which indicates the order in which the scripts should
The value can be (literally or as the result of a fn) any of:
- nil
do nothing (maybe as the result of a fn with a conditional; or as a way to
skip a bootstrap-action defined in a base)
- [ba-name script-name-or-path args]
ba-name is an arbitrary string used to label the script when it is run
script-name-or-path is either a simple name like "my-config.sh" or a full path
starting with "s3://". If you supply a name only, it will be looked for under
:std-scripts-prefix of the :bucket. See :scripts-src-path above, generally
anything in that location can just be referred to by name.
- [ba-name script-name-or-path]
as above, but no arguments for the script
- [script-name-or-path]
as above, but ba-name will be "Custom Config"
Example:
:bootstrap-action.N "s3"
Modify the hadoop configuration. Any key starting with ":hadoop-config." is
concatenated to the default config (see :hadoop-config.* in
lemur.base/update-base). The part of the key following the dot is ignored,
but serves to avoid overlap with hadoop-config keys from any included base.
Use "lemur dry-run <job-def.clj>" to see the current hadoop-config. keys.
bootstrap-action script:
hadoop config file that should be modified.
"-c" => "/home/hadoop/conf/core-site.xml"
"-h" => "/home/hadoop/conf/hdfs-site.xml"
"-m" => "/home/hadoop/conf/mapred-site.xml"
specify a Map of name value like this.
EXAMPLE
To run cluster in non default region, specify AWS API endpoint
(list of endpoints #emr_region)
:endpoint "elasticmapreduce.eu-west-1.amazonaws.com"
To run cluster in VPC subnet, specify subnet's id
:subnet-id "subnet-b35104f5"
job entry point
A symbolic name given to the step. This is what is displayed in a jobflow
:step-name "some other name"
The jar to use for this step.
not copied under the base-uri path.
Defaults for command line options
See the docs on "JOB ARGS" in help.txt
:args.data-uri is RECOMMENDED. data-uri is important if you use local
mode, as the value of :data-uri is adjusted for that purpose.
Also note that args like :foo and :bar? below would be automatically added
to (catch-args):
:args.foo "some value"
:args.bar false
:args.positional ["foo" "bar"]
Fire! (i.e. start the cluster and run the steps)
fire! returns right away. The jobflow-id is saved (context-get :jobflow-id).
(fire! cluster steps)
steps is a list (in-line or collection) of steps to run, or a "fn of eopts",
cluster is defined by a previous defcluster, or a fn that returns a single cluster.
:provisioned
:accepted
:ready
(wait <stage>)
If you want to block on step completion use wait-on-step as below;
returns a map with information on how the job completed. If the timeout expires it might look like
{:timeout true, :success false}
if the job completes before the timeout expires it might look like
{:success true}
Read the function documentation for more details.
|
com.climate.services.aws.emr : as
(comment ***
Run "lemur help" for an overview and description of the concepts and
syntax in this file.
***)
Essentially , this does a Clojure ( use ) , so all symbols from each base are automatically
control , you can use require or other standard Clojure constructs ( e.g. : only ) .
(use-base
'your.org.base)
The --bar example uses a fn for the default . When the command line help is printed ,
: default - doc metadata on the function . Here are two ways to do that :
1 . [: bar " bar help text " ( with - meta ( fn [ eopts ] (: dummy eopts ) ) { : default - doc " same as dummy " } ) ]
2 . ( defn ^{:default - doc " same as dummy " } barfn
[: bar " bar help text " ( ) ]
In the last line , pddd is necessary , b / c defn puts that metadat on the var , rather than the fn itself .
Also note that you can specify default values in ( see
" Defaults for command line options " ) . A default in defcluster or a base will
Each function is either a 0 - arg function or a 1 - arg function . In the latter case , eopts
is passed in . eopts includes all your values in defcluster , the command line options ,
( lfn [ dataset ]
( contains ? # { " ahps " " stage_iv " } dataset )
" --dataset must be specified as ' ahps ' or ' stage_iv ' " ) )
( - opts : file : days - file )
( - opts : required : numeric : num - days ) )
While you can include arbitrary Clojure code anywhere , use hooks for a more
(defcluster sample-cluster
DEFAULT values
The default is the cluster name specified as the first arg to
: - file true
: num - instances 1
create tags for instances in your cluster . Read more at
This example requests up to 30 additional m1.xlarge nodes , and we are willing to
pay up to 80 % of the difference between the reserve price and the demand price .
NO DEFAULT . Example :
so they can be accessed from the AWS console . No impact on performance .
To enable ec2 monitoring ( basic stats are collected and viewable in the AWS console ) , set to true
Specify files that should be uploaded from your local fs to s3 ( or s3 to s3 , or local to local ) .
NO DEFAULT . Examples :
: upload [ " file1 " " /tmp / " ]
- file1 from your CWD uploaded to $ { data - uri}/file1
- /tmp / uploaded to $ { data - uri}/file2
[ " ./foo.txt " " data.txt " ]
- file from your CWD uploaded to $ { data - uri}/file
- bar / file from your CWD uploaded to $ { data - uri}/COUNTIES
be executed . Use " lemur dry - run " to display the that are currently set .
args is a vector of string arguments for the BA script
The value is a collection of strings , which are the args passed to Amazon 's hadoop
"
In short , the config consists of pairs : the first entry is -c , -m or -h and indicates the
And the second is a name = value to add to the file .
NOTE : since this is implemented via a Bootstrap Action , it has no impact in local mode .
For example , the entry below sets the max map tasks to 7 .
: hadoop-config.custom [ " -m " " mapred.tasktracker.map.tasks.maximum=7 " ]
For local mode only , to set ENVIRONMENT VARIABLES for Hadoop , you can
: local { : hadoop - env { " HADOOP_HEAPSIZE " " 2048 " } }
)
Define one or more steps
(defstep sample-step
REQUIRED The classname for the class with the main function , i.e. the Hadoop
:main-class "com.your-co.some.Class"
listing and the AWS console .
DEFAULT is the name given to defstep minus ' -step ' suffix if it exists .
DEFAULT the jar specified in : runtime - jar or : jar - src - path , but this JAR is
: step - jar " s3 / foo / bar.jar "
Same as for ( but limited in scope to the step )
:args.passthrough true
:args.data-uri true
)
which returns a step ( created by defstep or a StepConfig object ) or a collection of steps .
(fire! sample-cluster sample-step)
If you want to block on cluster startup , where < stage > is one of
( wait - on - step step timeout - seconds )
|
aed3eb326ff4b7a7c7c19c5bdae753616a6b20fd3e38f83547923cb3b0a6cdbb | aryx/yacfe | test.ml | open Common
(* try put stuff in parsing_c/test_parsing_c.ml or analyze_c/test_analyze_c.ml
* instead of in this file.
*)
open Ast_c
(*****************************************************************************)
(* to be called by ocaml toplevel, to test. *)
(*****************************************************************************)
let cprogram_of_file file =
(* useful only when called from toplevel *)
Flag_parsing_c.std_h := "/home/pad/c-yacfe/config/macros/standard.h";
Parse_c.init_defs !Flag_parsing_c.std_h;
let (program2, _stat) = Parse_c.parse_c_and_cpp file in
program2
(*****************************************************************************)
(* Misc *)
(*****************************************************************************)
(*****************************************************************************)
(* Main entry for Arg *)
(*****************************************************************************)
let actions () = [
]
| null | https://raw.githubusercontent.com/aryx/yacfe/86a4994822abca03ec9e03f1a7e60eca66db0a08/test.ml | ocaml | try put stuff in parsing_c/test_parsing_c.ml or analyze_c/test_analyze_c.ml
* instead of in this file.
***************************************************************************
to be called by ocaml toplevel, to test.
***************************************************************************
useful only when called from toplevel
***************************************************************************
Misc
***************************************************************************
***************************************************************************
Main entry for Arg
*************************************************************************** | open Common
open Ast_c
let cprogram_of_file file =
Flag_parsing_c.std_h := "/home/pad/c-yacfe/config/macros/standard.h";
Parse_c.init_defs !Flag_parsing_c.std_h;
let (program2, _stat) = Parse_c.parse_c_and_cpp file in
program2
let actions () = [
]
|
51527d671b88a45ee55f1a9d1e95dafb169f34b3d3f5a6b673761a2e827bc4d9 | t-cool/cl-lemma | main.lisp | (defpackage cl-lemma/tests/main
(:use :cl
:cl-lemma
:rove))
(in-package cl-lemma/tests/main)
;; NOTE: To run this test file, execute `(asdf:test-system :cl-lemma)' in your Lisp.
(deftest lemmatize
(testing "noun"
(ok (equal (cl-lemma:lemma "leaves" :noun) "leaf"))
(ok (equal (cl-lemma:lemma "libraries" :noun) "library"))
)
(testing "verb"
(ok (equal (cl-lemma:lemma "leaves" :verb) "leave"))
(ok (equal (cl-lemma:lemma "went" :verb) "go"))
(ok (equal (cl-lemma:lemma "abbreviated" :verb) "abbreviate"))
(ok (equal (cl-lemma:lemma "arisen" :verb) "arise"))
(ok (equal (cl-lemma:lemma "bound" :verb) "bind"))
)
(testing "adjective"
(ok (equal (cl-lemma:lemma "better" :adj) "good"))
)
(testing "adverb"
(ok (equal (cl-lemma:lemma "better" :adv) "well"))
)
(testing "general"
(ok (equal (cl-lemma:lemma "studied") "study"))
(ok (equal (cl-lemma:lemma "abbreviated") "abbreviate")) )
)
| null | https://raw.githubusercontent.com/t-cool/cl-lemma/e93f73d1cff2623cd0ba14083076c43d366e72f7/tests/main.lisp | lisp | NOTE: To run this test file, execute `(asdf:test-system :cl-lemma)' in your Lisp. | (defpackage cl-lemma/tests/main
(:use :cl
:cl-lemma
:rove))
(in-package cl-lemma/tests/main)
(deftest lemmatize
(testing "noun"
(ok (equal (cl-lemma:lemma "leaves" :noun) "leaf"))
(ok (equal (cl-lemma:lemma "libraries" :noun) "library"))
)
(testing "verb"
(ok (equal (cl-lemma:lemma "leaves" :verb) "leave"))
(ok (equal (cl-lemma:lemma "went" :verb) "go"))
(ok (equal (cl-lemma:lemma "abbreviated" :verb) "abbreviate"))
(ok (equal (cl-lemma:lemma "arisen" :verb) "arise"))
(ok (equal (cl-lemma:lemma "bound" :verb) "bind"))
)
(testing "adjective"
(ok (equal (cl-lemma:lemma "better" :adj) "good"))
)
(testing "adverb"
(ok (equal (cl-lemma:lemma "better" :adv) "well"))
)
(testing "general"
(ok (equal (cl-lemma:lemma "studied") "study"))
(ok (equal (cl-lemma:lemma "abbreviated") "abbreviate")) )
)
|
4c6c15d7d3c5022dc49e2bbcfb7eb5edd235887826b9bc805cb75597567bf0ca | re-path/studio | styles.cljs | (ns repath.studio.styles
(:require [stylefy.core :as stylefy]
[clojure.string :as str]))
(defn square-styles [size]
{:width size
:height size
:line-height size})
(defn ->!important
[value]
(str value " !important"))
(defn ->px
[value]
(str value "px"))
;; Load Source Sans Pro font
(stylefy/font-face {:font-family "Source Sans Pro"
:src "url('fonts/Source_Sans_Pro/SourceSansPro-Light.ttf')"
:font-weight "300"
:font-style "normal"})
(stylefy/font-face {:font-family "Source Sans Pro"
:src "url('fonts/Source_Sans_Pro/SourceSansPro-Regular.ttf')"
:font-weight "400"
:font-style "normal"})
(stylefy/font-face {:font-family "Source Sans Pro"
:src "url('fonts/Source_Sans_Pro/SourceSansPro-SemiBold.ttf')"
:font-weight "500"
:font-style "normal"})
(stylefy/font-face {:font-family "Source Sans Pro"
:src "url('fonts/Source_Sans_Pro/SourceSansPro-Bold.ttf')"
:font-weight "600"
:font-style "normal"})
;; Load Source Code Pro font
(stylefy/font-face {:font-family "Source Code Pro"
:src "url('fonts/Source_Code_Pro/SourceCodePro-Light.ttf')"
:font-weight "light"
:font-style "light"})
(stylefy/font-face {:font-family "Source Code Pro"
:src "url('fonts/Source_Code_Pro/SourceCodePro-Regular.ttf')"
:font-weight "normal"
:font-style "regular"})
(stylefy/font-face {:font-family "Source Code Pro"
:src "url('fonts/Source_Code_Pro/SourceCodePro-SemiBold.ttf')"
:font-weight "semi-bold"
:font-style "semibold"})
(stylefy/font-face {:font-family "Source Code Pro"
:src "url('fonts/Source_Code_Pro/SourceCodePro-Bold.ttf')"
:font-weight "bold"
:font-style "bold"})
(def font-family "Source Sans Pro")
(def font-family-mono "Source Code Pro")
;; SEE -and-palettes
( def level-0 " # 2E3440 " )
( def level-1 " # 3B4252 " )
( def level-2 " # 434C5E " )
( def level-3 " # 4C566A " )
( def active " # 4C566A " )
( def accent " # 88C0D0 " )
( def font - color " # " )
;; (def error-color "#BF616A")
( def font - color - disabled " rgba(255 , 255 , 255 , .3 ) " )
;; (def font-color-muted "##D8DEE9")
( def font - color - hovered " # ECEFF4 " )
( def font - color - active " rgba(255 , 255 , 255 , 1 ) " )
( def border - color " rgba(255 , 255 , 255 , ) " )
;; (def background-error "#BF616A")
;; (def background-warning "#D08770")
;; (def background-success "#A3BE8C")
;; Light Theme
( def level-0 " # d1d1d1 " )
;; (def level-1 "#e1e1e1")
;; (def level-2 "#eee")
;; (def level-3 "#fff")
;; (def active "#fff")
;; (def accent "#ec407a")
( def font - color " # rgba(0 , 0 , 0 , .8 ) " )
;; (def error-color "#f78484")
( def font - color - disabled " rgba(0 , 0 , 0 , .4 ) " )
;; (def font-color-muted "rgba(0, 0, 0, .6)")
;; (def font-color-hovered "#rgba(0, 0, 0, .95)")
( def font - color - active " rgba(0 , 0 , 0 , 1 ) " )
;; (def border-color "rgba(0, 0, 0, .15)")
( def background - error " # 962121 " )
;; (def background-warning "#a56a00")
;; (def background-success "#1c611c")
(def level-0 "#212121")
(def level-1 "#282828")
(def level-2 "#313131")
(def level-3 "#414141")
(def overlay "rgba(255, 255, 255, .1)")
(def accent "#ec407a")
(def font-color "rgba(255, 255, 255, .7)")
(def error-color "#f78484")
(def font-color-disabled "rgba(255, 255, 255, .3)")
(def font-color-muted "rgba(255, 255, 255, .5)")
(def font-color-hovered "rgba(255, 255, 255, .9)")
(def font-color-active "rgba(255, 255, 255, 1)")
(def border-color "rgba(255, 255, 255, .15)")
(def background-error "#962121")
(def background-warning "#a56a00")
(def background-success "#1c611c")
(stylefy/class "error" {:background background-error})
(stylefy/class "warning" {:background background-warning})
(stylefy/class "success" {:background background-success})
(def h-padding "12px")
(def v-padding "8px")
(def padding (str v-padding " " h-padding))
(def icon-size 17)
(def form-element-style
{:outline "none"
:background level-2
:border 0
:padding "4px 12px"
:box-sizing "border-box"
:line-height "18px"
:width "100%"
:font-size "12px"
:box-shadow (->!important "none")
:color (->!important font-color)
::stylefy/mode {:focus {:border-color font-color-muted}}})
(stylefy/tag "body" {:margin 0
:padding 0
:background (->!important level-0)
:overflow "hidden"
:font-family font-family
:font-size "13px"
:user-select "none"
:color font-color
:fill font-color})
(stylefy/tag "::-webkit-scrollbar" {:width "10px"
:height "10px"})
(stylefy/tag "::-webkit-scrollbar-thumb" {:background overlay})
(stylefy/tag "::-webkit-scrollbar-corner" {:background overlay})
(stylefy/tag "::-webkit-scrollbar-track" {:background "transparent"})
(stylefy/tag "input[type=range]" {:-webkit-appearance "none"
:padding "5px"
:margin 0
:background level-2
::stylefy/mode [[:focus {:outline "none"}]
[:hover {:cursor "col-resize"}]]})
(stylefy/tag "input[type=range]::-webkit-slider-runnable-track" {:height "16px"
:background level-1
:border "0"
:border-radius 0})
(stylefy/tag "input[type=range]::-webkit-slider-thumb" {:-webkit-appearance "none"
:border "none"
:height "16px"
:width "4px"
:border-radius 0
:background font-color
:margin-top "0"})
(stylefy/class "v-scroll" {:overflow "hidden"
:box-sizing "border-box"
::stylefy/mode {:hover {:overflow-y "auto"}}})
(def button-styles {:background-color "transparent"
:border 0
:padding 0
:color font-color
:fill font-color
:font-family font-family
:font-size "1em"
:outline "none"
:cursor "pointer"
:position "relative"
:-webkit-app-region "no-drag"
::stylefy/mode {:hover {:cursor "pointer"
:color font-color-active
:fill font-color-active}
:active {:background-color overlay}}})
(def flex-box {:display "flex"})
(stylefy/class "v-box" (merge flex-box {:flex-direction "column"}))
(stylefy/class "h-box" flex-box)
(stylefy/tag "a" {:color accent
:cursor "pointer"
:text-decoration "none"})
(stylefy/tag "pre" {:font-family "Source Code Pro, monospace"})
(stylefy/class "tooltip" {:position "absolute"
:background-color level-3
:border-radius "4px"
:z-index 1
:margin "8px"
:line-height "24px"
:padding "0 8px"})
(stylefy/tag "button" button-styles)
(stylefy/class "button" button-styles)
(stylefy/class "small" (merge (square-styles "22px !important")
{:margin "0 !important"
:border-radius "2px !important"
::stylefy/manual [[:svg (square-styles "13px !important")]]}))
(stylefy/class "divider-v" {:margin "0 4px"
:border-left (str "1px solid " border-color)
:height "28px"})
(stylefy/class "divider" {:margin "4px 0"
:border-bottom (str "1px solid " border-color)})
(stylefy/class "selected" {:background-color (->!important overlay)})
(stylefy/class "muted" {:color font-color-muted})
(stylefy/class "disabled" {:opacity ".5"
:cursor (->!important "initial")
:pointer-events "none"
::stylefy/mode {:hover {:background-color (->!important "inherit")}}})
(stylefy/class "icon" {:display "flex"
:justify-content "center"
::stylefy/manual [[:div {:display "flex"
:fill "inherit"}]]})
(stylefy/class "icon-button" (merge button-styles
(square-styles "33px")
{:margin "2px"
:border-radius "4px"
::stylefy/mode {:hover {:color font-color-active}
:disabled {:background "transparent"}
:active {:color font-color-active
:background overlay}}}))
(stylefy/class "v-divider" {:margin "4px"
:border-left (str "1px solid " border-color)
:height "28px"})
(stylefy/class "h-divider" {:margin "4px"
:border-top (str "1px solid " border-color)
:width "28px"})
(stylefy/class "sidebar" {:flex "0 0 auto"})
(stylefy/class "shortcut" {:flex "1 0"
:text-align "right"})
(def color-picker-styles {:background (->!important "transparent")
:box-shadow (->!important "none")
:color (->!important font-color)
::stylefy/manual [[:div {:border-width (->!important "0")
:color (->!important font-color)}]
[:svg {:fill (->!important font-color)
:background (->!important "transparent")}]]})
(stylefy/class "chrome-picker" color-picker-styles)
(stylefy/class "photoshop-picker" color-picker-styles)
(stylefy/class "color-rect" {:width "33px"
:height "33px"
:position "absolute"
:cursor "pointer"
:box-sizing "border-box"
:border-width "1px"
:border-style "solid"
:border-color "#aaa"})
(stylefy/class "color-drip" {:max-width (->px icon-size)
:height (->px icon-size)
:flex "1"
:cursor "pointer"})
(stylefy/class "command-palette" {:width "200px"
:position "absolute"
:top "20px"
:left "calc(50% - 100px)"})
(stylefy/class "resize-handler" {:width "5px"
:left "-2px"
:height "100%"
:z-index 1
:cursor "ew-resize"
:position "absolute"
:transition "background .3s"
::stylefy/mode {:hover {:background accent}
:active {:background accent}}})
(stylefy/class "drag-overlay" {:position "absolute"
:z-index "1"
:cursor "ew-resize"
:top "0"
:left "0"
:right "0"
:bottom "0"}) | null | https://raw.githubusercontent.com/re-path/studio/811a5cd24e5a467807057893eefd30c9cf1110f6/src/repath/studio/styles.cljs | clojure | Load Source Sans Pro font
Load Source Code Pro font
SEE -and-palettes
(def error-color "#BF616A")
(def font-color-muted "##D8DEE9")
(def background-error "#BF616A")
(def background-warning "#D08770")
(def background-success "#A3BE8C")
Light Theme
(def level-1 "#e1e1e1")
(def level-2 "#eee")
(def level-3 "#fff")
(def active "#fff")
(def accent "#ec407a")
(def error-color "#f78484")
(def font-color-muted "rgba(0, 0, 0, .6)")
(def font-color-hovered "#rgba(0, 0, 0, .95)")
(def border-color "rgba(0, 0, 0, .15)")
(def background-warning "#a56a00")
(def background-success "#1c611c") | (ns repath.studio.styles
(:require [stylefy.core :as stylefy]
[clojure.string :as str]))
(defn square-styles [size]
{:width size
:height size
:line-height size})
(defn ->!important
[value]
(str value " !important"))
(defn ->px
[value]
(str value "px"))
(stylefy/font-face {:font-family "Source Sans Pro"
:src "url('fonts/Source_Sans_Pro/SourceSansPro-Light.ttf')"
:font-weight "300"
:font-style "normal"})
(stylefy/font-face {:font-family "Source Sans Pro"
:src "url('fonts/Source_Sans_Pro/SourceSansPro-Regular.ttf')"
:font-weight "400"
:font-style "normal"})
(stylefy/font-face {:font-family "Source Sans Pro"
:src "url('fonts/Source_Sans_Pro/SourceSansPro-SemiBold.ttf')"
:font-weight "500"
:font-style "normal"})
(stylefy/font-face {:font-family "Source Sans Pro"
:src "url('fonts/Source_Sans_Pro/SourceSansPro-Bold.ttf')"
:font-weight "600"
:font-style "normal"})
(stylefy/font-face {:font-family "Source Code Pro"
:src "url('fonts/Source_Code_Pro/SourceCodePro-Light.ttf')"
:font-weight "light"
:font-style "light"})
(stylefy/font-face {:font-family "Source Code Pro"
:src "url('fonts/Source_Code_Pro/SourceCodePro-Regular.ttf')"
:font-weight "normal"
:font-style "regular"})
(stylefy/font-face {:font-family "Source Code Pro"
:src "url('fonts/Source_Code_Pro/SourceCodePro-SemiBold.ttf')"
:font-weight "semi-bold"
:font-style "semibold"})
(stylefy/font-face {:font-family "Source Code Pro"
:src "url('fonts/Source_Code_Pro/SourceCodePro-Bold.ttf')"
:font-weight "bold"
:font-style "bold"})
(def font-family "Source Sans Pro")
(def font-family-mono "Source Code Pro")
( def level-0 " # 2E3440 " )
( def level-1 " # 3B4252 " )
( def level-2 " # 434C5E " )
( def level-3 " # 4C566A " )
( def active " # 4C566A " )
( def accent " # 88C0D0 " )
( def font - color " # " )
( def font - color - disabled " rgba(255 , 255 , 255 , .3 ) " )
( def font - color - hovered " # ECEFF4 " )
( def font - color - active " rgba(255 , 255 , 255 , 1 ) " )
( def border - color " rgba(255 , 255 , 255 , ) " )
( def level-0 " # d1d1d1 " )
( def font - color " # rgba(0 , 0 , 0 , .8 ) " )
( def font - color - disabled " rgba(0 , 0 , 0 , .4 ) " )
( def font - color - active " rgba(0 , 0 , 0 , 1 ) " )
( def background - error " # 962121 " )
(def level-0 "#212121")
(def level-1 "#282828")
(def level-2 "#313131")
(def level-3 "#414141")
(def overlay "rgba(255, 255, 255, .1)")
(def accent "#ec407a")
(def font-color "rgba(255, 255, 255, .7)")
(def error-color "#f78484")
(def font-color-disabled "rgba(255, 255, 255, .3)")
(def font-color-muted "rgba(255, 255, 255, .5)")
(def font-color-hovered "rgba(255, 255, 255, .9)")
(def font-color-active "rgba(255, 255, 255, 1)")
(def border-color "rgba(255, 255, 255, .15)")
(def background-error "#962121")
(def background-warning "#a56a00")
(def background-success "#1c611c")
(stylefy/class "error" {:background background-error})
(stylefy/class "warning" {:background background-warning})
(stylefy/class "success" {:background background-success})
(def h-padding "12px")
(def v-padding "8px")
(def padding (str v-padding " " h-padding))
(def icon-size 17)
(def form-element-style
{:outline "none"
:background level-2
:border 0
:padding "4px 12px"
:box-sizing "border-box"
:line-height "18px"
:width "100%"
:font-size "12px"
:box-shadow (->!important "none")
:color (->!important font-color)
::stylefy/mode {:focus {:border-color font-color-muted}}})
(stylefy/tag "body" {:margin 0
:padding 0
:background (->!important level-0)
:overflow "hidden"
:font-family font-family
:font-size "13px"
:user-select "none"
:color font-color
:fill font-color})
(stylefy/tag "::-webkit-scrollbar" {:width "10px"
:height "10px"})
(stylefy/tag "::-webkit-scrollbar-thumb" {:background overlay})
(stylefy/tag "::-webkit-scrollbar-corner" {:background overlay})
(stylefy/tag "::-webkit-scrollbar-track" {:background "transparent"})
(stylefy/tag "input[type=range]" {:-webkit-appearance "none"
:padding "5px"
:margin 0
:background level-2
::stylefy/mode [[:focus {:outline "none"}]
[:hover {:cursor "col-resize"}]]})
(stylefy/tag "input[type=range]::-webkit-slider-runnable-track" {:height "16px"
:background level-1
:border "0"
:border-radius 0})
(stylefy/tag "input[type=range]::-webkit-slider-thumb" {:-webkit-appearance "none"
:border "none"
:height "16px"
:width "4px"
:border-radius 0
:background font-color
:margin-top "0"})
(stylefy/class "v-scroll" {:overflow "hidden"
:box-sizing "border-box"
::stylefy/mode {:hover {:overflow-y "auto"}}})
(def button-styles {:background-color "transparent"
:border 0
:padding 0
:color font-color
:fill font-color
:font-family font-family
:font-size "1em"
:outline "none"
:cursor "pointer"
:position "relative"
:-webkit-app-region "no-drag"
::stylefy/mode {:hover {:cursor "pointer"
:color font-color-active
:fill font-color-active}
:active {:background-color overlay}}})
(def flex-box {:display "flex"})
(stylefy/class "v-box" (merge flex-box {:flex-direction "column"}))
(stylefy/class "h-box" flex-box)
(stylefy/tag "a" {:color accent
:cursor "pointer"
:text-decoration "none"})
(stylefy/tag "pre" {:font-family "Source Code Pro, monospace"})
(stylefy/class "tooltip" {:position "absolute"
:background-color level-3
:border-radius "4px"
:z-index 1
:margin "8px"
:line-height "24px"
:padding "0 8px"})
(stylefy/tag "button" button-styles)
(stylefy/class "button" button-styles)
(stylefy/class "small" (merge (square-styles "22px !important")
{:margin "0 !important"
:border-radius "2px !important"
::stylefy/manual [[:svg (square-styles "13px !important")]]}))
(stylefy/class "divider-v" {:margin "0 4px"
:border-left (str "1px solid " border-color)
:height "28px"})
(stylefy/class "divider" {:margin "4px 0"
:border-bottom (str "1px solid " border-color)})
(stylefy/class "selected" {:background-color (->!important overlay)})
(stylefy/class "muted" {:color font-color-muted})
(stylefy/class "disabled" {:opacity ".5"
:cursor (->!important "initial")
:pointer-events "none"
::stylefy/mode {:hover {:background-color (->!important "inherit")}}})
(stylefy/class "icon" {:display "flex"
:justify-content "center"
::stylefy/manual [[:div {:display "flex"
:fill "inherit"}]]})
(stylefy/class "icon-button" (merge button-styles
(square-styles "33px")
{:margin "2px"
:border-radius "4px"
::stylefy/mode {:hover {:color font-color-active}
:disabled {:background "transparent"}
:active {:color font-color-active
:background overlay}}}))
(stylefy/class "v-divider" {:margin "4px"
:border-left (str "1px solid " border-color)
:height "28px"})
(stylefy/class "h-divider" {:margin "4px"
:border-top (str "1px solid " border-color)
:width "28px"})
(stylefy/class "sidebar" {:flex "0 0 auto"})
(stylefy/class "shortcut" {:flex "1 0"
:text-align "right"})
(def color-picker-styles {:background (->!important "transparent")
:box-shadow (->!important "none")
:color (->!important font-color)
::stylefy/manual [[:div {:border-width (->!important "0")
:color (->!important font-color)}]
[:svg {:fill (->!important font-color)
:background (->!important "transparent")}]]})
(stylefy/class "chrome-picker" color-picker-styles)
(stylefy/class "photoshop-picker" color-picker-styles)
(stylefy/class "color-rect" {:width "33px"
:height "33px"
:position "absolute"
:cursor "pointer"
:box-sizing "border-box"
:border-width "1px"
:border-style "solid"
:border-color "#aaa"})
(stylefy/class "color-drip" {:max-width (->px icon-size)
:height (->px icon-size)
:flex "1"
:cursor "pointer"})
(stylefy/class "command-palette" {:width "200px"
:position "absolute"
:top "20px"
:left "calc(50% - 100px)"})
(stylefy/class "resize-handler" {:width "5px"
:left "-2px"
:height "100%"
:z-index 1
:cursor "ew-resize"
:position "absolute"
:transition "background .3s"
::stylefy/mode {:hover {:background accent}
:active {:background accent}}})
(stylefy/class "drag-overlay" {:position "absolute"
:z-index "1"
:cursor "ew-resize"
:top "0"
:left "0"
:right "0"
:bottom "0"}) |
95aaa463b44a4bc091b9dfbd8a02abda88ece0ab60796ffc4439f3bd8217cb6a | chrisdone/duet | Spec.hs | # LANGUAGE TemplateHaskell #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE FlexibleContexts #
# LANGUAGE RecordWildCards #
# LANGUAGE TupleSections #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE LambdaCase #
-- |
import Control.Monad.Logger
import Control.Monad.Supply
import Control.Monad.Writer
import Data.Bifunctor
import Duet.Infer
import Duet.Parser
import Duet.Simple
import Duet.Types
import Test.Hspec
main :: IO ()
main = hspec spec
spec :: SpecWith ()
spec =
describe
"Compilation"
(do it
"Basic compile and run constant"
(shouldBe
(first
(const ())
(runNoLoggingT
((evalSupplyT
(do decls <- parseText "test" "main = 1"
(binds, ctx) <- createContext decls
things <-
execWriterT
(runStepper
100
ctx
(fmap (fmap typeSignatureA) binds)
"main")
pure things)
[1 ..]))))
(Right [LiteralExpression () (IntegerLiteral 1)]))
it
"Basic compile and run constant lambda"
(shouldBe
(first
(const ())
(runNoLoggingT
((evalSupplyT
(do decls <- parseText "test" "main = (\\x -> x) 1"
(binds, ctx) <- createContext decls
things <-
execWriterT
(runStepper
100
ctx
(fmap (fmap typeSignatureA) binds)
"main")
pure things)
[1 ..]))))
(Right
[ ApplicationExpression
()
(LambdaExpression
()
(Alternative
{ alternativeLabel = ()
, alternativePatterns =
[VariablePattern () (ValueName 49 "x")]
, alternativeExpression =
VariableExpression () (ValueName 49 "x")
}))
(LiteralExpression () (IntegerLiteral 1))
, LiteralExpression () (IntegerLiteral 1)
]))
it
"Seq"
(shouldBe
(second
last
(first
(const ())
(runNoLoggingT
((evalSupplyT
(do decls <-
parseText
"test"
"seq =\n\
\ \\x y ->\n\
\ case x of\n\
\ !_ -> y\n\
\loop = loop\n\
\main = seq loop 1"
(binds, ctx) <- createContext decls
things <-
execWriterT
(runStepper
100
ctx
(fmap (fmap typeSignatureA) binds)
"main")
pure things)
[1 ..])))))
(Right
(CaseExpression
()
(VariableExpression () (ValueName 49 "loop"))
[ CaseAlt
{ caseAltLabel = ()
, caseAltPattern = BangPattern (WildcardPattern () "_")
, caseAltExpression =
LiteralExpression () (IntegerLiteral 1)
}
]))))
| null | https://raw.githubusercontent.com/chrisdone/duet/959d40db68f4c2df04cabb7677724900d4f71db4/test/Spec.hs | haskell | # LANGUAGE OverloadedStrings #
| | # LANGUAGE TemplateHaskell #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE FlexibleContexts #
# LANGUAGE RecordWildCards #
# LANGUAGE TupleSections #
# LANGUAGE LambdaCase #
import Control.Monad.Logger
import Control.Monad.Supply
import Control.Monad.Writer
import Data.Bifunctor
import Duet.Infer
import Duet.Parser
import Duet.Simple
import Duet.Types
import Test.Hspec
main :: IO ()
main = hspec spec
spec :: SpecWith ()
spec =
describe
"Compilation"
(do it
"Basic compile and run constant"
(shouldBe
(first
(const ())
(runNoLoggingT
((evalSupplyT
(do decls <- parseText "test" "main = 1"
(binds, ctx) <- createContext decls
things <-
execWriterT
(runStepper
100
ctx
(fmap (fmap typeSignatureA) binds)
"main")
pure things)
[1 ..]))))
(Right [LiteralExpression () (IntegerLiteral 1)]))
it
"Basic compile and run constant lambda"
(shouldBe
(first
(const ())
(runNoLoggingT
((evalSupplyT
(do decls <- parseText "test" "main = (\\x -> x) 1"
(binds, ctx) <- createContext decls
things <-
execWriterT
(runStepper
100
ctx
(fmap (fmap typeSignatureA) binds)
"main")
pure things)
[1 ..]))))
(Right
[ ApplicationExpression
()
(LambdaExpression
()
(Alternative
{ alternativeLabel = ()
, alternativePatterns =
[VariablePattern () (ValueName 49 "x")]
, alternativeExpression =
VariableExpression () (ValueName 49 "x")
}))
(LiteralExpression () (IntegerLiteral 1))
, LiteralExpression () (IntegerLiteral 1)
]))
it
"Seq"
(shouldBe
(second
last
(first
(const ())
(runNoLoggingT
((evalSupplyT
(do decls <-
parseText
"test"
"seq =\n\
\ \\x y ->\n\
\ case x of\n\
\ !_ -> y\n\
\loop = loop\n\
\main = seq loop 1"
(binds, ctx) <- createContext decls
things <-
execWriterT
(runStepper
100
ctx
(fmap (fmap typeSignatureA) binds)
"main")
pure things)
[1 ..])))))
(Right
(CaseExpression
()
(VariableExpression () (ValueName 49 "loop"))
[ CaseAlt
{ caseAltLabel = ()
, caseAltPattern = BangPattern (WildcardPattern () "_")
, caseAltExpression =
LiteralExpression () (IntegerLiteral 1)
}
]))))
|
c94a41e15d24319c3f864acd120415bd3a266da963659f3d4734c35a3577e818 | ijvcms/chuanqi_dev | map_10402.erl | -module(map_10402).
-export([
range/0,
data/0
]).
range() -> {20, 12}.
data() ->
{
{1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},
{1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1},
{1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1},
{1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1},
{1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1},
{1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1},
{1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1},
{1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1},
{1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1},
{1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1},
{1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1},
{1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}
}.
| null | https://raw.githubusercontent.com/ijvcms/chuanqi_dev/7742184bded15f25be761c4f2d78834249d78097/server/trunk/server/src/map_data/map_10402.erl | erlang | -module(map_10402).
-export([
range/0,
data/0
]).
range() -> {20, 12}.
data() ->
{
{1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},
{1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1},
{1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1},
{1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1},
{1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1},
{1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1},
{1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1},
{1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1},
{1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1},
{1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1},
{1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1},
{1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}
}.
| |
22264ff8279777c269da53086c18e82ec7e87d71509ccb6a1eb72ed2af5db4ec | coalton-lang/coalton | ast-subsitutions.lisp | (defpackage #:coalton-impl/codegen/ast-substitutions
(:use
#:cl
#:coalton-impl/util
#:coalton-impl/codegen/ast)
(:export
#:ast-substitution ; STRUCT
CONSTRUCTOR
ACCESSOR
ACCESSOR
#:ast-substitution-list ; TYPE
))
(in-package #:coalton-impl/codegen/ast-substitutions)
(defstruct ast-substitution
(from (required 'from) :type symbol :read-only t)
(to (required 'to) :type node :read-only t))
(defun ast-substitution-list-p (x)
(and (alexandria:proper-list-p x)
(every #'ast-substitution-p x)))
(deftype ast-substitution-list ()
'(satisfies ast-substitution-list-p))
(defgeneric apply-ast-substitution (subs node)
(:method (subs (list list))
(loop :for node :in list
:collect (apply-ast-substitution subs node)))
(:method (subs (node node-literal))
(declare (type ast-substitution-list subs)
(ignore subs)
(values node))
node)
(:method (subs (node node-lisp))
(declare (type ast-substitution-list subs)
(ignore subs)
(values node))
node)
(:method (subs (node node-variable))
(declare (type ast-substitution-list subs)
(values node))
(let ((res (find (node-variable-value node) subs :key #'ast-substitution-from)))
(if res
(ast-substitution-to res)
node)))
(:method (subs (node node-application))
(declare (type ast-substitution-list subs)
(values node))
(make-node-application
:type (node-type node)
:rator (apply-ast-substitution subs (node-application-rator node))
:rands (apply-ast-substitution subs (node-application-rands node))))
(:method (subs (node node-direct-application))
(declare (type ast-substitution-list subs)
(values node))
(when (find (node-direct-application-rator node) subs :key #'ast-substitution-from)
(coalton-bug
"Failure to apply ast substitution on variable ~A to node-direct-application"
(node-direct-application-rator node)))
(make-node-direct-application
:type (node-type node)
:rator-type (node-direct-application-rator-type node)
:rator (node-direct-application-rator node)
:rands (apply-ast-substitution subs (node-direct-application-rands node))))
(:method (subs (node node-abstraction))
(declare (type ast-substitution-list subs)
(values node))
(make-node-abstraction
:type (node-type node)
:vars (node-abstraction-vars node)
:subexpr (apply-ast-substitution subs (node-abstraction-subexpr node))))
(:method (subs (node node-bare-abstraction))
(declare (type ast-substitution-list subs)
(values node))
(make-node-bare-abstraction
:type (node-type node)
:vars (node-bare-abstraction-vars node)
:subexpr (apply-ast-substitution subs (node-bare-abstraction-subexpr node))))
(:method (subs (node node-let))
(declare (type ast-substitution-list subs)
(values node))
(make-node-let
:type (node-type node)
:bindings (loop :for (name . node) :in (node-let-bindings node)
:do (when (find name subs :key #'ast-substitution-from)
(coalton-bug
"Failure to apply ast substitution on variable ~A to node-let"
name))
:collect (cons name (apply-ast-substitution subs node)))
:subexpr (apply-ast-substitution subs (node-let-subexpr node))))
(:method (subs (node match-branch))
(declare (type ast-substitution-list subs)
(values match-branch))
(make-match-branch
:pattern (match-branch-pattern node)
:bindings (match-branch-bindings node)
:body (apply-ast-substitution subs (match-branch-body node))))
(:method (subs (node node-match))
(declare (type ast-substitution-list subs)
(values node))
(make-node-match
:type (node-type node)
:expr (apply-ast-substitution subs (node-match-expr node))
:branches (apply-ast-substitution subs (node-match-branches node))))
(:method (subs (node node-seq))
(declare (type ast-substitution-list subs)
(values node))
(make-node-seq
:type (node-type node)
:nodes (apply-ast-substitution subs (node-seq-nodes node))))
(:method (subs (node node-return))
(declare (type ast-substitution-list subs)
(values node))
(make-node-return
:type (node-type node)
:expr (apply-ast-substitution subs (node-return-expr node))))
(:method (subs (node node-field))
(declare (type ast-substitution-list subs)
(values node))
(make-node-field
:type (node-type node)
:name (node-field-name node)
:dict (apply-ast-substitution subs (node-field-dict node))))
(:method (subs (node node-dynamic-extent))
(declare (type ast-substitution-list subs)
(values node))
(make-node-dynamic-extent
:type (node-type node)
:name (node-dynamic-extent-name node)
:node (apply-ast-substitution subs (node-dynamic-extent-node node))
:body (apply-ast-substitution subs (node-dynamic-extent-body node))))
(:method (subs (node node-bind))
(declare (type ast-substitution-list subs)
(values node))
(make-node-bind
:type (node-type node)
:name (node-bind-name node)
:expr (apply-ast-substitution subs (node-bind-expr node))
:body (apply-ast-substitution subs (node-bind-body node)))))
| null | https://raw.githubusercontent.com/coalton-lang/coalton/a8d779e824bb362c01d3218cfbb3394f9858850f/src/codegen/ast-subsitutions.lisp | lisp | STRUCT
TYPE | (defpackage #:coalton-impl/codegen/ast-substitutions
(:use
#:cl
#:coalton-impl/util
#:coalton-impl/codegen/ast)
(:export
CONSTRUCTOR
ACCESSOR
ACCESSOR
))
(in-package #:coalton-impl/codegen/ast-substitutions)
(defstruct ast-substitution
(from (required 'from) :type symbol :read-only t)
(to (required 'to) :type node :read-only t))
(defun ast-substitution-list-p (x)
(and (alexandria:proper-list-p x)
(every #'ast-substitution-p x)))
(deftype ast-substitution-list ()
'(satisfies ast-substitution-list-p))
(defgeneric apply-ast-substitution (subs node)
(:method (subs (list list))
(loop :for node :in list
:collect (apply-ast-substitution subs node)))
(:method (subs (node node-literal))
(declare (type ast-substitution-list subs)
(ignore subs)
(values node))
node)
(:method (subs (node node-lisp))
(declare (type ast-substitution-list subs)
(ignore subs)
(values node))
node)
(:method (subs (node node-variable))
(declare (type ast-substitution-list subs)
(values node))
(let ((res (find (node-variable-value node) subs :key #'ast-substitution-from)))
(if res
(ast-substitution-to res)
node)))
(:method (subs (node node-application))
(declare (type ast-substitution-list subs)
(values node))
(make-node-application
:type (node-type node)
:rator (apply-ast-substitution subs (node-application-rator node))
:rands (apply-ast-substitution subs (node-application-rands node))))
(:method (subs (node node-direct-application))
(declare (type ast-substitution-list subs)
(values node))
(when (find (node-direct-application-rator node) subs :key #'ast-substitution-from)
(coalton-bug
"Failure to apply ast substitution on variable ~A to node-direct-application"
(node-direct-application-rator node)))
(make-node-direct-application
:type (node-type node)
:rator-type (node-direct-application-rator-type node)
:rator (node-direct-application-rator node)
:rands (apply-ast-substitution subs (node-direct-application-rands node))))
(:method (subs (node node-abstraction))
(declare (type ast-substitution-list subs)
(values node))
(make-node-abstraction
:type (node-type node)
:vars (node-abstraction-vars node)
:subexpr (apply-ast-substitution subs (node-abstraction-subexpr node))))
(:method (subs (node node-bare-abstraction))
(declare (type ast-substitution-list subs)
(values node))
(make-node-bare-abstraction
:type (node-type node)
:vars (node-bare-abstraction-vars node)
:subexpr (apply-ast-substitution subs (node-bare-abstraction-subexpr node))))
(:method (subs (node node-let))
(declare (type ast-substitution-list subs)
(values node))
(make-node-let
:type (node-type node)
:bindings (loop :for (name . node) :in (node-let-bindings node)
:do (when (find name subs :key #'ast-substitution-from)
(coalton-bug
"Failure to apply ast substitution on variable ~A to node-let"
name))
:collect (cons name (apply-ast-substitution subs node)))
:subexpr (apply-ast-substitution subs (node-let-subexpr node))))
(:method (subs (node match-branch))
(declare (type ast-substitution-list subs)
(values match-branch))
(make-match-branch
:pattern (match-branch-pattern node)
:bindings (match-branch-bindings node)
:body (apply-ast-substitution subs (match-branch-body node))))
(:method (subs (node node-match))
(declare (type ast-substitution-list subs)
(values node))
(make-node-match
:type (node-type node)
:expr (apply-ast-substitution subs (node-match-expr node))
:branches (apply-ast-substitution subs (node-match-branches node))))
(:method (subs (node node-seq))
(declare (type ast-substitution-list subs)
(values node))
(make-node-seq
:type (node-type node)
:nodes (apply-ast-substitution subs (node-seq-nodes node))))
(:method (subs (node node-return))
(declare (type ast-substitution-list subs)
(values node))
(make-node-return
:type (node-type node)
:expr (apply-ast-substitution subs (node-return-expr node))))
(:method (subs (node node-field))
(declare (type ast-substitution-list subs)
(values node))
(make-node-field
:type (node-type node)
:name (node-field-name node)
:dict (apply-ast-substitution subs (node-field-dict node))))
(:method (subs (node node-dynamic-extent))
(declare (type ast-substitution-list subs)
(values node))
(make-node-dynamic-extent
:type (node-type node)
:name (node-dynamic-extent-name node)
:node (apply-ast-substitution subs (node-dynamic-extent-node node))
:body (apply-ast-substitution subs (node-dynamic-extent-body node))))
(:method (subs (node node-bind))
(declare (type ast-substitution-list subs)
(values node))
(make-node-bind
:type (node-type node)
:name (node-bind-name node)
:expr (apply-ast-substitution subs (node-bind-expr node))
:body (apply-ast-substitution subs (node-bind-body node)))))
|
aa94f5a9465734316a8bbe7e520220c9060b300a1b7fd764eec6ece54e011ca2 | bmeurer/ocaml-arm | genprintval.mli | (***********************************************************************)
(* *)
(* OCaml *)
(* *)
, projet Cristal , INRIA Rocquencourt
(* *)
Copyright 1996 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the Q Public License version 1.0 .
(* *)
(***********************************************************************)
$ Id$
(* Printing of values *)
open Types
open Format
module type OBJ =
sig
type t
val obj : t -> 'a
val is_block : t -> bool
val tag : t -> int
val size : t -> int
val field : t -> int -> t
end
module type EVALPATH =
sig
type valu
val eval_path: Path.t -> valu
exception Error
val same_value: valu -> valu -> bool
end
module type S =
sig
type t
val install_printer :
Path.t -> Types.type_expr -> (formatter -> t -> unit) -> unit
val remove_printer : Path.t -> unit
val outval_of_untyped_exception : t -> Outcometree.out_value
val outval_of_value :
int -> int ->
(int -> t -> Types.type_expr -> Outcometree.out_value option) ->
Env.t -> t -> type_expr -> Outcometree.out_value
end
module Make(O : OBJ)(EVP : EVALPATH with type valu = O.t) :
(S with type t = O.t)
| null | https://raw.githubusercontent.com/bmeurer/ocaml-arm/43f7689c76a349febe3d06ae7a4fc1d52984fd8b/toplevel/genprintval.mli | ocaml | *********************************************************************
OCaml
*********************************************************************
Printing of values | , projet Cristal , INRIA Rocquencourt
Copyright 1996 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the Q Public License version 1.0 .
$ Id$
open Types
open Format
module type OBJ =
sig
type t
val obj : t -> 'a
val is_block : t -> bool
val tag : t -> int
val size : t -> int
val field : t -> int -> t
end
module type EVALPATH =
sig
type valu
val eval_path: Path.t -> valu
exception Error
val same_value: valu -> valu -> bool
end
module type S =
sig
type t
val install_printer :
Path.t -> Types.type_expr -> (formatter -> t -> unit) -> unit
val remove_printer : Path.t -> unit
val outval_of_untyped_exception : t -> Outcometree.out_value
val outval_of_value :
int -> int ->
(int -> t -> Types.type_expr -> Outcometree.out_value option) ->
Env.t -> t -> type_expr -> Outcometree.out_value
end
module Make(O : OBJ)(EVP : EVALPATH with type valu = O.t) :
(S with type t = O.t)
|
8c1697734afcf753cf007e26126266cc92fe46c43556288fea518730625516de | yuriy-chumak/ol | callcc.scm | ;; funny call/cc tests
;; defining y with self application via call/cc
(define Y
(λ (e) ((call/cc call/cc) (λ (f) (e (λ (x) (((call/cc (call/cc call/cc)) f) x)))))))
(define fakt
(Y (λ (self) (λ (x) (if (= x 0) 1 (* x (self (- x 1))))))))
(print (fakt 10))
| null | https://raw.githubusercontent.com/yuriy-chumak/ol/83dd03d311339763682eab02cbe0c1321daa25bc/tests/callcc.scm | scheme | funny call/cc tests
defining y with self application via call/cc |
(define Y
(λ (e) ((call/cc call/cc) (λ (f) (e (λ (x) (((call/cc (call/cc call/cc)) f) x)))))))
(define fakt
(Y (λ (self) (λ (x) (if (= x 0) 1 (* x (self (- x 1))))))))
(print (fakt 10))
|
fd4241814ccfb6e41456baa493672575beac1cf022cdf5fb95f93b4a67fc959b | greg42/openOfficeMarkup | DocumentParser.hs |
- ----------------------------------------------------------------------------
- " THE BEER - WARE LICENSE " ( Revision 42 ):
- < > wrote this file . As long as you retain this notice you
- can do whatever you want with this stuff . If we meet some day , and you
- think this stuff is worth it , you can buy me a beer in return .
- ----------------------------------------------------------------------------
- ----------------------------------------------------------------------------
- "THE BEER-WARE LICENSE" (Revision 42):
- <> wrote this file. As long as you retain this notice you
- can do whatever you want with this stuff. If we meet some day, and you
- think this stuff is worth it, you can buy me a beer in return. Gregor Kopf
- ----------------------------------------------------------------------------
-}
|
Module : Text . Udoc .
Description : Udoc document parser
Copyright : ( c ) , 2012
License : BEER - WARE LICENSE ( Revision 42 )
Maintainer :
Stability : experimental
This module contains the implementation of the udoc parser .
Module : Text.Udoc.DocumentParser
Description : Udoc document parser
Copyright : (c) Gregor Kopf, 2012
License : BEER-WARE LICENSE (Revision 42)
Maintainer :
Stability : experimental
This module contains the implementation of the udoc parser.
-}
# LANGUAGE FlexibleContexts #
module Text.Udoc.DocumentParser where
import Text.ParserCombinators.Parsec hiding (State, try, spaces)
import qualified Text.ParserCombinators.Parsec as P
import qualified Text.ParserCombinators.Parsec.Error as PE
import Text.Parsec.Prim (parserZero, runParserT, ParsecT, try)
import qualified Text.Parsec.Prim as PP
import Control.Monad
import Control.Monad.State
import Text.JSON
import Text.Udoc.Document
import Data.Either
import Data.Char
import Data.Maybe
import Data.Functor.Identity
import Text.Parsec.Indent
import Text.Parsec.Pos
import Control.Applicative hiding ((<|>), many, optional)
import Text.Read
import Data.List
data SyntaxOption = SkipNewlinesAfterUlist
| SkipNewlinesAfterImage
| BacktickSource
| SkipNewlinesAfterSourceOrQuoteBlock
| BlockQuotes
| FencedCodeBlocks
| NewStyleOlist
deriving (Eq, Read, Show)
type SyntaxFlavor = [SyntaxOption]
data ParserState = ParserState {
parserStateFlavor :: SyntaxFlavor
, parserStateLastInlineOpeningTag :: Char
, parserStateCurrentListLevel :: Int
}
-- | A parser state without any syntax options set
defaultParserState :: ParserState
defaultParserState = ParserState [] '{' 0
-- | Indentation sensitive parser
type IParse r = ParsecT String ParserState (State SourcePos) r
| The type for HandleSpecialCommand : Takes a name , arguments and returns
-- a new parser
type HSP = String -> [(String, String)] -> IParse DocumentItem
-- | Returns whether or not a parsing option is set.
isOptionSet :: SyntaxOption -> IParse Bool
isOptionSet opt = (elem opt . parserStateFlavor) <$> P.getState
-- | Executes a parser if any only if a configuration option is set.
whenOptionSet :: SyntaxOption -> IParse () -> IParse ()
whenOptionSet opt act = do
s <- isOptionSet opt
when s $ act
-- | A command is an entity in a document that will cause the backend renderer
-- to perform a special operation. Commands in this markup language take the
general form [ command argument = value , = value2 ] . Therefore , a Command
-- is a tuple consisting of the command name and the command arguments.
type Command = (String, [(String, String)])
-- | Parse a udoc document and return the document items.
parseDocument :: ParserState -> HSP -> String -> Either ParseError ([DocumentItem], ParserState)
parseDocument initialState hsp input =
myParse id parser input
where myParse f p src = fst
$ flip runState (f $ initialPos "")
$ runParserT p initialState "" src
parser = do items <- documentItems hsp
s <- P.getState
return (items, s)
-- | Parse an inline udoc document and return the document items (e.g. to
-- | parse table cells). In case of an error use the given initial source
-- | position as error position.
-- |
-- | TODO: As soon as its possible to determine the initial position of
-- | each table cell it would be nice to combine the initial
-- | position and the error position to determine the real
-- | position.
parseInlineDocument :: ParserState -> SourcePos -> HSP -> String -> Either ParseError ([DocumentItem], ParserState)
parseInlineDocument initialState currentPosition handleSpecialCommand source =
fixPosition $ fst $ runState runParser (initialPos fileName)
where
fileName :: String
fileName = sourceName currentPosition
runParser :: State SourcePos (Either ParseError ([DocumentItem], ParserState))
runParser = runParserT parser initialState fileName source
parser :: IParse ([DocumentItem], ParserState)
parser = do
itemHandler <- documentItems handleSpecialCommand
currentState <- P.getState
return (itemHandler, currentState)
fixPosition :: Either ParseError ([DocumentItem], ParserState) -> Either ParseError ([DocumentItem], ParserState)
fixPosition result = case result of
Left error -> Left $ PE.setErrorPos (updateErrorPos currentPosition (PE.errorPos error)) error
right -> right
-- | Use the position of the last parsed parent document character as new
-- | error position.
updateErrorPos :: SourcePos -> SourcePos -> SourcePos
updateErrorPos initialPos errorPos =
setSourceColumn (setSourceLine errorPos $ (sourceLine initialPos)) (sourceColumn initialPos)
| Skips zero or more space or tab characters .
spaces :: IParse ()
spaces = skipMany $ oneOf " \t"
| Skipts zero of more space , tab and newline characters .
whiteSpace :: IParse ()
whiteSpace = skipMany $ oneOf " \t\n"
-- | Top level parser. It will parse headings or paragraphs until
-- eof is found.
documentItems :: HSP -> IParse [DocumentItem]
documentItems hsp = do
whiteSpace
-- Before we start our paragraph based parsing, let's see if the
document starts with one or more meta tags . If so , we just
-- include them separately, i.e., without a surrounding paragraph.
docHead <- many $ tryCommand isMetaTag
whiteSpace
items <- many $ (try $ heading hsp)
<|> (try $ optionIf BlockQuotes $ blockQuote)
<|> (try $ optionIf FencedCodeBlocks $ fencedCodeBlock)
<|> paragraph hsp
whiteSpace
eof
return $ docHead ++ items
where tryCommand pred = try $ do
cmd <- extendedCommand hsp
optional newline
if pred cmd
then return cmd
else fail "Did not find expected command"
isMetaTag (ItemMetaTag _) = True
isMetaTag _ = False
optionIf opt a = do
s <- isOptionSet opt
if s
then a
else fail ""
| A string between two double quotes .
quotedContent :: IParse String
quotedContent =
between (char '"') (char '"') (many1 (wordChar <|> char ' '))
-- | A command parameter. This is a string of the form: key = value. The
-- value may be quoted.
commandParameter :: IParse (String, String)
commandParameter = do whiteSpace
name <- many1 alphaNum
spaces
char '='
spaces
value <- quotedContent <|> (many1 $ noneOf "\n ,\t\"[]")
whiteSpace
return (name, value)
-- | The inner part of a command. This matches a string of the form:
-- command key=value.
command :: IParse Command
command = do
whiteSpace
commandName <- many1 (alphaNum <|> char '/')
whiteSpace
params <- commandParameter `sepBy` (char ',')
whiteSpace
return (commandName, params)
-- | A command surrounded by square brackets.
squareBrCommand :: IParse Command
squareBrCommand =
between (char '[') (char ']') (do ret <- command; spaces; return ret)
-- | Some text surrounded by curly brackets. This will internally be
-- represented as a command called "_s" (for source code)
inlineSource :: IParse Command
inlineSource = do backticks <- isOptionSet BacktickSource
let chars = if backticks then "{`" else "{"
opener <- oneOf chars
PP.modifyState $ \x -> x { parserStateLastInlineOpeningTag = opener }
return ("_s", [])
-- | Some text surrounded by double quotes. This will internally be
-- represented as a command called "_q" (for quote)
inlineQuote :: IParse Command
inlineQuote = char '"' >> return ("_q", [])
-- | Looks up a list of keys from an association list. If all keys are found,
-- returns Just [values]. Otherwise, returns nothing.
getMandatory :: (Eq a) =>
[a] -- ^ Keys to be looked up
-> [(a, b)] -- ^ An association list
-> Maybe [b] -- ^ The result
getMandatory keys aList = mapM ((flip lookup) aList) keys
| Looks up a list of keys from an association list . If at least one of the
-- keys are not found, this runction returns Nothing. Otherwise, it will return
-- Just a new association list. The keys in this new association list will
-- however not be the original keys that were looked up. Instead, the lookup
-- keys will be renamed.
mandRename :: (Eq a) =>
[(a, b)] -- ^ A pair: (lookup key, new key)
-> [(a, c)] -- ^ An association list
-> Maybe [(b, c)] -- ^ The result with the lookup keys renamed
mandRename mandKeyName aList =
zip <$> (Just $ map snd mandKeyName) <*>
(getMandatory (map fst mandKeyName) aList)
-- | Looks up a list of keys from an association list and builds a new
-- association list, holding the found values. The keys in the new list are
-- obtained by renaming the old keys.
optRename :: (Eq a) =>
[(a, b)] -- ^ A pair: (lookup key, new key)
-> [(a, c)] -- ^ An association list
-> [(b, c)] -- ^ The result with the lookup keys renamed
optRename optKeyName aList =
let values = map ((flip lookup) aList) (map fst optKeyName)
getJust ( Just 3 , Just 3 ) = Just ( 3 , 4 )
-- getJust (Nothing, Just 2) = Nothing
getJust x = ((,)) <$> fst x <*> snd x
in
catMaybes $ map getJust (zip (map (Just . snd) optKeyName) values)
| A combination of mandRename and optRename . This function tries to extract
-- all required and optional arguments from a list. The obtained arguments will
-- be renamed and then a function will be invoked on both resulting argument
-- lists. The result of the function will be returned.
getArgumentsOrFail :: (Monad m, Eq a, Show a) =>
[(a, b)] -- ^ A renaming pair for the mandatory args
-> [(a, b)] -- ^ A renaming pair for the optional args
-> [(a, c)] -- ^ An association list
-> ([(b,c)] -> [(b,c)] -> d) -- ^ A function for handling
-- the resulting lists of mandatory
-- and optional arguments
-> m d -- ^ The result
getArgumentsOrFail mandArgs optArgs aList f =
let mand = mandRename mandArgs aList
opt = optRename optArgs aList
in
case mand of
Nothing -> fail $ "Missing argument. Epecting: " ++
(show $ map fst mandArgs) ++
" but only got " ++ (show $ map fst aList)
Just m' -> return $ f m' opt
{-| Lookup a required tag attribute that may not exist. -}
mLookup :: (Show a, Monad m, Eq a) => a -> [(a , b)] -> String -> m b
mLookup k al error_message = maybe (fail error_message) return $ lookup k al
-- | Creates an ItemMetaTag from the following data: a tag name, the list
-- of mandatory properties and the list of optional properties.
createMetaTag :: String -- ^ The name of the tag type
-> [(String, String)] -- ^ The mandatory properties
-> [(String, String)] -- ^ The optional properties
-> DocumentItem -- ^ The resulting document item
createMetaTag t mprops oprops = ItemMetaTag $ [("type", t)] ++ mprops ++ oprops
-- | Tries to create a meta tag specified by is name. To create the tag, this
-- function will lookup all mandatory and optional arguments from the argument
-- list that has been supplied. If this worked out, it will return an
-- ItemMetaTag.
handleMetaTag :: (Monad m, Show a, Eq a) =>
String -- ^ The name of the tag type
-> [(a, String)] -- ^ Mandatory tag arguments
-> [(a, String)] -- ^ Optional tag arguments
-> [(a, String)] -- ^ The parsed tag arguments
-> m DocumentItem -- ^ The resulting item
handleMetaTag t mand opt aList =
getArgumentsOrFail mand opt aList (createMetaTag t)
-- | Checks that all required arguments are present and then creates the
-- meta tag with the type label.
handleLab :: [(String, String)] -> IParse DocumentItem
handleLab = handleMetaTag "label" [("name", "name")] []
-- | Checks that all required arguments are present and then creates the
-- meta tag with the type ref.
handleRef :: [(String, String)] -> IParse DocumentItem
handleRef = handleMetaTag "ref" [("label", "label")] [("style", "style")]
-- | Checks that all required arguments are present and then creates the
-- meta tag with the type imgref.
handleImgRef :: [(String, String)] -> IParse DocumentItem
handleImgRef = handleMetaTag "imgref" [("label", "label")] []
-- | Checks that all required arguments are present and then creates the
-- meta tag with the type tblref.
handleTblRef :: [(String, String)] -> IParse DocumentItem
handleTblRef = handleMetaTag "tblref" [("label", "label")] []
-- | Handles the "setpos" tag, which is used internally to signal
the parser that the current ' SourcePos ' changed .
handleSetPos :: [(String, String)] -> IParse DocumentItem
handleSetPos args = do
ifHave "filename" args $ \filename ->
modifySourcePos $ (flip setSourceName) filename
ifHave "line" args $ \linenumber ->
modifySourcePos $ (flip setSourceLine) (read linenumber)
ifHave "column" args $ \column ->
modifySourcePos $ (flip setSourceColumn) (read column)
handleMetaTag "setpos" [] [("filename", "filename"), ("line", "line"), ("column", "column")] args
where ifHave x l a = case lookup x l of
Just v -> a v
Nothing -> return ()
modifySourcePos f = getPosition >>= (setPosition . f)
-- | Handles the flavor command, which can be used to activate markup
-- extensions.
handleFlavor :: [(String, String)] -> IParse DocumentItem
handleFlavor args = do
tag <- handleMetaTag "flavor" [("name", "name")] [] args
case (lookup "name" args >>= readMaybe) of
Nothing -> fail $ "Cannot parse udoc extension name " ++ (show $ lookup "name" args)
Just e -> PP.modifyState $ \x -> x { parserStateFlavor = (e:parserStateFlavor x) }
return tag
| Creates an ItemDocumentMetaContainer from the container type , its
-- properties and its content.
createMetaContainer :: String -- ^ The container type
-> [(String, String)] -- ^ The container properties
-> [DocumentItem] -- ^ The container content
-> DocumentItem -- ^ The resulting item
createMetaContainer t props content =
ItemDocumentContainer $ DocumentMetaContainer ([("type", t)] ++ props) content
| A command is either inlineSource or a regular command surrounded
-- by square brackets.
extendedCommand' :: IParse Command
extendedCommand' = inlineSource <|> inlineQuote <|> squareBrCommand
-- | This parses a command and handles it accordingly.
extendedCommand :: HSP -> IParse DocumentItem
extendedCommand hsp = do
(name, args) <- (spaces >> extendedCommand')
result <- handleExtendedCommand name args hsp
return result
-- | This works as some sort of lookahead: it expects a given command. However,
-- it will not consume any input.
extendedCommandName :: String -> IParse ()
extendedCommandName name = try (do (name', args) <- extendedCommand'
if name == name'
then do return ()
else do fail ""
) <?> "the tag [" ++ name ++ "]"
-- | If the last item in a list of items is a word, this function will remove
-- the last trailing newline of this word.
removeTrailingNewline :: [DocumentItem] -> [DocumentItem]
removeTrailingNewline [] = []
removeTrailingNewline items =
init items ++ nl (last items)
where nl (ItemWord w) = [ItemWord $ dropWhileEnd isSpace w]
nl x = [x]
-- | Handle an extended command. This is called once a command
-- has been found. It's responsible for returning the appropriate
-- data structure for the parse tree.
handleExtendedCommand :: String -- ^ The command name
-> [(String, String)] -- ^ The command's arguments
-> HSP -- ^ The supported special commands
-> IParse DocumentItem
handleExtendedCommand name args handleSpecialCommand =
case name of
"b" -> do skipEmptyLines
bold <- containerContentsUntil (extendedCommandName "/b")
handleSpecialCommand
return $ ItemDocumentContainer $ DocumentBoldFace bold
"i" -> do skipEmptyLines
italic <- containerContentsUntil (extendedCommandName "/i") handleSpecialCommand
return $ ItemDocumentContainer $ DocumentItalicFace italic
"br" -> return $ ItemLinebreak
"meta" -> return $ ItemMetaTag args
"pb" -> return $ ItemMetaTag [("type", "pagebreak")]
"image" -> do let scaling = fromMaybe "1" $ lookup "scaling" args
alignment = fromMaybe "center" $ lookup "align" args
label <- mLookup "label" args "Missing label in image tag"
caption <- mLookup "caption" args "Missing caption in image tag"
path <- mLookup "path" args "Missing path in image tag"
eatSpaces <- isOptionSet SkipNewlinesAfterImage
when eatSpaces skipEmptyLines
return $ ItemImage $ Image path caption label scaling alignment
"inlineImage" -> do let vOffset = fromMaybe "0" $ lookup "vOffset" args
path <- mLookup "path" args "Missing path in inlineImage tag"
return $ ItemMetaTag (
[ ("type", "inlineImage")
, ("path", path)
, ("vOffset", vOffset)
])
"table" -> do let mCL = ((,)) <$> lookup "caption" args <*> lookup "label" args
let style = fromMaybe "head_top" $ lookup "style" args
let mWidths = sequence $ map readMaybe $ map (filter (/= ' ')) $ split ',' $ fromMaybe "" $ lookup "widths" args
widths <- case mWidths of
Nothing -> fail "Cannot parse table widths argument."
Just w -> return w
skipEmptyLines
We need the position of the first row as ` table ` is
-- going to parse the whole table at once.
currentPosition <- P.getPosition
currentState <- P.getState
rows <- table
-- We simply apply our document parser to each table
-- cell.
rows <- forM rows $ \row -> do
cells <- forM row $ \cell -> do
case parseInlineDocument currentState currentPosition handleSpecialCommand cell of
Left err -> error $ "Error while parsing the table which is located at " ++ (show currentPosition) ++ ".\n\n" ++ (show err)
Right (inner, newS) -> do P.setState newS
return $ concat $ map stripOuterParagraph inner
return $ DocumentTableRow cells
return $ ItemDocumentContainer $ DocumentTable style mCL widths rows
"_s" -> do x <- parserStateLastInlineOpeningTag <$> P.getState
let chr = case x of
'{' -> '}'
'`' -> '`'
x -> x
source <- manyTill inlineVerbatimContent (char chr >> spaces)
return $ ItemDocumentContainer $ DocumentMetaContainer ([("type", "inlineSource")]) source
"_q" -> handleInlineQuote handleSpecialCommand
"source" -> do let language = fromMaybe "" $ lookup "language" args
skipEmptyLines
source <- manyTill (verbatimContent "[/source]") (extendedCommandName "/source")
eatSpaces <- isOptionSet SkipNewlinesAfterSourceOrQuoteBlock
when eatSpaces skipEmptyLines
return $ ItemDocumentContainer $ DocumentMetaContainer ([("type", "source"), ("language", language)]) (removeTrailingNewline source)
"label" -> handleLab args
"ref" -> handleRef args
"imgref" -> handleImgRef args
"tblref" -> handleTblRef args
"setpos" -> handleSetPos args
"quote" -> do optional newline
content <- manyTill (verbatimContent "[/quote]") (extendedCommandName "/quote")
eatSpaces <- isOptionSet SkipNewlinesAfterSourceOrQuoteBlock
when eatSpaces skipEmptyLines
return $ ItemDocumentContainer $ DocumentMetaContainer ([("type", "blockquote")]) (removeTrailingNewline content)
"flavor" -> handleFlavor args
-- If we end up here, we can at least check if the
-- identified command is some special-purpose
-- command
_ -> handleSpecialCommand name args
where stripOuterParagraph :: DocumentItem -> [DocumentItem]
stripOuterParagraph (ItemDocumentContainer (DocumentParagraph x)) = x
stripOuterParagraph x = [x]
split :: Eq a => a -> [a] -> [[a]]
split d [] = []
split d s = x : split d (drop 1 y) where (x,y) = span (/= d) s
| Parses one line from a table . Be aware , it really parses one line , not
-- one row.
oneTableLine :: IParse [String]
oneTableLine =
(many $ (notFollowedBy (extendedCommandName "/table") >> noneOf "|\n")) `sepBy` ((optional $ char ' ') >> (char '|') >> (optional $ char ' '))
-- | Utility for stopping parsing when a table ends
endOr :: a -> IParse a -> IParse a
endOr val action = try $ ((extendedCommandName "/table") >> return val)
<|> action
-- | Actual table parsing function. Takes a flag that tells whether or not the
-- table has to be parsed in "multi-line mode" (i.e., whether horizontal row
-- delimiters are necessary or not) and a current table structure. Returns a
-- new table structure.
table' :: Bool -> [[String]] -> IParse [[String]]
table' ml table = do
skipEmptyLines
endOr table $ do
lookAhead anyToken
l <- oneTableLine
let (newTable, newMl) = tableAppend ml l table
table' newMl newTable
-- | Correctly appends a row to a table, depending on wheter the table is
-- to be parsed in multi-line mode or not.
tableAppend :: Bool -> [String] -> [[String]] -> ([[String]], Bool)
tableAppend ml l table
| (not ml) && isDelimiter l && null table = (table, True)
| (not ml) && isDelimiter l = ([foldl (zipWith (\a b -> a ++ b ++ "\n")) emptyRow table] ++ [take (length $ table !! 0) emptyRow], True)
| ml && isDelimiter l = (table ++ [take (length $ table !! 0) emptyRow], True)
| not ml = (table ++ [l], False)
| ml && length table > 0 = ((init table) ++ [zipWith (\a b -> a ++ b ++ "\n") (last table) l], True)
| otherwise = (table, ml) -- Should not happen
where isDelimiter (l:[]) = all ((||) <$> (=='-') <*> (=='+')) (trimEnd l)
isDelimiter _ = False
emptyRow = repeat ""
trimEnd l = dropWhileEnd isSpace l
-- | Convenience wrapper around our table parsing function
table :: IParse [[String]]
table = do
t <- table' False []
return $ takeWhile (not . all (=="")) t
-- | Simply parse a paragraph.
paragraph :: HSP -> IParse DocumentItem
paragraph hsp = do
bq <- isOptionSet BlockQuotes
fc <- isOptionSet FencedCodeBlocks
let without = [(bq, blockQuoteBegin), (fc, fencedCodeBlockBegin)]
let withouts = foldl (\p (flag, parser) -> if flag then (p <|> (try parser)) else p) parserZero without
paragraphWithout withouts hsp
-- | Parse a paragraph. This Paragraph could contain a list of words or lists or
-- special commands. However, this parser will fail if parser x succeeds.
paragraphWithout :: IParse () -- ^ The parser that may not succeed
-> HSP -- ^ The supported special commands
-> IParse DocumentItem
paragraphWithout x hsp = do
lines <- many1 ( notFollowedBy x >>
(
(do x <- try $ line hsp; optional newline; return x)
<|> (do x <- try $ extendedCommand hsp; optional newline; return [x])
<|> (do x <- try $ uList hsp; return [x])
<|> (do x <- try $ oList hsp; return [x])
)
) <?> "a properly indented paragraph, command or list"
skipEmptyLines
return $ ItemDocumentContainer $ DocumentParagraph $ concat lines
-- | Parses escaped character sequences (such as \[) and returns the according
-- character.
escaped :: Char -> IParse Char
escaped x = (string ("\\"++[x])) >> return x
| Parses one character in a regular word of the text .
wordChar :: IParse Char
wordChar = do
bts <- isOptionSet BacktickSource
fcb <- isOptionSet FencedCodeBlocks
let additional = if bts || fcb
then "`"
else ""
doWordChar additional
where doWordChar additional =
(try $ escaped '[')
<|> (try $ escaped ']')
<|> (try $ escaped '|')
<|> (try $ escaped '{')
<|> (try $ escaped '}')
<|> (try $ escaped '"')
<|> (try $ escaped '\\')
<|> (try $ escaped '`')
<|> (try $ escaped '#')
<|> (noneOf $ " \t\n[]|{}\"" ++ additional)
<?> "a valid word character"
-- | Parses a whole word in the text of the document.
word :: IParse DocumentItem
word = do result <- many1 wordChar
spaces
return $ ItemWord result
-- | Contents of a source code section. Note that spaces, newlines and
-- tabs will be left as they are. However, the bold tag is supported!
verbatimContent :: String -> IParse DocumentItem
verbatimContent closingTag =
try (verbatimBold closingTag) <|> (verbatimText closingTag)
-- | Helper for bold text in verbatim content
verbatimBold :: String -- ^ The tag that will close the verbatim section.
-- could be [/code] for example.
-> IParse DocumentItem
verbatimBold closingTag = do
string "[b]"
bold <- manyTill (verbatimText closingTag) (extendedCommandName "/b")
return $ ItemDocumentContainer $ DocumentBoldFace (bold)
-- | Contents of the verbatim container. That might be everything, but
-- we handle [b] and [/b], in order to allow for bold parts in source
-- code.
verbatimText :: String -> IParse DocumentItem
verbatimText closingTag = do
result <- many1 (
(
(
(try $ lookAhead $ string "\\[b]")
<|> (try $ lookAhead $ string "\\[/b]")
<|> (try $ lookAhead $ string $ "\\" ++ closingTag)
) >>
(escaped '[')
)
<|>
(
(notFollowedBy $ string closingTag) >>
(notFollowedBy $ string "[b]") >>
(notFollowedBy $ string "[/b]") >>
(anyChar)
)
)
return $ ItemWord result
-- | Contents of the inline verbatim container - may basically be everything
-- besides { or }, which need to be escaped.
inlineVerbatimContent :: IParse DocumentItem
inlineVerbatimContent = do
result <- many1 (wordChar <|> oneOf "\n\t |\"[]")
return $ ItemWord result
-- | Contents of the inline quoted text container - may basically be everything
-- besides ", which needs to be escaped.
handleInlineQuote :: HSP -> IParse DocumentItem
handleInlineQuote hsp = do
text <- containerContentsUntil closingQuote hsp
return $ ItemDocumentContainer $ DocumentMetaContainer ([("type", "inlineQuote")]) text
where
closingQuote :: IParse ()
closingQuote = do
char '"'
return ()
-- | The start of the regular line of text. This is only a lookahead, which
-- will not match lists or headings (or block quotes if this feature is
-- enabled)
beginRegularLine :: IParse ()
beginRegularLine =
(notFollowedBy $ listItemBegin) >>
(notFollowedBy $ headingBegin)
-- | One line of text
line :: HSP -> IParse [DocumentItem]
line hsp =
spaces >> beginRegularLine >> (many1 word)
-- | An empty line of text
emptyline :: IParse ()
emptyline = do spaces
(char '\n' >> return ())
return ()
| all empty lines of text
skipEmptyLines :: IParse ()
skipEmptyLines = skipMany (try emptyline)
-- | This basically matches anything but paragraphs and headings
It will parse multiple words or one other item , but it will
-- fail on newline.
containerContentOneLine :: HSP -> IParse [DocumentItem]
containerContentOneLine hsp =
(try $ (:[]) <$> extendedCommand hsp)
<|> (try $ (:[]) <$> uList hsp)
<|> (try $ (:[]) <$> oList hsp)
<|> (beginRegularLine >> many1 word)
-- | If the last item in l is a Paragraph, then remove this paragraph
-- and replace it by its plain contents.
removeLastPara :: [DocumentItem] -> [DocumentItem]
removeLastPara [] = []
removeLastPara l =
let rev = reverse l
fst = removePara $ head rev
in
reverse ((reverse fst) ++ (tail rev))
| If the supplied DocumentItem is a DocumentParagraph , then just
return the Paragraph contents . Otherwise simply return the DocumentItem
-- that has been provided.
removePara :: DocumentItem -> [DocumentItem]
removePara (ItemDocumentContainer (DocumentParagraph l)) = l
removePara x = [x]
-- | Read container content until parser x succeeds. This will generally
return a list of DocumentItems , potentially containing Paragraphs .
-- If the last item in the list is a Paragraph, it will be replaced by
-- its contents.
containerContentsUntil :: IParse() -- ^ The parser that may not succeed
-> HSP -- ^ The supported special commands
-> IParse [DocumentItem]
containerContentsUntil x hsp = do
contents <- manyTill (containerContentWithout x hsp) (x)
return $ removeLastPara contents
-- | The contents of a container; may not contain anything matched by some
-- parser x.
containerContentWithout :: IParse () -- ^ Forbidden content
-> HSP -- ^ Supported special commands
-> IParse DocumentItem
containerContentWithout x hsp = notFollowedBy x >> paragraphWithout x hsp
-- | The contents of a container
containerContentBlock :: HSP -> IParse [DocumentItem]
containerContentBlock hsp = do
x <- many1 $ do
l <- containerContentOneLine hsp
spaces
return l
spaces
optional newline
spaces
return $ concat x
| The begin of an item in an un - ordered list . Returns the indentation level .
uListItemBegin :: IParse Int
uListItemBegin = do
i <- many $ char ' '
char '*'
j <- many $ char ' '
return $ ((length (i++j)) + 1)
| The body of an item in an un - ordered list
uListItemBody :: HSP -> Int -> IParse (UListItem, [DocumentItem])
uListItemBody hsp ind = do
content <- block (containerContentBlock hsp)
return $ (UListItem ind, (concat content))
| One item in an un - ordered list
uListItem :: HSP -> IParse (UListItem, [DocumentItem])
uListItem hsp =
do ind <- uListItemBegin
uListItemBody hsp ind
-- | Am un-ordered (bullet point) list
uList :: HSP -> IParse DocumentItem
uList hsp = do
checkIndent
lookAhead (uListItemBegin)
s <- P.getState
P.setState $ s { parserStateCurrentListLevel = parserStateCurrentListLevel s + 1 }
result <- block $ uListItem hsp
P.setState $ s { parserStateCurrentListLevel = parserStateCurrentListLevel s }
eatSpaces <- isOptionSet SkipNewlinesAfterUlist
when (parserStateCurrentListLevel s == 0 && eatSpaces) $ skipEmptyLines
return $ ItemDocumentContainer (DocumentUList result)
-- | The begin of an item in an ordered list. Returns the indentation level
-- and the item's number.
oListItemBegin :: IParse (Int, String)
oListItemBegin = do
newStyle <- isOptionSet NewStyleOlist
if newStyle
then newOlistItemBegin
else oldOlistItemBegin
-- | The new version of ordered lists start with dotted numbers followed
-- by either a dot, the sequence .) or the ) character.
newOlistItemBegin :: IParse (Int, String)
newOlistItemBegin = do
i <- many $ char ' '
string "+"
many1 space
return ((length i), "0")
-- | The old version of ordered lists start with dotted numbers followed
-- by either a dot, the sequence .) or the ) character.
oldOlistItemBegin :: IParse (Int, String)
oldOlistItemBegin = do
i <- many $ char ' '
number <- dottedNumber
trailer <- ( (try $ string ".)") <|> string "." <|> string ")" <?> "a number in an enumerated list")
spaces
return ((length i), number)
| One item in an ordered list
oListItem :: HSP -> IParse (OListItem, [DocumentItem])
oListItem hsp =
do (ind, num) <- oListItemBegin
content <- block $ (containerContentBlock hsp)
return $ (OListItem ind num, (concat content))
-- | An ordered list.
oList :: HSP -> IParse DocumentItem
oList hsp =
do checkIndent
lookAhead oListItemBegin
items <- block $ oListItem hsp
return $ ItemDocumentContainer (DocumentOList items)
| A number like 1 , 1.2 or 1.2.3.4
dottedNumber :: IParse String
dottedNumber = do num <- many1 digit
rest <- try (char '.' >> dottedNumber) <|> return ""
if length rest == 0 then
return num
else
return (num ++ "." ++ rest)
-- | The begin of a list item: either the begin of an UListItem or the
-- begin of an OListItem.
listItemBegin :: IParse ()
listItemBegin =
((try uListItemBegin) >> return ()) <|> (oListItemBegin >> return ())
-- | The begin of a heading: a number of # characters. Returns the heading
-- level.
headingBegin :: IParse Int
headingBegin = do
spaces
level <- (many1 $ char '#')
spaces
return $ length level
-- | A heading
heading :: HSP -> IParse DocumentItem
heading hsp = do
level <- headingBegin
content <- many1 (
(
(do x <- try $ line hsp; return x)
<|> (do x <- try $ extendedCommand hsp; return [x])
)
)
skipEmptyLines
return $ ItemDocumentContainer $ DocumentHeading (Heading level Nothing) (concat content)
-- | The start of a block quote
blockQuoteBegin :: IParse ()
blockQuoteBegin = do
spaces
char '>'
spaces
-- | A block quote
blockQuote :: IParse DocumentItem
blockQuote = do
lines <- many1 $ do
blockQuoteBegin
thisLine <- many $ noneOf "\n"
optional newline
return thisLine
skipEmptyLines
return $ ItemDocumentContainer $ DocumentMetaContainer [("type","blockquote")] [ItemWord $ intercalate "\n" lines]
-- | The start of a fenced code block
fencedCodeBlockBegin :: IParse ()
fencedCodeBlockBegin = do
string "```"
return ()
-- | A fenced code block
fencedCodeBlock :: IParse DocumentItem
fencedCodeBlock = do
fencedCodeBlockBegin
language <- many $ noneOf "\n"
newline
lines <- many $ do
notFollowedBy $ string "```"
thisLine <- many $ noneOf "\n"
newline
return thisLine
string "```"
newline
skipEmptyLines
return $ ItemDocumentContainer $ DocumentMetaContainer [("type", "source"), ("language", language)] [ItemWord $ intercalate "\n" lines]
| null | https://raw.githubusercontent.com/greg42/openOfficeMarkup/46b99482625e945eb4b0f57c905c3c0e7224a2ca/markupParser/Text/Udoc/DocumentParser.hs | haskell | --------------------------------------------------------------------------
--------------------------------------------------------------------------
--------------------------------------------------------------------------
--------------------------------------------------------------------------
| A parser state without any syntax options set
| Indentation sensitive parser
a new parser
| Returns whether or not a parsing option is set.
| Executes a parser if any only if a configuration option is set.
| A command is an entity in a document that will cause the backend renderer
to perform a special operation. Commands in this markup language take the
is a tuple consisting of the command name and the command arguments.
| Parse a udoc document and return the document items.
| Parse an inline udoc document and return the document items (e.g. to
| parse table cells). In case of an error use the given initial source
| position as error position.
|
| TODO: As soon as its possible to determine the initial position of
| each table cell it would be nice to combine the initial
| position and the error position to determine the real
| position.
| Use the position of the last parsed parent document character as new
| error position.
| Top level parser. It will parse headings or paragraphs until
eof is found.
Before we start our paragraph based parsing, let's see if the
include them separately, i.e., without a surrounding paragraph.
| A command parameter. This is a string of the form: key = value. The
value may be quoted.
| The inner part of a command. This matches a string of the form:
command key=value.
| A command surrounded by square brackets.
| Some text surrounded by curly brackets. This will internally be
represented as a command called "_s" (for source code)
| Some text surrounded by double quotes. This will internally be
represented as a command called "_q" (for quote)
| Looks up a list of keys from an association list. If all keys are found,
returns Just [values]. Otherwise, returns nothing.
^ Keys to be looked up
^ An association list
^ The result
keys are not found, this runction returns Nothing. Otherwise, it will return
Just a new association list. The keys in this new association list will
however not be the original keys that were looked up. Instead, the lookup
keys will be renamed.
^ A pair: (lookup key, new key)
^ An association list
^ The result with the lookup keys renamed
| Looks up a list of keys from an association list and builds a new
association list, holding the found values. The keys in the new list are
obtained by renaming the old keys.
^ A pair: (lookup key, new key)
^ An association list
^ The result with the lookup keys renamed
getJust (Nothing, Just 2) = Nothing
all required and optional arguments from a list. The obtained arguments will
be renamed and then a function will be invoked on both resulting argument
lists. The result of the function will be returned.
^ A renaming pair for the mandatory args
^ A renaming pair for the optional args
^ An association list
^ A function for handling
the resulting lists of mandatory
and optional arguments
^ The result
| Lookup a required tag attribute that may not exist.
| Creates an ItemMetaTag from the following data: a tag name, the list
of mandatory properties and the list of optional properties.
^ The name of the tag type
^ The mandatory properties
^ The optional properties
^ The resulting document item
| Tries to create a meta tag specified by is name. To create the tag, this
function will lookup all mandatory and optional arguments from the argument
list that has been supplied. If this worked out, it will return an
ItemMetaTag.
^ The name of the tag type
^ Mandatory tag arguments
^ Optional tag arguments
^ The parsed tag arguments
^ The resulting item
| Checks that all required arguments are present and then creates the
meta tag with the type label.
| Checks that all required arguments are present and then creates the
meta tag with the type ref.
| Checks that all required arguments are present and then creates the
meta tag with the type imgref.
| Checks that all required arguments are present and then creates the
meta tag with the type tblref.
| Handles the "setpos" tag, which is used internally to signal
| Handles the flavor command, which can be used to activate markup
extensions.
properties and its content.
^ The container type
^ The container properties
^ The container content
^ The resulting item
by square brackets.
| This parses a command and handles it accordingly.
| This works as some sort of lookahead: it expects a given command. However,
it will not consume any input.
| If the last item in a list of items is a word, this function will remove
the last trailing newline of this word.
| Handle an extended command. This is called once a command
has been found. It's responsible for returning the appropriate
data structure for the parse tree.
^ The command name
^ The command's arguments
^ The supported special commands
going to parse the whole table at once.
We simply apply our document parser to each table
cell.
If we end up here, we can at least check if the
identified command is some special-purpose
command
one row.
| Utility for stopping parsing when a table ends
| Actual table parsing function. Takes a flag that tells whether or not the
table has to be parsed in "multi-line mode" (i.e., whether horizontal row
delimiters are necessary or not) and a current table structure. Returns a
new table structure.
| Correctly appends a row to a table, depending on wheter the table is
to be parsed in multi-line mode or not.
Should not happen
| Convenience wrapper around our table parsing function
| Simply parse a paragraph.
| Parse a paragraph. This Paragraph could contain a list of words or lists or
special commands. However, this parser will fail if parser x succeeds.
^ The parser that may not succeed
^ The supported special commands
| Parses escaped character sequences (such as \[) and returns the according
character.
| Parses a whole word in the text of the document.
| Contents of a source code section. Note that spaces, newlines and
tabs will be left as they are. However, the bold tag is supported!
| Helper for bold text in verbatim content
^ The tag that will close the verbatim section.
could be [/code] for example.
| Contents of the verbatim container. That might be everything, but
we handle [b] and [/b], in order to allow for bold parts in source
code.
| Contents of the inline verbatim container - may basically be everything
besides { or }, which need to be escaped.
| Contents of the inline quoted text container - may basically be everything
besides ", which needs to be escaped.
| The start of the regular line of text. This is only a lookahead, which
will not match lists or headings (or block quotes if this feature is
enabled)
| One line of text
| An empty line of text
| This basically matches anything but paragraphs and headings
fail on newline.
| If the last item in l is a Paragraph, then remove this paragraph
and replace it by its plain contents.
that has been provided.
| Read container content until parser x succeeds. This will generally
If the last item in the list is a Paragraph, it will be replaced by
its contents.
^ The parser that may not succeed
^ The supported special commands
| The contents of a container; may not contain anything matched by some
parser x.
^ Forbidden content
^ Supported special commands
| The contents of a container
| Am un-ordered (bullet point) list
| The begin of an item in an ordered list. Returns the indentation level
and the item's number.
| The new version of ordered lists start with dotted numbers followed
by either a dot, the sequence .) or the ) character.
| The old version of ordered lists start with dotted numbers followed
by either a dot, the sequence .) or the ) character.
| An ordered list.
| The begin of a list item: either the begin of an UListItem or the
begin of an OListItem.
| The begin of a heading: a number of # characters. Returns the heading
level.
| A heading
| The start of a block quote
| A block quote
| The start of a fenced code block
| A fenced code block |
- " THE BEER - WARE LICENSE " ( Revision 42 ):
- < > wrote this file . As long as you retain this notice you
- can do whatever you want with this stuff . If we meet some day , and you
- think this stuff is worth it , you can buy me a beer in return .
- "THE BEER-WARE LICENSE" (Revision 42):
- <> wrote this file. As long as you retain this notice you
- can do whatever you want with this stuff. If we meet some day, and you
- think this stuff is worth it, you can buy me a beer in return. Gregor Kopf
-}
|
Module : Text . Udoc .
Description : Udoc document parser
Copyright : ( c ) , 2012
License : BEER - WARE LICENSE ( Revision 42 )
Maintainer :
Stability : experimental
This module contains the implementation of the udoc parser .
Module : Text.Udoc.DocumentParser
Description : Udoc document parser
Copyright : (c) Gregor Kopf, 2012
License : BEER-WARE LICENSE (Revision 42)
Maintainer :
Stability : experimental
This module contains the implementation of the udoc parser.
-}
# LANGUAGE FlexibleContexts #
module Text.Udoc.DocumentParser where
import Text.ParserCombinators.Parsec hiding (State, try, spaces)
import qualified Text.ParserCombinators.Parsec as P
import qualified Text.ParserCombinators.Parsec.Error as PE
import Text.Parsec.Prim (parserZero, runParserT, ParsecT, try)
import qualified Text.Parsec.Prim as PP
import Control.Monad
import Control.Monad.State
import Text.JSON
import Text.Udoc.Document
import Data.Either
import Data.Char
import Data.Maybe
import Data.Functor.Identity
import Text.Parsec.Indent
import Text.Parsec.Pos
import Control.Applicative hiding ((<|>), many, optional)
import Text.Read
import Data.List
data SyntaxOption = SkipNewlinesAfterUlist
| SkipNewlinesAfterImage
| BacktickSource
| SkipNewlinesAfterSourceOrQuoteBlock
| BlockQuotes
| FencedCodeBlocks
| NewStyleOlist
deriving (Eq, Read, Show)
type SyntaxFlavor = [SyntaxOption]
data ParserState = ParserState {
parserStateFlavor :: SyntaxFlavor
, parserStateLastInlineOpeningTag :: Char
, parserStateCurrentListLevel :: Int
}
defaultParserState :: ParserState
defaultParserState = ParserState [] '{' 0
type IParse r = ParsecT String ParserState (State SourcePos) r
| The type for HandleSpecialCommand : Takes a name , arguments and returns
type HSP = String -> [(String, String)] -> IParse DocumentItem
isOptionSet :: SyntaxOption -> IParse Bool
isOptionSet opt = (elem opt . parserStateFlavor) <$> P.getState
whenOptionSet :: SyntaxOption -> IParse () -> IParse ()
whenOptionSet opt act = do
s <- isOptionSet opt
when s $ act
general form [ command argument = value , = value2 ] . Therefore , a Command
type Command = (String, [(String, String)])
parseDocument :: ParserState -> HSP -> String -> Either ParseError ([DocumentItem], ParserState)
parseDocument initialState hsp input =
myParse id parser input
where myParse f p src = fst
$ flip runState (f $ initialPos "")
$ runParserT p initialState "" src
parser = do items <- documentItems hsp
s <- P.getState
return (items, s)
parseInlineDocument :: ParserState -> SourcePos -> HSP -> String -> Either ParseError ([DocumentItem], ParserState)
parseInlineDocument initialState currentPosition handleSpecialCommand source =
fixPosition $ fst $ runState runParser (initialPos fileName)
where
fileName :: String
fileName = sourceName currentPosition
runParser :: State SourcePos (Either ParseError ([DocumentItem], ParserState))
runParser = runParserT parser initialState fileName source
parser :: IParse ([DocumentItem], ParserState)
parser = do
itemHandler <- documentItems handleSpecialCommand
currentState <- P.getState
return (itemHandler, currentState)
fixPosition :: Either ParseError ([DocumentItem], ParserState) -> Either ParseError ([DocumentItem], ParserState)
fixPosition result = case result of
Left error -> Left $ PE.setErrorPos (updateErrorPos currentPosition (PE.errorPos error)) error
right -> right
updateErrorPos :: SourcePos -> SourcePos -> SourcePos
updateErrorPos initialPos errorPos =
setSourceColumn (setSourceLine errorPos $ (sourceLine initialPos)) (sourceColumn initialPos)
| Skips zero or more space or tab characters .
spaces :: IParse ()
spaces = skipMany $ oneOf " \t"
| Skipts zero of more space , tab and newline characters .
whiteSpace :: IParse ()
whiteSpace = skipMany $ oneOf " \t\n"
documentItems :: HSP -> IParse [DocumentItem]
documentItems hsp = do
whiteSpace
document starts with one or more meta tags . If so , we just
docHead <- many $ tryCommand isMetaTag
whiteSpace
items <- many $ (try $ heading hsp)
<|> (try $ optionIf BlockQuotes $ blockQuote)
<|> (try $ optionIf FencedCodeBlocks $ fencedCodeBlock)
<|> paragraph hsp
whiteSpace
eof
return $ docHead ++ items
where tryCommand pred = try $ do
cmd <- extendedCommand hsp
optional newline
if pred cmd
then return cmd
else fail "Did not find expected command"
isMetaTag (ItemMetaTag _) = True
isMetaTag _ = False
optionIf opt a = do
s <- isOptionSet opt
if s
then a
else fail ""
| A string between two double quotes .
quotedContent :: IParse String
quotedContent =
between (char '"') (char '"') (many1 (wordChar <|> char ' '))
commandParameter :: IParse (String, String)
commandParameter = do whiteSpace
name <- many1 alphaNum
spaces
char '='
spaces
value <- quotedContent <|> (many1 $ noneOf "\n ,\t\"[]")
whiteSpace
return (name, value)
command :: IParse Command
command = do
whiteSpace
commandName <- many1 (alphaNum <|> char '/')
whiteSpace
params <- commandParameter `sepBy` (char ',')
whiteSpace
return (commandName, params)
squareBrCommand :: IParse Command
squareBrCommand =
between (char '[') (char ']') (do ret <- command; spaces; return ret)
inlineSource :: IParse Command
inlineSource = do backticks <- isOptionSet BacktickSource
let chars = if backticks then "{`" else "{"
opener <- oneOf chars
PP.modifyState $ \x -> x { parserStateLastInlineOpeningTag = opener }
return ("_s", [])
inlineQuote :: IParse Command
inlineQuote = char '"' >> return ("_q", [])
getMandatory :: (Eq a) =>
getMandatory keys aList = mapM ((flip lookup) aList) keys
| Looks up a list of keys from an association list . If at least one of the
mandRename :: (Eq a) =>
mandRename mandKeyName aList =
zip <$> (Just $ map snd mandKeyName) <*>
(getMandatory (map fst mandKeyName) aList)
optRename :: (Eq a) =>
optRename optKeyName aList =
let values = map ((flip lookup) aList) (map fst optKeyName)
getJust ( Just 3 , Just 3 ) = Just ( 3 , 4 )
getJust x = ((,)) <$> fst x <*> snd x
in
catMaybes $ map getJust (zip (map (Just . snd) optKeyName) values)
| A combination of mandRename and optRename . This function tries to extract
getArgumentsOrFail :: (Monad m, Eq a, Show a) =>
getArgumentsOrFail mandArgs optArgs aList f =
let mand = mandRename mandArgs aList
opt = optRename optArgs aList
in
case mand of
Nothing -> fail $ "Missing argument. Epecting: " ++
(show $ map fst mandArgs) ++
" but only got " ++ (show $ map fst aList)
Just m' -> return $ f m' opt
mLookup :: (Show a, Monad m, Eq a) => a -> [(a , b)] -> String -> m b
mLookup k al error_message = maybe (fail error_message) return $ lookup k al
createMetaTag t mprops oprops = ItemMetaTag $ [("type", t)] ++ mprops ++ oprops
handleMetaTag :: (Monad m, Show a, Eq a) =>
handleMetaTag t mand opt aList =
getArgumentsOrFail mand opt aList (createMetaTag t)
handleLab :: [(String, String)] -> IParse DocumentItem
handleLab = handleMetaTag "label" [("name", "name")] []
handleRef :: [(String, String)] -> IParse DocumentItem
handleRef = handleMetaTag "ref" [("label", "label")] [("style", "style")]
handleImgRef :: [(String, String)] -> IParse DocumentItem
handleImgRef = handleMetaTag "imgref" [("label", "label")] []
handleTblRef :: [(String, String)] -> IParse DocumentItem
handleTblRef = handleMetaTag "tblref" [("label", "label")] []
the parser that the current ' SourcePos ' changed .
handleSetPos :: [(String, String)] -> IParse DocumentItem
handleSetPos args = do
ifHave "filename" args $ \filename ->
modifySourcePos $ (flip setSourceName) filename
ifHave "line" args $ \linenumber ->
modifySourcePos $ (flip setSourceLine) (read linenumber)
ifHave "column" args $ \column ->
modifySourcePos $ (flip setSourceColumn) (read column)
handleMetaTag "setpos" [] [("filename", "filename"), ("line", "line"), ("column", "column")] args
where ifHave x l a = case lookup x l of
Just v -> a v
Nothing -> return ()
modifySourcePos f = getPosition >>= (setPosition . f)
handleFlavor :: [(String, String)] -> IParse DocumentItem
handleFlavor args = do
tag <- handleMetaTag "flavor" [("name", "name")] [] args
case (lookup "name" args >>= readMaybe) of
Nothing -> fail $ "Cannot parse udoc extension name " ++ (show $ lookup "name" args)
Just e -> PP.modifyState $ \x -> x { parserStateFlavor = (e:parserStateFlavor x) }
return tag
| Creates an ItemDocumentMetaContainer from the container type , its
createMetaContainer t props content =
ItemDocumentContainer $ DocumentMetaContainer ([("type", t)] ++ props) content
| A command is either inlineSource or a regular command surrounded
extendedCommand' :: IParse Command
extendedCommand' = inlineSource <|> inlineQuote <|> squareBrCommand
extendedCommand :: HSP -> IParse DocumentItem
extendedCommand hsp = do
(name, args) <- (spaces >> extendedCommand')
result <- handleExtendedCommand name args hsp
return result
extendedCommandName :: String -> IParse ()
extendedCommandName name = try (do (name', args) <- extendedCommand'
if name == name'
then do return ()
else do fail ""
) <?> "the tag [" ++ name ++ "]"
removeTrailingNewline :: [DocumentItem] -> [DocumentItem]
removeTrailingNewline [] = []
removeTrailingNewline items =
init items ++ nl (last items)
where nl (ItemWord w) = [ItemWord $ dropWhileEnd isSpace w]
nl x = [x]
-> IParse DocumentItem
handleExtendedCommand name args handleSpecialCommand =
case name of
"b" -> do skipEmptyLines
bold <- containerContentsUntil (extendedCommandName "/b")
handleSpecialCommand
return $ ItemDocumentContainer $ DocumentBoldFace bold
"i" -> do skipEmptyLines
italic <- containerContentsUntil (extendedCommandName "/i") handleSpecialCommand
return $ ItemDocumentContainer $ DocumentItalicFace italic
"br" -> return $ ItemLinebreak
"meta" -> return $ ItemMetaTag args
"pb" -> return $ ItemMetaTag [("type", "pagebreak")]
"image" -> do let scaling = fromMaybe "1" $ lookup "scaling" args
alignment = fromMaybe "center" $ lookup "align" args
label <- mLookup "label" args "Missing label in image tag"
caption <- mLookup "caption" args "Missing caption in image tag"
path <- mLookup "path" args "Missing path in image tag"
eatSpaces <- isOptionSet SkipNewlinesAfterImage
when eatSpaces skipEmptyLines
return $ ItemImage $ Image path caption label scaling alignment
"inlineImage" -> do let vOffset = fromMaybe "0" $ lookup "vOffset" args
path <- mLookup "path" args "Missing path in inlineImage tag"
return $ ItemMetaTag (
[ ("type", "inlineImage")
, ("path", path)
, ("vOffset", vOffset)
])
"table" -> do let mCL = ((,)) <$> lookup "caption" args <*> lookup "label" args
let style = fromMaybe "head_top" $ lookup "style" args
let mWidths = sequence $ map readMaybe $ map (filter (/= ' ')) $ split ',' $ fromMaybe "" $ lookup "widths" args
widths <- case mWidths of
Nothing -> fail "Cannot parse table widths argument."
Just w -> return w
skipEmptyLines
We need the position of the first row as ` table ` is
currentPosition <- P.getPosition
currentState <- P.getState
rows <- table
rows <- forM rows $ \row -> do
cells <- forM row $ \cell -> do
case parseInlineDocument currentState currentPosition handleSpecialCommand cell of
Left err -> error $ "Error while parsing the table which is located at " ++ (show currentPosition) ++ ".\n\n" ++ (show err)
Right (inner, newS) -> do P.setState newS
return $ concat $ map stripOuterParagraph inner
return $ DocumentTableRow cells
return $ ItemDocumentContainer $ DocumentTable style mCL widths rows
"_s" -> do x <- parserStateLastInlineOpeningTag <$> P.getState
let chr = case x of
'{' -> '}'
'`' -> '`'
x -> x
source <- manyTill inlineVerbatimContent (char chr >> spaces)
return $ ItemDocumentContainer $ DocumentMetaContainer ([("type", "inlineSource")]) source
"_q" -> handleInlineQuote handleSpecialCommand
"source" -> do let language = fromMaybe "" $ lookup "language" args
skipEmptyLines
source <- manyTill (verbatimContent "[/source]") (extendedCommandName "/source")
eatSpaces <- isOptionSet SkipNewlinesAfterSourceOrQuoteBlock
when eatSpaces skipEmptyLines
return $ ItemDocumentContainer $ DocumentMetaContainer ([("type", "source"), ("language", language)]) (removeTrailingNewline source)
"label" -> handleLab args
"ref" -> handleRef args
"imgref" -> handleImgRef args
"tblref" -> handleTblRef args
"setpos" -> handleSetPos args
"quote" -> do optional newline
content <- manyTill (verbatimContent "[/quote]") (extendedCommandName "/quote")
eatSpaces <- isOptionSet SkipNewlinesAfterSourceOrQuoteBlock
when eatSpaces skipEmptyLines
return $ ItemDocumentContainer $ DocumentMetaContainer ([("type", "blockquote")]) (removeTrailingNewline content)
"flavor" -> handleFlavor args
_ -> handleSpecialCommand name args
where stripOuterParagraph :: DocumentItem -> [DocumentItem]
stripOuterParagraph (ItemDocumentContainer (DocumentParagraph x)) = x
stripOuterParagraph x = [x]
split :: Eq a => a -> [a] -> [[a]]
split d [] = []
split d s = x : split d (drop 1 y) where (x,y) = span (/= d) s
| Parses one line from a table . Be aware , it really parses one line , not
oneTableLine :: IParse [String]
oneTableLine =
(many $ (notFollowedBy (extendedCommandName "/table") >> noneOf "|\n")) `sepBy` ((optional $ char ' ') >> (char '|') >> (optional $ char ' '))
endOr :: a -> IParse a -> IParse a
endOr val action = try $ ((extendedCommandName "/table") >> return val)
<|> action
table' :: Bool -> [[String]] -> IParse [[String]]
table' ml table = do
skipEmptyLines
endOr table $ do
lookAhead anyToken
l <- oneTableLine
let (newTable, newMl) = tableAppend ml l table
table' newMl newTable
tableAppend :: Bool -> [String] -> [[String]] -> ([[String]], Bool)
tableAppend ml l table
| (not ml) && isDelimiter l && null table = (table, True)
| (not ml) && isDelimiter l = ([foldl (zipWith (\a b -> a ++ b ++ "\n")) emptyRow table] ++ [take (length $ table !! 0) emptyRow], True)
| ml && isDelimiter l = (table ++ [take (length $ table !! 0) emptyRow], True)
| not ml = (table ++ [l], False)
| ml && length table > 0 = ((init table) ++ [zipWith (\a b -> a ++ b ++ "\n") (last table) l], True)
where isDelimiter (l:[]) = all ((||) <$> (=='-') <*> (=='+')) (trimEnd l)
isDelimiter _ = False
emptyRow = repeat ""
trimEnd l = dropWhileEnd isSpace l
table :: IParse [[String]]
table = do
t <- table' False []
return $ takeWhile (not . all (=="")) t
paragraph :: HSP -> IParse DocumentItem
paragraph hsp = do
bq <- isOptionSet BlockQuotes
fc <- isOptionSet FencedCodeBlocks
let without = [(bq, blockQuoteBegin), (fc, fencedCodeBlockBegin)]
let withouts = foldl (\p (flag, parser) -> if flag then (p <|> (try parser)) else p) parserZero without
paragraphWithout withouts hsp
-> IParse DocumentItem
paragraphWithout x hsp = do
lines <- many1 ( notFollowedBy x >>
(
(do x <- try $ line hsp; optional newline; return x)
<|> (do x <- try $ extendedCommand hsp; optional newline; return [x])
<|> (do x <- try $ uList hsp; return [x])
<|> (do x <- try $ oList hsp; return [x])
)
) <?> "a properly indented paragraph, command or list"
skipEmptyLines
return $ ItemDocumentContainer $ DocumentParagraph $ concat lines
escaped :: Char -> IParse Char
escaped x = (string ("\\"++[x])) >> return x
| Parses one character in a regular word of the text .
wordChar :: IParse Char
wordChar = do
bts <- isOptionSet BacktickSource
fcb <- isOptionSet FencedCodeBlocks
let additional = if bts || fcb
then "`"
else ""
doWordChar additional
where doWordChar additional =
(try $ escaped '[')
<|> (try $ escaped ']')
<|> (try $ escaped '|')
<|> (try $ escaped '{')
<|> (try $ escaped '}')
<|> (try $ escaped '"')
<|> (try $ escaped '\\')
<|> (try $ escaped '`')
<|> (try $ escaped '#')
<|> (noneOf $ " \t\n[]|{}\"" ++ additional)
<?> "a valid word character"
word :: IParse DocumentItem
word = do result <- many1 wordChar
spaces
return $ ItemWord result
verbatimContent :: String -> IParse DocumentItem
verbatimContent closingTag =
try (verbatimBold closingTag) <|> (verbatimText closingTag)
-> IParse DocumentItem
verbatimBold closingTag = do
string "[b]"
bold <- manyTill (verbatimText closingTag) (extendedCommandName "/b")
return $ ItemDocumentContainer $ DocumentBoldFace (bold)
verbatimText :: String -> IParse DocumentItem
verbatimText closingTag = do
result <- many1 (
(
(
(try $ lookAhead $ string "\\[b]")
<|> (try $ lookAhead $ string "\\[/b]")
<|> (try $ lookAhead $ string $ "\\" ++ closingTag)
) >>
(escaped '[')
)
<|>
(
(notFollowedBy $ string closingTag) >>
(notFollowedBy $ string "[b]") >>
(notFollowedBy $ string "[/b]") >>
(anyChar)
)
)
return $ ItemWord result
inlineVerbatimContent :: IParse DocumentItem
inlineVerbatimContent = do
result <- many1 (wordChar <|> oneOf "\n\t |\"[]")
return $ ItemWord result
handleInlineQuote :: HSP -> IParse DocumentItem
handleInlineQuote hsp = do
text <- containerContentsUntil closingQuote hsp
return $ ItemDocumentContainer $ DocumentMetaContainer ([("type", "inlineQuote")]) text
where
closingQuote :: IParse ()
closingQuote = do
char '"'
return ()
beginRegularLine :: IParse ()
beginRegularLine =
(notFollowedBy $ listItemBegin) >>
(notFollowedBy $ headingBegin)
line :: HSP -> IParse [DocumentItem]
line hsp =
spaces >> beginRegularLine >> (many1 word)
emptyline :: IParse ()
emptyline = do spaces
(char '\n' >> return ())
return ()
| all empty lines of text
skipEmptyLines :: IParse ()
skipEmptyLines = skipMany (try emptyline)
It will parse multiple words or one other item , but it will
containerContentOneLine :: HSP -> IParse [DocumentItem]
containerContentOneLine hsp =
(try $ (:[]) <$> extendedCommand hsp)
<|> (try $ (:[]) <$> uList hsp)
<|> (try $ (:[]) <$> oList hsp)
<|> (beginRegularLine >> many1 word)
removeLastPara :: [DocumentItem] -> [DocumentItem]
removeLastPara [] = []
removeLastPara l =
let rev = reverse l
fst = removePara $ head rev
in
reverse ((reverse fst) ++ (tail rev))
| If the supplied DocumentItem is a DocumentParagraph , then just
return the Paragraph contents . Otherwise simply return the DocumentItem
removePara :: DocumentItem -> [DocumentItem]
removePara (ItemDocumentContainer (DocumentParagraph l)) = l
removePara x = [x]
return a list of DocumentItems , potentially containing Paragraphs .
-> IParse [DocumentItem]
containerContentsUntil x hsp = do
contents <- manyTill (containerContentWithout x hsp) (x)
return $ removeLastPara contents
-> IParse DocumentItem
containerContentWithout x hsp = notFollowedBy x >> paragraphWithout x hsp
containerContentBlock :: HSP -> IParse [DocumentItem]
containerContentBlock hsp = do
x <- many1 $ do
l <- containerContentOneLine hsp
spaces
return l
spaces
optional newline
spaces
return $ concat x
| The begin of an item in an un - ordered list . Returns the indentation level .
uListItemBegin :: IParse Int
uListItemBegin = do
i <- many $ char ' '
char '*'
j <- many $ char ' '
return $ ((length (i++j)) + 1)
| The body of an item in an un - ordered list
uListItemBody :: HSP -> Int -> IParse (UListItem, [DocumentItem])
uListItemBody hsp ind = do
content <- block (containerContentBlock hsp)
return $ (UListItem ind, (concat content))
| One item in an un - ordered list
uListItem :: HSP -> IParse (UListItem, [DocumentItem])
uListItem hsp =
do ind <- uListItemBegin
uListItemBody hsp ind
uList :: HSP -> IParse DocumentItem
uList hsp = do
checkIndent
lookAhead (uListItemBegin)
s <- P.getState
P.setState $ s { parserStateCurrentListLevel = parserStateCurrentListLevel s + 1 }
result <- block $ uListItem hsp
P.setState $ s { parserStateCurrentListLevel = parserStateCurrentListLevel s }
eatSpaces <- isOptionSet SkipNewlinesAfterUlist
when (parserStateCurrentListLevel s == 0 && eatSpaces) $ skipEmptyLines
return $ ItemDocumentContainer (DocumentUList result)
oListItemBegin :: IParse (Int, String)
oListItemBegin = do
newStyle <- isOptionSet NewStyleOlist
if newStyle
then newOlistItemBegin
else oldOlistItemBegin
newOlistItemBegin :: IParse (Int, String)
newOlistItemBegin = do
i <- many $ char ' '
string "+"
many1 space
return ((length i), "0")
oldOlistItemBegin :: IParse (Int, String)
oldOlistItemBegin = do
i <- many $ char ' '
number <- dottedNumber
trailer <- ( (try $ string ".)") <|> string "." <|> string ")" <?> "a number in an enumerated list")
spaces
return ((length i), number)
| One item in an ordered list
oListItem :: HSP -> IParse (OListItem, [DocumentItem])
oListItem hsp =
do (ind, num) <- oListItemBegin
content <- block $ (containerContentBlock hsp)
return $ (OListItem ind num, (concat content))
oList :: HSP -> IParse DocumentItem
oList hsp =
do checkIndent
lookAhead oListItemBegin
items <- block $ oListItem hsp
return $ ItemDocumentContainer (DocumentOList items)
| A number like 1 , 1.2 or 1.2.3.4
dottedNumber :: IParse String
dottedNumber = do num <- many1 digit
rest <- try (char '.' >> dottedNumber) <|> return ""
if length rest == 0 then
return num
else
return (num ++ "." ++ rest)
listItemBegin :: IParse ()
listItemBegin =
((try uListItemBegin) >> return ()) <|> (oListItemBegin >> return ())
headingBegin :: IParse Int
headingBegin = do
spaces
level <- (many1 $ char '#')
spaces
return $ length level
heading :: HSP -> IParse DocumentItem
heading hsp = do
level <- headingBegin
content <- many1 (
(
(do x <- try $ line hsp; return x)
<|> (do x <- try $ extendedCommand hsp; return [x])
)
)
skipEmptyLines
return $ ItemDocumentContainer $ DocumentHeading (Heading level Nothing) (concat content)
blockQuoteBegin :: IParse ()
blockQuoteBegin = do
spaces
char '>'
spaces
blockQuote :: IParse DocumentItem
blockQuote = do
lines <- many1 $ do
blockQuoteBegin
thisLine <- many $ noneOf "\n"
optional newline
return thisLine
skipEmptyLines
return $ ItemDocumentContainer $ DocumentMetaContainer [("type","blockquote")] [ItemWord $ intercalate "\n" lines]
fencedCodeBlockBegin :: IParse ()
fencedCodeBlockBegin = do
string "```"
return ()
fencedCodeBlock :: IParse DocumentItem
fencedCodeBlock = do
fencedCodeBlockBegin
language <- many $ noneOf "\n"
newline
lines <- many $ do
notFollowedBy $ string "```"
thisLine <- many $ noneOf "\n"
newline
return thisLine
string "```"
newline
skipEmptyLines
return $ ItemDocumentContainer $ DocumentMetaContainer [("type", "source"), ("language", language)] [ItemWord $ intercalate "\n" lines]
|
ac49671863bd8de7caffa278de4880817e0e3ebc77f20c53bd32ec8062fa779f | JHU-PL-Lab/jaylang | mc91_95.ml | let rec m x =
if x > 100
then x - 10
else m (m (x + 11))
let main n =
if n <= 95
then assert (m n = 91)
else ()
| null | https://raw.githubusercontent.com/JHU-PL-Lab/jaylang/484b3876986a515fb57b11768a1b3b50418cde0c/benchmark/cases/mochi_origin/mochi/mc91_95.ml | ocaml | let rec m x =
if x > 100
then x - 10
else m (m (x + 11))
let main n =
if n <= 95
then assert (m n = 91)
else ()
| |
e025748559f1f5c088b012133a53382c18762f2b8b8f7b1f586009f2e3f85f29 | mariachris/Concuerror | workers.erl | -module(workers).
-export([workers/0]).
-export([scenarios/0]).
-define(LOW, 1).
-define(HIGH, 2).
-define(ADD, 10).
-define(WORKERS, 2).
scenarios() -> [{?MODULE, inf, dpor}].
workers() ->
Self = self(),
Pid =
spawn(fun() -> server(?WORKERS, lists:seq(?LOW, ?HIGH), [], Self) end),
spawner(?WORKERS, Pid),
receive
{ok, Res} ->
Xp = lists:seq(?LOW + ?ADD, ?HIGH + ?ADD),
Res = Xp
end.
server(0, [], Result, Parent) ->
Parent ! {ok, lists:sort(Result)};
server(Workers, Work, Result, Parent) ->
receive
{res, R} ->
server(Workers, Work, [R|Result], Parent)
after 0 ->
receive
{work, Pid} ->
case Work of
[W|Ork] ->
Pid ! {work, W},
server(Workers, Ork, Result, Parent);
[] ->
Pid ! no_work,
server(Workers, Work, Result, Parent)
end;
exit ->
server(Workers - 1, Work, Result, Parent)
end
end.
spawner(0, Pid) -> ok;
spawner(N, Pid) ->
spawn(fun() -> worker(Pid) end),
spawner(N-1, Pid).
worker(Pid) ->
Pid ! {work, self()},
receive
{work, N} ->
Pid ! {res, N + ?ADD},
worker(Pid);
no_work ->
Pid ! exit
end.
| null | https://raw.githubusercontent.com/mariachris/Concuerror/87e63f10ac615bf2eeac5b0916ef54d11a933e0b/testsuite/suites/dpor/src/workers.erl | erlang | -module(workers).
-export([workers/0]).
-export([scenarios/0]).
-define(LOW, 1).
-define(HIGH, 2).
-define(ADD, 10).
-define(WORKERS, 2).
scenarios() -> [{?MODULE, inf, dpor}].
workers() ->
Self = self(),
Pid =
spawn(fun() -> server(?WORKERS, lists:seq(?LOW, ?HIGH), [], Self) end),
spawner(?WORKERS, Pid),
receive
{ok, Res} ->
Xp = lists:seq(?LOW + ?ADD, ?HIGH + ?ADD),
Res = Xp
end.
server(0, [], Result, Parent) ->
Parent ! {ok, lists:sort(Result)};
server(Workers, Work, Result, Parent) ->
receive
{res, R} ->
server(Workers, Work, [R|Result], Parent)
after 0 ->
receive
{work, Pid} ->
case Work of
[W|Ork] ->
Pid ! {work, W},
server(Workers, Ork, Result, Parent);
[] ->
Pid ! no_work,
server(Workers, Work, Result, Parent)
end;
exit ->
server(Workers - 1, Work, Result, Parent)
end
end.
spawner(0, Pid) -> ok;
spawner(N, Pid) ->
spawn(fun() -> worker(Pid) end),
spawner(N-1, Pid).
worker(Pid) ->
Pid ! {work, self()},
receive
{work, N} ->
Pid ! {res, N + ?ADD},
worker(Pid);
no_work ->
Pid ! exit
end.
| |
f674167256b852d58f513121547d089f83937941b62ea6cfab50d0e04dfa5557 | klutometis/clrs | 15.4-1.scm | (require-extension syntax-case check)
(require '../15.4/section)
(import section-15.4)
(let ((X '(1 0 0 1 0 1 0 1))
(Y '(0 1 0 1 1 0 1 1 0)))
(let-values (((c b) (lcs-length X Y)))
(check (lcs b X (- (length X) 1) (- (length Y) 1)) =>
'(1 0 0 1 1 0))))
| null | https://raw.githubusercontent.com/klutometis/clrs/f85a8f0036f0946c9e64dde3259a19acc62b74a1/15.4/15.4-1.scm | scheme | (require-extension syntax-case check)
(require '../15.4/section)
(import section-15.4)
(let ((X '(1 0 0 1 0 1 0 1))
(Y '(0 1 0 1 1 0 1 1 0)))
(let-values (((c b) (lcs-length X Y)))
(check (lcs b X (- (length X) 1) (- (length Y) 1)) =>
'(1 0 0 1 1 0))))
| |
8a0e02fcce9eed7df0c11ef876e44e80ed8a684f340d0bcc659ed26350db89b8 | ku-fpg/natural-transformation | Natural.hs | # LANGUAGE CPP #
{-# LANGUAGE DeriveDataTypeable #-}
# LANGUAGE FlexibleInstances #
# LANGUAGE FunctionalDependencies #
{-# LANGUAGE GADTs #-}
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE PolyKinds #
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE Safe #-}
# LANGUAGE TypeOperators #
|
Module : Control . Natural
Copyright : ( C ) 2015 The University of Kansas
License : BSD - style ( see the file LICENSE )
Maintainer :
Stability : Experimental
A data type and class for natural transformations .
Module: Control.Natural
Copyright: (C) 2015 The University of Kansas
License: BSD-style (see the file LICENSE)
Maintainer: Andy Gill
Stability: Experimental
A data type and class for natural transformations.
-}
module Control.Natural
* Newtype for a Natural Transformation
(:~>)(..)
-- * Type Synonym for a Natural Transformation
, type (~>)
-- * Conversion functions between the newtype and the synonym
, wrapNT
, unwrapNT
-- * Class for Natural Transformations
, Transformation(..)
) where
import qualified Control.Category as C (Category(..))
#if !(MIN_VERSION_base(4,8,0))
import Data.Monoid (Monoid(..))
#endif
#if !(MIN_VERSION_base(4,11,0))
import Data.Semigroup (Semigroup(..))
#endif
import Data.Typeable
---------------------------------------------------------------------------
Naming of ~ > , : ~ > and $ $ are taken ( with permission ) from @indexed@ package .
---------------------------------------------------------------------------
infixr 0 ~>
| A natural transformation from @f@ to
type f ~> g = forall x. f x -> g x
infixr 0 :~>, $$
-- | A natural transformation suitable for storing in a container.
newtype f :~> g = NT { ($$) :: f ~> g }
deriving Typeable
instance C.Category (:~>) where
id = NT id
NT f . NT g = NT (f . g)
instance f ~ g => Semigroup (f :~> g) where
NT f <> NT g = NT (f . g)
instance f ~ g => Monoid (f :~> g) where
mempty = NT id
mappend = (<>)
infix 0 #
| A ( natural ) transformation is inside @t@ , and contains @f@ and @g@
-- (typically 'Functor's).
--
-- The order of arguments allows the use of @GeneralizedNewtypeDeriving@ to wrap
-- a ':~>', but maintain the 'Transformation' constraint. Thus, @#@ can be used
-- on abstract data types.
class Transformation f g t | t -> f g where
-- | The invocation method for a natural transformation.
(#) :: t -> forall a . f a -> g a
instance Transformation f g (f :~> g) where
NT f # g = f g
-- | 'wrapNT' builds our natural transformation abstraction out of
-- a natural transformation function.
--
-- An alias to 'NT' provided for symmetry with 'unwrapNT'.
--
wrapNT :: (forall a . f a -> g a) -> f :~> g
wrapNT = NT
-- | 'unwrapNT' is the nonfix version of @#@. It is used to break natural
-- transformation wrappers, including ':~>'.
unwrapNT :: Transformation f g t => t -> (forall a . f a -> g a)
unwrapNT = (#)
| null | https://raw.githubusercontent.com/ku-fpg/natural-transformation/24d05f3e63f716f04ba78fd35a0da33a1fe0c5c6/src/Control/Natural.hs | haskell | # LANGUAGE DeriveDataTypeable #
# LANGUAGE GADTs #
# LANGUAGE RankNTypes #
# LANGUAGE Safe #
* Type Synonym for a Natural Transformation
* Conversion functions between the newtype and the synonym
* Class for Natural Transformations
-------------------------------------------------------------------------
-------------------------------------------------------------------------
| A natural transformation suitable for storing in a container.
(typically 'Functor's).
The order of arguments allows the use of @GeneralizedNewtypeDeriving@ to wrap
a ':~>', but maintain the 'Transformation' constraint. Thus, @#@ can be used
on abstract data types.
| The invocation method for a natural transformation.
| 'wrapNT' builds our natural transformation abstraction out of
a natural transformation function.
An alias to 'NT' provided for symmetry with 'unwrapNT'.
| 'unwrapNT' is the nonfix version of @#@. It is used to break natural
transformation wrappers, including ':~>'. | # LANGUAGE CPP #
# LANGUAGE FlexibleInstances #
# LANGUAGE FunctionalDependencies #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE PolyKinds #
# LANGUAGE TypeOperators #
|
Module : Control . Natural
Copyright : ( C ) 2015 The University of Kansas
License : BSD - style ( see the file LICENSE )
Maintainer :
Stability : Experimental
A data type and class for natural transformations .
Module: Control.Natural
Copyright: (C) 2015 The University of Kansas
License: BSD-style (see the file LICENSE)
Maintainer: Andy Gill
Stability: Experimental
A data type and class for natural transformations.
-}
module Control.Natural
* Newtype for a Natural Transformation
(:~>)(..)
, type (~>)
, wrapNT
, unwrapNT
, Transformation(..)
) where
import qualified Control.Category as C (Category(..))
#if !(MIN_VERSION_base(4,8,0))
import Data.Monoid (Monoid(..))
#endif
#if !(MIN_VERSION_base(4,11,0))
import Data.Semigroup (Semigroup(..))
#endif
import Data.Typeable
Naming of ~ > , : ~ > and $ $ are taken ( with permission ) from @indexed@ package .
infixr 0 ~>
| A natural transformation from @f@ to
type f ~> g = forall x. f x -> g x
infixr 0 :~>, $$
newtype f :~> g = NT { ($$) :: f ~> g }
deriving Typeable
instance C.Category (:~>) where
id = NT id
NT f . NT g = NT (f . g)
instance f ~ g => Semigroup (f :~> g) where
NT f <> NT g = NT (f . g)
instance f ~ g => Monoid (f :~> g) where
mempty = NT id
mappend = (<>)
infix 0 #
| A ( natural ) transformation is inside @t@ , and contains @f@ and @g@
class Transformation f g t | t -> f g where
(#) :: t -> forall a . f a -> g a
instance Transformation f g (f :~> g) where
NT f # g = f g
wrapNT :: (forall a . f a -> g a) -> f :~> g
wrapNT = NT
unwrapNT :: Transformation f g t => t -> (forall a . f a -> g a)
unwrapNT = (#)
|
5a23f8d485eacdf37eedde9c96c2b96c9c5121510390e35e4686c1596b54e4b5 | mbj/stratosphere | BatchTransformInputProperty.hs | module Stratosphere.SageMaker.ModelExplainabilityJobDefinition.BatchTransformInputProperty (
module Exports, BatchTransformInputProperty(..),
mkBatchTransformInputProperty
) where
import qualified Data.Aeson as JSON
import qualified Stratosphere.Prelude as Prelude
import Stratosphere.Property
import {-# SOURCE #-} Stratosphere.SageMaker.ModelExplainabilityJobDefinition.DatasetFormatProperty as Exports
import Stratosphere.ResourceProperties
import Stratosphere.Value
data BatchTransformInputProperty
= BatchTransformInputProperty {dataCapturedDestinationS3Uri :: (Value Prelude.Text),
datasetFormat :: DatasetFormatProperty,
featuresAttribute :: (Prelude.Maybe (Value Prelude.Text)),
inferenceAttribute :: (Prelude.Maybe (Value Prelude.Text)),
localPath :: (Value Prelude.Text),
probabilityAttribute :: (Prelude.Maybe (Value Prelude.Text)),
s3DataDistributionType :: (Prelude.Maybe (Value Prelude.Text)),
s3InputMode :: (Prelude.Maybe (Value Prelude.Text))}
mkBatchTransformInputProperty ::
Value Prelude.Text
-> DatasetFormatProperty
-> Value Prelude.Text -> BatchTransformInputProperty
mkBatchTransformInputProperty
dataCapturedDestinationS3Uri
datasetFormat
localPath
= BatchTransformInputProperty
{dataCapturedDestinationS3Uri = dataCapturedDestinationS3Uri,
datasetFormat = datasetFormat, localPath = localPath,
featuresAttribute = Prelude.Nothing,
inferenceAttribute = Prelude.Nothing,
probabilityAttribute = Prelude.Nothing,
s3DataDistributionType = Prelude.Nothing,
s3InputMode = Prelude.Nothing}
instance ToResourceProperties BatchTransformInputProperty where
toResourceProperties BatchTransformInputProperty {..}
= ResourceProperties
{awsType = "AWS::SageMaker::ModelExplainabilityJobDefinition.BatchTransformInput",
supportsTags = Prelude.False,
properties = Prelude.fromList
((Prelude.<>)
["DataCapturedDestinationS3Uri"
JSON..= dataCapturedDestinationS3Uri,
"DatasetFormat" JSON..= datasetFormat,
"LocalPath" JSON..= localPath]
(Prelude.catMaybes
[(JSON..=) "FeaturesAttribute" Prelude.<$> featuresAttribute,
(JSON..=) "InferenceAttribute" Prelude.<$> inferenceAttribute,
(JSON..=) "ProbabilityAttribute" Prelude.<$> probabilityAttribute,
(JSON..=) "S3DataDistributionType"
Prelude.<$> s3DataDistributionType,
(JSON..=) "S3InputMode" Prelude.<$> s3InputMode]))}
instance JSON.ToJSON BatchTransformInputProperty where
toJSON BatchTransformInputProperty {..}
= JSON.object
(Prelude.fromList
((Prelude.<>)
["DataCapturedDestinationS3Uri"
JSON..= dataCapturedDestinationS3Uri,
"DatasetFormat" JSON..= datasetFormat,
"LocalPath" JSON..= localPath]
(Prelude.catMaybes
[(JSON..=) "FeaturesAttribute" Prelude.<$> featuresAttribute,
(JSON..=) "InferenceAttribute" Prelude.<$> inferenceAttribute,
(JSON..=) "ProbabilityAttribute" Prelude.<$> probabilityAttribute,
(JSON..=) "S3DataDistributionType"
Prelude.<$> s3DataDistributionType,
(JSON..=) "S3InputMode" Prelude.<$> s3InputMode])))
instance Property "DataCapturedDestinationS3Uri" BatchTransformInputProperty where
type PropertyType "DataCapturedDestinationS3Uri" BatchTransformInputProperty = Value Prelude.Text
set newValue BatchTransformInputProperty {..}
= BatchTransformInputProperty
{dataCapturedDestinationS3Uri = newValue, ..}
instance Property "DatasetFormat" BatchTransformInputProperty where
type PropertyType "DatasetFormat" BatchTransformInputProperty = DatasetFormatProperty
set newValue BatchTransformInputProperty {..}
= BatchTransformInputProperty {datasetFormat = newValue, ..}
instance Property "FeaturesAttribute" BatchTransformInputProperty where
type PropertyType "FeaturesAttribute" BatchTransformInputProperty = Value Prelude.Text
set newValue BatchTransformInputProperty {..}
= BatchTransformInputProperty
{featuresAttribute = Prelude.pure newValue, ..}
instance Property "InferenceAttribute" BatchTransformInputProperty where
type PropertyType "InferenceAttribute" BatchTransformInputProperty = Value Prelude.Text
set newValue BatchTransformInputProperty {..}
= BatchTransformInputProperty
{inferenceAttribute = Prelude.pure newValue, ..}
instance Property "LocalPath" BatchTransformInputProperty where
type PropertyType "LocalPath" BatchTransformInputProperty = Value Prelude.Text
set newValue BatchTransformInputProperty {..}
= BatchTransformInputProperty {localPath = newValue, ..}
instance Property "ProbabilityAttribute" BatchTransformInputProperty where
type PropertyType "ProbabilityAttribute" BatchTransformInputProperty = Value Prelude.Text
set newValue BatchTransformInputProperty {..}
= BatchTransformInputProperty
{probabilityAttribute = Prelude.pure newValue, ..}
instance Property "S3DataDistributionType" BatchTransformInputProperty where
type PropertyType "S3DataDistributionType" BatchTransformInputProperty = Value Prelude.Text
set newValue BatchTransformInputProperty {..}
= BatchTransformInputProperty
{s3DataDistributionType = Prelude.pure newValue, ..}
instance Property "S3InputMode" BatchTransformInputProperty where
type PropertyType "S3InputMode" BatchTransformInputProperty = Value Prelude.Text
set newValue BatchTransformInputProperty {..}
= BatchTransformInputProperty
{s3InputMode = Prelude.pure newValue, ..} | null | https://raw.githubusercontent.com/mbj/stratosphere/c70f301715425247efcda29af4f3fcf7ec04aa2f/services/sagemaker/gen/Stratosphere/SageMaker/ModelExplainabilityJobDefinition/BatchTransformInputProperty.hs | haskell | # SOURCE # | module Stratosphere.SageMaker.ModelExplainabilityJobDefinition.BatchTransformInputProperty (
module Exports, BatchTransformInputProperty(..),
mkBatchTransformInputProperty
) where
import qualified Data.Aeson as JSON
import qualified Stratosphere.Prelude as Prelude
import Stratosphere.Property
import Stratosphere.ResourceProperties
import Stratosphere.Value
data BatchTransformInputProperty
= BatchTransformInputProperty {dataCapturedDestinationS3Uri :: (Value Prelude.Text),
datasetFormat :: DatasetFormatProperty,
featuresAttribute :: (Prelude.Maybe (Value Prelude.Text)),
inferenceAttribute :: (Prelude.Maybe (Value Prelude.Text)),
localPath :: (Value Prelude.Text),
probabilityAttribute :: (Prelude.Maybe (Value Prelude.Text)),
s3DataDistributionType :: (Prelude.Maybe (Value Prelude.Text)),
s3InputMode :: (Prelude.Maybe (Value Prelude.Text))}
mkBatchTransformInputProperty ::
Value Prelude.Text
-> DatasetFormatProperty
-> Value Prelude.Text -> BatchTransformInputProperty
mkBatchTransformInputProperty
dataCapturedDestinationS3Uri
datasetFormat
localPath
= BatchTransformInputProperty
{dataCapturedDestinationS3Uri = dataCapturedDestinationS3Uri,
datasetFormat = datasetFormat, localPath = localPath,
featuresAttribute = Prelude.Nothing,
inferenceAttribute = Prelude.Nothing,
probabilityAttribute = Prelude.Nothing,
s3DataDistributionType = Prelude.Nothing,
s3InputMode = Prelude.Nothing}
instance ToResourceProperties BatchTransformInputProperty where
toResourceProperties BatchTransformInputProperty {..}
= ResourceProperties
{awsType = "AWS::SageMaker::ModelExplainabilityJobDefinition.BatchTransformInput",
supportsTags = Prelude.False,
properties = Prelude.fromList
((Prelude.<>)
["DataCapturedDestinationS3Uri"
JSON..= dataCapturedDestinationS3Uri,
"DatasetFormat" JSON..= datasetFormat,
"LocalPath" JSON..= localPath]
(Prelude.catMaybes
[(JSON..=) "FeaturesAttribute" Prelude.<$> featuresAttribute,
(JSON..=) "InferenceAttribute" Prelude.<$> inferenceAttribute,
(JSON..=) "ProbabilityAttribute" Prelude.<$> probabilityAttribute,
(JSON..=) "S3DataDistributionType"
Prelude.<$> s3DataDistributionType,
(JSON..=) "S3InputMode" Prelude.<$> s3InputMode]))}
instance JSON.ToJSON BatchTransformInputProperty where
toJSON BatchTransformInputProperty {..}
= JSON.object
(Prelude.fromList
((Prelude.<>)
["DataCapturedDestinationS3Uri"
JSON..= dataCapturedDestinationS3Uri,
"DatasetFormat" JSON..= datasetFormat,
"LocalPath" JSON..= localPath]
(Prelude.catMaybes
[(JSON..=) "FeaturesAttribute" Prelude.<$> featuresAttribute,
(JSON..=) "InferenceAttribute" Prelude.<$> inferenceAttribute,
(JSON..=) "ProbabilityAttribute" Prelude.<$> probabilityAttribute,
(JSON..=) "S3DataDistributionType"
Prelude.<$> s3DataDistributionType,
(JSON..=) "S3InputMode" Prelude.<$> s3InputMode])))
instance Property "DataCapturedDestinationS3Uri" BatchTransformInputProperty where
type PropertyType "DataCapturedDestinationS3Uri" BatchTransformInputProperty = Value Prelude.Text
set newValue BatchTransformInputProperty {..}
= BatchTransformInputProperty
{dataCapturedDestinationS3Uri = newValue, ..}
instance Property "DatasetFormat" BatchTransformInputProperty where
type PropertyType "DatasetFormat" BatchTransformInputProperty = DatasetFormatProperty
set newValue BatchTransformInputProperty {..}
= BatchTransformInputProperty {datasetFormat = newValue, ..}
instance Property "FeaturesAttribute" BatchTransformInputProperty where
type PropertyType "FeaturesAttribute" BatchTransformInputProperty = Value Prelude.Text
set newValue BatchTransformInputProperty {..}
= BatchTransformInputProperty
{featuresAttribute = Prelude.pure newValue, ..}
instance Property "InferenceAttribute" BatchTransformInputProperty where
type PropertyType "InferenceAttribute" BatchTransformInputProperty = Value Prelude.Text
set newValue BatchTransformInputProperty {..}
= BatchTransformInputProperty
{inferenceAttribute = Prelude.pure newValue, ..}
instance Property "LocalPath" BatchTransformInputProperty where
type PropertyType "LocalPath" BatchTransformInputProperty = Value Prelude.Text
set newValue BatchTransformInputProperty {..}
= BatchTransformInputProperty {localPath = newValue, ..}
instance Property "ProbabilityAttribute" BatchTransformInputProperty where
type PropertyType "ProbabilityAttribute" BatchTransformInputProperty = Value Prelude.Text
set newValue BatchTransformInputProperty {..}
= BatchTransformInputProperty
{probabilityAttribute = Prelude.pure newValue, ..}
instance Property "S3DataDistributionType" BatchTransformInputProperty where
type PropertyType "S3DataDistributionType" BatchTransformInputProperty = Value Prelude.Text
set newValue BatchTransformInputProperty {..}
= BatchTransformInputProperty
{s3DataDistributionType = Prelude.pure newValue, ..}
instance Property "S3InputMode" BatchTransformInputProperty where
type PropertyType "S3InputMode" BatchTransformInputProperty = Value Prelude.Text
set newValue BatchTransformInputProperty {..}
= BatchTransformInputProperty
{s3InputMode = Prelude.pure newValue, ..} |
b5caa5cdecfc74c6d1be9126a11a733038818a0125213a412d409871e172e4fa | babashka/babashka | yaml_test.clj | (ns babashka.yaml-test
(:require [babashka.test-utils :as test-utils]
[clojure.string :as str]
[clojure.test :refer [deftest is testing]]))
(def simple-yaml-str "topic: [point 1, point 2]")
(deftest yaml-edn-read-test
(let [parsed-edn (test-utils/bb nil (str "(yaml/parse-string \"" simple-yaml-str "\")"))
emitted-yaml (test-utils/bb parsed-edn "(yaml/generate-string *input*)")]
(is (every? #(str/includes? emitted-yaml %) ["topic:" "point 1" "point 2"]))))
(def round-trip-prog
(str "(yaml/generate-string (read-string (pr-str (yaml/parse-string \"" simple-yaml-str "\"))))"))
(deftest yaml-data-readers-test
(let [emitted-yaml (test-utils/bb nil round-trip-prog)]
(is (every? #(str/includes? emitted-yaml %) ["topic:" "point 1" "point 2"]))))
| null | https://raw.githubusercontent.com/babashka/babashka/407bd74a00395bdec8d89ab36ff330593859bb94/test/babashka/yaml_test.clj | clojure | (ns babashka.yaml-test
(:require [babashka.test-utils :as test-utils]
[clojure.string :as str]
[clojure.test :refer [deftest is testing]]))
(def simple-yaml-str "topic: [point 1, point 2]")
(deftest yaml-edn-read-test
(let [parsed-edn (test-utils/bb nil (str "(yaml/parse-string \"" simple-yaml-str "\")"))
emitted-yaml (test-utils/bb parsed-edn "(yaml/generate-string *input*)")]
(is (every? #(str/includes? emitted-yaml %) ["topic:" "point 1" "point 2"]))))
(def round-trip-prog
(str "(yaml/generate-string (read-string (pr-str (yaml/parse-string \"" simple-yaml-str "\"))))"))
(deftest yaml-data-readers-test
(let [emitted-yaml (test-utils/bb nil round-trip-prog)]
(is (every? #(str/includes? emitted-yaml %) ["topic:" "point 1" "point 2"]))))
| |
7a0a0cb8892881e0457dac1fb492900c215cafd178fd94fa81551f6ff11ead36 | basho/sidejob | sidejob_worker.erl | %% -------------------------------------------------------------------
%%
Copyright ( c ) 2013 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.
%%
%% -------------------------------------------------------------------
%% @doc
%% This module implements the sidejob_worker logic used by all worker
processes created to manage a sidejob resource . This code emulates
the gen_server API , wrapping a provided user - specified module which
%% implements the gen_server behavior.
%%
%% The primary purpose of this module is updating the usage information
%% published in a given resource's ETS table, such that capacity limiting
%% operates correctly. The sidejob_worker also cooperates with a given
%% {@link sidejob_resource_stats} server to maintain statistics about a
%% given resource.
%%
%% By default, a sidejob_worker calculates resource usage based on message
%% queue size. However, the user-specified module can also choose to
%% implement the `current_usage/1' and `rate/1' callbacks to change how
%% usage is calculated. An example is the {@link sidejob_supervisor} module
%% which reports usage as: queue size + num_children.
-module(sidejob_worker).
-behaviour(gen_server).
%% API
-export([start_link/6, reg_name/1, reg_name/2, workers/2]).
%% gen_server callbacks
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
terminate/2, code_change/3]).
-record(state, {id :: non_neg_integer(),
ets :: term(),
width :: pos_integer(),
limit :: pos_integer(),
reporter :: term(),
mod :: module(),
modstate :: term(),
usage :: custom | default,
last_mq_len = 0 :: non_neg_integer(),
enqueue = 0 :: non_neg_integer(),
dequeue = 0 :: non_neg_integer()}).
%%%===================================================================
%%% API
%%%===================================================================
reg_name(Id) ->
IdBin = list_to_binary(integer_to_list(Id)),
binary_to_atom(<<"sidejob_worker_", IdBin/binary>>, latin1).
reg_name(Name, Id) when is_atom(Name) ->
reg_name(atom_to_binary(Name, latin1), Id);
reg_name(NameBin, Id) ->
WorkerName = iolist_to_binary([NameBin, "_", integer_to_list(Id)]),
binary_to_atom(WorkerName, latin1).
workers(Name, Count) ->
NameBin = atom_to_binary(Name, latin1),
[reg_name(NameBin, Id) || Id <- lists:seq(1,Count)].
start_link(RegName, ResName, Id, ETS, StatsName, Mod) ->
gen_server:start_link({local, RegName}, ?MODULE,
[ResName, Id, ETS, StatsName, Mod], []).
%%%===================================================================
%%% gen_server callbacks
%%%===================================================================
init([ResName, Id, ETS, StatsName, Mod]) ->
%% TODO: Add ability to pass args
case Mod:init([ResName]) of
{ok, ModState} ->
Exports = proplists:get_value(exports, Mod:module_info()),
Usage = case lists:member({current_usage, 1}, Exports) of
true ->
custom;
false ->
default
end,
schedule_tick(),
Width = ResName:width(),
Limit = ResName:limit(),
State = #state{id=Id,
ets=ETS,
mod=Mod,
modstate=ModState,
usage=Usage,
width=Width,
limit=Limit,
reporter=StatsName},
ets:insert(ETS, [{usage,0}, {full,0}]),
{ok, State};
Other ->
Other
end.
handle_call(Request, From, State=#state{mod=Mod,
modstate=ModState}) ->
Result = Mod:handle_call(Request, From, ModState),
{Pos, ModState2} = case Result of
{reply,_Reply,NewState} ->
{3, NewState};
{reply,_Reply,NewState,hibernate} ->
{3, NewState};
{reply,_Reply,NewState,_Timeout} ->
{3, NewState};
{noreply,NewState} ->
{2, NewState};
{noreply,NewState,hibernate} ->
{2, NewState};
{noreply,NewState,_Timeout} ->
{2, NewState};
{stop,_Reason,_Reply,NewState} ->
{4, NewState};
{stop,_Reason,NewState} ->
{3, NewState}
end,
State2 = State#state{modstate=ModState2},
State3 = update_rate(update_usage(State2)),
Return = setelement(Pos, Result, State3),
Return.
handle_cast(Request, State=#state{mod=Mod,
modstate=ModState}) ->
Result = Mod:handle_cast(Request, ModState),
{Pos, ModState2} = case Result of
{noreply,NewState} ->
{2, NewState};
{noreply,NewState,hibernate} ->
{2, NewState};
{noreply,NewState,_Timeout} ->
{2, NewState};
{stop,_Reason,NewState} ->
{3, NewState}
end,
State2 = State#state{modstate=ModState2},
State3 = update_rate(update_usage(State2)),
Return = setelement(Pos, Result, State3),
Return.
handle_info('$sidejob_worker_tick', State) ->
State2 = tick(State),
schedule_tick(),
{noreply, State2};
handle_info(Info, State=#state{mod=Mod,
modstate=ModState}) ->
Result = Mod:handle_info(Info, ModState),
{Pos, ModState2} = case Result of
{noreply,NewState} ->
{2, NewState};
{noreply,NewState,hibernate} ->
{2, NewState};
{noreply,NewState,_Timeout} ->
{2, NewState};
{stop,_Reason,NewState} ->
{3, NewState}
end,
State2 = State#state{modstate=ModState2},
State3 = update_rate(update_usage(State2)),
Return = setelement(Pos, Result, State3),
Return.
terminate(_Reason, _State) ->
ok.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
%%%===================================================================
Internal functions
%%%===================================================================
schedule_tick() ->
erlang:send_after(1000, self(), '$sidejob_worker_tick').
tick(State=#state{id=Id, reporter=Reporter}) ->
Usage = current_usage(State),
{In, Out, State2} = current_rate(State),
sidejob_resource_stats:report(Reporter, Id, Usage, In, Out),
State2.
update_usage(State=#state{ets=ETS, width=Width, limit=Limit}) ->
Usage = current_usage(State),
Full = case Usage >= (Limit div Width) of
true ->
1;
false ->
0
end,
ets:insert(ETS, [{usage, Usage},
{full, Full}]),
State.
current_usage(#state{usage=default}) ->
{message_queue_len, Len} = process_info(self(), message_queue_len),
Len;
current_usage(#state{usage=custom, mod=Mod, modstate=ModState}) ->
Mod:current_usage(ModState).
update_rate(State=#state{usage=custom}) ->
%% Assume this is updated internally in the custom module
State;
update_rate(State=#state{usage=default,
last_mq_len=LastLen}) ->
{message_queue_len, Len} = process_info(self(), message_queue_len),
Enqueue = Len - LastLen + 1,
Dequeue = State#state.dequeue + 1,
State#state{enqueue=Enqueue, dequeue=Dequeue}.
%% TODO: Probably should rename since it resets rate
current_rate(State=#state{usage=default,
enqueue=Enqueue,
dequeue=Dequeue}) ->
State2 = State#state{enqueue=0, dequeue=0},
{Enqueue, Dequeue, State2};
current_rate(State=#state{usage=custom, mod=Mod, modstate=ModState}) ->
{Enqueue, Dequeue, ModState2} = Mod:rate(ModState),
State2 = State#state{modstate=ModState2},
{Enqueue, Dequeue, State2}.
| null | https://raw.githubusercontent.com/basho/sidejob/1c377578c0956e91ebbb98a798c5d4b6d0959c99/src/sidejob_worker.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.
-------------------------------------------------------------------
@doc
This module implements the sidejob_worker logic used by all worker
implements the gen_server behavior.
The primary purpose of this module is updating the usage information
published in a given resource's ETS table, such that capacity limiting
operates correctly. The sidejob_worker also cooperates with a given
{@link sidejob_resource_stats} server to maintain statistics about a
given resource.
By default, a sidejob_worker calculates resource usage based on message
queue size. However, the user-specified module can also choose to
implement the `current_usage/1' and `rate/1' callbacks to change how
usage is calculated. An example is the {@link sidejob_supervisor} module
which reports usage as: queue size + num_children.
API
gen_server callbacks
===================================================================
API
===================================================================
===================================================================
gen_server callbacks
===================================================================
TODO: Add ability to pass args
===================================================================
===================================================================
Assume this is updated internally in the custom module
TODO: Probably should rename since it resets rate | Copyright ( c ) 2013 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
processes created to manage a sidejob resource . This code emulates
the gen_server API , wrapping a provided user - specified module which
-module(sidejob_worker).
-behaviour(gen_server).
-export([start_link/6, reg_name/1, reg_name/2, workers/2]).
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
terminate/2, code_change/3]).
-record(state, {id :: non_neg_integer(),
ets :: term(),
width :: pos_integer(),
limit :: pos_integer(),
reporter :: term(),
mod :: module(),
modstate :: term(),
usage :: custom | default,
last_mq_len = 0 :: non_neg_integer(),
enqueue = 0 :: non_neg_integer(),
dequeue = 0 :: non_neg_integer()}).
reg_name(Id) ->
IdBin = list_to_binary(integer_to_list(Id)),
binary_to_atom(<<"sidejob_worker_", IdBin/binary>>, latin1).
reg_name(Name, Id) when is_atom(Name) ->
reg_name(atom_to_binary(Name, latin1), Id);
reg_name(NameBin, Id) ->
WorkerName = iolist_to_binary([NameBin, "_", integer_to_list(Id)]),
binary_to_atom(WorkerName, latin1).
workers(Name, Count) ->
NameBin = atom_to_binary(Name, latin1),
[reg_name(NameBin, Id) || Id <- lists:seq(1,Count)].
start_link(RegName, ResName, Id, ETS, StatsName, Mod) ->
gen_server:start_link({local, RegName}, ?MODULE,
[ResName, Id, ETS, StatsName, Mod], []).
init([ResName, Id, ETS, StatsName, Mod]) ->
case Mod:init([ResName]) of
{ok, ModState} ->
Exports = proplists:get_value(exports, Mod:module_info()),
Usage = case lists:member({current_usage, 1}, Exports) of
true ->
custom;
false ->
default
end,
schedule_tick(),
Width = ResName:width(),
Limit = ResName:limit(),
State = #state{id=Id,
ets=ETS,
mod=Mod,
modstate=ModState,
usage=Usage,
width=Width,
limit=Limit,
reporter=StatsName},
ets:insert(ETS, [{usage,0}, {full,0}]),
{ok, State};
Other ->
Other
end.
handle_call(Request, From, State=#state{mod=Mod,
modstate=ModState}) ->
Result = Mod:handle_call(Request, From, ModState),
{Pos, ModState2} = case Result of
{reply,_Reply,NewState} ->
{3, NewState};
{reply,_Reply,NewState,hibernate} ->
{3, NewState};
{reply,_Reply,NewState,_Timeout} ->
{3, NewState};
{noreply,NewState} ->
{2, NewState};
{noreply,NewState,hibernate} ->
{2, NewState};
{noreply,NewState,_Timeout} ->
{2, NewState};
{stop,_Reason,_Reply,NewState} ->
{4, NewState};
{stop,_Reason,NewState} ->
{3, NewState}
end,
State2 = State#state{modstate=ModState2},
State3 = update_rate(update_usage(State2)),
Return = setelement(Pos, Result, State3),
Return.
handle_cast(Request, State=#state{mod=Mod,
modstate=ModState}) ->
Result = Mod:handle_cast(Request, ModState),
{Pos, ModState2} = case Result of
{noreply,NewState} ->
{2, NewState};
{noreply,NewState,hibernate} ->
{2, NewState};
{noreply,NewState,_Timeout} ->
{2, NewState};
{stop,_Reason,NewState} ->
{3, NewState}
end,
State2 = State#state{modstate=ModState2},
State3 = update_rate(update_usage(State2)),
Return = setelement(Pos, Result, State3),
Return.
handle_info('$sidejob_worker_tick', State) ->
State2 = tick(State),
schedule_tick(),
{noreply, State2};
handle_info(Info, State=#state{mod=Mod,
modstate=ModState}) ->
Result = Mod:handle_info(Info, ModState),
{Pos, ModState2} = case Result of
{noreply,NewState} ->
{2, NewState};
{noreply,NewState,hibernate} ->
{2, NewState};
{noreply,NewState,_Timeout} ->
{2, NewState};
{stop,_Reason,NewState} ->
{3, NewState}
end,
State2 = State#state{modstate=ModState2},
State3 = update_rate(update_usage(State2)),
Return = setelement(Pos, Result, State3),
Return.
terminate(_Reason, _State) ->
ok.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
Internal functions
schedule_tick() ->
erlang:send_after(1000, self(), '$sidejob_worker_tick').
tick(State=#state{id=Id, reporter=Reporter}) ->
Usage = current_usage(State),
{In, Out, State2} = current_rate(State),
sidejob_resource_stats:report(Reporter, Id, Usage, In, Out),
State2.
update_usage(State=#state{ets=ETS, width=Width, limit=Limit}) ->
Usage = current_usage(State),
Full = case Usage >= (Limit div Width) of
true ->
1;
false ->
0
end,
ets:insert(ETS, [{usage, Usage},
{full, Full}]),
State.
current_usage(#state{usage=default}) ->
{message_queue_len, Len} = process_info(self(), message_queue_len),
Len;
current_usage(#state{usage=custom, mod=Mod, modstate=ModState}) ->
Mod:current_usage(ModState).
update_rate(State=#state{usage=custom}) ->
State;
update_rate(State=#state{usage=default,
last_mq_len=LastLen}) ->
{message_queue_len, Len} = process_info(self(), message_queue_len),
Enqueue = Len - LastLen + 1,
Dequeue = State#state.dequeue + 1,
State#state{enqueue=Enqueue, dequeue=Dequeue}.
current_rate(State=#state{usage=default,
enqueue=Enqueue,
dequeue=Dequeue}) ->
State2 = State#state{enqueue=0, dequeue=0},
{Enqueue, Dequeue, State2};
current_rate(State=#state{usage=custom, mod=Mod, modstate=ModState}) ->
{Enqueue, Dequeue, ModState2} = Mod:rate(ModState),
State2 = State#state{modstate=ModState2},
{Enqueue, Dequeue, State2}.
|
f226af3ffc23728d855e3fe4b5d2943a476ff93c88f65221003b165214f7e4cc | nrnrnr/qc-- | x86i.ml | module type S = sig
module Reloc : Sledlib.RELOCATABLE
type rel8
type rel16
type rel32
type mem
type eaddr
type t
val rel8 : reloc:nativeint Reloc.relocatable -> rel8
val rel16 : reloc:nativeint Reloc.relocatable -> rel16
val rel32 : reloc:nativeint Reloc.relocatable -> rel32
val indir : reg:nativeint -> mem
val disp8 : d:nativeint Reloc.relocatable -> reg:nativeint -> mem
val disp32 : d:nativeint Reloc.relocatable -> reg:nativeint -> mem
val abs32 : a:nativeint Reloc.relocatable -> mem
val reg : reg:nativeint -> eaddr
val index :
[ 0 .. 7 ]
[ 0 .. 3 ]
val index8 :
[ 0 .. 7 ]
[ 0 .. 3 ]
val index32 :
[ 0 .. 7 ]
[ 0 .. 3 ]
val shortindex :
[ 0 .. 7 ]
[ 0 .. 3 ]
val e : mem:mem -> eaddr
[ ~128 .. 127 ]
[ ~128 .. 127 ]
[ ~128 .. 127 ]
[ ~128 .. 127 ]
[ ~128 .. 127 ]
[ ~128 .. 127 ]
[ ~128 .. 127 ]
[ ~128 .. 127 ]
[ ~32768 .. 32767 ]
[ ~32768 .. 32767 ]
[ ~32768 .. 32767 ]
[ ~32768 .. 32767 ]
[ ~32768 .. 32767 ]
[ ~32768 .. 32767 ]
[ ~32768 .. 32767 ]
[ ~32768 .. 32767 ]
val addieax : i32:nativeint -> t
val orieax : i32:nativeint -> t
val adcieax : i32:nativeint -> t
val sbbieax : i32:nativeint -> t
val andieax : i32:nativeint -> t
val subieax : i32:nativeint -> t
val xorieax : i32:nativeint -> t
val cmpieax : i32:nativeint -> t
[ ~128 .. 127 ]
[ ~128 .. 127 ]
[ ~128 .. 127 ]
[ ~128 .. 127 ]
[ ~128 .. 127 ]
[ ~128 .. 127 ]
[ ~128 .. 127 ]
[ ~128 .. 127 ]
[ ~32768 .. 32767 ]
[ ~32768 .. 32767 ]
[ ~32768 .. 32767 ]
[ ~32768 .. 32767 ]
[ ~32768 .. 32767 ]
[ ~32768 .. 32767 ]
[ ~32768 .. 32767 ]
[ ~32768 .. 32767 ]
val addid : eaddr:eaddr -> i32:nativeint -> t
val orid : eaddr:eaddr -> i32:nativeint -> t
val adcid : eaddr:eaddr -> i32:nativeint -> t
val sbbid : eaddr:eaddr -> i32:nativeint -> t
val andid : eaddr:eaddr -> i32:nativeint -> t
val subid : eaddr:eaddr -> i32:nativeint -> t
val xorid : eaddr:eaddr -> i32:nativeint -> t
val cmpid : eaddr:eaddr -> i32:nativeint -> t
[ ~128 .. 127 ]
[ ~128 .. 127 ]
[ ~128 .. 127 ]
[ ~128 .. 127 ]
[ ~128 .. 127 ]
[ ~128 .. 127 ]
[ ~128 .. 127 ]
[ ~128 .. 127 ]
[ ~128 .. 127 ]
[ ~128 .. 127 ]
[ ~128 .. 127 ]
[ ~128 .. 127 ]
[ ~128 .. 127 ]
[ ~128 .. 127 ]
[ ~128 .. 127 ]
[ ~128 .. 127 ]
val addmrb : eaddr:eaddr -> reg8:nativeint -> t
val ormrb : eaddr:eaddr -> reg8:nativeint -> t
val adcmrb : eaddr:eaddr -> reg8:nativeint -> t
val sbbmrb : eaddr:eaddr -> reg8:nativeint -> t
val andmrb : eaddr:eaddr -> reg8:nativeint -> t
val submrb : eaddr:eaddr -> reg8:nativeint -> t
val xormrb : eaddr:eaddr -> reg8:nativeint -> t
val cmpmrb : eaddr:eaddr -> reg8:nativeint -> t
val addmrow : eaddr:eaddr -> reg:nativeint -> t
val addmrod : eaddr:eaddr -> reg:nativeint -> t
val ormrow : eaddr:eaddr -> reg:nativeint -> t
val ormrod : eaddr:eaddr -> reg:nativeint -> t
val adcmrow : eaddr:eaddr -> reg:nativeint -> t
val adcmrod : eaddr:eaddr -> reg:nativeint -> t
val sbbmrow : eaddr:eaddr -> reg:nativeint -> t
val sbbmrod : eaddr:eaddr -> reg:nativeint -> t
val andmrow : eaddr:eaddr -> reg:nativeint -> t
val andmrod : eaddr:eaddr -> reg:nativeint -> t
val submrow : eaddr:eaddr -> reg:nativeint -> t
val submrod : eaddr:eaddr -> reg:nativeint -> t
val xormrow : eaddr:eaddr -> reg:nativeint -> t
val xormrod : eaddr:eaddr -> reg:nativeint -> t
val cmpmrow : eaddr:eaddr -> reg:nativeint -> t
val cmpmrod : eaddr:eaddr -> reg:nativeint -> t
val addrmb : reg8:nativeint -> eaddr:eaddr -> t
val orrmb : reg8:nativeint -> eaddr:eaddr -> t
val adcrmb : reg8:nativeint -> eaddr:eaddr -> t
val sbbrmb : reg8:nativeint -> eaddr:eaddr -> t
val andrmb : reg8:nativeint -> eaddr:eaddr -> t
val subrmb : reg8:nativeint -> eaddr:eaddr -> t
val xorrmb : reg8:nativeint -> eaddr:eaddr -> t
val cmprmb : reg8:nativeint -> eaddr:eaddr -> t
val addrmow : reg:nativeint -> eaddr:eaddr -> t
val addrmod : reg:nativeint -> eaddr:eaddr -> t
val orrmow : reg:nativeint -> eaddr:eaddr -> t
val orrmod : reg:nativeint -> eaddr:eaddr -> t
val adcrmow : reg:nativeint -> eaddr:eaddr -> t
val adcrmod : reg:nativeint -> eaddr:eaddr -> t
val sbbrmow : reg:nativeint -> eaddr:eaddr -> t
val sbbrmod : reg:nativeint -> eaddr:eaddr -> t
val andrmow : reg:nativeint -> eaddr:eaddr -> t
val andrmod : reg:nativeint -> eaddr:eaddr -> t
val subrmow : reg:nativeint -> eaddr:eaddr -> t
val subrmod : reg:nativeint -> eaddr:eaddr -> t
val xorrmow : reg:nativeint -> eaddr:eaddr -> t
val xorrmod : reg:nativeint -> eaddr:eaddr -> t
val cmprmow : reg:nativeint -> eaddr:eaddr -> t
val cmprmod : reg:nativeint -> eaddr:eaddr -> t
val aaa : unit -> t
val aad : unit -> t
val aam : unit -> t
val aas : unit -> t
val arpl : eaddr:eaddr -> reg16:nativeint -> t
val boundow : reg:nativeint -> mem:mem -> t
val boundod : reg:nativeint -> mem:mem -> t
val bsfow : reg:nativeint -> eaddr:eaddr -> t
val bsfod : reg:nativeint -> eaddr:eaddr -> t
val bsrow : reg:nativeint -> eaddr:eaddr -> t
val bsrod : reg:nativeint -> eaddr:eaddr -> t
[ 0 .. 7 ]
val btow : eaddr:eaddr -> reg:nativeint -> t
val btod : eaddr:eaddr -> reg:nativeint -> t
[ ~128 .. 127 ]
[ ~128 .. 127 ]
val btcow : eaddr:eaddr -> reg:nativeint -> t
val btcod : eaddr:eaddr -> reg:nativeint -> t
[ ~128 .. 127 ]
[ ~128 .. 127 ]
val btrow : eaddr:eaddr -> reg:nativeint -> t
val btrod : eaddr:eaddr -> reg:nativeint -> t
[ ~128 .. 127 ]
[ ~128 .. 127 ]
val btsow : eaddr:eaddr -> reg:nativeint -> t
val btsod : eaddr:eaddr -> reg:nativeint -> t
[ ~128 .. 127 ]
[ ~128 .. 127 ]
val call_jvow : reloc:nativeint Reloc.relocatable -> t
val call_jvod : reloc:nativeint Reloc.relocatable -> t
val call_epow : mem:mem -> t
val call_epod : mem:mem -> t
val call_apow : cs:nativeint -> ip:nativeint -> t
val call_apod : cs:nativeint -> ip:nativeint -> t
val call_evow : eaddr:eaddr -> t
val call_evod : eaddr:eaddr -> t
val cbw : unit -> t
val cwde : unit -> t
val clc : unit -> t
val cld : unit -> t
val cli : unit -> t
val clts : unit -> t
val cmc : unit -> t
val cmpsbaw : unit -> t
val cmpsbad : unit -> t
val cmpsvowaw : unit -> t
val cmpsvowad : unit -> t
val cmpsvodaw : unit -> t
val cmpsvodad : unit -> t
val cmpxchg_eb_gb : eaddr:eaddr -> reg:nativeint -> t
val cmpxchg_ev_gvow : eaddr:eaddr -> reg:nativeint -> t
val cmpxchg_ev_gvod : eaddr:eaddr -> reg:nativeint -> t
val cmpxchg8b : mem:mem -> t
val cpuid : unit -> t
val cwd : unit -> t
val cdq : unit -> t
val daa : unit -> t
val das : unit -> t
val dec_eb : eaddr:eaddr -> t
val dec_evow : eaddr:eaddr -> t
val dec_evod : eaddr:eaddr -> t
[ 0 .. 7 ]
[ 0 .. 7 ]
val dival : eaddr:eaddr -> t
val divax : eaddr:eaddr -> t
val diveax : eaddr:eaddr -> t
val enter :
[ ~128 .. 127 ]
val f2xm1 : unit -> t
val fabs : unit -> t
val fadd_r32 : mem:mem -> t
val fadd_r64 : mem:mem -> t
val fadd_st_sti : idx:nativeint -> t
val fadd_sti_st : idx:nativeint -> t
val faddp_sti_st : idx:nativeint -> t
val fiadd_i32 : mem:mem -> t
val fiadd_i16 : mem:mem -> t
val fbld : mem:mem -> t
val fbstp : mem:mem -> t
val fchs : unit -> t
val fnclex : unit -> t
val fcom_r32 : mem:mem -> t
val fcom_r64 : mem:mem -> t
val fcomp_r32 : mem:mem -> t
val fcomp_r64 : mem:mem -> t
val fcom_st_sti : idx:nativeint -> t
val fcomp_st_sti : idx:nativeint -> t
val fcompp : unit -> t
val fcos : unit -> t
val fdecstp : unit -> t
val fdiv_r32 : mem:mem -> t
val fdiv_r64 : mem:mem -> t
val fdiv_st_sti : idx:nativeint -> t
val fdiv_sti_st : idx:nativeint -> t
val fdivp_sti_st : idx:nativeint -> t
val fdivr_r32 : mem:mem -> t
val fdivr_r64 : mem:mem -> t
val fdivr_st_sti : idx:nativeint -> t
val fdivr_sti_st : idx:nativeint -> t
val fdivrp_sti_st : idx:nativeint -> t
val ffree : idx:nativeint -> t
val ficom_i32 : mem:mem -> t
val ficom_i16 : mem:mem -> t
val ficomp_i32 : mem:mem -> t
val ficomp_i16 : mem:mem -> t
val fild_lsi16 : mem:mem -> t
val fild_lsi32 : mem:mem -> t
val fild64 : mem:mem -> t
val finit : unit -> t
val fist_lsi16 : mem:mem -> t
val fist_lsi32 : mem:mem -> t
val fistp_lsi16 : mem:mem -> t
val fistp_lsi32 : mem:mem -> t
val fistp64 : mem:mem -> t
val fld_lsr32 : mem:mem -> t
val fld_lsr64 : mem:mem -> t
val fld80 : mem:mem -> t
val fld_sti : idx:nativeint -> t
val fld1 : unit -> t
val fldl2t : unit -> t
val fldl2e : unit -> t
val fldpi : unit -> t
val fldlg2 : unit -> t
val fldln2 : unit -> t
val fldz : unit -> t
val fldcw : mem:mem -> t
val fldenv : mem:mem -> t
val fmul_r32 : mem:mem -> t
val fmul_r64 : mem:mem -> t
val fmul_st_sti : idx:nativeint -> t
val fmul_sti_st : idx:nativeint -> t
val fmulp_sti_st : idx:nativeint -> t
val fnop : unit -> t
val fpatan : unit -> t
val fprem : unit -> t
val fprem1 : unit -> t
val fptan : unit -> t
val frndint : unit -> t
val frstor : mem:mem -> t
val fnsave : mem:mem -> t
val fscale : unit -> t
val fsin : unit -> t
val fsincos : unit -> t
val fsqrt : unit -> t
val fst_lsr32 : mem:mem -> t
val fst_lsr64 : mem:mem -> t
val fstp_lsr32 : mem:mem -> t
val fstp_lsr64 : mem:mem -> t
val fstp80 : mem:mem -> t
val fst_st_sti : idx:nativeint -> t
val fstp_st_sti : idx:nativeint -> t
val fstcw : mem:mem -> t
val fstenv : mem:mem -> t
val fstsw : mem:mem -> t
val fstsw_ax : unit -> t
val fsub_r32 : mem:mem -> t
val fsub_r64 : mem:mem -> t
val fsub_st_sti : idx:nativeint -> t
val fsub_sti_st : idx:nativeint -> t
val fsubp_sti_st : idx:nativeint -> t
val fsubr_r32 : mem:mem -> t
val fsubr_r64 : mem:mem -> t
val fsubr_st_sti : idx:nativeint -> t
val fsubr_sti_st : idx:nativeint -> t
val fsubrp_sti_st : idx:nativeint -> t
val ftst : unit -> t
val fucom : idx:nativeint -> t
val fucomp : idx:nativeint -> t
val fucompp : unit -> t
val fxam : unit -> t
val fxch : idx:nativeint -> t
val fxtract : unit -> t
val fyl2x : unit -> t
val fyl2xp1 : unit -> t
val hlt : unit -> t
val idiv : eaddr:eaddr -> t
val idivax : eaddr:eaddr -> t
val idiveax : eaddr:eaddr -> t
val imulb : eaddr:eaddr -> t
val imulow : eaddr:eaddr -> t
val imulod : eaddr:eaddr -> t
val imulrmow : reg:nativeint -> eaddr:eaddr -> t
val imulrmod : reg:nativeint -> eaddr:eaddr -> t
val imul_ibow :
[ ~128 .. 127 ]
val imul_ibod :
[ ~128 .. 127 ]
val imul_ivw :
[ ~32768 .. 32767 ]
val imul_ivd : reg:nativeint -> eaddr:eaddr -> i32:nativeint -> t
[ ~128 .. 127 ]
[ ~128 .. 127 ]
[ ~128 .. 127 ]
val in_al_dx : unit -> t
val in_eax_dxow : unit -> t
val in_eax_dxod : unit -> t
val inc_eb : eaddr:eaddr -> t
val inc_evow : eaddr:eaddr -> t
val inc_evod : eaddr:eaddr -> t
[ 0 .. 7 ]
[ 0 .. 7 ]
val insb : unit -> t
val insvow : unit -> t
val insvod : unit -> t
val int3 : unit -> t
[ ~128 .. 127 ]
val into : unit -> t
val invd : unit -> t
val invlpg : mem:mem -> t
val iret : unit -> t
val jb_o : reloc:nativeint Reloc.relocatable -> t
val jb_no : reloc:nativeint Reloc.relocatable -> t
val jb_b : reloc:nativeint Reloc.relocatable -> t
val jb_nb : reloc:nativeint Reloc.relocatable -> t
val jb_z : reloc:nativeint Reloc.relocatable -> t
val jb_nz : reloc:nativeint Reloc.relocatable -> t
val jb_be : reloc:nativeint Reloc.relocatable -> t
val jb_nbe : reloc:nativeint Reloc.relocatable -> t
val jb_s : reloc:nativeint Reloc.relocatable -> t
val jb_ns : reloc:nativeint Reloc.relocatable -> t
val jb_p : reloc:nativeint Reloc.relocatable -> t
val jb_np : reloc:nativeint Reloc.relocatable -> t
val jb_l : reloc:nativeint Reloc.relocatable -> t
val jb_nl : reloc:nativeint Reloc.relocatable -> t
val jb_le : reloc:nativeint Reloc.relocatable -> t
val jb_nle : reloc:nativeint Reloc.relocatable -> t
val jv_oow : reloc:nativeint Reloc.relocatable -> t
val jv_noow : reloc:nativeint Reloc.relocatable -> t
val jv_bow : reloc:nativeint Reloc.relocatable -> t
val jv_nbow : reloc:nativeint Reloc.relocatable -> t
val jv_zow : reloc:nativeint Reloc.relocatable -> t
val jv_nzow : reloc:nativeint Reloc.relocatable -> t
val jv_beow : reloc:nativeint Reloc.relocatable -> t
val jv_nbeow : reloc:nativeint Reloc.relocatable -> t
val jv_sow : reloc:nativeint Reloc.relocatable -> t
val jv_nsow : reloc:nativeint Reloc.relocatable -> t
val jv_pow : reloc:nativeint Reloc.relocatable -> t
val jv_npow : reloc:nativeint Reloc.relocatable -> t
val jv_low : reloc:nativeint Reloc.relocatable -> t
val jv_nlow : reloc:nativeint Reloc.relocatable -> t
val jv_leow : reloc:nativeint Reloc.relocatable -> t
val jv_nleow : reloc:nativeint Reloc.relocatable -> t
val jv_ood : reloc:nativeint Reloc.relocatable -> t
val jv_nood : reloc:nativeint Reloc.relocatable -> t
val jv_bod : reloc:nativeint Reloc.relocatable -> t
val jv_nbod : reloc:nativeint Reloc.relocatable -> t
val jv_zod : reloc:nativeint Reloc.relocatable -> t
val jv_nzod : reloc:nativeint Reloc.relocatable -> t
val jv_beod : reloc:nativeint Reloc.relocatable -> t
val jv_nbeod : reloc:nativeint Reloc.relocatable -> t
val jv_sod : reloc:nativeint Reloc.relocatable -> t
val jv_nsod : reloc:nativeint Reloc.relocatable -> t
val jv_pod : reloc:nativeint Reloc.relocatable -> t
val jv_npod : reloc:nativeint Reloc.relocatable -> t
val jv_lod : reloc:nativeint Reloc.relocatable -> t
val jv_nlod : reloc:nativeint Reloc.relocatable -> t
val jv_leod : reloc:nativeint Reloc.relocatable -> t
val jv_nleod : reloc:nativeint Reloc.relocatable -> t
val jcxz : reloc:nativeint Reloc.relocatable -> t
val jmp_jb : reloc:nativeint Reloc.relocatable -> t
val jmp_jvow : reloc:nativeint Reloc.relocatable -> t
val jmp_jvod : reloc:nativeint Reloc.relocatable -> t
val jmp_apow : cs:nativeint -> ip:nativeint -> t
val jmp_apod : cs:nativeint -> ip:nativeint -> t
val jmp_evow : eaddr:eaddr -> t
val jmp_evod : eaddr:eaddr -> t
val jmp_epow : mem:mem -> t
val jmp_epod : mem:mem -> t
val ldsow : reg:nativeint -> mem:mem -> t
val ldsod : reg:nativeint -> mem:mem -> t
val lesow : reg:nativeint -> mem:mem -> t
val lesod : reg:nativeint -> mem:mem -> t
val lfsow : reg:nativeint -> mem:mem -> t
val lfsod : reg:nativeint -> mem:mem -> t
val lgsow : reg:nativeint -> mem:mem -> t
val lgsod : reg:nativeint -> mem:mem -> t
val lssow : reg:nativeint -> mem:mem -> t
val lssod : reg:nativeint -> mem:mem -> t
val leaow : reg:nativeint -> mem:mem -> t
val leaod : reg:nativeint -> mem:mem -> t
val leave : unit -> t
val lgdt : mem:mem -> t
val lidt : mem:mem -> t
val lldt : eaddr:eaddr -> t
val lmsw : eaddr:eaddr -> t
val lock : unit -> t
val lodsb : unit -> t
val lodsvow : unit -> t
val lodsvod : unit -> t
val lahf : unit -> t
val larow : reg:nativeint -> eaddr:eaddr -> t
val larod : reg:nativeint -> eaddr:eaddr -> t
val loopow : reloc:nativeint Reloc.relocatable -> t
val loopod : reloc:nativeint Reloc.relocatable -> t
val loopeow : reloc:nativeint Reloc.relocatable -> t
val loopeod : reloc:nativeint Reloc.relocatable -> t
val loopneow : reloc:nativeint Reloc.relocatable -> t
val loopneod : reloc:nativeint Reloc.relocatable -> t
val lslow : reg:nativeint -> eaddr:eaddr -> t
val lslod : reg:nativeint -> eaddr:eaddr -> t
val ltr : eaddr:eaddr -> t
val movmrb : eaddr:eaddr -> reg:nativeint -> t
val movmrow : eaddr:eaddr -> reg:nativeint -> t
val movmrod : eaddr:eaddr -> reg:nativeint -> t
val movrmb : reg:nativeint -> eaddr:eaddr -> t
val movrmow : reg:nativeint -> eaddr:eaddr -> t
val movrmod : reg:nativeint -> eaddr:eaddr -> t
[ 0 .. 7 ]
[ 0 .. 7 ]
val mov_al_ob : offset:nativeint -> t
val mov_eax_ovow : offset:nativeint -> t
val mov_eax_ovod : offset:nativeint -> t
val mov_ob_al : offset:nativeint -> t
val mov_ov_eaxow : offset:nativeint -> t
val mov_ov_eaxod : offset:nativeint -> t
[ ~128 .. 127 ]
val moviw :
[ ~32768 .. 32767 ]
[ 0 .. 7 ]
[ ~128 .. 127 ]
[ ~32768 .. 32767 ]
val mov_ev_ivod : eaddr:eaddr -> i32:nativeint -> t
val mov_cd_rd : cr:nativeint -> reg:nativeint -> t
val mov_rd_cd : reg:nativeint -> cr:nativeint -> t
val mov_dd_rd : dr:nativeint -> reg:nativeint -> t
val mov_rd_dd : reg:nativeint -> dr:nativeint -> t
val movsb : unit -> t
val movsvow : unit -> t
val movsvod : unit -> t
[ 0 .. 7 ]
[ 0 .. 7 ]
[ 0 .. 7 ]
[ 0 .. 7 ]
[ 0 .. 7 ]
[ 0 .. 7 ]
val mul_al : eaddr:eaddr -> t
val mul_axow : eaddr:eaddr -> t
val mul_axod : eaddr:eaddr -> t
val negb : eaddr:eaddr -> t
val negow : eaddr:eaddr -> t
val negod : eaddr:eaddr -> t
val nop : unit -> t
val notb : eaddr:eaddr -> t
val notow : eaddr:eaddr -> t
val notod : eaddr:eaddr -> t
[ ~128 .. 127 ]
[ ~128 .. 127 ]
[ ~128 .. 127 ]
val out_dx_al : unit -> t
val out_dx_eaxow : unit -> t
val out_dx_eaxod : unit -> t
val outsb : unit -> t
val outsvow : unit -> t
val outsvod : unit -> t
val pop_evow : mem:mem -> t
val pop_evod : mem:mem -> t
[ 0 .. 7 ]
[ 0 .. 7 ]
val pop_es : unit -> t
val pop_ss : unit -> t
val pop_ds : unit -> t
val pop_fs : unit -> t
val pop_gs : unit -> t
val popaow : unit -> t
val popaod : unit -> t
val popfow : unit -> t
val popfod : unit -> t
val push_evow : eaddr:eaddr -> t
val push_evod : eaddr:eaddr -> t
[ 0 .. 7 ]
[ 0 .. 7 ]
[ ~128 .. 127 ]
[ ~32768 .. 32767 ]
val push_ivod : i32:nativeint -> t
val push_cs : unit -> t
val push_ss : unit -> t
val push_ds : unit -> t
val push_es : unit -> t
val push_fs : unit -> t
val push_gs : unit -> t
val pushaow : unit -> t
val pushaod : unit -> t
val pushfow : unit -> t
val pushfod : unit -> t
val rolb_eb_1 : eaddr:eaddr -> t
val rolb_eb_cl : eaddr:eaddr -> t
val rorb_eb_1 : eaddr:eaddr -> t
val rorb_eb_cl : eaddr:eaddr -> t
val rclb_eb_1 : eaddr:eaddr -> t
val rclb_eb_cl : eaddr:eaddr -> t
val rcrb_eb_1 : eaddr:eaddr -> t
val rcrb_eb_cl : eaddr:eaddr -> t
val shlsalb_eb_1 : eaddr:eaddr -> t
val shlsalb_eb_cl : eaddr:eaddr -> t
val shrb_eb_1 : eaddr:eaddr -> t
val shrb_eb_cl : eaddr:eaddr -> t
val sarb_eb_1 : eaddr:eaddr -> t
val sarb_eb_cl : eaddr:eaddr -> t
val rolb_ev_1ow : eaddr:eaddr -> t
val rolb_ev_1od : eaddr:eaddr -> t
val rolb_ev_clow : eaddr:eaddr -> t
val rolb_ev_clod : eaddr:eaddr -> t
val rorb_ev_1ow : eaddr:eaddr -> t
val rorb_ev_1od : eaddr:eaddr -> t
val rorb_ev_clow : eaddr:eaddr -> t
val rorb_ev_clod : eaddr:eaddr -> t
val rclb_ev_1ow : eaddr:eaddr -> t
val rclb_ev_1od : eaddr:eaddr -> t
val rclb_ev_clow : eaddr:eaddr -> t
val rclb_ev_clod : eaddr:eaddr -> t
val rcrb_ev_1ow : eaddr:eaddr -> t
val rcrb_ev_1od : eaddr:eaddr -> t
val rcrb_ev_clow : eaddr:eaddr -> t
val rcrb_ev_clod : eaddr:eaddr -> t
val shlsalb_ev_1ow : eaddr:eaddr -> t
val shlsalb_ev_1od : eaddr:eaddr -> t
val shlsalb_ev_clow : eaddr:eaddr -> t
val shlsalb_ev_clod : eaddr:eaddr -> t
val shrb_ev_1ow : eaddr:eaddr -> t
val shrb_ev_1od : eaddr:eaddr -> t
val shrb_ev_clow : eaddr:eaddr -> t
val shrb_ev_clod : eaddr:eaddr -> t
val sarb_ev_1ow : eaddr:eaddr -> t
val sarb_ev_1od : eaddr:eaddr -> t
val sarb_ev_clow : eaddr:eaddr -> t
val sarb_ev_clod : eaddr:eaddr -> t
[ ~128 .. 127 ]
[ ~128 .. 127 ]
[ ~128 .. 127 ]
[ ~128 .. 127 ]
[ ~128 .. 127 ]
[ ~128 .. 127 ]
[ ~128 .. 127 ]
[ ~128 .. 127 ]
[ ~128 .. 127 ]
[ ~128 .. 127 ]
[ ~128 .. 127 ]
[ ~128 .. 127 ]
[ ~128 .. 127 ]
[ ~128 .. 127 ]
[ ~128 .. 127 ]
[ ~128 .. 127 ]
[ ~128 .. 127 ]
[ ~128 .. 127 ]
[ ~128 .. 127 ]
[ ~128 .. 127 ]
[ ~128 .. 127 ]
val rdmsr : unit -> t
val rep : unit -> t
val repne : unit -> t
val ret : unit -> t
val ret_far : unit -> t
[ 0 .. 65535 ]
[ 0 .. 65535 ]
val rsm : unit -> t
val sahf : unit -> t
val scasb : unit -> t
val scasvow : unit -> t
val scasvod : unit -> t
val setb_o : eaddr:eaddr -> t
val setb_no : eaddr:eaddr -> t
val setb_b : eaddr:eaddr -> t
val setb_nb : eaddr:eaddr -> t
val setb_z : eaddr:eaddr -> t
val setb_nz : eaddr:eaddr -> t
val setb_be : eaddr:eaddr -> t
val setb_nbe : eaddr:eaddr -> t
val setb_s : eaddr:eaddr -> t
val setb_ns : eaddr:eaddr -> t
val setb_p : eaddr:eaddr -> t
val setb_np : eaddr:eaddr -> t
val setb_l : eaddr:eaddr -> t
val setb_nl : eaddr:eaddr -> t
val setb_le : eaddr:eaddr -> t
val setb_nle : eaddr:eaddr -> t
val sgdt : mem:mem -> t
val sidt : mem:mem -> t
val shrd_ibow : eaddr:eaddr -> reg:nativeint -> count:nativeint -> t
val shrd_ibod : eaddr:eaddr -> reg:nativeint -> count:nativeint -> t
val shld_ibow : eaddr:eaddr -> reg:nativeint -> count:nativeint -> t
val shld_ibod : eaddr:eaddr -> reg:nativeint -> count:nativeint -> t
val shrd_clow : eaddr:eaddr -> reg:nativeint -> t
val shrd_clod : eaddr:eaddr -> reg:nativeint -> t
val shld_clow : eaddr:eaddr -> reg:nativeint -> t
val shld_clod : eaddr:eaddr -> reg:nativeint -> t
val sldt : eaddr:eaddr -> t
val smsw : eaddr:eaddr -> t
val stc : unit -> t
val std : unit -> t
val sti : unit -> t
val stosb : unit -> t
val stosvow : unit -> t
val stosvod : unit -> t
val str : mem:mem -> t
[ 0 .. 255 ]
[ 0 .. 65535 ]
val test_eax_ivod : i32:nativeint -> t
[ 0 .. 255 ]
[ 0 .. 65535 ]
val test_ed_id : eaddr:eaddr -> i32:nativeint -> t
val test_eb_gb : eaddr:eaddr -> reg:nativeint -> t
val test_ev_gvow : eaddr:eaddr -> reg:nativeint -> t
val test_ev_gvod : eaddr:eaddr -> reg:nativeint -> t
val verr : eaddr:eaddr -> t
val verw : eaddr:eaddr -> t
val wait : unit -> t
val wbinvd : unit -> t
val wrmsr : unit -> t
val xadd_eb_gb : eaddr:eaddr -> reg:nativeint -> t
val xadd_ev_gvow : eaddr:eaddr -> reg:nativeint -> t
val xadd_ev_gvod : eaddr:eaddr -> reg:nativeint -> t
[ 0 .. 7 ]
[ 0 .. 7 ]
val xchg_eb_gb : eaddr:eaddr -> reg:nativeint -> t
val xchg_ev_gvow : eaddr:eaddr -> reg:nativeint -> t
val xchg_ev_gvod : eaddr:eaddr -> reg:nativeint -> t
val xlatb : unit -> t
val fclex : unit -> t
val fsave : mem:mem -> t
val fnstcw : mem:mem -> t
val fnstenv : mem:mem -> t
val fnstsw : mem:mem -> t
val fnstsw_ax : unit -> t
val fwait : unit -> t
end
module type Maker =
functor (Reloc : Sledlib.RELOCATABLE) -> S with module Reloc = Reloc
| null | https://raw.githubusercontent.com/nrnrnr/qc--/ec56191b669729e7ce8181a2bd97a912842ea716/gen/x86i.ml | ocaml | module type S = sig
module Reloc : Sledlib.RELOCATABLE
type rel8
type rel16
type rel32
type mem
type eaddr
type t
val rel8 : reloc:nativeint Reloc.relocatable -> rel8
val rel16 : reloc:nativeint Reloc.relocatable -> rel16
val rel32 : reloc:nativeint Reloc.relocatable -> rel32
val indir : reg:nativeint -> mem
val disp8 : d:nativeint Reloc.relocatable -> reg:nativeint -> mem
val disp32 : d:nativeint Reloc.relocatable -> reg:nativeint -> mem
val abs32 : a:nativeint Reloc.relocatable -> mem
val reg : reg:nativeint -> eaddr
val index :
[ 0 .. 7 ]
[ 0 .. 3 ]
val index8 :
[ 0 .. 7 ]
[ 0 .. 3 ]
val index32 :
[ 0 .. 7 ]
[ 0 .. 3 ]
val shortindex :
[ 0 .. 7 ]
[ 0 .. 3 ]
val e : mem:mem -> eaddr
[ ~128 .. 127 ]
[ ~128 .. 127 ]
[ ~128 .. 127 ]
[ ~128 .. 127 ]
[ ~128 .. 127 ]
[ ~128 .. 127 ]
[ ~128 .. 127 ]
[ ~128 .. 127 ]
[ ~32768 .. 32767 ]
[ ~32768 .. 32767 ]
[ ~32768 .. 32767 ]
[ ~32768 .. 32767 ]
[ ~32768 .. 32767 ]
[ ~32768 .. 32767 ]
[ ~32768 .. 32767 ]
[ ~32768 .. 32767 ]
val addieax : i32:nativeint -> t
val orieax : i32:nativeint -> t
val adcieax : i32:nativeint -> t
val sbbieax : i32:nativeint -> t
val andieax : i32:nativeint -> t
val subieax : i32:nativeint -> t
val xorieax : i32:nativeint -> t
val cmpieax : i32:nativeint -> t
[ ~128 .. 127 ]
[ ~128 .. 127 ]
[ ~128 .. 127 ]
[ ~128 .. 127 ]
[ ~128 .. 127 ]
[ ~128 .. 127 ]
[ ~128 .. 127 ]
[ ~128 .. 127 ]
[ ~32768 .. 32767 ]
[ ~32768 .. 32767 ]
[ ~32768 .. 32767 ]
[ ~32768 .. 32767 ]
[ ~32768 .. 32767 ]
[ ~32768 .. 32767 ]
[ ~32768 .. 32767 ]
[ ~32768 .. 32767 ]
val addid : eaddr:eaddr -> i32:nativeint -> t
val orid : eaddr:eaddr -> i32:nativeint -> t
val adcid : eaddr:eaddr -> i32:nativeint -> t
val sbbid : eaddr:eaddr -> i32:nativeint -> t
val andid : eaddr:eaddr -> i32:nativeint -> t
val subid : eaddr:eaddr -> i32:nativeint -> t
val xorid : eaddr:eaddr -> i32:nativeint -> t
val cmpid : eaddr:eaddr -> i32:nativeint -> t
[ ~128 .. 127 ]
[ ~128 .. 127 ]
[ ~128 .. 127 ]
[ ~128 .. 127 ]
[ ~128 .. 127 ]
[ ~128 .. 127 ]
[ ~128 .. 127 ]
[ ~128 .. 127 ]
[ ~128 .. 127 ]
[ ~128 .. 127 ]
[ ~128 .. 127 ]
[ ~128 .. 127 ]
[ ~128 .. 127 ]
[ ~128 .. 127 ]
[ ~128 .. 127 ]
[ ~128 .. 127 ]
val addmrb : eaddr:eaddr -> reg8:nativeint -> t
val ormrb : eaddr:eaddr -> reg8:nativeint -> t
val adcmrb : eaddr:eaddr -> reg8:nativeint -> t
val sbbmrb : eaddr:eaddr -> reg8:nativeint -> t
val andmrb : eaddr:eaddr -> reg8:nativeint -> t
val submrb : eaddr:eaddr -> reg8:nativeint -> t
val xormrb : eaddr:eaddr -> reg8:nativeint -> t
val cmpmrb : eaddr:eaddr -> reg8:nativeint -> t
val addmrow : eaddr:eaddr -> reg:nativeint -> t
val addmrod : eaddr:eaddr -> reg:nativeint -> t
val ormrow : eaddr:eaddr -> reg:nativeint -> t
val ormrod : eaddr:eaddr -> reg:nativeint -> t
val adcmrow : eaddr:eaddr -> reg:nativeint -> t
val adcmrod : eaddr:eaddr -> reg:nativeint -> t
val sbbmrow : eaddr:eaddr -> reg:nativeint -> t
val sbbmrod : eaddr:eaddr -> reg:nativeint -> t
val andmrow : eaddr:eaddr -> reg:nativeint -> t
val andmrod : eaddr:eaddr -> reg:nativeint -> t
val submrow : eaddr:eaddr -> reg:nativeint -> t
val submrod : eaddr:eaddr -> reg:nativeint -> t
val xormrow : eaddr:eaddr -> reg:nativeint -> t
val xormrod : eaddr:eaddr -> reg:nativeint -> t
val cmpmrow : eaddr:eaddr -> reg:nativeint -> t
val cmpmrod : eaddr:eaddr -> reg:nativeint -> t
val addrmb : reg8:nativeint -> eaddr:eaddr -> t
val orrmb : reg8:nativeint -> eaddr:eaddr -> t
val adcrmb : reg8:nativeint -> eaddr:eaddr -> t
val sbbrmb : reg8:nativeint -> eaddr:eaddr -> t
val andrmb : reg8:nativeint -> eaddr:eaddr -> t
val subrmb : reg8:nativeint -> eaddr:eaddr -> t
val xorrmb : reg8:nativeint -> eaddr:eaddr -> t
val cmprmb : reg8:nativeint -> eaddr:eaddr -> t
val addrmow : reg:nativeint -> eaddr:eaddr -> t
val addrmod : reg:nativeint -> eaddr:eaddr -> t
val orrmow : reg:nativeint -> eaddr:eaddr -> t
val orrmod : reg:nativeint -> eaddr:eaddr -> t
val adcrmow : reg:nativeint -> eaddr:eaddr -> t
val adcrmod : reg:nativeint -> eaddr:eaddr -> t
val sbbrmow : reg:nativeint -> eaddr:eaddr -> t
val sbbrmod : reg:nativeint -> eaddr:eaddr -> t
val andrmow : reg:nativeint -> eaddr:eaddr -> t
val andrmod : reg:nativeint -> eaddr:eaddr -> t
val subrmow : reg:nativeint -> eaddr:eaddr -> t
val subrmod : reg:nativeint -> eaddr:eaddr -> t
val xorrmow : reg:nativeint -> eaddr:eaddr -> t
val xorrmod : reg:nativeint -> eaddr:eaddr -> t
val cmprmow : reg:nativeint -> eaddr:eaddr -> t
val cmprmod : reg:nativeint -> eaddr:eaddr -> t
val aaa : unit -> t
val aad : unit -> t
val aam : unit -> t
val aas : unit -> t
val arpl : eaddr:eaddr -> reg16:nativeint -> t
val boundow : reg:nativeint -> mem:mem -> t
val boundod : reg:nativeint -> mem:mem -> t
val bsfow : reg:nativeint -> eaddr:eaddr -> t
val bsfod : reg:nativeint -> eaddr:eaddr -> t
val bsrow : reg:nativeint -> eaddr:eaddr -> t
val bsrod : reg:nativeint -> eaddr:eaddr -> t
[ 0 .. 7 ]
val btow : eaddr:eaddr -> reg:nativeint -> t
val btod : eaddr:eaddr -> reg:nativeint -> t
[ ~128 .. 127 ]
[ ~128 .. 127 ]
val btcow : eaddr:eaddr -> reg:nativeint -> t
val btcod : eaddr:eaddr -> reg:nativeint -> t
[ ~128 .. 127 ]
[ ~128 .. 127 ]
val btrow : eaddr:eaddr -> reg:nativeint -> t
val btrod : eaddr:eaddr -> reg:nativeint -> t
[ ~128 .. 127 ]
[ ~128 .. 127 ]
val btsow : eaddr:eaddr -> reg:nativeint -> t
val btsod : eaddr:eaddr -> reg:nativeint -> t
[ ~128 .. 127 ]
[ ~128 .. 127 ]
val call_jvow : reloc:nativeint Reloc.relocatable -> t
val call_jvod : reloc:nativeint Reloc.relocatable -> t
val call_epow : mem:mem -> t
val call_epod : mem:mem -> t
val call_apow : cs:nativeint -> ip:nativeint -> t
val call_apod : cs:nativeint -> ip:nativeint -> t
val call_evow : eaddr:eaddr -> t
val call_evod : eaddr:eaddr -> t
val cbw : unit -> t
val cwde : unit -> t
val clc : unit -> t
val cld : unit -> t
val cli : unit -> t
val clts : unit -> t
val cmc : unit -> t
val cmpsbaw : unit -> t
val cmpsbad : unit -> t
val cmpsvowaw : unit -> t
val cmpsvowad : unit -> t
val cmpsvodaw : unit -> t
val cmpsvodad : unit -> t
val cmpxchg_eb_gb : eaddr:eaddr -> reg:nativeint -> t
val cmpxchg_ev_gvow : eaddr:eaddr -> reg:nativeint -> t
val cmpxchg_ev_gvod : eaddr:eaddr -> reg:nativeint -> t
val cmpxchg8b : mem:mem -> t
val cpuid : unit -> t
val cwd : unit -> t
val cdq : unit -> t
val daa : unit -> t
val das : unit -> t
val dec_eb : eaddr:eaddr -> t
val dec_evow : eaddr:eaddr -> t
val dec_evod : eaddr:eaddr -> t
[ 0 .. 7 ]
[ 0 .. 7 ]
val dival : eaddr:eaddr -> t
val divax : eaddr:eaddr -> t
val diveax : eaddr:eaddr -> t
val enter :
[ ~128 .. 127 ]
val f2xm1 : unit -> t
val fabs : unit -> t
val fadd_r32 : mem:mem -> t
val fadd_r64 : mem:mem -> t
val fadd_st_sti : idx:nativeint -> t
val fadd_sti_st : idx:nativeint -> t
val faddp_sti_st : idx:nativeint -> t
val fiadd_i32 : mem:mem -> t
val fiadd_i16 : mem:mem -> t
val fbld : mem:mem -> t
val fbstp : mem:mem -> t
val fchs : unit -> t
val fnclex : unit -> t
val fcom_r32 : mem:mem -> t
val fcom_r64 : mem:mem -> t
val fcomp_r32 : mem:mem -> t
val fcomp_r64 : mem:mem -> t
val fcom_st_sti : idx:nativeint -> t
val fcomp_st_sti : idx:nativeint -> t
val fcompp : unit -> t
val fcos : unit -> t
val fdecstp : unit -> t
val fdiv_r32 : mem:mem -> t
val fdiv_r64 : mem:mem -> t
val fdiv_st_sti : idx:nativeint -> t
val fdiv_sti_st : idx:nativeint -> t
val fdivp_sti_st : idx:nativeint -> t
val fdivr_r32 : mem:mem -> t
val fdivr_r64 : mem:mem -> t
val fdivr_st_sti : idx:nativeint -> t
val fdivr_sti_st : idx:nativeint -> t
val fdivrp_sti_st : idx:nativeint -> t
val ffree : idx:nativeint -> t
val ficom_i32 : mem:mem -> t
val ficom_i16 : mem:mem -> t
val ficomp_i32 : mem:mem -> t
val ficomp_i16 : mem:mem -> t
val fild_lsi16 : mem:mem -> t
val fild_lsi32 : mem:mem -> t
val fild64 : mem:mem -> t
val finit : unit -> t
val fist_lsi16 : mem:mem -> t
val fist_lsi32 : mem:mem -> t
val fistp_lsi16 : mem:mem -> t
val fistp_lsi32 : mem:mem -> t
val fistp64 : mem:mem -> t
val fld_lsr32 : mem:mem -> t
val fld_lsr64 : mem:mem -> t
val fld80 : mem:mem -> t
val fld_sti : idx:nativeint -> t
val fld1 : unit -> t
val fldl2t : unit -> t
val fldl2e : unit -> t
val fldpi : unit -> t
val fldlg2 : unit -> t
val fldln2 : unit -> t
val fldz : unit -> t
val fldcw : mem:mem -> t
val fldenv : mem:mem -> t
val fmul_r32 : mem:mem -> t
val fmul_r64 : mem:mem -> t
val fmul_st_sti : idx:nativeint -> t
val fmul_sti_st : idx:nativeint -> t
val fmulp_sti_st : idx:nativeint -> t
val fnop : unit -> t
val fpatan : unit -> t
val fprem : unit -> t
val fprem1 : unit -> t
val fptan : unit -> t
val frndint : unit -> t
val frstor : mem:mem -> t
val fnsave : mem:mem -> t
val fscale : unit -> t
val fsin : unit -> t
val fsincos : unit -> t
val fsqrt : unit -> t
val fst_lsr32 : mem:mem -> t
val fst_lsr64 : mem:mem -> t
val fstp_lsr32 : mem:mem -> t
val fstp_lsr64 : mem:mem -> t
val fstp80 : mem:mem -> t
val fst_st_sti : idx:nativeint -> t
val fstp_st_sti : idx:nativeint -> t
val fstcw : mem:mem -> t
val fstenv : mem:mem -> t
val fstsw : mem:mem -> t
val fstsw_ax : unit -> t
val fsub_r32 : mem:mem -> t
val fsub_r64 : mem:mem -> t
val fsub_st_sti : idx:nativeint -> t
val fsub_sti_st : idx:nativeint -> t
val fsubp_sti_st : idx:nativeint -> t
val fsubr_r32 : mem:mem -> t
val fsubr_r64 : mem:mem -> t
val fsubr_st_sti : idx:nativeint -> t
val fsubr_sti_st : idx:nativeint -> t
val fsubrp_sti_st : idx:nativeint -> t
val ftst : unit -> t
val fucom : idx:nativeint -> t
val fucomp : idx:nativeint -> t
val fucompp : unit -> t
val fxam : unit -> t
val fxch : idx:nativeint -> t
val fxtract : unit -> t
val fyl2x : unit -> t
val fyl2xp1 : unit -> t
val hlt : unit -> t
val idiv : eaddr:eaddr -> t
val idivax : eaddr:eaddr -> t
val idiveax : eaddr:eaddr -> t
val imulb : eaddr:eaddr -> t
val imulow : eaddr:eaddr -> t
val imulod : eaddr:eaddr -> t
val imulrmow : reg:nativeint -> eaddr:eaddr -> t
val imulrmod : reg:nativeint -> eaddr:eaddr -> t
val imul_ibow :
[ ~128 .. 127 ]
val imul_ibod :
[ ~128 .. 127 ]
val imul_ivw :
[ ~32768 .. 32767 ]
val imul_ivd : reg:nativeint -> eaddr:eaddr -> i32:nativeint -> t
[ ~128 .. 127 ]
[ ~128 .. 127 ]
[ ~128 .. 127 ]
val in_al_dx : unit -> t
val in_eax_dxow : unit -> t
val in_eax_dxod : unit -> t
val inc_eb : eaddr:eaddr -> t
val inc_evow : eaddr:eaddr -> t
val inc_evod : eaddr:eaddr -> t
[ 0 .. 7 ]
[ 0 .. 7 ]
val insb : unit -> t
val insvow : unit -> t
val insvod : unit -> t
val int3 : unit -> t
[ ~128 .. 127 ]
val into : unit -> t
val invd : unit -> t
val invlpg : mem:mem -> t
val iret : unit -> t
val jb_o : reloc:nativeint Reloc.relocatable -> t
val jb_no : reloc:nativeint Reloc.relocatable -> t
val jb_b : reloc:nativeint Reloc.relocatable -> t
val jb_nb : reloc:nativeint Reloc.relocatable -> t
val jb_z : reloc:nativeint Reloc.relocatable -> t
val jb_nz : reloc:nativeint Reloc.relocatable -> t
val jb_be : reloc:nativeint Reloc.relocatable -> t
val jb_nbe : reloc:nativeint Reloc.relocatable -> t
val jb_s : reloc:nativeint Reloc.relocatable -> t
val jb_ns : reloc:nativeint Reloc.relocatable -> t
val jb_p : reloc:nativeint Reloc.relocatable -> t
val jb_np : reloc:nativeint Reloc.relocatable -> t
val jb_l : reloc:nativeint Reloc.relocatable -> t
val jb_nl : reloc:nativeint Reloc.relocatable -> t
val jb_le : reloc:nativeint Reloc.relocatable -> t
val jb_nle : reloc:nativeint Reloc.relocatable -> t
val jv_oow : reloc:nativeint Reloc.relocatable -> t
val jv_noow : reloc:nativeint Reloc.relocatable -> t
val jv_bow : reloc:nativeint Reloc.relocatable -> t
val jv_nbow : reloc:nativeint Reloc.relocatable -> t
val jv_zow : reloc:nativeint Reloc.relocatable -> t
val jv_nzow : reloc:nativeint Reloc.relocatable -> t
val jv_beow : reloc:nativeint Reloc.relocatable -> t
val jv_nbeow : reloc:nativeint Reloc.relocatable -> t
val jv_sow : reloc:nativeint Reloc.relocatable -> t
val jv_nsow : reloc:nativeint Reloc.relocatable -> t
val jv_pow : reloc:nativeint Reloc.relocatable -> t
val jv_npow : reloc:nativeint Reloc.relocatable -> t
val jv_low : reloc:nativeint Reloc.relocatable -> t
val jv_nlow : reloc:nativeint Reloc.relocatable -> t
val jv_leow : reloc:nativeint Reloc.relocatable -> t
val jv_nleow : reloc:nativeint Reloc.relocatable -> t
val jv_ood : reloc:nativeint Reloc.relocatable -> t
val jv_nood : reloc:nativeint Reloc.relocatable -> t
val jv_bod : reloc:nativeint Reloc.relocatable -> t
val jv_nbod : reloc:nativeint Reloc.relocatable -> t
val jv_zod : reloc:nativeint Reloc.relocatable -> t
val jv_nzod : reloc:nativeint Reloc.relocatable -> t
val jv_beod : reloc:nativeint Reloc.relocatable -> t
val jv_nbeod : reloc:nativeint Reloc.relocatable -> t
val jv_sod : reloc:nativeint Reloc.relocatable -> t
val jv_nsod : reloc:nativeint Reloc.relocatable -> t
val jv_pod : reloc:nativeint Reloc.relocatable -> t
val jv_npod : reloc:nativeint Reloc.relocatable -> t
val jv_lod : reloc:nativeint Reloc.relocatable -> t
val jv_nlod : reloc:nativeint Reloc.relocatable -> t
val jv_leod : reloc:nativeint Reloc.relocatable -> t
val jv_nleod : reloc:nativeint Reloc.relocatable -> t
val jcxz : reloc:nativeint Reloc.relocatable -> t
val jmp_jb : reloc:nativeint Reloc.relocatable -> t
val jmp_jvow : reloc:nativeint Reloc.relocatable -> t
val jmp_jvod : reloc:nativeint Reloc.relocatable -> t
val jmp_apow : cs:nativeint -> ip:nativeint -> t
val jmp_apod : cs:nativeint -> ip:nativeint -> t
val jmp_evow : eaddr:eaddr -> t
val jmp_evod : eaddr:eaddr -> t
val jmp_epow : mem:mem -> t
val jmp_epod : mem:mem -> t
val ldsow : reg:nativeint -> mem:mem -> t
val ldsod : reg:nativeint -> mem:mem -> t
val lesow : reg:nativeint -> mem:mem -> t
val lesod : reg:nativeint -> mem:mem -> t
val lfsow : reg:nativeint -> mem:mem -> t
val lfsod : reg:nativeint -> mem:mem -> t
val lgsow : reg:nativeint -> mem:mem -> t
val lgsod : reg:nativeint -> mem:mem -> t
val lssow : reg:nativeint -> mem:mem -> t
val lssod : reg:nativeint -> mem:mem -> t
val leaow : reg:nativeint -> mem:mem -> t
val leaod : reg:nativeint -> mem:mem -> t
val leave : unit -> t
val lgdt : mem:mem -> t
val lidt : mem:mem -> t
val lldt : eaddr:eaddr -> t
val lmsw : eaddr:eaddr -> t
val lock : unit -> t
val lodsb : unit -> t
val lodsvow : unit -> t
val lodsvod : unit -> t
val lahf : unit -> t
val larow : reg:nativeint -> eaddr:eaddr -> t
val larod : reg:nativeint -> eaddr:eaddr -> t
val loopow : reloc:nativeint Reloc.relocatable -> t
val loopod : reloc:nativeint Reloc.relocatable -> t
val loopeow : reloc:nativeint Reloc.relocatable -> t
val loopeod : reloc:nativeint Reloc.relocatable -> t
val loopneow : reloc:nativeint Reloc.relocatable -> t
val loopneod : reloc:nativeint Reloc.relocatable -> t
val lslow : reg:nativeint -> eaddr:eaddr -> t
val lslod : reg:nativeint -> eaddr:eaddr -> t
val ltr : eaddr:eaddr -> t
val movmrb : eaddr:eaddr -> reg:nativeint -> t
val movmrow : eaddr:eaddr -> reg:nativeint -> t
val movmrod : eaddr:eaddr -> reg:nativeint -> t
val movrmb : reg:nativeint -> eaddr:eaddr -> t
val movrmow : reg:nativeint -> eaddr:eaddr -> t
val movrmod : reg:nativeint -> eaddr:eaddr -> t
[ 0 .. 7 ]
[ 0 .. 7 ]
val mov_al_ob : offset:nativeint -> t
val mov_eax_ovow : offset:nativeint -> t
val mov_eax_ovod : offset:nativeint -> t
val mov_ob_al : offset:nativeint -> t
val mov_ov_eaxow : offset:nativeint -> t
val mov_ov_eaxod : offset:nativeint -> t
[ ~128 .. 127 ]
val moviw :
[ ~32768 .. 32767 ]
[ 0 .. 7 ]
[ ~128 .. 127 ]
[ ~32768 .. 32767 ]
val mov_ev_ivod : eaddr:eaddr -> i32:nativeint -> t
val mov_cd_rd : cr:nativeint -> reg:nativeint -> t
val mov_rd_cd : reg:nativeint -> cr:nativeint -> t
val mov_dd_rd : dr:nativeint -> reg:nativeint -> t
val mov_rd_dd : reg:nativeint -> dr:nativeint -> t
val movsb : unit -> t
val movsvow : unit -> t
val movsvod : unit -> t
[ 0 .. 7 ]
[ 0 .. 7 ]
[ 0 .. 7 ]
[ 0 .. 7 ]
[ 0 .. 7 ]
[ 0 .. 7 ]
val mul_al : eaddr:eaddr -> t
val mul_axow : eaddr:eaddr -> t
val mul_axod : eaddr:eaddr -> t
val negb : eaddr:eaddr -> t
val negow : eaddr:eaddr -> t
val negod : eaddr:eaddr -> t
val nop : unit -> t
val notb : eaddr:eaddr -> t
val notow : eaddr:eaddr -> t
val notod : eaddr:eaddr -> t
[ ~128 .. 127 ]
[ ~128 .. 127 ]
[ ~128 .. 127 ]
val out_dx_al : unit -> t
val out_dx_eaxow : unit -> t
val out_dx_eaxod : unit -> t
val outsb : unit -> t
val outsvow : unit -> t
val outsvod : unit -> t
val pop_evow : mem:mem -> t
val pop_evod : mem:mem -> t
[ 0 .. 7 ]
[ 0 .. 7 ]
val pop_es : unit -> t
val pop_ss : unit -> t
val pop_ds : unit -> t
val pop_fs : unit -> t
val pop_gs : unit -> t
val popaow : unit -> t
val popaod : unit -> t
val popfow : unit -> t
val popfod : unit -> t
val push_evow : eaddr:eaddr -> t
val push_evod : eaddr:eaddr -> t
[ 0 .. 7 ]
[ 0 .. 7 ]
[ ~128 .. 127 ]
[ ~32768 .. 32767 ]
val push_ivod : i32:nativeint -> t
val push_cs : unit -> t
val push_ss : unit -> t
val push_ds : unit -> t
val push_es : unit -> t
val push_fs : unit -> t
val push_gs : unit -> t
val pushaow : unit -> t
val pushaod : unit -> t
val pushfow : unit -> t
val pushfod : unit -> t
val rolb_eb_1 : eaddr:eaddr -> t
val rolb_eb_cl : eaddr:eaddr -> t
val rorb_eb_1 : eaddr:eaddr -> t
val rorb_eb_cl : eaddr:eaddr -> t
val rclb_eb_1 : eaddr:eaddr -> t
val rclb_eb_cl : eaddr:eaddr -> t
val rcrb_eb_1 : eaddr:eaddr -> t
val rcrb_eb_cl : eaddr:eaddr -> t
val shlsalb_eb_1 : eaddr:eaddr -> t
val shlsalb_eb_cl : eaddr:eaddr -> t
val shrb_eb_1 : eaddr:eaddr -> t
val shrb_eb_cl : eaddr:eaddr -> t
val sarb_eb_1 : eaddr:eaddr -> t
val sarb_eb_cl : eaddr:eaddr -> t
val rolb_ev_1ow : eaddr:eaddr -> t
val rolb_ev_1od : eaddr:eaddr -> t
val rolb_ev_clow : eaddr:eaddr -> t
val rolb_ev_clod : eaddr:eaddr -> t
val rorb_ev_1ow : eaddr:eaddr -> t
val rorb_ev_1od : eaddr:eaddr -> t
val rorb_ev_clow : eaddr:eaddr -> t
val rorb_ev_clod : eaddr:eaddr -> t
val rclb_ev_1ow : eaddr:eaddr -> t
val rclb_ev_1od : eaddr:eaddr -> t
val rclb_ev_clow : eaddr:eaddr -> t
val rclb_ev_clod : eaddr:eaddr -> t
val rcrb_ev_1ow : eaddr:eaddr -> t
val rcrb_ev_1od : eaddr:eaddr -> t
val rcrb_ev_clow : eaddr:eaddr -> t
val rcrb_ev_clod : eaddr:eaddr -> t
val shlsalb_ev_1ow : eaddr:eaddr -> t
val shlsalb_ev_1od : eaddr:eaddr -> t
val shlsalb_ev_clow : eaddr:eaddr -> t
val shlsalb_ev_clod : eaddr:eaddr -> t
val shrb_ev_1ow : eaddr:eaddr -> t
val shrb_ev_1od : eaddr:eaddr -> t
val shrb_ev_clow : eaddr:eaddr -> t
val shrb_ev_clod : eaddr:eaddr -> t
val sarb_ev_1ow : eaddr:eaddr -> t
val sarb_ev_1od : eaddr:eaddr -> t
val sarb_ev_clow : eaddr:eaddr -> t
val sarb_ev_clod : eaddr:eaddr -> t
[ ~128 .. 127 ]
[ ~128 .. 127 ]
[ ~128 .. 127 ]
[ ~128 .. 127 ]
[ ~128 .. 127 ]
[ ~128 .. 127 ]
[ ~128 .. 127 ]
[ ~128 .. 127 ]
[ ~128 .. 127 ]
[ ~128 .. 127 ]
[ ~128 .. 127 ]
[ ~128 .. 127 ]
[ ~128 .. 127 ]
[ ~128 .. 127 ]
[ ~128 .. 127 ]
[ ~128 .. 127 ]
[ ~128 .. 127 ]
[ ~128 .. 127 ]
[ ~128 .. 127 ]
[ ~128 .. 127 ]
[ ~128 .. 127 ]
val rdmsr : unit -> t
val rep : unit -> t
val repne : unit -> t
val ret : unit -> t
val ret_far : unit -> t
[ 0 .. 65535 ]
[ 0 .. 65535 ]
val rsm : unit -> t
val sahf : unit -> t
val scasb : unit -> t
val scasvow : unit -> t
val scasvod : unit -> t
val setb_o : eaddr:eaddr -> t
val setb_no : eaddr:eaddr -> t
val setb_b : eaddr:eaddr -> t
val setb_nb : eaddr:eaddr -> t
val setb_z : eaddr:eaddr -> t
val setb_nz : eaddr:eaddr -> t
val setb_be : eaddr:eaddr -> t
val setb_nbe : eaddr:eaddr -> t
val setb_s : eaddr:eaddr -> t
val setb_ns : eaddr:eaddr -> t
val setb_p : eaddr:eaddr -> t
val setb_np : eaddr:eaddr -> t
val setb_l : eaddr:eaddr -> t
val setb_nl : eaddr:eaddr -> t
val setb_le : eaddr:eaddr -> t
val setb_nle : eaddr:eaddr -> t
val sgdt : mem:mem -> t
val sidt : mem:mem -> t
val shrd_ibow : eaddr:eaddr -> reg:nativeint -> count:nativeint -> t
val shrd_ibod : eaddr:eaddr -> reg:nativeint -> count:nativeint -> t
val shld_ibow : eaddr:eaddr -> reg:nativeint -> count:nativeint -> t
val shld_ibod : eaddr:eaddr -> reg:nativeint -> count:nativeint -> t
val shrd_clow : eaddr:eaddr -> reg:nativeint -> t
val shrd_clod : eaddr:eaddr -> reg:nativeint -> t
val shld_clow : eaddr:eaddr -> reg:nativeint -> t
val shld_clod : eaddr:eaddr -> reg:nativeint -> t
val sldt : eaddr:eaddr -> t
val smsw : eaddr:eaddr -> t
val stc : unit -> t
val std : unit -> t
val sti : unit -> t
val stosb : unit -> t
val stosvow : unit -> t
val stosvod : unit -> t
val str : mem:mem -> t
[ 0 .. 255 ]
[ 0 .. 65535 ]
val test_eax_ivod : i32:nativeint -> t
[ 0 .. 255 ]
[ 0 .. 65535 ]
val test_ed_id : eaddr:eaddr -> i32:nativeint -> t
val test_eb_gb : eaddr:eaddr -> reg:nativeint -> t
val test_ev_gvow : eaddr:eaddr -> reg:nativeint -> t
val test_ev_gvod : eaddr:eaddr -> reg:nativeint -> t
val verr : eaddr:eaddr -> t
val verw : eaddr:eaddr -> t
val wait : unit -> t
val wbinvd : unit -> t
val wrmsr : unit -> t
val xadd_eb_gb : eaddr:eaddr -> reg:nativeint -> t
val xadd_ev_gvow : eaddr:eaddr -> reg:nativeint -> t
val xadd_ev_gvod : eaddr:eaddr -> reg:nativeint -> t
[ 0 .. 7 ]
[ 0 .. 7 ]
val xchg_eb_gb : eaddr:eaddr -> reg:nativeint -> t
val xchg_ev_gvow : eaddr:eaddr -> reg:nativeint -> t
val xchg_ev_gvod : eaddr:eaddr -> reg:nativeint -> t
val xlatb : unit -> t
val fclex : unit -> t
val fsave : mem:mem -> t
val fnstcw : mem:mem -> t
val fnstenv : mem:mem -> t
val fnstsw : mem:mem -> t
val fnstsw_ax : unit -> t
val fwait : unit -> t
end
module type Maker =
functor (Reloc : Sledlib.RELOCATABLE) -> S with module Reloc = Reloc
| |
60ad84fd0a34e9ea6e4e4e57459de3c0fe444812d5a9ea47ce89aebaab8e2ea2 | mirage/ocaml-qcow | qcow_metadata.mli |
* Copyright ( C ) 2017 Docker Inc
*
* Permission to use , copy , modify , and distribute this software for any
* purpose with or without fee is hereby granted , provided that the above
* copyright notice and this permission notice appear in all copies .
*
* THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
* ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE .
*
* Copyright (C) 2017 Docker Inc
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*)
open Qcow_types
type t
* metadata : clusters containing references and clusters containing
reference counts .
reference counts. *)
type error = [ Mirage_block.error | `Msg of string ]
type write_error = [ Mirage_block.write_error | `Msg of string ]
val make:
cache:Qcow_cache.t
-> cluster_bits:int
-> locks:Qcow_locks.t
-> unit -> t
(** Construct a qcow metadata structure given a set of cluster read/write/flush
operations *)
val set_cluster_map: t -> Qcow_cluster_map.t -> unit
(** Set the associated cluster map (which will be updated on every cluster
write) *)
type contents
module Refcounts: sig
type t
* A cluster full of 16bit refcounts
val of_contents: contents -> t
(** Interpret the given cluster as a refcount cluster *)
val get: t -> int -> int
(** [get t n] return the [n]th refcount within [t] *)
val set: t -> int -> int -> unit
(** [set t n v] set the [n]th refcount within [t] to [v] *)
end
module Physical: sig
type t
* A cluster full of 64 bit cluster pointers
val of_contents: contents -> t
* Interpret the given cluster as a cluster of 64 bit pointers
val get: t -> int -> Qcow_physical.t
(** [get t n] return the [n]th physical address within [t] *)
val set: t -> int -> Qcow_physical.t -> unit
(** [set t n v] set the [n]th physical address within [t] to [v] *)
val len: t -> int
(** [len t] returns the number of physical addresses within [t] *)
end
val erase: contents -> unit
(** Set the cluster contents to zeroes *)
val read_and_lock: ?client:Qcow_locks.Client.t -> t -> Cluster.t -> (contents * Qcow_locks.lock, error) result Lwt.t
val read: ?client:Qcow_locks.Client.t -> t -> Cluster.t -> (contents -> ('a, error) result Lwt.t) -> ('a, error) result Lwt.t
(** Read the contents of the given cluster and provide them to the given function *)
val update: ?client:Qcow_locks.Client.t -> t -> Cluster.t -> (contents -> ('a, write_error) result Lwt.t) -> ('a, write_error) result Lwt.t
(** Read the contents of the given cluster, transform them through the given
function and write the results back to disk *)
| null | https://raw.githubusercontent.com/mirage/ocaml-qcow/2418c66627dcce8420bcb06d7547db171528060a/lib/qcow_metadata.mli | ocaml | * Construct a qcow metadata structure given a set of cluster read/write/flush
operations
* Set the associated cluster map (which will be updated on every cluster
write)
* Interpret the given cluster as a refcount cluster
* [get t n] return the [n]th refcount within [t]
* [set t n v] set the [n]th refcount within [t] to [v]
* [get t n] return the [n]th physical address within [t]
* [set t n v] set the [n]th physical address within [t] to [v]
* [len t] returns the number of physical addresses within [t]
* Set the cluster contents to zeroes
* Read the contents of the given cluster and provide them to the given function
* Read the contents of the given cluster, transform them through the given
function and write the results back to disk |
* Copyright ( C ) 2017 Docker Inc
*
* Permission to use , copy , modify , and distribute this software for any
* purpose with or without fee is hereby granted , provided that the above
* copyright notice and this permission notice appear in all copies .
*
* THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
* ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE .
*
* Copyright (C) 2017 Docker Inc
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*)
open Qcow_types
type t
* metadata : clusters containing references and clusters containing
reference counts .
reference counts. *)
type error = [ Mirage_block.error | `Msg of string ]
type write_error = [ Mirage_block.write_error | `Msg of string ]
val make:
cache:Qcow_cache.t
-> cluster_bits:int
-> locks:Qcow_locks.t
-> unit -> t
val set_cluster_map: t -> Qcow_cluster_map.t -> unit
type contents
module Refcounts: sig
type t
* A cluster full of 16bit refcounts
val of_contents: contents -> t
val get: t -> int -> int
val set: t -> int -> int -> unit
end
module Physical: sig
type t
* A cluster full of 64 bit cluster pointers
val of_contents: contents -> t
* Interpret the given cluster as a cluster of 64 bit pointers
val get: t -> int -> Qcow_physical.t
val set: t -> int -> Qcow_physical.t -> unit
val len: t -> int
end
val erase: contents -> unit
val read_and_lock: ?client:Qcow_locks.Client.t -> t -> Cluster.t -> (contents * Qcow_locks.lock, error) result Lwt.t
val read: ?client:Qcow_locks.Client.t -> t -> Cluster.t -> (contents -> ('a, error) result Lwt.t) -> ('a, error) result Lwt.t
val update: ?client:Qcow_locks.Client.t -> t -> Cluster.t -> (contents -> ('a, write_error) result Lwt.t) -> ('a, write_error) result Lwt.t
|
2997d44aafc133c758765425e7c7788e1faba498f5f571d1e65bb3fdcc804679 | dongcarl/guix | node.scm | ;;; GNU Guix --- Functional package management for GNU
Copyright © 2016 < >
Copyright © 2019 < >
;;;
;;; This file is part of GNU Guix.
;;;
GNU is free software ; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation ; either version 3 of the License , or ( at
;;; your option) any later version.
;;;
;;; GNU Guix is distributed in the hope that it will be useful, but
;;; WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;; GNU General Public License for more details.
;;;
You should have received a copy of the GNU General Public License
along with GNU . If not , see < / > .
(define-module (guix build-system node)
#:use-module (guix utils)
#:use-module (guix packages)
#:use-module (guix derivations)
#:use-module (guix search-paths)
#:use-module (guix build-system)
#:use-module (guix build-system gnu)
#:use-module (ice-9 match)
#:export (%node-build-system-modules
node-build
node-build-system))
(define %node-build-system-modules
;; Build-side modules imported by default.
`((guix build node-build-system)
(guix build json)
,@%gnu-build-system-modules))
(define (default-node)
"Return the default Node package."
;; Lazily resolve the binding to avoid a circular dependency.
(let ((node (resolve-interface '(gnu packages node))))
(module-ref node 'node-lts)))
(define* (lower name
#:key source inputs native-inputs outputs system target
(node (default-node))
#:allow-other-keys
#:rest arguments)
"Return a bag for NAME."
(define private-keywords
'(#:source #:target #:node #:inputs #:native-inputs))
(and (not target) ;XXX: no cross-compilation
(bag
(name name)
(system system)
(host-inputs `(,@(if source
`(("source" ,source))
'())
,@inputs
;; Keep the standard inputs of 'gnu-build-system'.
,@(standard-packages)))
(build-inputs `(("node" ,node)
,@native-inputs))
(outputs outputs)
(build node-build)
(arguments (strip-keyword-arguments private-keywords arguments)))))
(define* (node-build store name inputs
#:key
(test-target "test")
(tests? #t)
(phases '(@ (guix build node-build-system)
%standard-phases))
(outputs '("out"))
(search-paths '())
(system (%current-system))
(guile #f)
(imported-modules %node-build-system-modules)
(modules '((guix build node-build-system)
(guix build utils))))
"Build SOURCE using NODE and INPUTS."
(define builder
`(begin
(use-modules ,@modules)
(node-build #:name ,name
#:source ,(match (assoc-ref inputs "source")
(((? derivation? source))
(derivation->output-path source))
((source) source)
(source source))
#:system ,system
#:test-target ,test-target
#:tests? ,tests?
#:phases ,phases
#:outputs %outputs
#:search-paths ',(map search-path-specification->sexp
search-paths)
#:inputs %build-inputs)))
(define guile-for-build
(match guile
((? package?)
(package-derivation store guile system #:graft? #f))
(#f
(let* ((distro (resolve-interface '(gnu packages commencement)))
(guile (module-ref distro 'guile-final)))
(package-derivation store guile system #:graft? #f)))))
(build-expression->derivation store name builder
#:inputs inputs
#:system system
#:modules imported-modules
#:outputs outputs
#:guile-for-build guile-for-build))
(define node-build-system
(build-system
(name 'node)
(description "The Node build system")
(lower lower)))
| null | https://raw.githubusercontent.com/dongcarl/guix/82543e9649da2da9a5285ede4ec4f718fd740fcb/guix/build-system/node.scm | scheme | GNU Guix --- Functional package management for GNU
This file is part of GNU Guix.
you can redistribute it and/or modify it
either version 3 of the License , or ( at
your option) any later version.
GNU Guix is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
Build-side modules imported by default.
Lazily resolve the binding to avoid a circular dependency.
XXX: no cross-compilation
Keep the standard inputs of 'gnu-build-system'. | Copyright © 2016 < >
Copyright © 2019 < >
under the terms of the GNU General Public License as published by
You should have received a copy of the GNU General Public License
along with GNU . If not , see < / > .
(define-module (guix build-system node)
#:use-module (guix utils)
#:use-module (guix packages)
#:use-module (guix derivations)
#:use-module (guix search-paths)
#:use-module (guix build-system)
#:use-module (guix build-system gnu)
#:use-module (ice-9 match)
#:export (%node-build-system-modules
node-build
node-build-system))
(define %node-build-system-modules
`((guix build node-build-system)
(guix build json)
,@%gnu-build-system-modules))
(define (default-node)
"Return the default Node package."
(let ((node (resolve-interface '(gnu packages node))))
(module-ref node 'node-lts)))
(define* (lower name
#:key source inputs native-inputs outputs system target
(node (default-node))
#:allow-other-keys
#:rest arguments)
"Return a bag for NAME."
(define private-keywords
'(#:source #:target #:node #:inputs #:native-inputs))
(bag
(name name)
(system system)
(host-inputs `(,@(if source
`(("source" ,source))
'())
,@inputs
,@(standard-packages)))
(build-inputs `(("node" ,node)
,@native-inputs))
(outputs outputs)
(build node-build)
(arguments (strip-keyword-arguments private-keywords arguments)))))
(define* (node-build store name inputs
#:key
(test-target "test")
(tests? #t)
(phases '(@ (guix build node-build-system)
%standard-phases))
(outputs '("out"))
(search-paths '())
(system (%current-system))
(guile #f)
(imported-modules %node-build-system-modules)
(modules '((guix build node-build-system)
(guix build utils))))
"Build SOURCE using NODE and INPUTS."
(define builder
`(begin
(use-modules ,@modules)
(node-build #:name ,name
#:source ,(match (assoc-ref inputs "source")
(((? derivation? source))
(derivation->output-path source))
((source) source)
(source source))
#:system ,system
#:test-target ,test-target
#:tests? ,tests?
#:phases ,phases
#:outputs %outputs
#:search-paths ',(map search-path-specification->sexp
search-paths)
#:inputs %build-inputs)))
(define guile-for-build
(match guile
((? package?)
(package-derivation store guile system #:graft? #f))
(#f
(let* ((distro (resolve-interface '(gnu packages commencement)))
(guile (module-ref distro 'guile-final)))
(package-derivation store guile system #:graft? #f)))))
(build-expression->derivation store name builder
#:inputs inputs
#:system system
#:modules imported-modules
#:outputs outputs
#:guile-for-build guile-for-build))
(define node-build-system
(build-system
(name 'node)
(description "The Node build system")
(lower lower)))
|
2c9a75545c15fae4ac409913f19bd31e40dd7a520bc8c3fa3a8cbf96cf37b8b8 | CLowcay/hgbc | CPU.hs | # LANGUAGE FlexibleInstances #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE RecordWildCards #
# LANGUAGE TypeFamilies #
module Machine.GBC.CPU
( RegisterFile (..),
Mode (..),
State (..),
Has (..),
M (..),
init,
ports,
getMode,
setMode,
getCycleClocks,
setCycleClocks,
getCallDepth,
getBacktrace,
reset,
getRegisterFile,
readR8,
writeR8,
readR16,
readR16pp,
writeR16,
writeR16pp,
readPC,
writePC,
readF,
writeF,
testFlag,
setFlags,
setFlagsMask,
setIME,
clearIME,
testIME,
flagCY,
flagN,
flagH,
flagZ,
flagIME,
flagDoubleSpeed,
testCondition,
step,
)
where
import Control.Exception (throwIO)
import Control.Monad.Reader (MonadIO (..), ReaderT (ReaderT), asks, replicateM_, when)
import Data.Bits (Bits (..))
import Data.Foldable (for_)
import Data.IORef (IORef, newIORef, readIORef, writeIORef)
import Data.Int (Int32, Int8)
import qualified Data.Vector.Storable.Mutable as VSM
import Data.Word (Word16, Word32, Word8)
import Foreign.Ptr (castPtr)
import Foreign.Storable (Storable (..))
import qualified Machine.GBC.Bus as Bus
import qualified Machine.GBC.CPU.Backtrace as Backtrace
import Machine.GBC.CPU.Decode (MonadFetch (..), decodeAndExecute)
import Machine.GBC.CPU.ISA (ConditionCode (..), MonadSm83x (..), Register16 (..), Register8 (..), RegisterHalf (..), RegisterPushPop (..))
import Machine.GBC.CPU.Interrupts (Interrupt)
import qualified Machine.GBC.CPU.Interrupts as Interrupt
import Machine.GBC.Errors (Fault (InvalidInstruction))
import qualified Machine.GBC.Memory as Memory
import Machine.GBC.Mode (EmulatorMode (DMG))
import Machine.GBC.Primitive.Port (Port)
import qualified Machine.GBC.Primitive.Port as Port
import Machine.GBC.Primitive.UnboxedRef (UnboxedRef, newUnboxedRef, readUnboxedRef, writeUnboxedRef)
import qualified Machine.GBC.Registers as R
import Machine.GBC.Util (isFlagSet, (.<<.), (.>>.))
import Prelude hiding (init)
-- | The register file.
data RegisterFile = RegisterFile
{ regF :: !Word8,
regA :: !Word8,
regC :: !Word8,
regB :: !Word8,
regE :: !Word8,
regD :: !Word8,
regL :: !Word8,
regH :: !Word8,
regSP :: !Word16,
regPC :: !Word16,
regHidden :: !Word16
}
deriving (Eq, Ord, Show)
offsetF, offsetA, offsetC, offsetB :: Int
offsetF = 0
offsetA = 1
offsetC = 2
offsetB = 3
offsetE, offsetD, offsetL, offsetH :: Int
offsetE = 4
offsetD = 5
offsetL = 6
offsetH = 7
offsetAF, offsetBC, offsetDE, offsetHL :: Int
offsetAF = 0
offsetBC = 1
offsetDE = 2
offsetHL = 3
offsetPC, offsetSP, offsetHidden :: Int
offsetSP = 4
offsetPC = 5
offsetHidden = 6
instance Storable RegisterFile where
sizeOf _ = 14
alignment _ = 2
peek ptr = do
regA <- peekElemOff (castPtr ptr) offsetA
regB <- peekElemOff (castPtr ptr) offsetB
regC <- peekElemOff (castPtr ptr) offsetC
regD <- peekElemOff (castPtr ptr) offsetD
regE <- peekElemOff (castPtr ptr) offsetE
regF <- peekElemOff (castPtr ptr) offsetF
regH <- peekElemOff (castPtr ptr) offsetH
regL <- peekElemOff (castPtr ptr) offsetL
regSP <- peekElemOff (castPtr ptr) offsetSP
regPC <- peekElemOff (castPtr ptr) offsetPC
regHidden <- peekElemOff (castPtr ptr) offsetHidden
pure RegisterFile {..}
poke ptr RegisterFile {..} = do
pokeElemOff (castPtr ptr) offsetA regA
pokeElemOff (castPtr ptr) offsetB regB
pokeElemOff (castPtr ptr) offsetC regC
pokeElemOff (castPtr ptr) offsetD regD
pokeElemOff (castPtr ptr) offsetE regE
pokeElemOff (castPtr ptr) offsetF regF
pokeElemOff (castPtr ptr) offsetH regH
pokeElemOff (castPtr ptr) offsetL regL
pokeElemOff (castPtr ptr) offsetSP regSP
pokeElemOff (castPtr ptr) offsetPC regPC
pokeElemOff (castPtr ptr) offsetHidden regHidden
-- | The current CPU mode.
data Mode = ModeHalt | ModeStop | ModeNormal deriving (Eq, Ord, Show, Bounded, Enum)
-- | The internal CPU state.
data State = State
{ cpuType :: !EmulatorMode,
registers :: !(VSM.IOVector RegisterFile),
portIF :: !Port,
portIE :: !Port,
portKEY1 :: !Port,
cpuMode :: !(IORef Mode),
cycleClocks :: !(UnboxedRef Int),
callDepth :: !(UnboxedRef Int),
backtrace :: !Backtrace.Backtrace,
haltBug :: !(IORef Bool) -- True to trigger the halt bug
}
class Memory.Has env => Has env where
forState :: env -> State
-- | Initialize a new CPU.
init :: Port -> Port -> IORef EmulatorMode -> IO State
init portIF portIE modeRef = do
cpuType <- readIORef modeRef
registers <- VSM.new 1
portKEY1 <-
Port.newWithReadAction
0x7E
0x01
( \key1 -> do
mode <- readIORef modeRef
if mode == DMG then pure 0xFF else pure key1
)
Port.alwaysUpdate
cpuMode <- newIORef ModeNormal
cycleClocks <- newUnboxedRef 4
callDepth <- newUnboxedRef 0
backtrace <- Backtrace.new 8
haltBug <- newIORef False
pure State {..}
ports :: State -> [(Word16, Port)]
ports State {..} = [(R.KEY1, portKEY1)]
-- | Get the current cpu mode.
# INLINEABLE getMode #
getMode :: Has env => ReaderT env IO Mode
getMode = do
State {..} <- asks forState
liftIO $ readIORef cpuMode
-- | Get the CPU mode.
# INLINEABLE setMode #
setMode :: Has env => Mode -> ReaderT env IO ()
setMode mode = do
State {..} <- asks forState
liftIO $ writeIORef cpuMode mode
-- | Get the values of all the registers.
# INLINEABLE getRegisterFile #
getRegisterFile :: Has env => ReaderT env IO RegisterFile
getRegisterFile = do
State {..} <- asks forState
liftIO $ VSM.unsafeRead registers 0
-- | Read data from the register file.
# INLINE readRegister #
readRegister :: (Has env, Storable a) => Int -> ReaderT env IO a
readRegister offset = do
State {..} <- asks forState
liftIO $ VSM.unsafeRead (VSM.unsafeCast registers) offset
-- | Write data to the register file.
# INLINE writeRegister #
writeRegister :: (Has env, Storable a) => Int -> a -> ReaderT env IO ()
writeRegister offset value = do
State {..} <- asks forState
liftIO $ VSM.unsafeWrite (VSM.unsafeCast registers) offset value
-- | Read a single register.
# INLINEABLE readR8 #
readR8 :: Has env => Register8 -> ReaderT env IO Word8
readR8 = readRegister . offsetR8
-- | Write a single register.
# INLINEABLE writeR8 #
writeR8 :: Has env => Register8 -> Word8 -> ReaderT env IO ()
writeR8 register = writeRegister $ offsetR8 register
-- | Get the offset in the register file of a single register.
offsetR8 :: Register8 -> Int
offsetR8 RegA = offsetA
offsetR8 RegB = offsetB
offsetR8 RegC = offsetC
offsetR8 RegD = offsetD
offsetR8 RegE = offsetE
offsetR8 RegH = offsetH
offsetR8 RegL = offsetL
| Read a 16 - bit register .
# INLINEABLE readR16 #
readR16 :: Has env => Register16 -> ReaderT env IO Word16
readR16 = readRegister . offsetR16
| Write a 16 - bit register .
# INLINEABLE writeR16 #
writeR16 :: Has env => Register16 -> Word16 -> ReaderT env IO ()
writeR16 register = writeRegister $ offsetR16 register
-- | Get the offset in the register file of a register pair.
offsetR16 :: Register16 -> Int
offsetR16 RegBC = offsetBC
offsetR16 RegDE = offsetDE
offsetR16 RegHL = offsetHL
offsetR16 RegSP = offsetSP
| Read a 16 - bit register .
{-# INLINEABLE readR16pp #-}
readR16pp :: Has env => RegisterPushPop -> ReaderT env IO Word16
readR16pp register = readRegister (offsetR16pp register)
| Write a 16 - bit register .
# INLINEABLE writeR16pp #
writeR16pp :: Has env => RegisterPushPop -> Word16 -> ReaderT env IO ()
writeR16pp PushPopAF v = writeRegister offsetF (v .&. 0xFFF0)
writeR16pp register v = writeRegister (offsetR16pp register) v
-- | Get the offset in the register file of a register pair.
offsetR16pp :: RegisterPushPop -> Int
offsetR16pp PushPopBC = offsetBC
offsetR16pp PushPopDE = offsetDE
offsetR16pp PushPopHL = offsetHL
offsetR16pp PushPopAF = offsetAF
# INLINEABLE readRHalf #
readRHalf :: Has env => RegisterHalf -> ReaderT env IO Word8
readRHalf RegSPL = readRegister (2 * offsetSP)
readRHalf RegSPH = readRegister (2 * offsetSP + 1)
readRHalf RegPCL = readRegister (2 * offsetPC)
readRHalf RegPCH = readRegister (2 * offsetPC + 1)
-- | Read the PC register.
# INLINEABLE readPC #
readPC :: Has env => ReaderT env IO Word16
readPC = readRegister offsetPC
-- | Write the PC register.
{-# INLINEABLE writePC #-}
writePC :: Has env => Word16 -> ReaderT env IO ()
writePC = writeRegister offsetPC
type Flag = Word8
flagZ, flagN, flagH, flagCY :: Flag
flagZ = 0x80
flagN = 0x40
flagH = 0x20
flagCY = 0x10
allExceptCY :: Word8
allExceptCY = flagZ .|. flagN .|. flagH
allExceptZ :: Word8
allExceptZ = flagH .|. flagN .|. flagCY
allExceptN :: Word8
allExceptN = flagH .|. flagCY .|. flagZ
-- Master interrupt enable flag
# INLINEABLE flagIME #
flagIME :: Word16
flagIME = 0x0100
# INLINEABLE flagSetIME #
flagSetIME :: Word16
flagSetIME = 0x0200
-- | Check if a flag is set.
# INLINE testFlag #
testFlag :: Has env => Flag -> ReaderT env IO Bool
testFlag flag = do
f <- readRegister offsetF
pure (f .&. flag /= 0)
-- | Check if a condition code is true.
# INLINE testCondition #
testCondition :: Has env => ConditionCode -> ReaderT env IO Bool
testCondition CondNZ = not <$> testFlag flagZ
testCondition CondZ = testFlag flagZ
testCondition CondNC = not <$> testFlag flagCY
testCondition CondC = testFlag flagCY
-- | Read the F register.
# INLINE readF #
readF :: Has env => ReaderT env IO Word8
readF = readRegister offsetF
-- | Write the F register.
# INLINE writeF #
writeF :: Has env => Word8 -> ReaderT env IO ()
writeF = writeRegister offsetF
-- | Set all the flags.
# INLINE setFlags #
setFlags :: Has env => Word8 -> ReaderT env IO ()
setFlags = writeF
-- | Set some flags.
# INLINE setFlagsMask #
setFlagsMask ::
Has env =>
-- | bitmask containing flags to set.
Word8 ->
-- | new flags values.
Word8 ->
ReaderT env IO ()
setFlagsMask mask flags = do
oldFlags <- readF
writeF ((oldFlags .&. complement mask) .|. (flags .&. mask))
-- | Set the master interrupt flag.
# INLINE setIME #
setIME :: Has env => ReaderT env IO ()
setIME = do
ime <- readRegister offsetHidden
writeRegister offsetHidden (ime .|. flagIME)
-- | Clear the master interrupt flag.
# INLINE clearIME #
clearIME :: Has env => ReaderT env IO ()
clearIME = do
ime <- readRegister offsetHidden
writeRegister offsetHidden (ime .&. complement (flagIME .|. flagSetIME))
# INLINE setIMENext #
setIMENext :: Has env => ReaderT env IO ()
setIMENext = do
ime <- readRegister offsetHidden
writeRegister offsetHidden (ime .|. flagSetIME)
# INLINE updateIME #
updateIME :: Has env => ReaderT env IO ()
updateIME = do
ime <- readRegister offsetHidden
when (ime .&. flagSetIME /= 0) $
writeRegister offsetHidden ((ime .|. flagIME) .&. complement flagSetIME)
-- | Check the status of the interrupt flag.
# INLINE testIME #
testIME :: Has env => ReaderT env IO Bool
testIME = do
ime <- readRegister offsetHidden
pure (ime .&. flagIME /= 0)
-- | Reset the CPU.
# INLINEABLE reset #
reset :: (Has env, Bus.Has env) => ReaderT env IO ()
reset = do
State {..} <- asks forState
writeR8 RegA 0
writeF 0
writeR8 RegB 0
writeR8 RegC 0
writeR8 RegD 0
writeR8 RegE 0
writeR8 RegH 0
writeR8 RegL 0
writeR16 RegSP 0
writeRegister offsetHidden (0 :: Word8)
setIME
writePC 0
Port.writeDirect portKEY1 0x7E
liftIO $ writeIORef cpuMode ModeNormal
liftIO $ writeIORef haltBug False
writeUnboxedRef cycleClocks 4
writeUnboxedRef callDepth 0
Backtrace.reset backtrace
Memory.writeByte R.P1 0xFF
Memory.writeByte R.DIV 0
Memory.writeByte R.SC 0
Memory.writeByte R.SB 0
Memory.writeByte R.TIMA 0
Memory.writeByte R.TMA 0
Memory.writeByte R.TAC 0
Memory.writeByte R.NR10 0
Memory.writeByte R.NR11 0
Memory.writeByte R.NR12 0
Memory.writeByte R.NR13 0
Memory.writeByte R.NR14 0
Memory.writeByte R.NR21 0
Memory.writeByte R.NR22 0
Memory.writeByte R.NR23 0
Memory.writeByte R.NR24 0
Memory.writeByte R.NR30 0
Memory.writeByte R.NR31 0
Memory.writeByte R.NR32 0
Memory.writeByte R.NR33 0
Memory.writeByte R.NR34 0
Memory.writeByte R.NR41 0
Memory.writeByte R.NR42 0
Memory.writeByte R.NR43 0
Memory.writeByte R.NR44 0
Memory.writeByte R.NR50 0
Memory.writeByte R.NR51 0
Memory.writeByte R.NR52 0
Memory.writeByte R.LCDC 0
Memory.writeByte R.SCY 0
Memory.writeByte R.SCX 0
Memory.writeByte R.LYC 0
Memory.writeByte R.BGP 0
Memory.writeByte R.OBP0 0
Memory.writeByte R.OBP1 0
Memory.writeByte R.WY 0
Memory.writeByte R.WX 0
Memory.writeByte R.IE 0
Memory.writeByte R.IF 0
-- Wave memory
Memory.writeByte 0xFF30 0x00
Memory.writeByte 0xFF31 0xFF
Memory.writeByte 0xFF32 0x00
Memory.writeByte 0xFF33 0xFF
Memory.writeByte 0xFF34 0x00
Memory.writeByte 0xFF35 0xFF
Memory.writeByte 0xFF36 0x00
Memory.writeByte 0xFF37 0xFF
Memory.writeByte 0xFF38 0x00
Memory.writeByte 0xFF39 0xFF
Memory.writeByte 0xFF3A 0x00
Memory.writeByte 0xFF3B 0xFF
Memory.writeByte 0xFF3C 0x00
Memory.writeByte 0xFF3D 0xFF
Memory.writeByte 0xFF3E 0x00
Memory.writeByte 0xFF3F 0xFF
Memory.resetAndBoot $ do
-- Set all registers and ports to their post-boot values.
writeR8 RegA 0x11
writeF 0x80
writeR8 RegB 0x00
writeR8 RegC 0x00
writeR8 RegD 0x00
writeR8 RegE 0x08
writeR8 RegH 0x00
writeR8 RegL 0x7C
writeR16 RegSP 0xFFFE
writeRegister offsetHidden (0 :: Word16)
setIME
writePC 0x100
Memory.writeByte R.NR52 0xF1
Memory.writeByte R.NR11 0xBF
Memory.writeByte R.NR12 0x11
Memory.writeByte R.NR50 0x77
Memory.writeByte R.NR51 0xF3
Memory.writeByte R.NR14 0x80
Memory.writeByte R.NR12 0xF3
Memory.writeByte R.LCDC 0x91
Memory.writeByte R.BGP 0xFC
Memory.writeByte R.OBP0 0xFF
Memory.writeByte R.OBP1 0xFF
Memory.writeByte R.BCPS 0x88
Memory.writeByte R.OCPS 0x90
Memory.writeByte R.IF 0xE1
for_ ([0xFF80 ..] `zip` atFF80) (uncurry Memory.writeByte)
replicateM_ 2462 Bus.delay
where
-- Values that would be written by the boot ROM if we had one.
atFF80 =
[0xCE, 0xED, 0x66, 0x66, 0xCC, 0x0D, 0x00, 0x0B]
++ [0x03, 0x73, 0x00, 0x83, 0x00, 0x0C, 0x00, 0x0D]
++ [0x00, 0x08, 0x11, 0x1F, 0x88, 0x89, 0x00, 0x0E]
++ [0xDC, 0xCC, 0x6E, 0xE6, 0xDD, 0xDD, 0xD9, 0x99]
++ [0xBB, 0xBB, 0x67, 0x63, 0x6E, 0x0E, 0xEC, 0xCC]
++ [0xDD, 0xDC, 0x99, 0x9F, 0xBB, 0xB9, 0x33, 0x3E]
type Operator = Word16 -> Word16 -> Word16
-- | Perform an arithmetic operation and adjust the flags.
# INLINE adder8 #
adder8 :: Word8 -> Operator -> Word8 -> Word16 -> (Word8, Word8)
adder8 a1 op a2 carry =
let wa1 = fromIntegral a1
wa2 = fromIntegral a2
wr = (wa1 `op` wa2 `op` carry) .&. 0x01FF
r = fromIntegral wr
carryH = ((wa1 .&. 0x0F) `op` (wa2 .&. 0x0F) `op` carry) >= 0x10
flags =
(if r == 0 then flagZ else 0)
.|. (if carryH then flagH else 0)
.|. (if wr >= 0x0100 then flagCY else 0)
in (r, flags)
getCarry :: Has env => ReaderT env IO Word16
getCarry = do
f <- readF
pure ((fromIntegral f .>>. 4) .&. 1)
-- | Perform an increment operation and adjust the flags.
# INLINE inc8 #
inc8 :: Word8 -> Word8 -> (Word8, Word8)
inc8 value x =
let r = value + x
carryH = (value .&. 0x10) /= (r .&. 0x010)
flags = (if r == 0 then flagZ else 0) .|. (if carryH then flagH else 0)
in (r, flags)
flagDoubleSpeed :: Word8
flagDoubleSpeed = 0x80
flagSpeedSwitch :: Word8
flagSpeedSwitch = 0x01
interruptVector :: Interrupt -> Word16
interruptVector Interrupt.VBlank = 0x40
interruptVector Interrupt.LCDCStat = 0x48
interruptVector Interrupt.TimerOverflow = 0x50
interruptVector Interrupt.EndSerialTransfer = 0x58
interruptVector Interrupt.P1Low = 0x60
interruptVector Interrupt.Cancelled = 0
-- | Fetch, decode, and execute a single instruction.
# INLINEABLE step #
step :: (Has env, Bus.Has env) => ReaderT env IO ()
step = do
State {..} <- asks forState
ime <- testIME
updateIME
-- Deal with HALT mode
mode <- liftIO (readIORef cpuMode)
case mode of
ModeNormal -> do
pc <- readPC
byte <- Bus.read pc
interrupts <- Interrupt.getPending portIF portIE
if interrupts /= 0 && ime
then handleInterrupt interrupts
else do
writePC (pc + 1)
run (decodeAndExecute byte)
ModeHalt -> do
interrupts <- Interrupt.getPending portIF portIE
if interrupts == 0
then Bus.delay
else do
liftIO (writeIORef cpuMode ModeNormal)
if ime
then Bus.delay >> handleInterrupt interrupts
else do
doHaltBug <- liftIO (readIORef haltBug)
if doHaltBug
then do
liftIO (writeIORef haltBug False)
-- Fetch the next byte but don't increment PC
run . decodeAndExecute =<< Bus.read =<< readPC
else run (decodeAndExecute =<< nextByte)
ModeStop -> do
interrupts <- Interrupt.getPending portIF portIE
if interrupts == 0
then Bus.delay
else do
liftIO (writeIORef cpuMode ModeNormal)
if ime
then Bus.delay >> handleInterrupt interrupts
else run (decodeAndExecute =<< nextByte)
where
handleInterrupt interrupts = do
State {..} <- asks forState
Bus.delay
Bus.delay
sp <- readR16 RegSP
writeR16 RegSP (sp - 2)
Bus.write (sp - 1) =<< readRHalf RegPCH
ie <- Port.readDirect portIE
Bus.write (sp - 2) =<< readRHalf RegPCL
let nextInterrupt = Interrupt.getNext (interrupts .&. ie)
let vector = interruptVector nextInterrupt
callStackPushed vector
writePC vector
clearIME
Interrupt.clear portIF nextInterrupt
# INLINE getCycleClocks #
getCycleClocks :: Has env => ReaderT env IO Int
getCycleClocks = do
ref <- asks (cycleClocks . forState)
readUnboxedRef ref
# INLINE setCycleClocks #
setCycleClocks :: Has env => Int -> ReaderT env IO ()
setCycleClocks clocks = do
ref <- asks (cycleClocks . forState)
writeUnboxedRef ref clocks
# INLINE getCallDepth #
getCallDepth :: Has env => ReaderT env IO Int
getCallDepth = do
State {..} <- asks forState
readUnboxedRef callDepth
getBacktrace :: Has env => ReaderT env IO [(Word16, Word16)]
getBacktrace = do
State {..} <- asks forState
Backtrace.toList backtrace
# INLINE callStackPushed #
callStackPushed :: Has env => Word16 -> ReaderT env IO ()
callStackPushed offset = do
State {..} <- asks forState
bank <- Memory.getBank offset
d <- readUnboxedRef callDepth
writeUnboxedRef callDepth (d + 1)
Backtrace.push backtrace bank offset
{-# INLINE callStackPopped #-}
callStackPopped :: Has env => ReaderT env IO ()
callStackPopped = do
State {..} <- asks forState
d <- readUnboxedRef callDepth
writeUnboxedRef callDepth (d - 1)
Backtrace.pop backtrace
newtype M env a = M {run :: ReaderT env IO a}
deriving (Functor, Applicative, Monad, MonadIO)
instance (Bus.Has env, Has env) => MonadFetch (M env) where
# INLINE nextByte #
nextByte = M $ do
pc <- readPC
writePC (pc + 1)
Bus.read pc
instance (Bus.Has env, Has env) => MonadSm83x (M env) where
type ExecuteResult (M env) = ()
# INLINE ldrr #
ldrr r r' = M (writeR8 r =<< readR8 r')
# INLINE ldrn #
ldrn r n = M (writeR8 r n)
# INLINE ldrHL #
ldrHL r = M (writeR8 r =<< Bus.read =<< readR16 RegHL)
# INLINE ldHLr #
ldHLr r = M $ do
hl <- readR16 RegHL
Bus.write hl =<< readR8 r
# INLINE ldHLn #
ldHLn n = M $ do
hl <- readR16 RegHL
Bus.write hl n
# INLINE ldaBC #
ldaBC = M (writeR8 RegA =<< Bus.read =<< readR16 RegBC)
# INLINE ldaDE #
ldaDE = M (writeR8 RegA =<< Bus.read =<< readR16 RegDE)
# INLINE ldaC #
ldaC = M $ do
c <- readR8 RegC
writeR8 RegA =<< Bus.read (0xFF00 + fromIntegral c)
# INLINE ldCa #
ldCa = M $ do
c <- readR8 RegC
Bus.write (0xFF00 + fromIntegral c) =<< readR8 RegA
# INLINE ldan #
ldan n = M (writeR8 RegA =<< Bus.read (0xFF00 + fromIntegral n))
# INLINE ldna #
ldna n = M (Bus.write (0xFF00 + fromIntegral n) =<< readR8 RegA)
# INLINE ldann #
ldann nn = M (writeR8 RegA =<< Bus.read nn)
# INLINE ldnna #
ldnna nn = M (Bus.write nn =<< readR8 RegA)
# INLINE ldaHLI #
ldaHLI = M $ do
hl <- readR16 RegHL
writeR16 RegHL (hl + 1)
writeR8 RegA =<< Bus.read hl
# INLINE ldaHLD #
ldaHLD = M $ do
hl <- readR16 RegHL
writeR16 RegHL (hl - 1)
writeR8 RegA =<< Bus.read hl
# INLINE ldBCa #
ldBCa = M $ do
bc <- readR16 RegBC
Bus.write bc =<< readR8 RegA
# INLINE ldDEa #
ldDEa = M $ do
de <- readR16 RegDE
Bus.write de =<< readR8 RegA
# INLINE ldHLIa #
ldHLIa = M $ do
hl <- readR16 RegHL
writeR16 RegHL (hl + 1)
Bus.write hl =<< readR8 RegA
# INLINE ldHLDa #
ldHLDa = M $ do
hl <- readR16 RegHL
writeR16 RegHL (hl - 1)
Bus.write hl =<< readR8 RegA
# INLINE ldddnn #
ldddnn dd nn = M (writeR16 dd nn)
# INLINE ldSPHL #
ldSPHL = M $ do
writeR16 RegSP =<< readR16 RegHL
Bus.delay
# INLINE push #
push qq = M $ do
Bus.delay
push16 =<< readR16pp qq
# INLINE pop #
pop qq = M (writeR16pp qq =<< pop16)
# INLINE ldhl #
ldhl i = M $ do
sp <- fromIntegral <$> readR16 RegSP
let wi = fromIntegral i :: Int32
let wr = sp + wi
let carryH = (sp .&. 0x00000010) `xor` (wi .&. 0x00000010) /= (wr .&. 0x00000010)
let carryCY = (sp .&. 0x00000100) `xor` (wi .&. 0x00000100) /= (wr .&. 0x00000100)
writeR16 RegHL (fromIntegral wr)
setFlags ((if carryCY then flagCY else 0) .|. (if carryH then flagH else 0))
Bus.delay
# INLINE ldnnSP #
ldnnSP nn = M $ do
Bus.write nn =<< readRHalf RegSPL
Bus.write (nn + 1) =<< readRHalf RegSPH
# INLINE addr #
addr r = M $ do
v <- readR8 r
add8 v 0
# INLINE addn #
addn n = M (add8 n 0)
# INLINE addhl #
addhl = M $ do
v <- Bus.read =<< readR16 RegHL
add8 v 0
# INLINE adcr #
adcr r = M $ do
v <- readR8 r
add8 v =<< getCarry
# INLINE adcn #
adcn n = M (add8 n =<< getCarry)
# INLINE adchl #
adchl = M $ do
v <- Bus.read =<< readR16 RegHL
add8 v =<< getCarry
# INLINE subr #
subr r = M $ do
v <- readR8 r
sub8 v 0
# INLINE subn #
subn n = M (sub8 n 0)
{-# INLINE subhl #-}
subhl = M $ do
v <- Bus.read =<< readR16 RegHL
sub8 v 0
# INLINE sbcr #
sbcr r = M $ do
v <- readR8 r
carry <- getCarry
sub8 v carry
# INLINE sbcn #
sbcn n = M $ do
carry <- getCarry
sub8 n carry
# INLINE sbchl #
sbchl = M $ do
v <- Bus.read =<< readR16 RegHL
carry <- getCarry
sub8 v carry
# INLINE andr #
andr r = M (andOp8 =<< readR8 r)
# INLINE andn #
andn n = M (andOp8 n)
# INLINE andhl #
andhl = M (andOp8 =<< Bus.read =<< readR16 RegHL)
# INLINE orr #
orr r = M (orOp8 =<< readR8 r)
# INLINE orn #
orn n = M (orOp8 n)
# INLINE orhl #
orhl = M (orOp8 =<< Bus.read =<< readR16 RegHL)
# INLINE xorr #
xorr r = M (xorOp8 =<< readR8 r)
{-# INLINE xorn #-}
xorn n = M (xorOp8 n)
# INLINE xorhl #
xorhl = M (xorOp8 =<< Bus.read =<< readR16 RegHL)
# INLINE cpr #
cpr r = M $ do
a <- readR8 RegA
v <- readR8 r
let (_, flags) = adder8 a (-) v 0
setFlags (flagN .|. flags)
# INLINE cpn #
cpn n = M $ do
a <- readR8 RegA
let (_, flags) = adder8 a (-) n 0
setFlags (flagN .|. flags)
# INLINE cphl #
cphl = M $ do
a <- readR8 RegA
v <- Bus.read =<< readR16 RegHL
let (_, flags) = adder8 a (-) v 0
setFlags (flagN .|. flags)
# INLINE incr #
incr r = M $ do
v <- readR8 r
let (v', flags) = inc8 v 1
writeR8 r v'
setFlagsMask allExceptCY flags
# INLINE inchl #
inchl = M $ do
hl <- readR16 RegHL
v <- Bus.read hl
let (v', flags) = inc8 v 1
setFlagsMask allExceptCY flags
Bus.write hl v'
# INLINE decr #
decr r = M $ do
v <- readR8 r
let (v', flags) = inc8 v (negate 1)
writeR8 r v'
setFlagsMask allExceptCY (flags .|. flagN)
# INLINE dechl #
dechl = M $ do
hl <- readR16 RegHL
v <- Bus.read hl
let (v', flags) = inc8 v (negate 1)
setFlagsMask allExceptCY (flags .|. flagN)
Bus.write hl v'
# INLINE addhlss #
addhlss ss = M $ do
hl <- readR16 RegHL
v <- readR16 ss
let hl' = fromIntegral hl
let v' = fromIntegral v
let wr = hl' + v' :: Word32
let carryH = (hl' .&. 0x00001000) `xor` (v' .&. 0x00001000) /= (wr .&. 0x00001000)
let carryCY = (wr .&. 0x00010000) /= 0
writeR16 RegHL (fromIntegral wr)
setFlagsMask allExceptZ ((if carryH then flagH else 0) .|. (if carryCY then flagCY else 0))
Bus.delay
# INLINE addSP #
addSP e = M $ do
sp <- readR16 RegSP
let sp' = fromIntegral sp
let e' = fromIntegral e
let wr = e' + sp' :: Int32
let carryH = (sp' .&. 0x00000010) `xor` (e' .&. 0x00000010) /= (wr .&. 0x00000010)
let carryCY = (sp' .&. 0x00000100) `xor` (e' .&. 0x00000100) /= (wr .&. 0x00000100)
writeR16 RegSP (fromIntegral (wr .&. 0xFFFF))
setFlags ((if carryH then flagH else 0) .|. (if carryCY then flagCY else 0))
Bus.delay
Bus.delay
# INLINE incss #
incss ss = M $ do
v <- readR16 ss
writeR16 ss (v + 1)
Bus.delay
# INLINE decss #
decss ss = M $ do
v <- readR16 ss
writeR16 ss (v - 1)
Bus.delay
# INLINE rlca #
rlca = M $ do
v <- readR8 RegA
setFlags (if v .&. 0x80 /= 0 then flagCY else 0)
writeR8 RegA (rotateL v 1)
# INLINE rla #
rla = M $ do
v <- readR8 RegA
let ir = rotateL v 1
hasCY <- testFlag flagCY
setFlags (if v .&. 0x80 /= 0 then flagCY else 0)
writeR8 RegA (if hasCY then ir .|. 0x01 else ir .&. 0xFE)
# INLINE rrca #
rrca = M $ do
v <- readR8 RegA
setFlags (if v .&. 0x01 /= 0 then flagCY else 0)
writeR8 RegA (rotateR v 1)
# INLINE rra #
rra = M $ do
v <- readR8 RegA
let ir = rotateR v 1
hasCY <- testFlag flagCY
setFlags (if v .&. 0x01 /= 0 then flagCY else 0)
writeR8 RegA (if hasCY then ir .|. 0x80 else ir .&. 0x7F)
# INLINE rlcr #
rlcr r = M (writeR8 r =<< rlc =<< readR8 r)
# INLINE rlchl #
rlchl = M $ do
hl <- readR16 RegHL
v <- Bus.read hl
Bus.write hl =<< rlc v
# INLINE rlr #
rlr r = M (writeR8 r =<< rl =<< readR8 r)
# INLINE rlhl #
rlhl = M $ do
hl <- readR16 RegHL
v <- Bus.read hl
Bus.write hl =<< rl v
# INLINE rrcr #
rrcr r = M (writeR8 r =<< rrc =<< readR8 r)
# INLINE rrchl #
rrchl = M $ do
hl <- readR16 RegHL
v <- Bus.read hl
Bus.write hl =<< rrc v
# INLINE rrr #
rrr r = M (writeR8 r =<< rr =<< readR8 r)
# INLINE rrhl #
rrhl = M $ do
hl <- readR16 RegHL
v <- Bus.read hl
Bus.write hl =<< rr v
# INLINE slar #
slar r = M (writeR8 r =<< sla =<< readR8 r)
# INLINE slahl #
slahl = M $ do
hl <- readR16 RegHL
v <- Bus.read hl
Bus.write hl =<< sla v
# INLINE srar #
srar r = M (writeR8 r =<< sra =<< readR8 r)
# INLINE srahl #
srahl = M $ do
hl <- readR16 RegHL
v <- Bus.read hl
Bus.write hl =<< sra v
# INLINE srlr #
srlr r = M (writeR8 r =<< srl =<< readR8 r)
# INLINE srlhl #
srlhl = M $ do
hl <- readR16 RegHL
v <- Bus.read hl
Bus.write hl =<< srl v
# INLINE swapr #
swapr r = M (writeR8 r =<< swap =<< readR8 r)
# INLINE swaphl #
swaphl = M $ do
hl <- readR16 RegHL
v <- Bus.read hl
Bus.write hl =<< swap v
# INLINE bitr #
bitr r b = M $ do
v <- readR8 r
setFlagsMask allExceptCY (flagH .|. (if v `testBit` fromIntegral b then 0 else flagZ))
# INLINE bithl #
bithl b = M $ do
v <- Bus.read =<< readR16 RegHL
setFlagsMask allExceptCY (flagH .|. (if v `testBit` fromIntegral b then 0 else flagZ))
# INLINE setr #
setr r b = M $ do
v <- readR8 r
writeR8 r (v `setBit` fromIntegral b)
# INLINE sethl #
sethl b = M $ do
hl <- readR16 RegHL
v <- Bus.read hl
Bus.write hl (v `setBit` fromIntegral b)
# INLINE resr #
resr r b = M $ do
v <- readR8 r
writeR8 r (v `clearBit` fromIntegral b)
# INLINE reshl #
reshl b = M $ do
hl <- readR16 RegHL
v <- Bus.read hl
Bus.write hl (v `clearBit` fromIntegral b)
# INLINE jpnn #
jpnn nn = M (Bus.delay >> writePC nn)
# INLINE jphl #
jphl = M (writePC =<< readR16 RegHL)
# INLINE jpccnn #
jpccnn cc nn = M $ do
shouldJump <- testCondition cc
when shouldJump $ Bus.delay >> writePC nn
# INLINE jr #
jr e = M (doJR e)
# INLINE jrcc #
jrcc cc e = M $ do
shouldJump <- testCondition cc
when shouldJump $ doJR e
# INLINE call #
call nn = M (doCall nn)
# INLINE callcc #
callcc cc nn = M $ do
shouldJump <- testCondition cc
when shouldJump $ doCall nn
# INLINE ret #
ret = M doRet
# INLINE reti #
reti = M (setIME >> doRet)
# INLINE retcc #
retcc cc = M $ do
Bus.delay
shouldJump <- testCondition cc
when shouldJump doRet
# INLINE rst #
rst t = M (doCall (8 * fromIntegral t))
# INLINE daa #
daa = M $ do
flags <- readF
a <- readR8 RegA
let isH = isFlagSet flagH flags
let isN = isFlagSet flagN flags
let isCy = isFlagSet flagCY flags
let aWide = fromIntegral a :: Int
let rWide =
if isN
then
let aWide' = if isH then (aWide - 0x06) .&. 0xFF else aWide
in if isCy then aWide' - 0x60 else aWide'
else
let aWide' = if isH || aWide .&. 0x0F > 9 then aWide + 0x06 else aWide
in if isCy || aWide' > 0x9F then aWide' + 0x60 else aWide'
let r = fromIntegral (rWide .&. 0xFF)
writeR8 RegA r
setFlagsMask
allExceptN
((if isCy || rWide .&. 0x100 == 0x100 then flagCY else 0) .|. (if r == 0 then flagZ else 0))
# INLINE cpl #
cpl = M $ do
a <- readR8 RegA
writeR8 RegA (complement a)
let flagHN = flagH .|. flagN in setFlagsMask flagHN flagHN
# INLINE nop #
nop = pure ()
# INLINE ccf #
ccf = M $ do
cf <- testFlag flagCY
setFlagsMask allExceptZ (if cf then 0 else flagCY)
# INLINE scf #
scf = M (setFlagsMask allExceptZ flagCY)
# INLINE di #
di = M clearIME
# INLINE ei #
ei = M setIMENext
# INLINE halt #
halt = M $ do
State {..} <- asks forState
interrupts <- Interrupt.getPending portIF portIE
ime <- testIME
when (not ime && interrupts /= 0) $ liftIO $ writeIORef haltBug True
setMode ModeHalt
# INLINE stop #
stop = M $ do
State {..} <- asks forState
key1 <- Port.readDirect portKEY1
if isFlagSet flagSpeedSwitch key1
then
if isFlagSet flagDoubleSpeed key1
then do
Port.writeDirect portKEY1 0x7E
writeUnboxedRef cycleClocks 4
else do
Port.writeDirect portKEY1 (flagDoubleSpeed .|. 0x7E)
writeUnboxedRef cycleClocks 2
else setMode ModeStop
# INLINE invalid #
invalid b = liftIO (throwIO (InvalidInstruction b))
# INLINE doCall #
doCall :: (Has env, Bus.Has env) => Word16 -> ReaderT env IO ()
doCall nn = do
callStackPushed nn
Bus.delay
push16 =<< readPC
writePC nn
# INLINE doRet #
doRet :: (Has env, Bus.Has env) => ReaderT env IO ()
doRet = do
callStackPopped
r <- pop16
Bus.delay
writePC r
# INLINE doJR #
doJR :: (Has env, Bus.Has env) => Int8 -> ReaderT env IO ()
doJR e = do
Bus.delay
pc <- readPC
writePC (pc + fromIntegral e)
# INLINE push16 #
push16 :: (Has env, Bus.Has env) => Word16 -> ReaderT env IO ()
push16 value = do
sp <- readR16 RegSP
writeR16 RegSP (sp - 2)
Bus.write (sp - 1) (fromIntegral (value .>>. 8))
Bus.write (sp - 2) (fromIntegral (value .&. 0xFF))
# INLINE pop16 #
pop16 :: (Has env, Bus.Has env) => ReaderT env IO Word16
pop16 = do
sp <- readR16 RegSP
valueL <- Bus.read sp
valueH <- Bus.read (sp + 1)
writeR16 RegSP (sp + 2)
pure ((fromIntegral valueH .<<. 8) .|. fromIntegral valueL)
# INLINE add8 #
add8 :: Has env => Word8 -> Word16 -> ReaderT env IO ()
add8 x carry = do
a <- readR8 RegA
let (a', flags) = adder8 a (+) x carry
writeR8 RegA a'
setFlags flags
# INLINE sub8 #
sub8 :: Has env => Word8 -> Word16 -> ReaderT env IO ()
sub8 x carry = do
a <- readR8 RegA
let (a', flags) = adder8 a (-) x carry
writeR8 RegA a'
setFlags (flags .|. flagN)
{-# INLINE andOp8 #-}
andOp8 :: Has env => Word8 -> ReaderT env IO ()
andOp8 x = do
a <- readR8 RegA
let a' = a .&. x
writeR8 RegA a'
setFlags (flagH .|. (if a' == 0 then flagZ else 0))
# INLINE xorOp8 #
xorOp8 :: Has env => Word8 -> ReaderT env IO ()
xorOp8 x = do
a <- readR8 RegA
let a' = a `xor` x
writeR8 RegA a'
setFlags (if a' == 0 then flagZ else 0)
# INLINE orOp8 #
orOp8 :: Has env => Word8 -> ReaderT env IO ()
orOp8 x = do
a <- readR8 RegA
let a' = a .|. x
writeR8 RegA a'
setFlags (if a' == 0 then flagZ else 0)
# INLINE rlc #
rlc :: Has env => Word8 -> ReaderT env IO Word8
rlc v = do
setFlags (if v == 0 then flagZ else if v .&. 0x80 /= 0 then flagCY else 0)
pure (rotateL v 1)
# INLINE rl #
rl :: Has env => Word8 -> ReaderT env IO Word8
rl v = do
let ir = rotateL v 1
hasCY <- testFlag flagCY
let r = if hasCY then ir .|. 0x01 else ir .&. 0xFE
setFlags ((if r == 0 then flagZ else 0) .|. (if v .&. 0x80 /= 0 then flagCY else 0))
pure r
# INLINE rrc #
rrc :: Has env => Word8 -> ReaderT env IO Word8
rrc v = do
setFlags (if v == 0 then flagZ else if v .&. 0x01 /= 0 then flagCY else 0)
pure (rotateR v 1)
# INLINE rr #
rr :: Has env => Word8 -> ReaderT env IO Word8
rr v = do
let ir = rotateR v 1
hasCY <- testFlag flagCY
let r = if hasCY then ir .|. 0x80 else ir .&. 0x7F
setFlags ((if r == 0 then flagZ else 0) .|. (if v .&. 0x01 /= 0 then flagCY else 0))
pure r
# INLINE sla #
sla :: Has env => Word8 -> ReaderT env IO Word8
sla v = do
let r = v .<<. 1
setFlags ((if v .&. 0x80 /= 0 then flagCY else 0) .|. (if r == 0 then flagZ else 0))
pure r
# INLINE sra #
sra :: Has env => Word8 -> ReaderT env IO Word8
sra v = do
let r = (fromIntegral v .>>. 1) :: Int8
setFlags ((if v .&. 0x01 /= 0 then flagCY else 0) .|. (if r == 0 then flagZ else 0))
pure (fromIntegral r)
# INLINE srl #
srl :: Has env => Word8 -> ReaderT env IO Word8
srl v = do
let r = v .>>. 1
setFlags ((if v .&. 0x01 /= 0 then flagCY else 0) .|. (if r == 0 then flagZ else 0))
pure r
# INLINE swap #
swap :: Has env => Word8 -> ReaderT env IO Word8
swap v = do
setFlags (if v == 0 then flagZ else 0)
pure ((v .>>. 4) .|. (v .<<. 4))
| null | https://raw.githubusercontent.com/CLowcay/hgbc/76a8cf91f3c3b160eadf019bc8fc75ef07601c2f/core/src/Machine/GBC/CPU.hs | haskell | | The register file.
| The current CPU mode.
| The internal CPU state.
True to trigger the halt bug
| Initialize a new CPU.
| Get the current cpu mode.
| Get the CPU mode.
| Get the values of all the registers.
| Read data from the register file.
| Write data to the register file.
| Read a single register.
| Write a single register.
| Get the offset in the register file of a single register.
| Get the offset in the register file of a register pair.
# INLINEABLE readR16pp #
| Get the offset in the register file of a register pair.
| Read the PC register.
| Write the PC register.
# INLINEABLE writePC #
Master interrupt enable flag
| Check if a flag is set.
| Check if a condition code is true.
| Read the F register.
| Write the F register.
| Set all the flags.
| Set some flags.
| bitmask containing flags to set.
| new flags values.
| Set the master interrupt flag.
| Clear the master interrupt flag.
| Check the status of the interrupt flag.
| Reset the CPU.
Wave memory
Set all registers and ports to their post-boot values.
Values that would be written by the boot ROM if we had one.
| Perform an arithmetic operation and adjust the flags.
| Perform an increment operation and adjust the flags.
| Fetch, decode, and execute a single instruction.
Deal with HALT mode
Fetch the next byte but don't increment PC
# INLINE callStackPopped #
# INLINE subhl #
# INLINE xorn #
# INLINE andOp8 # | # LANGUAGE FlexibleInstances #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE RecordWildCards #
# LANGUAGE TypeFamilies #
module Machine.GBC.CPU
( RegisterFile (..),
Mode (..),
State (..),
Has (..),
M (..),
init,
ports,
getMode,
setMode,
getCycleClocks,
setCycleClocks,
getCallDepth,
getBacktrace,
reset,
getRegisterFile,
readR8,
writeR8,
readR16,
readR16pp,
writeR16,
writeR16pp,
readPC,
writePC,
readF,
writeF,
testFlag,
setFlags,
setFlagsMask,
setIME,
clearIME,
testIME,
flagCY,
flagN,
flagH,
flagZ,
flagIME,
flagDoubleSpeed,
testCondition,
step,
)
where
import Control.Exception (throwIO)
import Control.Monad.Reader (MonadIO (..), ReaderT (ReaderT), asks, replicateM_, when)
import Data.Bits (Bits (..))
import Data.Foldable (for_)
import Data.IORef (IORef, newIORef, readIORef, writeIORef)
import Data.Int (Int32, Int8)
import qualified Data.Vector.Storable.Mutable as VSM
import Data.Word (Word16, Word32, Word8)
import Foreign.Ptr (castPtr)
import Foreign.Storable (Storable (..))
import qualified Machine.GBC.Bus as Bus
import qualified Machine.GBC.CPU.Backtrace as Backtrace
import Machine.GBC.CPU.Decode (MonadFetch (..), decodeAndExecute)
import Machine.GBC.CPU.ISA (ConditionCode (..), MonadSm83x (..), Register16 (..), Register8 (..), RegisterHalf (..), RegisterPushPop (..))
import Machine.GBC.CPU.Interrupts (Interrupt)
import qualified Machine.GBC.CPU.Interrupts as Interrupt
import Machine.GBC.Errors (Fault (InvalidInstruction))
import qualified Machine.GBC.Memory as Memory
import Machine.GBC.Mode (EmulatorMode (DMG))
import Machine.GBC.Primitive.Port (Port)
import qualified Machine.GBC.Primitive.Port as Port
import Machine.GBC.Primitive.UnboxedRef (UnboxedRef, newUnboxedRef, readUnboxedRef, writeUnboxedRef)
import qualified Machine.GBC.Registers as R
import Machine.GBC.Util (isFlagSet, (.<<.), (.>>.))
import Prelude hiding (init)
data RegisterFile = RegisterFile
{ regF :: !Word8,
regA :: !Word8,
regC :: !Word8,
regB :: !Word8,
regE :: !Word8,
regD :: !Word8,
regL :: !Word8,
regH :: !Word8,
regSP :: !Word16,
regPC :: !Word16,
regHidden :: !Word16
}
deriving (Eq, Ord, Show)
offsetF, offsetA, offsetC, offsetB :: Int
offsetF = 0
offsetA = 1
offsetC = 2
offsetB = 3
offsetE, offsetD, offsetL, offsetH :: Int
offsetE = 4
offsetD = 5
offsetL = 6
offsetH = 7
offsetAF, offsetBC, offsetDE, offsetHL :: Int
offsetAF = 0
offsetBC = 1
offsetDE = 2
offsetHL = 3
offsetPC, offsetSP, offsetHidden :: Int
offsetSP = 4
offsetPC = 5
offsetHidden = 6
instance Storable RegisterFile where
sizeOf _ = 14
alignment _ = 2
peek ptr = do
regA <- peekElemOff (castPtr ptr) offsetA
regB <- peekElemOff (castPtr ptr) offsetB
regC <- peekElemOff (castPtr ptr) offsetC
regD <- peekElemOff (castPtr ptr) offsetD
regE <- peekElemOff (castPtr ptr) offsetE
regF <- peekElemOff (castPtr ptr) offsetF
regH <- peekElemOff (castPtr ptr) offsetH
regL <- peekElemOff (castPtr ptr) offsetL
regSP <- peekElemOff (castPtr ptr) offsetSP
regPC <- peekElemOff (castPtr ptr) offsetPC
regHidden <- peekElemOff (castPtr ptr) offsetHidden
pure RegisterFile {..}
poke ptr RegisterFile {..} = do
pokeElemOff (castPtr ptr) offsetA regA
pokeElemOff (castPtr ptr) offsetB regB
pokeElemOff (castPtr ptr) offsetC regC
pokeElemOff (castPtr ptr) offsetD regD
pokeElemOff (castPtr ptr) offsetE regE
pokeElemOff (castPtr ptr) offsetF regF
pokeElemOff (castPtr ptr) offsetH regH
pokeElemOff (castPtr ptr) offsetL regL
pokeElemOff (castPtr ptr) offsetSP regSP
pokeElemOff (castPtr ptr) offsetPC regPC
pokeElemOff (castPtr ptr) offsetHidden regHidden
data Mode = ModeHalt | ModeStop | ModeNormal deriving (Eq, Ord, Show, Bounded, Enum)
data State = State
{ cpuType :: !EmulatorMode,
registers :: !(VSM.IOVector RegisterFile),
portIF :: !Port,
portIE :: !Port,
portKEY1 :: !Port,
cpuMode :: !(IORef Mode),
cycleClocks :: !(UnboxedRef Int),
callDepth :: !(UnboxedRef Int),
backtrace :: !Backtrace.Backtrace,
}
class Memory.Has env => Has env where
forState :: env -> State
init :: Port -> Port -> IORef EmulatorMode -> IO State
init portIF portIE modeRef = do
cpuType <- readIORef modeRef
registers <- VSM.new 1
portKEY1 <-
Port.newWithReadAction
0x7E
0x01
( \key1 -> do
mode <- readIORef modeRef
if mode == DMG then pure 0xFF else pure key1
)
Port.alwaysUpdate
cpuMode <- newIORef ModeNormal
cycleClocks <- newUnboxedRef 4
callDepth <- newUnboxedRef 0
backtrace <- Backtrace.new 8
haltBug <- newIORef False
pure State {..}
ports :: State -> [(Word16, Port)]
ports State {..} = [(R.KEY1, portKEY1)]
# INLINEABLE getMode #
getMode :: Has env => ReaderT env IO Mode
getMode = do
State {..} <- asks forState
liftIO $ readIORef cpuMode
# INLINEABLE setMode #
setMode :: Has env => Mode -> ReaderT env IO ()
setMode mode = do
State {..} <- asks forState
liftIO $ writeIORef cpuMode mode
# INLINEABLE getRegisterFile #
getRegisterFile :: Has env => ReaderT env IO RegisterFile
getRegisterFile = do
State {..} <- asks forState
liftIO $ VSM.unsafeRead registers 0
# INLINE readRegister #
readRegister :: (Has env, Storable a) => Int -> ReaderT env IO a
readRegister offset = do
State {..} <- asks forState
liftIO $ VSM.unsafeRead (VSM.unsafeCast registers) offset
# INLINE writeRegister #
writeRegister :: (Has env, Storable a) => Int -> a -> ReaderT env IO ()
writeRegister offset value = do
State {..} <- asks forState
liftIO $ VSM.unsafeWrite (VSM.unsafeCast registers) offset value
# INLINEABLE readR8 #
readR8 :: Has env => Register8 -> ReaderT env IO Word8
readR8 = readRegister . offsetR8
# INLINEABLE writeR8 #
writeR8 :: Has env => Register8 -> Word8 -> ReaderT env IO ()
writeR8 register = writeRegister $ offsetR8 register
offsetR8 :: Register8 -> Int
offsetR8 RegA = offsetA
offsetR8 RegB = offsetB
offsetR8 RegC = offsetC
offsetR8 RegD = offsetD
offsetR8 RegE = offsetE
offsetR8 RegH = offsetH
offsetR8 RegL = offsetL
| Read a 16 - bit register .
# INLINEABLE readR16 #
readR16 :: Has env => Register16 -> ReaderT env IO Word16
readR16 = readRegister . offsetR16
| Write a 16 - bit register .
# INLINEABLE writeR16 #
writeR16 :: Has env => Register16 -> Word16 -> ReaderT env IO ()
writeR16 register = writeRegister $ offsetR16 register
offsetR16 :: Register16 -> Int
offsetR16 RegBC = offsetBC
offsetR16 RegDE = offsetDE
offsetR16 RegHL = offsetHL
offsetR16 RegSP = offsetSP
| Read a 16 - bit register .
readR16pp :: Has env => RegisterPushPop -> ReaderT env IO Word16
readR16pp register = readRegister (offsetR16pp register)
| Write a 16 - bit register .
# INLINEABLE writeR16pp #
writeR16pp :: Has env => RegisterPushPop -> Word16 -> ReaderT env IO ()
writeR16pp PushPopAF v = writeRegister offsetF (v .&. 0xFFF0)
writeR16pp register v = writeRegister (offsetR16pp register) v
offsetR16pp :: RegisterPushPop -> Int
offsetR16pp PushPopBC = offsetBC
offsetR16pp PushPopDE = offsetDE
offsetR16pp PushPopHL = offsetHL
offsetR16pp PushPopAF = offsetAF
# INLINEABLE readRHalf #
readRHalf :: Has env => RegisterHalf -> ReaderT env IO Word8
readRHalf RegSPL = readRegister (2 * offsetSP)
readRHalf RegSPH = readRegister (2 * offsetSP + 1)
readRHalf RegPCL = readRegister (2 * offsetPC)
readRHalf RegPCH = readRegister (2 * offsetPC + 1)
# INLINEABLE readPC #
readPC :: Has env => ReaderT env IO Word16
readPC = readRegister offsetPC
writePC :: Has env => Word16 -> ReaderT env IO ()
writePC = writeRegister offsetPC
type Flag = Word8
flagZ, flagN, flagH, flagCY :: Flag
flagZ = 0x80
flagN = 0x40
flagH = 0x20
flagCY = 0x10
allExceptCY :: Word8
allExceptCY = flagZ .|. flagN .|. flagH
allExceptZ :: Word8
allExceptZ = flagH .|. flagN .|. flagCY
allExceptN :: Word8
allExceptN = flagH .|. flagCY .|. flagZ
# INLINEABLE flagIME #
flagIME :: Word16
flagIME = 0x0100
# INLINEABLE flagSetIME #
flagSetIME :: Word16
flagSetIME = 0x0200
# INLINE testFlag #
testFlag :: Has env => Flag -> ReaderT env IO Bool
testFlag flag = do
f <- readRegister offsetF
pure (f .&. flag /= 0)
# INLINE testCondition #
testCondition :: Has env => ConditionCode -> ReaderT env IO Bool
testCondition CondNZ = not <$> testFlag flagZ
testCondition CondZ = testFlag flagZ
testCondition CondNC = not <$> testFlag flagCY
testCondition CondC = testFlag flagCY
# INLINE readF #
readF :: Has env => ReaderT env IO Word8
readF = readRegister offsetF
# INLINE writeF #
writeF :: Has env => Word8 -> ReaderT env IO ()
writeF = writeRegister offsetF
# INLINE setFlags #
setFlags :: Has env => Word8 -> ReaderT env IO ()
setFlags = writeF
# INLINE setFlagsMask #
setFlagsMask ::
Has env =>
Word8 ->
Word8 ->
ReaderT env IO ()
setFlagsMask mask flags = do
oldFlags <- readF
writeF ((oldFlags .&. complement mask) .|. (flags .&. mask))
# INLINE setIME #
setIME :: Has env => ReaderT env IO ()
setIME = do
ime <- readRegister offsetHidden
writeRegister offsetHidden (ime .|. flagIME)
# INLINE clearIME #
clearIME :: Has env => ReaderT env IO ()
clearIME = do
ime <- readRegister offsetHidden
writeRegister offsetHidden (ime .&. complement (flagIME .|. flagSetIME))
# INLINE setIMENext #
setIMENext :: Has env => ReaderT env IO ()
setIMENext = do
ime <- readRegister offsetHidden
writeRegister offsetHidden (ime .|. flagSetIME)
# INLINE updateIME #
updateIME :: Has env => ReaderT env IO ()
updateIME = do
ime <- readRegister offsetHidden
when (ime .&. flagSetIME /= 0) $
writeRegister offsetHidden ((ime .|. flagIME) .&. complement flagSetIME)
# INLINE testIME #
testIME :: Has env => ReaderT env IO Bool
testIME = do
ime <- readRegister offsetHidden
pure (ime .&. flagIME /= 0)
# INLINEABLE reset #
reset :: (Has env, Bus.Has env) => ReaderT env IO ()
reset = do
State {..} <- asks forState
writeR8 RegA 0
writeF 0
writeR8 RegB 0
writeR8 RegC 0
writeR8 RegD 0
writeR8 RegE 0
writeR8 RegH 0
writeR8 RegL 0
writeR16 RegSP 0
writeRegister offsetHidden (0 :: Word8)
setIME
writePC 0
Port.writeDirect portKEY1 0x7E
liftIO $ writeIORef cpuMode ModeNormal
liftIO $ writeIORef haltBug False
writeUnboxedRef cycleClocks 4
writeUnboxedRef callDepth 0
Backtrace.reset backtrace
Memory.writeByte R.P1 0xFF
Memory.writeByte R.DIV 0
Memory.writeByte R.SC 0
Memory.writeByte R.SB 0
Memory.writeByte R.TIMA 0
Memory.writeByte R.TMA 0
Memory.writeByte R.TAC 0
Memory.writeByte R.NR10 0
Memory.writeByte R.NR11 0
Memory.writeByte R.NR12 0
Memory.writeByte R.NR13 0
Memory.writeByte R.NR14 0
Memory.writeByte R.NR21 0
Memory.writeByte R.NR22 0
Memory.writeByte R.NR23 0
Memory.writeByte R.NR24 0
Memory.writeByte R.NR30 0
Memory.writeByte R.NR31 0
Memory.writeByte R.NR32 0
Memory.writeByte R.NR33 0
Memory.writeByte R.NR34 0
Memory.writeByte R.NR41 0
Memory.writeByte R.NR42 0
Memory.writeByte R.NR43 0
Memory.writeByte R.NR44 0
Memory.writeByte R.NR50 0
Memory.writeByte R.NR51 0
Memory.writeByte R.NR52 0
Memory.writeByte R.LCDC 0
Memory.writeByte R.SCY 0
Memory.writeByte R.SCX 0
Memory.writeByte R.LYC 0
Memory.writeByte R.BGP 0
Memory.writeByte R.OBP0 0
Memory.writeByte R.OBP1 0
Memory.writeByte R.WY 0
Memory.writeByte R.WX 0
Memory.writeByte R.IE 0
Memory.writeByte R.IF 0
Memory.writeByte 0xFF30 0x00
Memory.writeByte 0xFF31 0xFF
Memory.writeByte 0xFF32 0x00
Memory.writeByte 0xFF33 0xFF
Memory.writeByte 0xFF34 0x00
Memory.writeByte 0xFF35 0xFF
Memory.writeByte 0xFF36 0x00
Memory.writeByte 0xFF37 0xFF
Memory.writeByte 0xFF38 0x00
Memory.writeByte 0xFF39 0xFF
Memory.writeByte 0xFF3A 0x00
Memory.writeByte 0xFF3B 0xFF
Memory.writeByte 0xFF3C 0x00
Memory.writeByte 0xFF3D 0xFF
Memory.writeByte 0xFF3E 0x00
Memory.writeByte 0xFF3F 0xFF
Memory.resetAndBoot $ do
writeR8 RegA 0x11
writeF 0x80
writeR8 RegB 0x00
writeR8 RegC 0x00
writeR8 RegD 0x00
writeR8 RegE 0x08
writeR8 RegH 0x00
writeR8 RegL 0x7C
writeR16 RegSP 0xFFFE
writeRegister offsetHidden (0 :: Word16)
setIME
writePC 0x100
Memory.writeByte R.NR52 0xF1
Memory.writeByte R.NR11 0xBF
Memory.writeByte R.NR12 0x11
Memory.writeByte R.NR50 0x77
Memory.writeByte R.NR51 0xF3
Memory.writeByte R.NR14 0x80
Memory.writeByte R.NR12 0xF3
Memory.writeByte R.LCDC 0x91
Memory.writeByte R.BGP 0xFC
Memory.writeByte R.OBP0 0xFF
Memory.writeByte R.OBP1 0xFF
Memory.writeByte R.BCPS 0x88
Memory.writeByte R.OCPS 0x90
Memory.writeByte R.IF 0xE1
for_ ([0xFF80 ..] `zip` atFF80) (uncurry Memory.writeByte)
replicateM_ 2462 Bus.delay
where
atFF80 =
[0xCE, 0xED, 0x66, 0x66, 0xCC, 0x0D, 0x00, 0x0B]
++ [0x03, 0x73, 0x00, 0x83, 0x00, 0x0C, 0x00, 0x0D]
++ [0x00, 0x08, 0x11, 0x1F, 0x88, 0x89, 0x00, 0x0E]
++ [0xDC, 0xCC, 0x6E, 0xE6, 0xDD, 0xDD, 0xD9, 0x99]
++ [0xBB, 0xBB, 0x67, 0x63, 0x6E, 0x0E, 0xEC, 0xCC]
++ [0xDD, 0xDC, 0x99, 0x9F, 0xBB, 0xB9, 0x33, 0x3E]
type Operator = Word16 -> Word16 -> Word16
# INLINE adder8 #
adder8 :: Word8 -> Operator -> Word8 -> Word16 -> (Word8, Word8)
adder8 a1 op a2 carry =
let wa1 = fromIntegral a1
wa2 = fromIntegral a2
wr = (wa1 `op` wa2 `op` carry) .&. 0x01FF
r = fromIntegral wr
carryH = ((wa1 .&. 0x0F) `op` (wa2 .&. 0x0F) `op` carry) >= 0x10
flags =
(if r == 0 then flagZ else 0)
.|. (if carryH then flagH else 0)
.|. (if wr >= 0x0100 then flagCY else 0)
in (r, flags)
getCarry :: Has env => ReaderT env IO Word16
getCarry = do
f <- readF
pure ((fromIntegral f .>>. 4) .&. 1)
# INLINE inc8 #
inc8 :: Word8 -> Word8 -> (Word8, Word8)
inc8 value x =
let r = value + x
carryH = (value .&. 0x10) /= (r .&. 0x010)
flags = (if r == 0 then flagZ else 0) .|. (if carryH then flagH else 0)
in (r, flags)
flagDoubleSpeed :: Word8
flagDoubleSpeed = 0x80
flagSpeedSwitch :: Word8
flagSpeedSwitch = 0x01
interruptVector :: Interrupt -> Word16
interruptVector Interrupt.VBlank = 0x40
interruptVector Interrupt.LCDCStat = 0x48
interruptVector Interrupt.TimerOverflow = 0x50
interruptVector Interrupt.EndSerialTransfer = 0x58
interruptVector Interrupt.P1Low = 0x60
interruptVector Interrupt.Cancelled = 0
# INLINEABLE step #
step :: (Has env, Bus.Has env) => ReaderT env IO ()
step = do
State {..} <- asks forState
ime <- testIME
updateIME
mode <- liftIO (readIORef cpuMode)
case mode of
ModeNormal -> do
pc <- readPC
byte <- Bus.read pc
interrupts <- Interrupt.getPending portIF portIE
if interrupts /= 0 && ime
then handleInterrupt interrupts
else do
writePC (pc + 1)
run (decodeAndExecute byte)
ModeHalt -> do
interrupts <- Interrupt.getPending portIF portIE
if interrupts == 0
then Bus.delay
else do
liftIO (writeIORef cpuMode ModeNormal)
if ime
then Bus.delay >> handleInterrupt interrupts
else do
doHaltBug <- liftIO (readIORef haltBug)
if doHaltBug
then do
liftIO (writeIORef haltBug False)
run . decodeAndExecute =<< Bus.read =<< readPC
else run (decodeAndExecute =<< nextByte)
ModeStop -> do
interrupts <- Interrupt.getPending portIF portIE
if interrupts == 0
then Bus.delay
else do
liftIO (writeIORef cpuMode ModeNormal)
if ime
then Bus.delay >> handleInterrupt interrupts
else run (decodeAndExecute =<< nextByte)
where
handleInterrupt interrupts = do
State {..} <- asks forState
Bus.delay
Bus.delay
sp <- readR16 RegSP
writeR16 RegSP (sp - 2)
Bus.write (sp - 1) =<< readRHalf RegPCH
ie <- Port.readDirect portIE
Bus.write (sp - 2) =<< readRHalf RegPCL
let nextInterrupt = Interrupt.getNext (interrupts .&. ie)
let vector = interruptVector nextInterrupt
callStackPushed vector
writePC vector
clearIME
Interrupt.clear portIF nextInterrupt
# INLINE getCycleClocks #
getCycleClocks :: Has env => ReaderT env IO Int
getCycleClocks = do
ref <- asks (cycleClocks . forState)
readUnboxedRef ref
# INLINE setCycleClocks #
setCycleClocks :: Has env => Int -> ReaderT env IO ()
setCycleClocks clocks = do
ref <- asks (cycleClocks . forState)
writeUnboxedRef ref clocks
# INLINE getCallDepth #
getCallDepth :: Has env => ReaderT env IO Int
getCallDepth = do
State {..} <- asks forState
readUnboxedRef callDepth
getBacktrace :: Has env => ReaderT env IO [(Word16, Word16)]
getBacktrace = do
State {..} <- asks forState
Backtrace.toList backtrace
# INLINE callStackPushed #
callStackPushed :: Has env => Word16 -> ReaderT env IO ()
callStackPushed offset = do
State {..} <- asks forState
bank <- Memory.getBank offset
d <- readUnboxedRef callDepth
writeUnboxedRef callDepth (d + 1)
Backtrace.push backtrace bank offset
callStackPopped :: Has env => ReaderT env IO ()
callStackPopped = do
State {..} <- asks forState
d <- readUnboxedRef callDepth
writeUnboxedRef callDepth (d - 1)
Backtrace.pop backtrace
newtype M env a = M {run :: ReaderT env IO a}
deriving (Functor, Applicative, Monad, MonadIO)
instance (Bus.Has env, Has env) => MonadFetch (M env) where
# INLINE nextByte #
nextByte = M $ do
pc <- readPC
writePC (pc + 1)
Bus.read pc
instance (Bus.Has env, Has env) => MonadSm83x (M env) where
type ExecuteResult (M env) = ()
# INLINE ldrr #
ldrr r r' = M (writeR8 r =<< readR8 r')
# INLINE ldrn #
ldrn r n = M (writeR8 r n)
# INLINE ldrHL #
ldrHL r = M (writeR8 r =<< Bus.read =<< readR16 RegHL)
# INLINE ldHLr #
ldHLr r = M $ do
hl <- readR16 RegHL
Bus.write hl =<< readR8 r
# INLINE ldHLn #
ldHLn n = M $ do
hl <- readR16 RegHL
Bus.write hl n
# INLINE ldaBC #
ldaBC = M (writeR8 RegA =<< Bus.read =<< readR16 RegBC)
# INLINE ldaDE #
ldaDE = M (writeR8 RegA =<< Bus.read =<< readR16 RegDE)
# INLINE ldaC #
ldaC = M $ do
c <- readR8 RegC
writeR8 RegA =<< Bus.read (0xFF00 + fromIntegral c)
# INLINE ldCa #
ldCa = M $ do
c <- readR8 RegC
Bus.write (0xFF00 + fromIntegral c) =<< readR8 RegA
# INLINE ldan #
ldan n = M (writeR8 RegA =<< Bus.read (0xFF00 + fromIntegral n))
# INLINE ldna #
ldna n = M (Bus.write (0xFF00 + fromIntegral n) =<< readR8 RegA)
# INLINE ldann #
ldann nn = M (writeR8 RegA =<< Bus.read nn)
# INLINE ldnna #
ldnna nn = M (Bus.write nn =<< readR8 RegA)
# INLINE ldaHLI #
ldaHLI = M $ do
hl <- readR16 RegHL
writeR16 RegHL (hl + 1)
writeR8 RegA =<< Bus.read hl
# INLINE ldaHLD #
ldaHLD = M $ do
hl <- readR16 RegHL
writeR16 RegHL (hl - 1)
writeR8 RegA =<< Bus.read hl
# INLINE ldBCa #
ldBCa = M $ do
bc <- readR16 RegBC
Bus.write bc =<< readR8 RegA
# INLINE ldDEa #
ldDEa = M $ do
de <- readR16 RegDE
Bus.write de =<< readR8 RegA
# INLINE ldHLIa #
ldHLIa = M $ do
hl <- readR16 RegHL
writeR16 RegHL (hl + 1)
Bus.write hl =<< readR8 RegA
# INLINE ldHLDa #
ldHLDa = M $ do
hl <- readR16 RegHL
writeR16 RegHL (hl - 1)
Bus.write hl =<< readR8 RegA
# INLINE ldddnn #
ldddnn dd nn = M (writeR16 dd nn)
# INLINE ldSPHL #
ldSPHL = M $ do
writeR16 RegSP =<< readR16 RegHL
Bus.delay
# INLINE push #
push qq = M $ do
Bus.delay
push16 =<< readR16pp qq
# INLINE pop #
pop qq = M (writeR16pp qq =<< pop16)
# INLINE ldhl #
ldhl i = M $ do
sp <- fromIntegral <$> readR16 RegSP
let wi = fromIntegral i :: Int32
let wr = sp + wi
let carryH = (sp .&. 0x00000010) `xor` (wi .&. 0x00000010) /= (wr .&. 0x00000010)
let carryCY = (sp .&. 0x00000100) `xor` (wi .&. 0x00000100) /= (wr .&. 0x00000100)
writeR16 RegHL (fromIntegral wr)
setFlags ((if carryCY then flagCY else 0) .|. (if carryH then flagH else 0))
Bus.delay
# INLINE ldnnSP #
ldnnSP nn = M $ do
Bus.write nn =<< readRHalf RegSPL
Bus.write (nn + 1) =<< readRHalf RegSPH
# INLINE addr #
addr r = M $ do
v <- readR8 r
add8 v 0
# INLINE addn #
addn n = M (add8 n 0)
# INLINE addhl #
addhl = M $ do
v <- Bus.read =<< readR16 RegHL
add8 v 0
# INLINE adcr #
adcr r = M $ do
v <- readR8 r
add8 v =<< getCarry
# INLINE adcn #
adcn n = M (add8 n =<< getCarry)
# INLINE adchl #
adchl = M $ do
v <- Bus.read =<< readR16 RegHL
add8 v =<< getCarry
# INLINE subr #
subr r = M $ do
v <- readR8 r
sub8 v 0
# INLINE subn #
subn n = M (sub8 n 0)
subhl = M $ do
v <- Bus.read =<< readR16 RegHL
sub8 v 0
# INLINE sbcr #
sbcr r = M $ do
v <- readR8 r
carry <- getCarry
sub8 v carry
# INLINE sbcn #
sbcn n = M $ do
carry <- getCarry
sub8 n carry
# INLINE sbchl #
sbchl = M $ do
v <- Bus.read =<< readR16 RegHL
carry <- getCarry
sub8 v carry
# INLINE andr #
andr r = M (andOp8 =<< readR8 r)
# INLINE andn #
andn n = M (andOp8 n)
# INLINE andhl #
andhl = M (andOp8 =<< Bus.read =<< readR16 RegHL)
# INLINE orr #
orr r = M (orOp8 =<< readR8 r)
# INLINE orn #
orn n = M (orOp8 n)
# INLINE orhl #
orhl = M (orOp8 =<< Bus.read =<< readR16 RegHL)
# INLINE xorr #
xorr r = M (xorOp8 =<< readR8 r)
xorn n = M (xorOp8 n)
# INLINE xorhl #
xorhl = M (xorOp8 =<< Bus.read =<< readR16 RegHL)
# INLINE cpr #
cpr r = M $ do
a <- readR8 RegA
v <- readR8 r
let (_, flags) = adder8 a (-) v 0
setFlags (flagN .|. flags)
# INLINE cpn #
cpn n = M $ do
a <- readR8 RegA
let (_, flags) = adder8 a (-) n 0
setFlags (flagN .|. flags)
# INLINE cphl #
cphl = M $ do
a <- readR8 RegA
v <- Bus.read =<< readR16 RegHL
let (_, flags) = adder8 a (-) v 0
setFlags (flagN .|. flags)
# INLINE incr #
incr r = M $ do
v <- readR8 r
let (v', flags) = inc8 v 1
writeR8 r v'
setFlagsMask allExceptCY flags
# INLINE inchl #
inchl = M $ do
hl <- readR16 RegHL
v <- Bus.read hl
let (v', flags) = inc8 v 1
setFlagsMask allExceptCY flags
Bus.write hl v'
# INLINE decr #
decr r = M $ do
v <- readR8 r
let (v', flags) = inc8 v (negate 1)
writeR8 r v'
setFlagsMask allExceptCY (flags .|. flagN)
# INLINE dechl #
dechl = M $ do
hl <- readR16 RegHL
v <- Bus.read hl
let (v', flags) = inc8 v (negate 1)
setFlagsMask allExceptCY (flags .|. flagN)
Bus.write hl v'
# INLINE addhlss #
addhlss ss = M $ do
hl <- readR16 RegHL
v <- readR16 ss
let hl' = fromIntegral hl
let v' = fromIntegral v
let wr = hl' + v' :: Word32
let carryH = (hl' .&. 0x00001000) `xor` (v' .&. 0x00001000) /= (wr .&. 0x00001000)
let carryCY = (wr .&. 0x00010000) /= 0
writeR16 RegHL (fromIntegral wr)
setFlagsMask allExceptZ ((if carryH then flagH else 0) .|. (if carryCY then flagCY else 0))
Bus.delay
# INLINE addSP #
addSP e = M $ do
sp <- readR16 RegSP
let sp' = fromIntegral sp
let e' = fromIntegral e
let wr = e' + sp' :: Int32
let carryH = (sp' .&. 0x00000010) `xor` (e' .&. 0x00000010) /= (wr .&. 0x00000010)
let carryCY = (sp' .&. 0x00000100) `xor` (e' .&. 0x00000100) /= (wr .&. 0x00000100)
writeR16 RegSP (fromIntegral (wr .&. 0xFFFF))
setFlags ((if carryH then flagH else 0) .|. (if carryCY then flagCY else 0))
Bus.delay
Bus.delay
# INLINE incss #
incss ss = M $ do
v <- readR16 ss
writeR16 ss (v + 1)
Bus.delay
# INLINE decss #
decss ss = M $ do
v <- readR16 ss
writeR16 ss (v - 1)
Bus.delay
# INLINE rlca #
rlca = M $ do
v <- readR8 RegA
setFlags (if v .&. 0x80 /= 0 then flagCY else 0)
writeR8 RegA (rotateL v 1)
# INLINE rla #
rla = M $ do
v <- readR8 RegA
let ir = rotateL v 1
hasCY <- testFlag flagCY
setFlags (if v .&. 0x80 /= 0 then flagCY else 0)
writeR8 RegA (if hasCY then ir .|. 0x01 else ir .&. 0xFE)
# INLINE rrca #
rrca = M $ do
v <- readR8 RegA
setFlags (if v .&. 0x01 /= 0 then flagCY else 0)
writeR8 RegA (rotateR v 1)
# INLINE rra #
rra = M $ do
v <- readR8 RegA
let ir = rotateR v 1
hasCY <- testFlag flagCY
setFlags (if v .&. 0x01 /= 0 then flagCY else 0)
writeR8 RegA (if hasCY then ir .|. 0x80 else ir .&. 0x7F)
# INLINE rlcr #
rlcr r = M (writeR8 r =<< rlc =<< readR8 r)
# INLINE rlchl #
rlchl = M $ do
hl <- readR16 RegHL
v <- Bus.read hl
Bus.write hl =<< rlc v
# INLINE rlr #
rlr r = M (writeR8 r =<< rl =<< readR8 r)
# INLINE rlhl #
rlhl = M $ do
hl <- readR16 RegHL
v <- Bus.read hl
Bus.write hl =<< rl v
# INLINE rrcr #
rrcr r = M (writeR8 r =<< rrc =<< readR8 r)
# INLINE rrchl #
rrchl = M $ do
hl <- readR16 RegHL
v <- Bus.read hl
Bus.write hl =<< rrc v
# INLINE rrr #
rrr r = M (writeR8 r =<< rr =<< readR8 r)
# INLINE rrhl #
rrhl = M $ do
hl <- readR16 RegHL
v <- Bus.read hl
Bus.write hl =<< rr v
# INLINE slar #
slar r = M (writeR8 r =<< sla =<< readR8 r)
# INLINE slahl #
slahl = M $ do
hl <- readR16 RegHL
v <- Bus.read hl
Bus.write hl =<< sla v
# INLINE srar #
srar r = M (writeR8 r =<< sra =<< readR8 r)
# INLINE srahl #
srahl = M $ do
hl <- readR16 RegHL
v <- Bus.read hl
Bus.write hl =<< sra v
# INLINE srlr #
srlr r = M (writeR8 r =<< srl =<< readR8 r)
# INLINE srlhl #
srlhl = M $ do
hl <- readR16 RegHL
v <- Bus.read hl
Bus.write hl =<< srl v
# INLINE swapr #
swapr r = M (writeR8 r =<< swap =<< readR8 r)
# INLINE swaphl #
swaphl = M $ do
hl <- readR16 RegHL
v <- Bus.read hl
Bus.write hl =<< swap v
# INLINE bitr #
bitr r b = M $ do
v <- readR8 r
setFlagsMask allExceptCY (flagH .|. (if v `testBit` fromIntegral b then 0 else flagZ))
# INLINE bithl #
bithl b = M $ do
v <- Bus.read =<< readR16 RegHL
setFlagsMask allExceptCY (flagH .|. (if v `testBit` fromIntegral b then 0 else flagZ))
# INLINE setr #
setr r b = M $ do
v <- readR8 r
writeR8 r (v `setBit` fromIntegral b)
# INLINE sethl #
sethl b = M $ do
hl <- readR16 RegHL
v <- Bus.read hl
Bus.write hl (v `setBit` fromIntegral b)
# INLINE resr #
resr r b = M $ do
v <- readR8 r
writeR8 r (v `clearBit` fromIntegral b)
# INLINE reshl #
reshl b = M $ do
hl <- readR16 RegHL
v <- Bus.read hl
Bus.write hl (v `clearBit` fromIntegral b)
# INLINE jpnn #
jpnn nn = M (Bus.delay >> writePC nn)
# INLINE jphl #
jphl = M (writePC =<< readR16 RegHL)
# INLINE jpccnn #
jpccnn cc nn = M $ do
shouldJump <- testCondition cc
when shouldJump $ Bus.delay >> writePC nn
# INLINE jr #
jr e = M (doJR e)
# INLINE jrcc #
jrcc cc e = M $ do
shouldJump <- testCondition cc
when shouldJump $ doJR e
# INLINE call #
call nn = M (doCall nn)
# INLINE callcc #
callcc cc nn = M $ do
shouldJump <- testCondition cc
when shouldJump $ doCall nn
# INLINE ret #
ret = M doRet
# INLINE reti #
reti = M (setIME >> doRet)
# INLINE retcc #
retcc cc = M $ do
Bus.delay
shouldJump <- testCondition cc
when shouldJump doRet
# INLINE rst #
rst t = M (doCall (8 * fromIntegral t))
# INLINE daa #
daa = M $ do
flags <- readF
a <- readR8 RegA
let isH = isFlagSet flagH flags
let isN = isFlagSet flagN flags
let isCy = isFlagSet flagCY flags
let aWide = fromIntegral a :: Int
let rWide =
if isN
then
let aWide' = if isH then (aWide - 0x06) .&. 0xFF else aWide
in if isCy then aWide' - 0x60 else aWide'
else
let aWide' = if isH || aWide .&. 0x0F > 9 then aWide + 0x06 else aWide
in if isCy || aWide' > 0x9F then aWide' + 0x60 else aWide'
let r = fromIntegral (rWide .&. 0xFF)
writeR8 RegA r
setFlagsMask
allExceptN
((if isCy || rWide .&. 0x100 == 0x100 then flagCY else 0) .|. (if r == 0 then flagZ else 0))
# INLINE cpl #
cpl = M $ do
a <- readR8 RegA
writeR8 RegA (complement a)
let flagHN = flagH .|. flagN in setFlagsMask flagHN flagHN
# INLINE nop #
nop = pure ()
# INLINE ccf #
ccf = M $ do
cf <- testFlag flagCY
setFlagsMask allExceptZ (if cf then 0 else flagCY)
# INLINE scf #
scf = M (setFlagsMask allExceptZ flagCY)
# INLINE di #
di = M clearIME
# INLINE ei #
ei = M setIMENext
# INLINE halt #
halt = M $ do
State {..} <- asks forState
interrupts <- Interrupt.getPending portIF portIE
ime <- testIME
when (not ime && interrupts /= 0) $ liftIO $ writeIORef haltBug True
setMode ModeHalt
# INLINE stop #
stop = M $ do
State {..} <- asks forState
key1 <- Port.readDirect portKEY1
if isFlagSet flagSpeedSwitch key1
then
if isFlagSet flagDoubleSpeed key1
then do
Port.writeDirect portKEY1 0x7E
writeUnboxedRef cycleClocks 4
else do
Port.writeDirect portKEY1 (flagDoubleSpeed .|. 0x7E)
writeUnboxedRef cycleClocks 2
else setMode ModeStop
# INLINE invalid #
invalid b = liftIO (throwIO (InvalidInstruction b))
# INLINE doCall #
doCall :: (Has env, Bus.Has env) => Word16 -> ReaderT env IO ()
doCall nn = do
callStackPushed nn
Bus.delay
push16 =<< readPC
writePC nn
# INLINE doRet #
doRet :: (Has env, Bus.Has env) => ReaderT env IO ()
doRet = do
callStackPopped
r <- pop16
Bus.delay
writePC r
# INLINE doJR #
doJR :: (Has env, Bus.Has env) => Int8 -> ReaderT env IO ()
doJR e = do
Bus.delay
pc <- readPC
writePC (pc + fromIntegral e)
# INLINE push16 #
push16 :: (Has env, Bus.Has env) => Word16 -> ReaderT env IO ()
push16 value = do
sp <- readR16 RegSP
writeR16 RegSP (sp - 2)
Bus.write (sp - 1) (fromIntegral (value .>>. 8))
Bus.write (sp - 2) (fromIntegral (value .&. 0xFF))
# INLINE pop16 #
pop16 :: (Has env, Bus.Has env) => ReaderT env IO Word16
pop16 = do
sp <- readR16 RegSP
valueL <- Bus.read sp
valueH <- Bus.read (sp + 1)
writeR16 RegSP (sp + 2)
pure ((fromIntegral valueH .<<. 8) .|. fromIntegral valueL)
# INLINE add8 #
add8 :: Has env => Word8 -> Word16 -> ReaderT env IO ()
add8 x carry = do
a <- readR8 RegA
let (a', flags) = adder8 a (+) x carry
writeR8 RegA a'
setFlags flags
# INLINE sub8 #
sub8 :: Has env => Word8 -> Word16 -> ReaderT env IO ()
sub8 x carry = do
a <- readR8 RegA
let (a', flags) = adder8 a (-) x carry
writeR8 RegA a'
setFlags (flags .|. flagN)
andOp8 :: Has env => Word8 -> ReaderT env IO ()
andOp8 x = do
a <- readR8 RegA
let a' = a .&. x
writeR8 RegA a'
setFlags (flagH .|. (if a' == 0 then flagZ else 0))
# INLINE xorOp8 #
xorOp8 :: Has env => Word8 -> ReaderT env IO ()
xorOp8 x = do
a <- readR8 RegA
let a' = a `xor` x
writeR8 RegA a'
setFlags (if a' == 0 then flagZ else 0)
# INLINE orOp8 #
orOp8 :: Has env => Word8 -> ReaderT env IO ()
orOp8 x = do
a <- readR8 RegA
let a' = a .|. x
writeR8 RegA a'
setFlags (if a' == 0 then flagZ else 0)
# INLINE rlc #
rlc :: Has env => Word8 -> ReaderT env IO Word8
rlc v = do
setFlags (if v == 0 then flagZ else if v .&. 0x80 /= 0 then flagCY else 0)
pure (rotateL v 1)
# INLINE rl #
rl :: Has env => Word8 -> ReaderT env IO Word8
rl v = do
let ir = rotateL v 1
hasCY <- testFlag flagCY
let r = if hasCY then ir .|. 0x01 else ir .&. 0xFE
setFlags ((if r == 0 then flagZ else 0) .|. (if v .&. 0x80 /= 0 then flagCY else 0))
pure r
# INLINE rrc #
rrc :: Has env => Word8 -> ReaderT env IO Word8
rrc v = do
setFlags (if v == 0 then flagZ else if v .&. 0x01 /= 0 then flagCY else 0)
pure (rotateR v 1)
# INLINE rr #
rr :: Has env => Word8 -> ReaderT env IO Word8
rr v = do
let ir = rotateR v 1
hasCY <- testFlag flagCY
let r = if hasCY then ir .|. 0x80 else ir .&. 0x7F
setFlags ((if r == 0 then flagZ else 0) .|. (if v .&. 0x01 /= 0 then flagCY else 0))
pure r
# INLINE sla #
sla :: Has env => Word8 -> ReaderT env IO Word8
sla v = do
let r = v .<<. 1
setFlags ((if v .&. 0x80 /= 0 then flagCY else 0) .|. (if r == 0 then flagZ else 0))
pure r
# INLINE sra #
sra :: Has env => Word8 -> ReaderT env IO Word8
sra v = do
let r = (fromIntegral v .>>. 1) :: Int8
setFlags ((if v .&. 0x01 /= 0 then flagCY else 0) .|. (if r == 0 then flagZ else 0))
pure (fromIntegral r)
# INLINE srl #
srl :: Has env => Word8 -> ReaderT env IO Word8
srl v = do
let r = v .>>. 1
setFlags ((if v .&. 0x01 /= 0 then flagCY else 0) .|. (if r == 0 then flagZ else 0))
pure r
# INLINE swap #
swap :: Has env => Word8 -> ReaderT env IO Word8
swap v = do
setFlags (if v == 0 then flagZ else 0)
pure ((v .>>. 4) .|. (v .<<. 4))
|
6b4d77d03df829405974196a27d794bce6dfc42726ca8cec4269793e54ce9187 | keigoi/ocaml-mpst-light | linocaml.ml | open Concur_shims
type 'a lin = {__lin:'a}
type 'a data = {data:'a}
type (_,_,_,_) lens =
| Zero : ('a,'b,[`cons of 'a * 'xs], [`cons of 'b * 'xs]) lens
| Succ :
('x,'y,'xs,'ys) lens
-> ('x,'y,[`cons of 'a * 'xs], [`cons of 'a * 'ys]) lens
| Other :
('xs -> 'x) * ('xs -> 'y -> 'ys)
-> ('x,'y,'xs,'ys) lens
let _0 = Zero
let _1 = Succ Zero
let _2 = Succ (Succ Zero)
let rec lens_get : type x y xs ys. (x,y,xs,ys) lens -> xs -> x = fun l xs ->
match l,xs with
| Zero,(`cons(hd,_)) -> hd
| Succ l,(`cons(_,tl)) -> lens_get l tl
| Other(get,_),xs -> get xs
let rec lens_put : type x y xs ys. (x,y,xs,ys) lens -> xs -> y -> ys = fun l xs b ->
match l,xs with
| Zero,(`cons(_,tl)) -> `cons(b,tl)
| Succ l,(`cons(hd,tl)) -> `cons(hd,lens_put l tl b)
| Other (_,put),xs -> put xs b
type ('pre, 'post, 'a) monad = {__m:('pre -> ('post * 'a) IO.io)}
type 'f bind = 'f
type all_empty = [`cons of unit * 'xs] as 'xs
let return a =
{__m=(fun pre -> IO.return (pre, {data=a}))}
let return_lin v =
{__m=(fun pre ->
IO.return (pre, {__lin=v}))}
let bind m f =
{__m=(fun pre ->
IO.bind (m.__m pre) (fun (mid, {data=a}) -> (f a).__m mid))}
let bind_ m1 m2 =
{__m=(fun pre ->
IO.bind (m1.__m pre) (fun (mid, _) -> m2.__m mid))}
let bind_lin : 'pre 'mid 'a 'post 'b. ('pre, 'mid, 'a lin) monad
-> ('a lin -> ('mid, 'post, 'b) monad) bind
-> ('pre, 'post, 'b) monad = fun m f ->
{__m=(fun pre ->
IO.bind (m.__m pre) (fun (mid, x) -> (f x).__m mid))}
let (@>) : 'p 'q 'pre 'post 'a.
('p, 'q, 'a) monad
-> ('p, 'q, 'pre, 'post) lens
-> ('pre, 'post, 'a) monad = fun m l ->
{__m=(fun pre ->
IO.bind (m.__m (lens_get l pre)) (fun (q, a) -> IO.return (lens_put l pre q, a)))}
let (<@) l m = m @> l
let get_lin : 'a 'pre 'post. ('a lin, unit, 'pre, 'post) lens -> ('pre,'post,'a lin) monad =
fun l ->
{__m=(fun pre ->
IO.return (lens_put l pre (), lens_get l pre))}
let put_lin : 'a 'mid 'post 'pre. (unit,'a lin,'mid,'post) lens -> ('pre,'mid,'a lin) monad -> ('pre,'post,unit data) monad =
fun l m ->
{__m=(fun pre ->
IO.bind (m.__m pre) (fun (mid, v) ->
IO.return (lens_put l mid v, {data=()})))}
let put_linval : 'a 'pre 'post. (unit,'a lin,'pre,'post) lens -> 'a -> ('pre,'post,unit data) monad =
fun l v ->
{__m=(fun pre ->
IO.return (lens_put l pre {__lin=v}, {data=()}))}
let run =
fun f x ->
let rec all_empty = `cons((), all_empty) in
IO.bind ((f x).__m all_empty) (fun (_, {data=x}) -> IO.return x)
let run_ =
fun f ->
let rec all_empty = `cons((), all_empty) in
IO.bind ((f ()).__m all_empty) (fun (_, {data=x}) -> IO.return x)
module Syntax = struct
let bind_data = bind
let bind_lin = bind_lin
let bind_raw {__m=m} f = {__m=(fun pre -> IO.bind (m pre) (fun (mid,x) -> (f x).__m mid))}
let return_lin = return_lin
let get_lin = get_lin
let put_linval = put_linval
module Internal = struct
let _lin x = {__lin=x}
let _unlin ({__lin=x}) = x
let _mkbind : 'f. 'f -> 'f bind =
fun f -> f
let _run : 'pre 'post 'a. ('pre,'post,'a data) monad -> 'pre -> 'a IO.io =
fun m pre ->
IO.bind (m.__m pre) (fun (_, {data=v}) -> IO.return v)
let _dispose_env m =
{__m=(fun pre ->
IO.bind (m.__m pre) (fun (_,a) -> IO.return ((), a)))}
let _peek : 'pre 'post 'a. ('pre -> ('pre, 'post, 'a) monad) -> ('pre, 'post, 'a) monad =
fun f ->
{__m=(fun pre -> ((f pre).__m pre))}
let _poke : 'pre 'post. 'post -> ('pre, 'post, unit data) monad =
fun post ->
{__m=(fun _ -> IO.return (post, {data=()}))}
let _map_lin : 'a 'b 'pre 'post. ('a -> 'b) -> ('a lin, 'b lin, 'pre, 'post) lens -> ('pre, 'post, unit data) monad
= fun f l ->
{__m=fun pre -> IO.return (lens_put l pre @@ _lin (f (_unlin @@ lens_get l pre)), {data=()})}
end
end
| null | https://raw.githubusercontent.com/keigoi/ocaml-mpst-light/099658369798b9588cb744ee0b95d09ff6e50d9f/packages/linocaml-light/linocaml.ml | ocaml | open Concur_shims
type 'a lin = {__lin:'a}
type 'a data = {data:'a}
type (_,_,_,_) lens =
| Zero : ('a,'b,[`cons of 'a * 'xs], [`cons of 'b * 'xs]) lens
| Succ :
('x,'y,'xs,'ys) lens
-> ('x,'y,[`cons of 'a * 'xs], [`cons of 'a * 'ys]) lens
| Other :
('xs -> 'x) * ('xs -> 'y -> 'ys)
-> ('x,'y,'xs,'ys) lens
let _0 = Zero
let _1 = Succ Zero
let _2 = Succ (Succ Zero)
let rec lens_get : type x y xs ys. (x,y,xs,ys) lens -> xs -> x = fun l xs ->
match l,xs with
| Zero,(`cons(hd,_)) -> hd
| Succ l,(`cons(_,tl)) -> lens_get l tl
| Other(get,_),xs -> get xs
let rec lens_put : type x y xs ys. (x,y,xs,ys) lens -> xs -> y -> ys = fun l xs b ->
match l,xs with
| Zero,(`cons(_,tl)) -> `cons(b,tl)
| Succ l,(`cons(hd,tl)) -> `cons(hd,lens_put l tl b)
| Other (_,put),xs -> put xs b
type ('pre, 'post, 'a) monad = {__m:('pre -> ('post * 'a) IO.io)}
type 'f bind = 'f
type all_empty = [`cons of unit * 'xs] as 'xs
let return a =
{__m=(fun pre -> IO.return (pre, {data=a}))}
let return_lin v =
{__m=(fun pre ->
IO.return (pre, {__lin=v}))}
let bind m f =
{__m=(fun pre ->
IO.bind (m.__m pre) (fun (mid, {data=a}) -> (f a).__m mid))}
let bind_ m1 m2 =
{__m=(fun pre ->
IO.bind (m1.__m pre) (fun (mid, _) -> m2.__m mid))}
let bind_lin : 'pre 'mid 'a 'post 'b. ('pre, 'mid, 'a lin) monad
-> ('a lin -> ('mid, 'post, 'b) monad) bind
-> ('pre, 'post, 'b) monad = fun m f ->
{__m=(fun pre ->
IO.bind (m.__m pre) (fun (mid, x) -> (f x).__m mid))}
let (@>) : 'p 'q 'pre 'post 'a.
('p, 'q, 'a) monad
-> ('p, 'q, 'pre, 'post) lens
-> ('pre, 'post, 'a) monad = fun m l ->
{__m=(fun pre ->
IO.bind (m.__m (lens_get l pre)) (fun (q, a) -> IO.return (lens_put l pre q, a)))}
let (<@) l m = m @> l
let get_lin : 'a 'pre 'post. ('a lin, unit, 'pre, 'post) lens -> ('pre,'post,'a lin) monad =
fun l ->
{__m=(fun pre ->
IO.return (lens_put l pre (), lens_get l pre))}
let put_lin : 'a 'mid 'post 'pre. (unit,'a lin,'mid,'post) lens -> ('pre,'mid,'a lin) monad -> ('pre,'post,unit data) monad =
fun l m ->
{__m=(fun pre ->
IO.bind (m.__m pre) (fun (mid, v) ->
IO.return (lens_put l mid v, {data=()})))}
let put_linval : 'a 'pre 'post. (unit,'a lin,'pre,'post) lens -> 'a -> ('pre,'post,unit data) monad =
fun l v ->
{__m=(fun pre ->
IO.return (lens_put l pre {__lin=v}, {data=()}))}
let run =
fun f x ->
let rec all_empty = `cons((), all_empty) in
IO.bind ((f x).__m all_empty) (fun (_, {data=x}) -> IO.return x)
let run_ =
fun f ->
let rec all_empty = `cons((), all_empty) in
IO.bind ((f ()).__m all_empty) (fun (_, {data=x}) -> IO.return x)
module Syntax = struct
let bind_data = bind
let bind_lin = bind_lin
let bind_raw {__m=m} f = {__m=(fun pre -> IO.bind (m pre) (fun (mid,x) -> (f x).__m mid))}
let return_lin = return_lin
let get_lin = get_lin
let put_linval = put_linval
module Internal = struct
let _lin x = {__lin=x}
let _unlin ({__lin=x}) = x
let _mkbind : 'f. 'f -> 'f bind =
fun f -> f
let _run : 'pre 'post 'a. ('pre,'post,'a data) monad -> 'pre -> 'a IO.io =
fun m pre ->
IO.bind (m.__m pre) (fun (_, {data=v}) -> IO.return v)
let _dispose_env m =
{__m=(fun pre ->
IO.bind (m.__m pre) (fun (_,a) -> IO.return ((), a)))}
let _peek : 'pre 'post 'a. ('pre -> ('pre, 'post, 'a) monad) -> ('pre, 'post, 'a) monad =
fun f ->
{__m=(fun pre -> ((f pre).__m pre))}
let _poke : 'pre 'post. 'post -> ('pre, 'post, unit data) monad =
fun post ->
{__m=(fun _ -> IO.return (post, {data=()}))}
let _map_lin : 'a 'b 'pre 'post. ('a -> 'b) -> ('a lin, 'b lin, 'pre, 'post) lens -> ('pre, 'post, unit data) monad
= fun f l ->
{__m=fun pre -> IO.return (lens_put l pre @@ _lin (f (_unlin @@ lens_get l pre)), {data=()})}
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.