_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
|
---|---|---|---|---|---|---|---|---|
21386cfd3a75b463269165e5ae74bcc7c043398ec449055297588e4f73449b8d | alesaccoia/festival_flinger | cmu_us_aup_tagger.scm | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; ;;;
Carnegie Mellon University ; ; ;
and and ; ; ;
Copyright ( c ) 1998 - 2000 ; ; ;
All Rights Reserved . ; ; ;
;;; ;;;
;;; Permission is hereby granted, free of charge, to use and distribute ;;;
;;; this software and its documentation without restriction, including ;;;
;;; without limitation the rights to use, copy, modify, merge, publish, ;;;
;;; distribute, sublicense, and/or sell copies of this work, and to ;;;
;;; permit persons to whom this work is furnished to do so, subject to ;;;
;;; the following conditions: ;;;
1 . The code must retain the above copyright notice , this list of ; ; ;
;;; conditions and the following disclaimer. ;;;
2 . Any modifications must be clearly marked as such . ; ; ;
3 . Original authors ' names are not deleted . ; ; ;
4 . The authors ' names are not used to endorse or promote products ; ; ;
;;; derived from this software without specific prior written ;;;
;;; permission. ;;;
;;; ;;;
CARNEGIE MELLON UNIVERSITY AND THE CONTRIBUTORS TO THIS WORK ; ; ;
;;; DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ;;;
;;; ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT ;;;
SHALL CARNEGIE MELLON UNIVERSITY NOR THE CONTRIBUTORS BE LIABLE ; ; ;
;;; FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES ;;;
WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , IN ; ; ;
;;; AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ;;;
;;; ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF ;;;
;;; THIS SOFTWARE. ;;;
;;; ;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
POS tagger for English
;;;
;;; Load any necessary files here
(require 'pos)
(define (cmu_us_aup::select_tagger)
"(cmu_us_aup::select_tagger)
Set up the POS tagger English."
(set! pos_lex_name "english_poslex")
(set! pos_ngram_name 'english_pos_ngram)
(set! pos_supported t)
(set! guess_pos english_guess_pos) ;; need this for accents
)
(define (cmu_us_aup::reset_tagger)
"(cmu_us_aup::reset_tagger)
Reset tagging information."
t
)
(provide 'cmu_us_aup_tagger)
| null | https://raw.githubusercontent.com/alesaccoia/festival_flinger/87345aad3a3230751a8ff479f74ba1676217accd/lib/voices/us/cmu_us_aup_cg/festvox/cmu_us_aup_tagger.scm | scheme |
;;;
; ;
; ;
; ;
; ;
;;;
Permission is hereby granted, free of charge, to use and distribute ;;;
this software and its documentation without restriction, including ;;;
without limitation the rights to use, copy, modify, merge, publish, ;;;
distribute, sublicense, and/or sell copies of this work, and to ;;;
permit persons to whom this work is furnished to do so, subject to ;;;
the following conditions: ;;;
; ;
conditions and the following disclaimer. ;;;
; ;
; ;
; ;
derived from this software without specific prior written ;;;
permission. ;;;
;;;
; ;
DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ;;;
ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT ;;;
; ;
FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES ;;;
; ;
AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ;;;
ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF ;;;
THIS SOFTWARE. ;;;
;;;
Load any necessary files here
need this for accents | POS tagger for English
(require 'pos)
(define (cmu_us_aup::select_tagger)
"(cmu_us_aup::select_tagger)
Set up the POS tagger English."
(set! pos_lex_name "english_poslex")
(set! pos_ngram_name 'english_pos_ngram)
(set! pos_supported t)
)
(define (cmu_us_aup::reset_tagger)
"(cmu_us_aup::reset_tagger)
Reset tagging information."
t
)
(provide 'cmu_us_aup_tagger)
|
196bb39151ab201614ce81bcadeb5d6a835130b87cf173db33ce36aafe79d30a | input-output-hk/hydra | Party.hs | | Types and functions revolving around a Hydra ' Party ' . That is , a
-- participant in a Hydra Head, which signs transactions or snapshots in the
-- Hydra protocol.
module Hydra.Party where
import Hydra.Prelude hiding (show)
import Data.Aeson (ToJSONKey)
import Data.Aeson.Types (FromJSONKey)
import Hydra.Cardano.Api (AsType (AsVerificationKey), SerialiseAsRawBytes (deserialiseFromRawBytes, serialiseToRawBytes), SigningKey, VerificationKey, getVerificationKey, verificationKeyHash)
import Hydra.Crypto (AsType (AsHydraKey), HydraKey)
import qualified Hydra.Data.Party as OnChain
| Identifies a party in a Hydra head by it 's ' VerificationKey ' .
newtype Party = Party {vkey :: VerificationKey HydraKey}
deriving (Eq, Show, Generic)
deriving anyclass (ToJSON, FromJSON, FromJSONKey, ToJSONKey)
REVIEW : Do we really want to define or also use unordered - containers
based on Hashable ?
instance Ord Party where
Party{vkey = a} <= Party{vkey = b} =
verificationKeyHash a <= verificationKeyHash b
instance Arbitrary Party where
arbitrary = Party <$> arbitrary
instance FromCBOR Party where
fromCBOR = Party <$> fromCBOR
instance ToCBOR Party where
toCBOR Party{vkey} = toCBOR vkey
| Get the ' Party ' given some Hydra ' SigningKey ' .
deriveParty :: SigningKey HydraKey -> Party
deriveParty = Party . getVerificationKey
| Convert " high - level " ' Party ' to the " low - level " representation as used
on - chain . See ' Hydra . Data . Party . Party ' for an explanation why this is a
-- distinct type.
partyToChain :: Party -> OnChain.Party
partyToChain Party{vkey} =
OnChain.partyFromVerificationKeyBytes $ serialiseToRawBytes vkey
-- | Retrieve the "high-level" 'Party from the "low-level" on-chain
-- representation. This can fail because of the lower type-safety used on-chain
and a non - guaranteed verification key length . See ' Hydra . Data . Party . Party '
-- for an explanation why this is a distinct type.
partyFromChain :: MonadFail m => OnChain.Party -> m Party
partyFromChain =
maybe (fail "partyFromChain got Nothing") (pure . Party)
. deserialiseFromRawBytes (AsVerificationKey AsHydraKey)
. OnChain.partyToVerficationKeyBytes
| null | https://raw.githubusercontent.com/input-output-hk/hydra/cd4d7731813d608a7979d5a9cb5ece3bfa0a3892/hydra-node/src/Hydra/Party.hs | haskell | participant in a Hydra Head, which signs transactions or snapshots in the
Hydra protocol.
distinct type.
| Retrieve the "high-level" 'Party from the "low-level" on-chain
representation. This can fail because of the lower type-safety used on-chain
for an explanation why this is a distinct type. | | Types and functions revolving around a Hydra ' Party ' . That is , a
module Hydra.Party where
import Hydra.Prelude hiding (show)
import Data.Aeson (ToJSONKey)
import Data.Aeson.Types (FromJSONKey)
import Hydra.Cardano.Api (AsType (AsVerificationKey), SerialiseAsRawBytes (deserialiseFromRawBytes, serialiseToRawBytes), SigningKey, VerificationKey, getVerificationKey, verificationKeyHash)
import Hydra.Crypto (AsType (AsHydraKey), HydraKey)
import qualified Hydra.Data.Party as OnChain
| Identifies a party in a Hydra head by it 's ' VerificationKey ' .
newtype Party = Party {vkey :: VerificationKey HydraKey}
deriving (Eq, Show, Generic)
deriving anyclass (ToJSON, FromJSON, FromJSONKey, ToJSONKey)
REVIEW : Do we really want to define or also use unordered - containers
based on Hashable ?
instance Ord Party where
Party{vkey = a} <= Party{vkey = b} =
verificationKeyHash a <= verificationKeyHash b
instance Arbitrary Party where
arbitrary = Party <$> arbitrary
instance FromCBOR Party where
fromCBOR = Party <$> fromCBOR
instance ToCBOR Party where
toCBOR Party{vkey} = toCBOR vkey
| Get the ' Party ' given some Hydra ' SigningKey ' .
deriveParty :: SigningKey HydraKey -> Party
deriveParty = Party . getVerificationKey
| Convert " high - level " ' Party ' to the " low - level " representation as used
on - chain . See ' Hydra . Data . Party . Party ' for an explanation why this is a
partyToChain :: Party -> OnChain.Party
partyToChain Party{vkey} =
OnChain.partyFromVerificationKeyBytes $ serialiseToRawBytes vkey
and a non - guaranteed verification key length . See ' Hydra . Data . Party . Party '
partyFromChain :: MonadFail m => OnChain.Party -> m Party
partyFromChain =
maybe (fail "partyFromChain got Nothing") (pure . Party)
. deserialiseFromRawBytes (AsVerificationKey AsHydraKey)
. OnChain.partyToVerficationKeyBytes
|
c0df3595924a5a259347037d9832f1d6cc5913bf3dc77ed6a0e688e2565defe0 | fantasytree/fancy_game_server | client_open_rpc.erl | %%----------------------------------------------------
%% 客户端验证
%% **注意**以下调用都是开放的,请注意安全性
%%----------------------------------------------------
-module(client_open_rpc).
-export([handle/3]).
-include("common.hrl").
-include("conn.hrl").
-include("role.hrl").
请求验证账号登录
handle(1001, {Account, Platform, ZoneId, SessionId}, Conn = #conn{bind_obj = undefined}) ->
case check_acc(Account, Platform, ZoneId, SessionId) of
false ->
{stop, reply, {?false, ?T("帐号验证失败,无法登录")}};
true ->
Acc = {Account, Platform, ZoneId},
NewConn = Conn#conn{bind_obj = Acc},
case role_data:fetch(by_acc, Acc) of
{ok, #role{id = RoleId, name = Name}} ->
Rl = [{RoleId, Name}],
sys_conn:pack_send(self(), 1101, {?true, <<>>, Rl}),
{reply, {?true, <<>>}, NewConn};
false ->
sys_conn:pack_send(self(), 1101, {?true, <<>>, []}),
{reply, {?true, <<>>}, NewConn};
{error, _} ->
{stop, reply, {?false, ?T("获取角色列表失败,请稍后重试")}}
end
end;
容错匹配
handle(_Cmd, _Data, _Conn) ->
?DEBUG("无效的RPC调用[~w]: ~w, ~w", [_Cmd, _Data, _Conn]),
{stop, "错误的请求"}.
%% ----------------------------------------------------
私有函数
%% ----------------------------------------------------
检查帐号是否正确
check_acc(_Account, _Platform, _ZoneId, _SessionId) -> true.
| null | https://raw.githubusercontent.com/fantasytree/fancy_game_server/4ca93486fc0d5b6630170e79b48fb31e9c6e2358/src/mod/client/client_open_rpc.erl | erlang | ----------------------------------------------------
客户端验证
**注意**以下调用都是开放的,请注意安全性
----------------------------------------------------
----------------------------------------------------
---------------------------------------------------- | -module(client_open_rpc).
-export([handle/3]).
-include("common.hrl").
-include("conn.hrl").
-include("role.hrl").
请求验证账号登录
handle(1001, {Account, Platform, ZoneId, SessionId}, Conn = #conn{bind_obj = undefined}) ->
case check_acc(Account, Platform, ZoneId, SessionId) of
false ->
{stop, reply, {?false, ?T("帐号验证失败,无法登录")}};
true ->
Acc = {Account, Platform, ZoneId},
NewConn = Conn#conn{bind_obj = Acc},
case role_data:fetch(by_acc, Acc) of
{ok, #role{id = RoleId, name = Name}} ->
Rl = [{RoleId, Name}],
sys_conn:pack_send(self(), 1101, {?true, <<>>, Rl}),
{reply, {?true, <<>>}, NewConn};
false ->
sys_conn:pack_send(self(), 1101, {?true, <<>>, []}),
{reply, {?true, <<>>}, NewConn};
{error, _} ->
{stop, reply, {?false, ?T("获取角色列表失败,请稍后重试")}}
end
end;
容错匹配
handle(_Cmd, _Data, _Conn) ->
?DEBUG("无效的RPC调用[~w]: ~w, ~w", [_Cmd, _Data, _Conn]),
{stop, "错误的请求"}.
私有函数
检查帐号是否正确
check_acc(_Account, _Platform, _ZoneId, _SessionId) -> true.
|
5e93275b135e55a1bb9ea39c2b72db81ef64ac4e797eea386746abf567dc1adb | 8c6794b6/guile-tjit | t-nest-10.scm | ;;; More inlined procedure in nested loop.
;;;
;;; Calling procedure containing loop twice, adding results. Return
address of the first call to ` loop1 ' is different from the second
;;; call to `loop1'.
(define (loop1 n acc)
(let lp ((i n) (acc acc))
(if (< 0 i)
(lp (- i 1) (+ acc 2))
acc)))
(define (loop2 n)
(let lp ((i n) (acc 0))
(if (< 0 i)
(lp (- i 1) (+ (loop1 n 0)
(loop1 n 0)))
acc)))
(loop2 100)
| null | https://raw.githubusercontent.com/8c6794b6/guile-tjit/9566e480af2ff695e524984992626426f393414f/test-suite/tjit/t-nest-10.scm | scheme | More inlined procedure in nested loop.
Calling procedure containing loop twice, adding results. Return
call to `loop1'. | address of the first call to ` loop1 ' is different from the second
(define (loop1 n acc)
(let lp ((i n) (acc acc))
(if (< 0 i)
(lp (- i 1) (+ acc 2))
acc)))
(define (loop2 n)
(let lp ((i n) (acc 0))
(if (< 0 i)
(lp (- i 1) (+ (loop1 n 0)
(loop1 n 0)))
acc)))
(loop2 100)
|
d4e02e60366b1f2427916cd7ca748858ccf5bb1c3713d0b08ffcb27a9c5d06a4 | Bogdanp/racket-lua | compiler.rkt | #lang racket/base
(require (for-syntax racket/base
syntax/parse)
racket/format
racket/list
racket/match
racket/string
racket/syntax
"ast.rkt")
(provide
compile-chunk)
(define (compile-chunk chunk)
(define loc (Node-loc chunk))
(define return? (needs-return? chunk))
(with-syntax ([block (compile-block chunk)])
(with-syntax ([body (if return?
(syntax/loc* loc (#%let/cc #%return block (#%values)))
(syntax/loc* loc (#%begin block (#%values))))])
(syntax/loc* loc
((#%provide #%chunk)
(#%define _ENV (#%global))
(#%load-stdlib! _ENV)
(#%define (#%lua-module . #%rest)
body)
(#%define #%chunk
(#%adjust-va (#%lua-module))))))))
(define/match (compile-block _)
[((Block loc stmts))
(match (Lua->L1 stmts)
[(list)
(syntax/loc* loc (#%values))]
[stmts
(with-syntax ([(statement ...) (map compile-statement stmts)])
(syntax/loc* loc
(#%begin statement ...)))])])
(define/match (compile-statement e)
[((Assignment loc vars (list exprs ... (vararg vararg-expr))))
(with-syntax ([((attr-temp attr-exp) ...)
(vars->attr-temp&exprs vars)]
[((sub-lhs-temp sub-lhs-expr sub-rhs-temp sub-rhs-expr) ...)
(vars->sub-temp&exprs vars)]
[((temp var expr) ...)
(for/list ([idx (in-naturals)]
[var (in-list vars)]
[expr (in-list exprs)])
(list (format-id #f "#%temp~a" idx)
(compile-assignment-var var idx)
(compile-expr* expr)))]
[vararg-expr (compile-expr vararg-expr)]
[((va-temp va-var va-idx) ...)
(let ([start (min (length vars) (length exprs))])
(for/list ([tmp-idx (in-naturals start)]
[tbl-idx (in-naturals)]
[var (in-list (drop vars start))])
(list (format-id #f "#%temp~a" tmp-idx)
(compile-assignment-var var tmp-idx)
(add1 tbl-idx))))])
(syntax/loc* loc
(#%let
([attr-temp attr-exp]
...
[sub-lhs-temp sub-lhs-expr]
...
[sub-rhs-temp sub-rhs-expr]
...
[temp expr]
...
[#%t (#%apply #%table (#%adjust-va vararg-expr))])
(#%let
([va-temp (#%subscript #%t va-idx)] ...)
(#%set! var temp) ...
(#%set! va-var va-temp) ...))))]
[((Assignment loc vars exprs))
(let ([exprs (indexed exprs)])
(with-syntax ([((attr-temp attr-expr) ...)
(vars->attr-temp&exprs vars)]
[((sub-lhs-temp sub-lhs-expr sub-rhs-temp sub-rhs-expr) ...)
(vars->sub-temp&exprs vars)]
[((temp var expr) ...)
(for/list ([idx (in-naturals)]
[var (in-list vars)])
(define temp (format-id #f "#%temp~a" idx))
(define expr (hash-ref exprs idx 'nil))
(list temp
(compile-assignment-var var idx)
(compile-expr* expr)))])
(syntax/loc* loc
(#%let
([attr-temp attr-expr]
...
[sub-lhs-temp sub-lhs-expr]
...
[sub-rhs-temp sub-rhs-expr]
...
[temp expr]
...)
(#%set! var temp) ...))))]
[((Break loc))
(syntax/loc* loc
(#%break))]
[((or (? Call?)
(? CallMethod?)))
(compile-call e)]
[((Do loc block))
(with-syntax ([block (compile-block block)])
(syntax/loc* loc
(#%let () block)))]
[((For loc name init-expr limit-expr step-expr block))
(define break? (needs-break? block))
(with-syntax ([name (compile-expr name)]
[init-expr (compile-expr init-expr)]
[limit-expr (compile-expr limit-expr)]
[step-expr (compile-expr step-expr)]
[block (compile-block block)])
(with-syntax ([loop
(syntax/loc* loc
(#%let
([#%init init-expr]
[#%limit limit-expr]
[#%step step-expr])
(#%let #%for ([name #%init])
(#%when
(#%cond
[(< #%step 0) (>= name #%limit)]
[(> #%step 0) (<= name #%limit)]
[#%else (#%error "for: zero step")])
block
(#%for (+ name #%step))))))])
(if break?
(syntax/loc* loc (#%let/cc #%break loop))
(syntax/loc* loc loop))))]
[((ForIn loc names exprs block))
(define protect-stmt
(Protect
loc
(list
(While
loc #t
(Block
loc
(list*
(Assignment loc names (list (Call loc '#%iter '(#%state #%control))))
(Assignment loc '(#%control) (list (car names)))
(If loc
(Binop loc '== '#%control 'nil)
(Block loc (list (Break loc))) #f)
(Block-stmts block)))))
(list
(If loc
(Binop loc '~= '#%closing 'nil)
(Block loc (list (Call loc '#%closing null)))
#f))))
(compile-statement
(Let loc '(#%iter #%state #%control #%closing) exprs (list protect-stmt)))]
[((FuncDef loc (? list? names) params block))
(parameterize ([current-procedure-name (names->procedure-name names)])
(compile-statement
(Assignment loc
(list (names->subscripts loc names))
(list (Func loc params block)))))]
[((FuncDef loc name params block))
(parameterize ([current-procedure-name (compile-expr name)])
(compile-statement
(Assignment loc
(list name)
(list (Func loc params block)))))]
[((Goto loc (Name name-loc name)))
(with-syntax ([name (format-label-id name-loc name)])
(syntax/loc* loc
(name name)))]
[((If loc cond-expr then-block #f))
(with-syntax ([cond-expr (compile-expr* cond-expr)]
[then-block (compile-block then-block)])
(syntax/loc* loc
(#%when cond-expr then-block)))]
[((If loc cond-expr then-block (? If? elseif-block)))
(with-syntax ([cond-expr (compile-expr* cond-expr)]
[then-block (compile-block then-block)]
[else-block (compile-statement elseif-block)])
(syntax/loc* loc
(#%cond
[cond-expr then-block nil]
[#%else else-block nil])))]
[((If loc cond-expr then-block else-block))
(with-syntax ([cond-expr (compile-expr* cond-expr)]
[then-block (compile-block then-block)]
[else-block (compile-block else-block)])
(syntax/loc* loc
(#%cond
[cond-expr then-block nil]
[#%else else-block nil])))]
[((Label loc (Name name-loc name)))
(with-syntax ([name (format-label-id name-loc name)])
(syntax/loc* loc
(#%define name (#%call/cc #%values))))]
[((Let loc vars (list exprs ... (vararg vararg-expr)) stmts))
(with-syntax ([((temp var expr) ...)
(for/list ([idx (in-naturals)]
[var (in-list vars)]
[expr (in-list exprs)])
(list (format-id #f "#%temp~a" idx)
(compile-expr var)
(compile-expr* expr)))]
[vararg-expr (compile-expr vararg-expr)]
[((va-temp va-var va-idx) ...)
(let ([start (min (length vars) (length exprs))])
(for/list ([tmp-idx (in-naturals start)]
[tbl-idx (in-naturals)]
[var (in-list (drop vars start))])
(list (format-id #f "#%temp~a" tmp-idx)
(compile-expr var)
(add1 tbl-idx))))]
[(stmt ...) (maybe-void (map compile-statement stmts))])
(syntax/loc* loc
(#%let
([temp expr]
...
[#%t (#%apply #%table (#%adjust-va vararg-expr))])
(#%let
([va-temp (#%subscript #%t va-idx)] ...)
(#%let
([var temp]
...
[va-var va-temp]
...)
stmt ...)))))]
[((Let loc vars exprs stmts))
(let ([exprs (indexed exprs)])
(with-syntax ([((temp var expr) ...)
(for/list ([idx (in-naturals)]
[var (in-list vars)])
(define temp (format-id #f "#%temp~a" idx))
(define expr (hash-ref exprs idx 'nil))
(list temp
(compile-expr var)
(compile-expr* expr)))]
[(stmt ...) (maybe-void (map compile-statement stmts))])
(syntax/loc* loc
(#%let
([temp expr] ...)
(#%let
([var temp] ...)
stmt ...)))))]
[((LetFunction loc name params block stmts))
(with-syntax ([name (compile-expr name)]
[func-expr (compile-expr (Func loc params block))]
[(stmt ...) (maybe-void (map compile-statement stmts))])
(syntax/loc* loc
(#%letrec ([name func-expr])
stmt ...)))]
[((MethodDef loc names (Name _ attr) params block))
(parameterize ([current-procedure-name (names->method-name names attr)])
(compile-statement
(Assignment loc
(list (Subscript loc
(names->subscripts loc names)
(symbol->bytes attr)))
(list (Func loc (cons 'self params) block)))))]
[((Protect loc value-stmts post-stmts))
(with-syntax ([(value-stmt ...) (maybe-void (map compile-statement value-stmts))]
[(post-stmt ...) (maybe-void (map compile-statement post-stmts))])
(syntax/loc* loc
(#%dynamic-wind
#%void
(#%lambda () value-stmt ...)
(#%lambda () post-stmt ...))))]
[((Repeat loc cond-expr block))
(define break? (needs-break? block))
(with-syntax ([cond-expr (compile-expr cond-expr)]
[block (compile-block block)])
(with-syntax ([loop
(syntax/loc* loc
(#%let #%repeat ()
block
(#%unless cond-expr
(#%repeat))))])
(if break?
(syntax/loc* loc (#%let/cc #%break loop))
(syntax/loc* loc loop))))]
[((Return loc (list exprs ... (vararg vararg-expr))))
(with-syntax ([(expr ...) (map compile-expr* exprs)]
[vararg-expr (compile-expr vararg-expr)])
(syntax/loc* loc
(#%apply #%return expr ... (#%adjust-va vararg-expr))))]
[((Return loc exprs))
(with-syntax ([(expr ...) (map compile-expr* exprs)])
(syntax/loc* loc
(#%return expr ...)))]
[((While loc cond-expr block))
(define break? (needs-break? block))
(with-syntax ([cond-expr (compile-expr cond-expr)]
[block (compile-block block)])
(with-syntax ([loop
(syntax/loc* loc
(#%let #%while ()
(#%when cond-expr
block
(#%while))))])
(if break?
(syntax/loc* loc (#%let/cc #%break loop))
(syntax/loc* loc loop))))])
(define/match (compile-expr* e)
[((or (Call loc _ _)
(CallMethod loc _ _ _)))
(with-syntax ([expr (compile-expr e)])
(syntax/loc* loc
(#%adjust expr)))]
[(_)
(compile-expr e)])
(define/match (compile-expr e)
[((? boolean?)) (datum->syntax #f e)]
[((? number?)) (datum->syntax #f e)]
[((? bytes?)) (datum->syntax #f e)]
[((? symbol?)) (datum->syntax #f e)]
[((Attribute loc expr (Name _ name)))
(with-syntax ([expr (compile-expr* expr)]
[name (symbol->bytes name)])
(syntax/loc* loc
(#%subscript expr name)))]
[((Binop loc op lhs-expr rhs-expr))
(with-syntax ([binop (compile-expr op)]
[lhs-expr (compile-expr* lhs-expr)]
[rhs-expr (compile-expr* rhs-expr)])
(syntax/loc* loc
(binop lhs-expr rhs-expr)))]
[((or (? Call?) (? CallMethod?)))
(compile-call e)]
[((Func loc (list params ... '...) block))
(define return? (needs-return? block))
(with-syntax ([procedure-name (current-procedure-name)]
[(param ...) (map compile-expr params)]
[block (compile-block block)])
(with-syntax ([body (if return?
(syntax/loc* loc (#%let/cc #%return block (#%values)))
(syntax/loc* loc (#%begin block (#%values))))])
(syntax/loc* loc
(#%procedure-rename
(#%lambda ([param nil] ... . #%rest)
body)
procedure-name))))]
[((Func loc params block))
(define return? (needs-return? block))
(with-syntax ([procedure-name (current-procedure-name)]
[(param ...) (map compile-expr params)]
[block (compile-block block)])
(with-syntax ([body (if return?
(syntax/loc* loc (#%let/cc #%return block (#%values)))
(syntax/loc* loc (#%begin block (#%values))))])
(syntax/loc* loc
(#%procedure-rename
(#%lambda ([param nil] ... . #%unused-rest)
body)
procedure-name))))]
[((Name loc symbol))
(datum->syntax #f symbol loc (get-original-stx))]
[((Subscript loc expr field-expr))
(with-syntax ([expr (compile-expr* expr)]
[field-expr (compile-expr* field-expr)])
(syntax/loc* loc
(#%subscript expr field-expr)))]
[((Table loc (list field-exprs ... (Field _ (vararg vararg-expr)))))
(with-syntax ([(field-expr ...) (map compile-field field-exprs)]
[vararg-expr (compile-expr vararg-expr)])
(syntax/loc* loc
(#%apply #%table field-expr ... (#%adjust-va vararg-expr))))]
[((Table loc field-exprs))
(with-syntax ([(field-expr ...) (map compile-field field-exprs)])
(syntax/loc* loc
(#%table field-expr ...)))]
[((Unop loc op expr))
(with-syntax ([unop (compile-expr op)]
[expr (compile-expr* expr)])
(syntax/loc* loc
(unop expr)))])
(define/match (compile-call _e)
[((CallMethod loc target-expr (Name _ attr) arg-exprs))
(define subscript-expr (Subscript loc '#%instance (symbol->bytes attr)))
(with-syntax ([target-expr (compile-expr* target-expr)]
[call-expr (compile-expr (Call loc subscript-expr (cons '#%instance arg-exprs)))])
(syntax/loc* loc
(#%let ([#%instance target-expr]) call-expr)))]
[((Call loc rator-expr (list rand-exprs ... (vararg vararg-expr))))
(with-syntax ([rator-expr (compile-expr* rator-expr)]
[(rand-expr ...) (map compile-expr* rand-exprs)]
[vararg-expr (compile-expr vararg-expr)])
(syntax/loc* loc
(#%apply rator-expr rand-expr ... (#%adjust-va vararg-expr))))]
[((Call loc rator-expr rand-exprs))
(with-syntax ([rator-expr (compile-expr* rator-expr)]
[(rand-expr ...) (map compile-expr* rand-exprs)])
(syntax/loc* loc
(rator-expr rand-expr ...)))])
(define/match (compile-field _e)
[((Field loc expr))
(with-syntax ([expr (compile-expr* expr)])
(syntax/loc* loc
expr))]
[((FieldExpr loc field-expr value-expr))
(with-syntax ([field-expr (compile-expr* field-expr)]
[value-expr (compile-expr* value-expr)])
(syntax/loc* loc
(#%cons field-expr value-expr)))]
[((FieldLit loc (Name _ name) expr))
(with-syntax ([name (symbol->bytes name)]
[expr (compile-expr* expr)])
(syntax/loc* loc
(#%cons name expr)))])
;; passes ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Lua: The standard lua language.
;; L1: Removes Local{Assignment, Function}, adds Let
(define (Lua->L1 stmts)
(let loop ([res null]
[stmts stmts])
(match stmts
[(list)
(reverse res)]
[(cons (LocalAssignment loc names exprs) stmts)
(define node (Let loc names exprs (Lua->L1 stmts)))
(reverse (cons node res))]
[(cons (LocalFunction loc name params block) stmts)
(define node (LetFunction loc name params block (Lua->L1 stmts)))
(reverse (cons node res))]
[(cons stmt stmts)
(loop (cons stmt res) stmts)])))
;; help ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define-match-expander vararg
(lambda (stx)
(syntax-parse stx
[(_ e) #'(and (or (? Call?) (? CallMethod?) '#%rest) e)])))
(define symbol->bytes
(compose1 string->bytes/utf-8 symbol->string))
(define (format-label-id loc id)
(format-id #f "#%label:~a" id #:source loc))
(define (names->subscripts loc names)
(let loop ([target (car names)]
[names (cdr names)])
(cond
[(null? names) target]
[else
(define sub (Subscript loc target (symbol->bytes (Name-symbol (car names)))))
(loop sub (cdr names))])))
(define (indexed lst)
(for/hasheqv ([idx (in-naturals)]
[val (in-list lst)])
(values idx val)))
(define (vars->attr-temp&exprs vars)
(for/list ([idx (in-naturals)]
[var (in-list vars)]
#:when (Attribute? var))
(list (format-id #f "#%attr-temp~a" idx)
(compile-expr* (Attribute-e var)))))
(define (vars->sub-temp&exprs vars)
(for/list ([idx (in-naturals)]
[var (in-list vars)]
#:when (Subscript? var))
(list (format-id #f "#%sub-lhs-temp~a" idx)
(compile-expr* (Subscript-e var))
(format-id #f "#%sub-rhs-temp~a" idx)
(compile-expr* (Subscript-sub-e var)))))
(define (compile-assignment-var var idx)
(compile-expr
(match var
[(Attribute loc _ name)
(define temp (format-sym "#%attr-temp~a" idx))
(Attribute loc temp name)]
[(Subscript loc _ _)
(define lhs-temp (format-sym "#%sub-lhs-temp~a" idx))
(define rhs-temp (format-sym "#%sub-rhs-temp~a" idx))
(Subscript loc lhs-temp rhs-temp)]
[_
var])))
(define (format-sym fmt . args)
(string->symbol (apply format fmt args)))
(define (maybe-void stmts)
(if (null? stmts) '((#%void)) stmts))
(define ((make-statement-walker base-proc [enter-loops? #t]) e)
(let loop ([e e])
(match e
[(Block _ stmts)
(ormap loop stmts)]
[(Do _ block)
(loop block)]
[(For _ _ _ _ _ block)
#:when enter-loops?
(loop block)]
[(If _ _ then-block #f)
(loop then-block)]
[(If _ _ then-block else-block)
(or (loop then-block)
(loop else-block))]
[(Let _ _ _ stmts)
(ormap loop stmts)]
[(Repeat _ _ block)
#:when enter-loops?
(loop block)]
[(While _ _ block)
#:when enter-loops?
(loop block)]
[_
(base-proc e)])))
(define needs-break?
(make-statement-walker Break? #f))
(define needs-return?
(make-statement-walker Return?))
;; procedure names ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define current-procedure-name
(make-parameter 'anon))
(define (names->procedure-name names)
(string->symbol
(string-join
(for/list ([name (in-list names)])
(symbol->string (Name-symbol name)))
".")))
(define (names->method-name names attr)
(string->symbol (~a (names->procedure-name names) ":" attr)))
stxlocs ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ;
(define-syntax (syntax/loc* stx)
(syntax-parse stx
[(_ loc:expr form)
#'(replace-srcloc #'here loc #'form)]))
(define (replace-srcloc where-stx with-loc stx)
(cond
[(list? stx)
(for/list ([child-stx (in-list stx)])
(replace-srcloc where-stx with-loc child-stx))]
[(and (syntax? stx)
(equal? (syntax-source where-stx)
(syntax-source stx)))
(define content (replace-srcloc where-stx with-loc (syntax-e stx)))
(datum->syntax #f content with-loc stx)]
[else
stx]))
;; The 'original property on syntax is not preserved in compiled code.
;; This procedure works around that problem by calling `read-syntax'
;; at runtime for every newly-compiled module.
(define get-original-stx
(let ([stx #f])
(lambda ()
(unless stx
(set! stx (read-syntax "<compiler>" (open-input-string "id"))))
stx)))
| null | https://raw.githubusercontent.com/Bogdanp/racket-lua/cc3371948238d92d9d13dff1702391b79aa57886/lua-lib/lang/compiler.rkt | racket | passes ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Lua: The standard lua language.
L1: Removes Local{Assignment, Function}, adds Let
help ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
procedure names ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ;
The 'original property on syntax is not preserved in compiled code.
This procedure works around that problem by calling `read-syntax'
at runtime for every newly-compiled module. | #lang racket/base
(require (for-syntax racket/base
syntax/parse)
racket/format
racket/list
racket/match
racket/string
racket/syntax
"ast.rkt")
(provide
compile-chunk)
(define (compile-chunk chunk)
(define loc (Node-loc chunk))
(define return? (needs-return? chunk))
(with-syntax ([block (compile-block chunk)])
(with-syntax ([body (if return?
(syntax/loc* loc (#%let/cc #%return block (#%values)))
(syntax/loc* loc (#%begin block (#%values))))])
(syntax/loc* loc
((#%provide #%chunk)
(#%define _ENV (#%global))
(#%load-stdlib! _ENV)
(#%define (#%lua-module . #%rest)
body)
(#%define #%chunk
(#%adjust-va (#%lua-module))))))))
(define/match (compile-block _)
[((Block loc stmts))
(match (Lua->L1 stmts)
[(list)
(syntax/loc* loc (#%values))]
[stmts
(with-syntax ([(statement ...) (map compile-statement stmts)])
(syntax/loc* loc
(#%begin statement ...)))])])
(define/match (compile-statement e)
[((Assignment loc vars (list exprs ... (vararg vararg-expr))))
(with-syntax ([((attr-temp attr-exp) ...)
(vars->attr-temp&exprs vars)]
[((sub-lhs-temp sub-lhs-expr sub-rhs-temp sub-rhs-expr) ...)
(vars->sub-temp&exprs vars)]
[((temp var expr) ...)
(for/list ([idx (in-naturals)]
[var (in-list vars)]
[expr (in-list exprs)])
(list (format-id #f "#%temp~a" idx)
(compile-assignment-var var idx)
(compile-expr* expr)))]
[vararg-expr (compile-expr vararg-expr)]
[((va-temp va-var va-idx) ...)
(let ([start (min (length vars) (length exprs))])
(for/list ([tmp-idx (in-naturals start)]
[tbl-idx (in-naturals)]
[var (in-list (drop vars start))])
(list (format-id #f "#%temp~a" tmp-idx)
(compile-assignment-var var tmp-idx)
(add1 tbl-idx))))])
(syntax/loc* loc
(#%let
([attr-temp attr-exp]
...
[sub-lhs-temp sub-lhs-expr]
...
[sub-rhs-temp sub-rhs-expr]
...
[temp expr]
...
[#%t (#%apply #%table (#%adjust-va vararg-expr))])
(#%let
([va-temp (#%subscript #%t va-idx)] ...)
(#%set! var temp) ...
(#%set! va-var va-temp) ...))))]
[((Assignment loc vars exprs))
(let ([exprs (indexed exprs)])
(with-syntax ([((attr-temp attr-expr) ...)
(vars->attr-temp&exprs vars)]
[((sub-lhs-temp sub-lhs-expr sub-rhs-temp sub-rhs-expr) ...)
(vars->sub-temp&exprs vars)]
[((temp var expr) ...)
(for/list ([idx (in-naturals)]
[var (in-list vars)])
(define temp (format-id #f "#%temp~a" idx))
(define expr (hash-ref exprs idx 'nil))
(list temp
(compile-assignment-var var idx)
(compile-expr* expr)))])
(syntax/loc* loc
(#%let
([attr-temp attr-expr]
...
[sub-lhs-temp sub-lhs-expr]
...
[sub-rhs-temp sub-rhs-expr]
...
[temp expr]
...)
(#%set! var temp) ...))))]
[((Break loc))
(syntax/loc* loc
(#%break))]
[((or (? Call?)
(? CallMethod?)))
(compile-call e)]
[((Do loc block))
(with-syntax ([block (compile-block block)])
(syntax/loc* loc
(#%let () block)))]
[((For loc name init-expr limit-expr step-expr block))
(define break? (needs-break? block))
(with-syntax ([name (compile-expr name)]
[init-expr (compile-expr init-expr)]
[limit-expr (compile-expr limit-expr)]
[step-expr (compile-expr step-expr)]
[block (compile-block block)])
(with-syntax ([loop
(syntax/loc* loc
(#%let
([#%init init-expr]
[#%limit limit-expr]
[#%step step-expr])
(#%let #%for ([name #%init])
(#%when
(#%cond
[(< #%step 0) (>= name #%limit)]
[(> #%step 0) (<= name #%limit)]
[#%else (#%error "for: zero step")])
block
(#%for (+ name #%step))))))])
(if break?
(syntax/loc* loc (#%let/cc #%break loop))
(syntax/loc* loc loop))))]
[((ForIn loc names exprs block))
(define protect-stmt
(Protect
loc
(list
(While
loc #t
(Block
loc
(list*
(Assignment loc names (list (Call loc '#%iter '(#%state #%control))))
(Assignment loc '(#%control) (list (car names)))
(If loc
(Binop loc '== '#%control 'nil)
(Block loc (list (Break loc))) #f)
(Block-stmts block)))))
(list
(If loc
(Binop loc '~= '#%closing 'nil)
(Block loc (list (Call loc '#%closing null)))
#f))))
(compile-statement
(Let loc '(#%iter #%state #%control #%closing) exprs (list protect-stmt)))]
[((FuncDef loc (? list? names) params block))
(parameterize ([current-procedure-name (names->procedure-name names)])
(compile-statement
(Assignment loc
(list (names->subscripts loc names))
(list (Func loc params block)))))]
[((FuncDef loc name params block))
(parameterize ([current-procedure-name (compile-expr name)])
(compile-statement
(Assignment loc
(list name)
(list (Func loc params block)))))]
[((Goto loc (Name name-loc name)))
(with-syntax ([name (format-label-id name-loc name)])
(syntax/loc* loc
(name name)))]
[((If loc cond-expr then-block #f))
(with-syntax ([cond-expr (compile-expr* cond-expr)]
[then-block (compile-block then-block)])
(syntax/loc* loc
(#%when cond-expr then-block)))]
[((If loc cond-expr then-block (? If? elseif-block)))
(with-syntax ([cond-expr (compile-expr* cond-expr)]
[then-block (compile-block then-block)]
[else-block (compile-statement elseif-block)])
(syntax/loc* loc
(#%cond
[cond-expr then-block nil]
[#%else else-block nil])))]
[((If loc cond-expr then-block else-block))
(with-syntax ([cond-expr (compile-expr* cond-expr)]
[then-block (compile-block then-block)]
[else-block (compile-block else-block)])
(syntax/loc* loc
(#%cond
[cond-expr then-block nil]
[#%else else-block nil])))]
[((Label loc (Name name-loc name)))
(with-syntax ([name (format-label-id name-loc name)])
(syntax/loc* loc
(#%define name (#%call/cc #%values))))]
[((Let loc vars (list exprs ... (vararg vararg-expr)) stmts))
(with-syntax ([((temp var expr) ...)
(for/list ([idx (in-naturals)]
[var (in-list vars)]
[expr (in-list exprs)])
(list (format-id #f "#%temp~a" idx)
(compile-expr var)
(compile-expr* expr)))]
[vararg-expr (compile-expr vararg-expr)]
[((va-temp va-var va-idx) ...)
(let ([start (min (length vars) (length exprs))])
(for/list ([tmp-idx (in-naturals start)]
[tbl-idx (in-naturals)]
[var (in-list (drop vars start))])
(list (format-id #f "#%temp~a" tmp-idx)
(compile-expr var)
(add1 tbl-idx))))]
[(stmt ...) (maybe-void (map compile-statement stmts))])
(syntax/loc* loc
(#%let
([temp expr]
...
[#%t (#%apply #%table (#%adjust-va vararg-expr))])
(#%let
([va-temp (#%subscript #%t va-idx)] ...)
(#%let
([var temp]
...
[va-var va-temp]
...)
stmt ...)))))]
[((Let loc vars exprs stmts))
(let ([exprs (indexed exprs)])
(with-syntax ([((temp var expr) ...)
(for/list ([idx (in-naturals)]
[var (in-list vars)])
(define temp (format-id #f "#%temp~a" idx))
(define expr (hash-ref exprs idx 'nil))
(list temp
(compile-expr var)
(compile-expr* expr)))]
[(stmt ...) (maybe-void (map compile-statement stmts))])
(syntax/loc* loc
(#%let
([temp expr] ...)
(#%let
([var temp] ...)
stmt ...)))))]
[((LetFunction loc name params block stmts))
(with-syntax ([name (compile-expr name)]
[func-expr (compile-expr (Func loc params block))]
[(stmt ...) (maybe-void (map compile-statement stmts))])
(syntax/loc* loc
(#%letrec ([name func-expr])
stmt ...)))]
[((MethodDef loc names (Name _ attr) params block))
(parameterize ([current-procedure-name (names->method-name names attr)])
(compile-statement
(Assignment loc
(list (Subscript loc
(names->subscripts loc names)
(symbol->bytes attr)))
(list (Func loc (cons 'self params) block)))))]
[((Protect loc value-stmts post-stmts))
(with-syntax ([(value-stmt ...) (maybe-void (map compile-statement value-stmts))]
[(post-stmt ...) (maybe-void (map compile-statement post-stmts))])
(syntax/loc* loc
(#%dynamic-wind
#%void
(#%lambda () value-stmt ...)
(#%lambda () post-stmt ...))))]
[((Repeat loc cond-expr block))
(define break? (needs-break? block))
(with-syntax ([cond-expr (compile-expr cond-expr)]
[block (compile-block block)])
(with-syntax ([loop
(syntax/loc* loc
(#%let #%repeat ()
block
(#%unless cond-expr
(#%repeat))))])
(if break?
(syntax/loc* loc (#%let/cc #%break loop))
(syntax/loc* loc loop))))]
[((Return loc (list exprs ... (vararg vararg-expr))))
(with-syntax ([(expr ...) (map compile-expr* exprs)]
[vararg-expr (compile-expr vararg-expr)])
(syntax/loc* loc
(#%apply #%return expr ... (#%adjust-va vararg-expr))))]
[((Return loc exprs))
(with-syntax ([(expr ...) (map compile-expr* exprs)])
(syntax/loc* loc
(#%return expr ...)))]
[((While loc cond-expr block))
(define break? (needs-break? block))
(with-syntax ([cond-expr (compile-expr cond-expr)]
[block (compile-block block)])
(with-syntax ([loop
(syntax/loc* loc
(#%let #%while ()
(#%when cond-expr
block
(#%while))))])
(if break?
(syntax/loc* loc (#%let/cc #%break loop))
(syntax/loc* loc loop))))])
(define/match (compile-expr* e)
[((or (Call loc _ _)
(CallMethod loc _ _ _)))
(with-syntax ([expr (compile-expr e)])
(syntax/loc* loc
(#%adjust expr)))]
[(_)
(compile-expr e)])
(define/match (compile-expr e)
[((? boolean?)) (datum->syntax #f e)]
[((? number?)) (datum->syntax #f e)]
[((? bytes?)) (datum->syntax #f e)]
[((? symbol?)) (datum->syntax #f e)]
[((Attribute loc expr (Name _ name)))
(with-syntax ([expr (compile-expr* expr)]
[name (symbol->bytes name)])
(syntax/loc* loc
(#%subscript expr name)))]
[((Binop loc op lhs-expr rhs-expr))
(with-syntax ([binop (compile-expr op)]
[lhs-expr (compile-expr* lhs-expr)]
[rhs-expr (compile-expr* rhs-expr)])
(syntax/loc* loc
(binop lhs-expr rhs-expr)))]
[((or (? Call?) (? CallMethod?)))
(compile-call e)]
[((Func loc (list params ... '...) block))
(define return? (needs-return? block))
(with-syntax ([procedure-name (current-procedure-name)]
[(param ...) (map compile-expr params)]
[block (compile-block block)])
(with-syntax ([body (if return?
(syntax/loc* loc (#%let/cc #%return block (#%values)))
(syntax/loc* loc (#%begin block (#%values))))])
(syntax/loc* loc
(#%procedure-rename
(#%lambda ([param nil] ... . #%rest)
body)
procedure-name))))]
[((Func loc params block))
(define return? (needs-return? block))
(with-syntax ([procedure-name (current-procedure-name)]
[(param ...) (map compile-expr params)]
[block (compile-block block)])
(with-syntax ([body (if return?
(syntax/loc* loc (#%let/cc #%return block (#%values)))
(syntax/loc* loc (#%begin block (#%values))))])
(syntax/loc* loc
(#%procedure-rename
(#%lambda ([param nil] ... . #%unused-rest)
body)
procedure-name))))]
[((Name loc symbol))
(datum->syntax #f symbol loc (get-original-stx))]
[((Subscript loc expr field-expr))
(with-syntax ([expr (compile-expr* expr)]
[field-expr (compile-expr* field-expr)])
(syntax/loc* loc
(#%subscript expr field-expr)))]
[((Table loc (list field-exprs ... (Field _ (vararg vararg-expr)))))
(with-syntax ([(field-expr ...) (map compile-field field-exprs)]
[vararg-expr (compile-expr vararg-expr)])
(syntax/loc* loc
(#%apply #%table field-expr ... (#%adjust-va vararg-expr))))]
[((Table loc field-exprs))
(with-syntax ([(field-expr ...) (map compile-field field-exprs)])
(syntax/loc* loc
(#%table field-expr ...)))]
[((Unop loc op expr))
(with-syntax ([unop (compile-expr op)]
[expr (compile-expr* expr)])
(syntax/loc* loc
(unop expr)))])
(define/match (compile-call _e)
[((CallMethod loc target-expr (Name _ attr) arg-exprs))
(define subscript-expr (Subscript loc '#%instance (symbol->bytes attr)))
(with-syntax ([target-expr (compile-expr* target-expr)]
[call-expr (compile-expr (Call loc subscript-expr (cons '#%instance arg-exprs)))])
(syntax/loc* loc
(#%let ([#%instance target-expr]) call-expr)))]
[((Call loc rator-expr (list rand-exprs ... (vararg vararg-expr))))
(with-syntax ([rator-expr (compile-expr* rator-expr)]
[(rand-expr ...) (map compile-expr* rand-exprs)]
[vararg-expr (compile-expr vararg-expr)])
(syntax/loc* loc
(#%apply rator-expr rand-expr ... (#%adjust-va vararg-expr))))]
[((Call loc rator-expr rand-exprs))
(with-syntax ([rator-expr (compile-expr* rator-expr)]
[(rand-expr ...) (map compile-expr* rand-exprs)])
(syntax/loc* loc
(rator-expr rand-expr ...)))])
(define/match (compile-field _e)
[((Field loc expr))
(with-syntax ([expr (compile-expr* expr)])
(syntax/loc* loc
expr))]
[((FieldExpr loc field-expr value-expr))
(with-syntax ([field-expr (compile-expr* field-expr)]
[value-expr (compile-expr* value-expr)])
(syntax/loc* loc
(#%cons field-expr value-expr)))]
[((FieldLit loc (Name _ name) expr))
(with-syntax ([name (symbol->bytes name)]
[expr (compile-expr* expr)])
(syntax/loc* loc
(#%cons name expr)))])
(define (Lua->L1 stmts)
(let loop ([res null]
[stmts stmts])
(match stmts
[(list)
(reverse res)]
[(cons (LocalAssignment loc names exprs) stmts)
(define node (Let loc names exprs (Lua->L1 stmts)))
(reverse (cons node res))]
[(cons (LocalFunction loc name params block) stmts)
(define node (LetFunction loc name params block (Lua->L1 stmts)))
(reverse (cons node res))]
[(cons stmt stmts)
(loop (cons stmt res) stmts)])))
(define-match-expander vararg
(lambda (stx)
(syntax-parse stx
[(_ e) #'(and (or (? Call?) (? CallMethod?) '#%rest) e)])))
(define symbol->bytes
(compose1 string->bytes/utf-8 symbol->string))
(define (format-label-id loc id)
(format-id #f "#%label:~a" id #:source loc))
(define (names->subscripts loc names)
(let loop ([target (car names)]
[names (cdr names)])
(cond
[(null? names) target]
[else
(define sub (Subscript loc target (symbol->bytes (Name-symbol (car names)))))
(loop sub (cdr names))])))
(define (indexed lst)
(for/hasheqv ([idx (in-naturals)]
[val (in-list lst)])
(values idx val)))
(define (vars->attr-temp&exprs vars)
(for/list ([idx (in-naturals)]
[var (in-list vars)]
#:when (Attribute? var))
(list (format-id #f "#%attr-temp~a" idx)
(compile-expr* (Attribute-e var)))))
(define (vars->sub-temp&exprs vars)
(for/list ([idx (in-naturals)]
[var (in-list vars)]
#:when (Subscript? var))
(list (format-id #f "#%sub-lhs-temp~a" idx)
(compile-expr* (Subscript-e var))
(format-id #f "#%sub-rhs-temp~a" idx)
(compile-expr* (Subscript-sub-e var)))))
(define (compile-assignment-var var idx)
(compile-expr
(match var
[(Attribute loc _ name)
(define temp (format-sym "#%attr-temp~a" idx))
(Attribute loc temp name)]
[(Subscript loc _ _)
(define lhs-temp (format-sym "#%sub-lhs-temp~a" idx))
(define rhs-temp (format-sym "#%sub-rhs-temp~a" idx))
(Subscript loc lhs-temp rhs-temp)]
[_
var])))
(define (format-sym fmt . args)
(string->symbol (apply format fmt args)))
(define (maybe-void stmts)
(if (null? stmts) '((#%void)) stmts))
(define ((make-statement-walker base-proc [enter-loops? #t]) e)
(let loop ([e e])
(match e
[(Block _ stmts)
(ormap loop stmts)]
[(Do _ block)
(loop block)]
[(For _ _ _ _ _ block)
#:when enter-loops?
(loop block)]
[(If _ _ then-block #f)
(loop then-block)]
[(If _ _ then-block else-block)
(or (loop then-block)
(loop else-block))]
[(Let _ _ _ stmts)
(ormap loop stmts)]
[(Repeat _ _ block)
#:when enter-loops?
(loop block)]
[(While _ _ block)
#:when enter-loops?
(loop block)]
[_
(base-proc e)])))
(define needs-break?
(make-statement-walker Break? #f))
(define needs-return?
(make-statement-walker Return?))
(define current-procedure-name
(make-parameter 'anon))
(define (names->procedure-name names)
(string->symbol
(string-join
(for/list ([name (in-list names)])
(symbol->string (Name-symbol name)))
".")))
(define (names->method-name names attr)
(string->symbol (~a (names->procedure-name names) ":" attr)))
(define-syntax (syntax/loc* stx)
(syntax-parse stx
[(_ loc:expr form)
#'(replace-srcloc #'here loc #'form)]))
(define (replace-srcloc where-stx with-loc stx)
(cond
[(list? stx)
(for/list ([child-stx (in-list stx)])
(replace-srcloc where-stx with-loc child-stx))]
[(and (syntax? stx)
(equal? (syntax-source where-stx)
(syntax-source stx)))
(define content (replace-srcloc where-stx with-loc (syntax-e stx)))
(datum->syntax #f content with-loc stx)]
[else
stx]))
(define get-original-stx
(let ([stx #f])
(lambda ()
(unless stx
(set! stx (read-syntax "<compiler>" (open-input-string "id"))))
stx)))
|
ba2c04c09acccd7ffc0dee445ac7f638dc78113cc51a282dc667bcba9547791c | outergod/cl-m4 | m4-builtin.lisp | ;;;; cl-m4 - m4-builtin.lisp
Copyright ( C ) 2010 < >
This file is part of cl - m4 .
;;;; cl-m4 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.
;;;;
;;;; cl-m4 is distributed in the hope that it will be useful,
;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;;; GNU General Public License for more details.
;;;;
You should have received a copy of the GNU General Public License
;;;; along with this program. If not, see </>.
(in-package :cl-m4)
M4 builtin macros ahead .
;; internal functions
(defun pushm4macro (name fun &optional (replace t))
(let ((stack (gethash name *m4-runtime-lib*)))
(if stack
(if replace
(setf (aref stack (1- (fill-pointer stack))) fun)
(vector-push-extend fun stack))
(setf (gethash name *m4-runtime-lib*)
(make-array 1 :adjustable t :fill-pointer 1
:initial-contents
(list fun))))))
(defun popm4macro (name)
(let ((stack (gethash name *m4-runtime-lib*)))
(when stack
(if (> (fill-pointer stack) 1)
(vector-pop stack)
(remhash name *m4-runtime-lib*)))))
(defmacro defm4macro (name args (&key (arguments-only t) (minimum-arguments 0) (accept-macro-tokens nil)) &body body)
(let ((macro-name (gensym))
(macro-args (gensym))
(ignored-rest (gensym))
(internal-call (gensym)))
(flet ((transform-arguments (args)
(if accept-macro-tokens
args
`(mapcar #'(lambda (arg)
(if (stringp arg) arg ""))
,args))))
`(setf (gethash ,name *m4-lib*)
(make-array 1 :adjustable t :fill-pointer 1
:initial-contents
(list #'(lambda (,macro-name ,internal-call &rest ,macro-args)
(declare (ignore ,macro-name))
(cond ((eql :definition ,internal-call)
(concatenate 'string "<" ,name ">"))
((eql :expansion ,internal-call)
"")
((and ,arguments-only (not ,internal-call) (null ,macro-args)) ; most macros are only recognized with parameters
,name)
((< (length ,macro-args) ,minimum-arguments)
(m4-warn (format nil "too few arguments to builtin `~a'" ,name))
"")
(t ,(if (member '&rest args)
`(destructuring-bind ,args
,(transform-arguments macro-args)
,@body)
`(destructuring-bind (,@args &rest ,ignored-rest)
,(transform-arguments macro-args)
(when ,ignored-rest
(m4-warn (format nil "excess arguments to builtin `~a' ignored" ,name)))
,@body)))))))))))
(defun defm4runtimemacro (name expansion &optional (replace t))
(let ((fun (if (macro-token-p expansion)
(macro-token-m4macro expansion)
#'(lambda (macro-name internal-call &rest macro-args)
(if (find internal-call '(:definition :expansion))
expansion
(macro-return
(cl-ppcre:regex-replace-all "\\$(\\d+|#|\\*|@)" expansion
(replace-with-region
#'(lambda (match)
(cond ((string= "#" match)
(write-to-string (length macro-args)))
((string= "*" match)
(format nil "~{~a~^,~}" macro-args))
((string= "@" match)
(format nil
(concatenate 'string "~{" (m4-quote-string "~a") "~^,~}")
macro-args))
(t (let ((num (parse-integer match)))
(if (= 0 num)
macro-name
(or (nth (1- num) macro-args) ""))))))))))))))
(pushm4macro name fun replace)))
;; m4 macro implementations
(defm4macro "define" (name &optional (expansion "")) (:minimum-arguments 1 :accept-macro-tokens t)
(if (stringp name)
(prog1 ""
(when (string/= "" name)
(defm4runtimemacro name expansion)))
(prog1 "" (m4-warn "define: invalid macro name ignored"))))
(defm4macro "undefine" (&rest args) ()
(prog1 ""
(mapc #'(lambda (name)
(remhash name *m4-runtime-lib*))
args)))
(defm4macro "defn" (&rest args) ()
(cond ((= 0 (length args))
"")
((and (= 1 (length args))
(m4-macro (car args) t)) ; builtin macro
(signal 'macro-defn-invocation-condition
:macro (make-macro-token (m4-macro (car args) t) (car args))))
(t (macro-return
(apply #'concatenate 'string
(mapcar #'(lambda (name)
(let ((macro (m4-macro name)))
(if macro
(if (m4-macro name t)
(prog1 ""
(m4-warn (format nil "cannot concatenate builtin `~a'" name)))
(m4-quote-string (funcall macro name :expansion)))
"")))
args))))))
(defm4macro "pushdef" (name &optional (expansion "")) (:minimum-arguments 1)
(prog1 ""
(when (string/= "" name)
(defm4runtimemacro name expansion nil))))
(defm4macro "popdef" (&rest args) ()
(prog1 ""
(mapc #'popm4macro args)))
(defm4macro "indir" (name &rest args) (:minimum-arguments 1 :accept-macro-tokens t)
(if (stringp name)
(let ((macro (m4-macro name)))
(cond ((null macro)
(m4-warn (format nil "undefined macro `~a'" name))
"")
((null args)
(funcall macro name t))
(t (apply macro t name args))))
(prog1 "" (m4-warn "indir: invalid macro name ignored"))))
(defm4macro "builtin" (name &rest args) (:minimum-arguments 1 :accept-macro-tokens t)
(if (stringp name)
(let ((macro (m4-macro name t)))
(cond ((null macro)
(m4-warn (format nil "undefined builtin `~a'" name))
"")
((null args)
(funcall macro name t))
(t (apply macro name t args))))
(prog1 "" (m4-warn "builtin: invalid macro name ignored"))))
(defm4macro "ifdef" (name string-1 &optional (string-2 "")) (:minimum-arguments 2)
(macro-return
(if (m4-macro name)
string-1
string-2)))
(defm4macro "ifelse" (&rest args) ()
(labels ((ifelse (string-1 string-2 then &rest else)
(cond ((string= string-1 string-2)
(macro-return then))
((= 2 (list-length else))
(m4-warn "excess arguments to builtin `ifelse' ignored")
(macro-return (car else)))
((> (list-length else) 1)
(apply #'ifelse else))
(t (macro-return (car else))))))
(let ((num-args (list-length args)))
" Used with only one argument , the ifelse
; simply discards it and produces no output"
((= 2 num-args)
(m4-warn "too few arguments to builtin `ifelse'")
"")
((< num-args 5)
(ifelse (car args) (cadr args) (caddr args) (or (cadddr args) "")))
" If called with three or four arguments ... A final
fifth argument is ignored , after triggering a warning "
(m4-warn "excess arguments to builtin `ifelse' ignored")
(ifelse (car args) (cadr args) (caddr args) (cadddr args)))
(t (apply #'ifelse (car args) (cadr args) (caddr args) (cdddr args)))))))
(defm4macro "shift" (&rest args) ()
(macro-return (format nil (concatenate 'string "~{" (m4-quote-string "~a") "~^,~}") (cdr args))))
(defm4macro "dumpdef" (&rest args) (:arguments-only nil)
(prog1 ""
(dolist (name (sort (mapcar #'(lambda (name)
(let ((macro (m4-macro name)))
(if macro
(format nil "~a:~a~a" name #\tab (funcall macro name :definition))
(progn
(m4-warn (format nil "undefined macro `~a'" name))
""))))
(or args
(alexandria:hash-table-keys *m4-runtime-lib*)))
#'string<))
(format *error-output* "~a~%" name))))
TODO debugmode , debugfile
(defm4macro "traceon" (&rest args) (:arguments-only nil)
(prog1 "" (setq *m4-traced-macros* (append args *m4-traced-macros*))))
(defm4macro "traceoff" (&rest args) (:arguments-only nil)
(prog1 "" (setq *m4-traced-macros* (nset-difference *m4-traced-macros* args))))
(defm4macro "dnl" () (:arguments-only nil)
(signal 'macro-dnl-invocation-condition))
(defm4macro "changequote" (&optional (start "`") (end "'")) (:arguments-only nil)
(prog1 ""
(let ((end (if (string= "" end) "'" end)))
(setq *m4-quote-start* (quote-regexp start)
*m4-quote-end* (quote-regexp end)))))
(defm4macro "changecom" (&optional (start "") (end (string #\newline))) (:arguments-only nil)
(prog1 ""
(let ((end (if (string= "" end) (string #\newline) end)))
(setq *m4-comment-start* (quote-regexp start)
*m4-comment-end* (quote-regexp end)))))
(defm4macro "m4wrap" (&rest strings) (:minimum-arguments 1)
(prog1 ""
(push (format nil "~{~a~^ ~}" strings) *m4-wrap-stack*)))
(labels ((m4-include-file (file original-arg)
(cond ((or (string= "" original-arg)
(not (cl-fad:file-exists-p file)))
(format nil "cannot open `~a': No such file or directory" original-arg))
((cl-fad:directory-exists-p file)
(format nil "cannot open `~a': Is a directory" original-arg))
(t (handler-case (macro-return (with-open-file (stream file)
(let ((string (make-string (file-length stream))))
(read-sequence string stream)
string)))
(macro-invocation-condition (condition)
(signal condition))
(condition ()
(format nil "cannot open `~a': Permission denied" original-arg))))))
(m4-include (path warnfn)
(prog1 ""
(funcall warnfn
(if (eql :absolute (car (pathname-directory path)))
(m4-include-file path path)
(or (some #'(lambda (include-path)
(prog1 nil (m4-include-file (merge-pathnames path include-path) path)))
*m4-include-path*)
(m4-include-file (merge-pathnames path) path)))))))
(defm4macro "include" (file) (:minimum-arguments 1)
(m4-include file #'m4-warn))
(defm4macro "sinclude" (file) (:minimum-arguments 1)
(m4-include file #'identity))
(defm4macro "undivert" (&rest diversions) (:arguments-only nil)
(apply #'concatenate 'string
(if diversions
(mapcar #'(lambda (diversion)
(handler-case
(let ((parsed-number (if (string= "" diversion)
0 ; "Undiverting the empty string is the same as specifying diversion 0"
(parse-integer diversion :junk-allowed nil))))
(car (flush-m4-diversions parsed-number)))
(condition ()
(handler-case (m4-include diversion #'m4-warn)
(macro-invocation-condition (condition)
(macro-invocation-result condition))))))
diversions)
(flush-m4-diversions)))))
(defm4macro "divert" (&optional (number "0")) (:arguments-only nil)
(flet ((set-diversion (string)
(handler-case
(let ((parsed-number (parse-integer string :junk-allowed nil)))
(unless (minusp parsed-number)
(set-m4-diversion parsed-number))
(setq *m4-diversion* parsed-number))
(condition ()
(m4-warn "non-numeric argument to builtin `divert'")))))
(prog1 ""
(set-diversion (if (or (not (stringp number))
(string= "" number))
(prog1 "0" (m4-warn "empty string treated as 0 in builtin `divert'"))
number)))))
(defm4macro "divnum" () (:arguments-only nil)
(write-to-string *m4-diversion*)) ; What happens if changeword is enabled and integer-only macro
; names have been allowed??
(defm4macro "len" (string) (:minimum-arguments 1)
(write-to-string (length string)))
(defm4macro "index" (string &optional substring) (:minimum-arguments 1)
(if substring
(write-to-string (or (search substring string) -1))
(prog1 "0" (m4-warn "too few arguments to builtin `index'"))))
(defm4macro "regexp" (string &optional regexp replacement) (:minimum-arguments 1)
(if regexp
(with-regex-search-handler regexp
(multiple-value-bind (startpos registers)
(regex-search regexp string)
(if startpos
(if replacement
(let ((replace-result (m4-regex-replace replacement string registers)))
(macro-return (sanitize-m4-regex-replacement replace-result)))
(write-to-string startpos))
(if replacement "" "-1"))))
(prog1 "0" (m4-warn "too few arguments to builtin `regexp'"))))
(defm4macro "substr" (string &optional from length) (:minimum-arguments 1)
(if from
(flet ((string-or-0 (string)
(if (string= "" string)
(prog1 "0"
(m4-warn "empty string treated as 0 in builtin `substr'"))
string)))
(handler-case
(let* ((start (parse-integer (string-or-0 from) :junk-allowed nil))
(parsed-length (and length
(parse-integer (string-or-0 length) :junk-allowed nil)))
(end (if (or (not parsed-length)
(> (+ start parsed-length) (length string)))
(length string)
(+ start parsed-length))))
(if (< -1 start end)
(macro-return (subseq string start end))
""))
(macro-invocation-condition (condition)
(signal condition))
(condition ()
(m4-warn "non-numeric argument to builtin `substr'")
"")))
(progn
(m4-warn "too few arguments to builtin `substr'")
(macro-return string))))
(defm4macro "translit" (string &optional chars replacement) (:minimum-arguments 1)
(if chars
(macro-return (translate string chars replacement))
(progn
(m4-warn "too few arguments to builtin `translit'")
(macro-return string))))
(defm4macro "patsubst" (string &optional regexp (replacement "")) (:minimum-arguments 1)
(if regexp
(with-regex-search-handler regexp
(macro-return
(m4-regex-replace-all (sanitize-m4-regex-replacement replacement)
string (mapcar #'cdr (regex-search-all regexp string)))))
(prog1 string (m4-warn "too few arguments to builtin `patsubst'"))))
| null | https://raw.githubusercontent.com/outergod/cl-m4/9f6518b5a173a1234ae39ef45758927d329ded4a/src/m4-builtin.lisp | lisp | cl-m4 - m4-builtin.lisp
cl-m4 is free software; you can redistribute it and/or modify
either version 3 of the License , or
(at your option) any later version.
cl-m4 is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
along with this program. If not, see </>.
internal functions
most macros are only recognized with parameters
m4 macro implementations
builtin macro
simply discards it and produces no output"
"Undiverting the empty string is the same as specifying diversion 0"
What happens if changeword is enabled and integer-only macro
names have been allowed?? | Copyright ( C ) 2010 < >
This file is part of cl - m4 .
it under the terms of the GNU General Public License as published by
You should have received a copy of the GNU General Public License
(in-package :cl-m4)
M4 builtin macros ahead .
(defun pushm4macro (name fun &optional (replace t))
(let ((stack (gethash name *m4-runtime-lib*)))
(if stack
(if replace
(setf (aref stack (1- (fill-pointer stack))) fun)
(vector-push-extend fun stack))
(setf (gethash name *m4-runtime-lib*)
(make-array 1 :adjustable t :fill-pointer 1
:initial-contents
(list fun))))))
(defun popm4macro (name)
(let ((stack (gethash name *m4-runtime-lib*)))
(when stack
(if (> (fill-pointer stack) 1)
(vector-pop stack)
(remhash name *m4-runtime-lib*)))))
(defmacro defm4macro (name args (&key (arguments-only t) (minimum-arguments 0) (accept-macro-tokens nil)) &body body)
(let ((macro-name (gensym))
(macro-args (gensym))
(ignored-rest (gensym))
(internal-call (gensym)))
(flet ((transform-arguments (args)
(if accept-macro-tokens
args
`(mapcar #'(lambda (arg)
(if (stringp arg) arg ""))
,args))))
`(setf (gethash ,name *m4-lib*)
(make-array 1 :adjustable t :fill-pointer 1
:initial-contents
(list #'(lambda (,macro-name ,internal-call &rest ,macro-args)
(declare (ignore ,macro-name))
(cond ((eql :definition ,internal-call)
(concatenate 'string "<" ,name ">"))
((eql :expansion ,internal-call)
"")
,name)
((< (length ,macro-args) ,minimum-arguments)
(m4-warn (format nil "too few arguments to builtin `~a'" ,name))
"")
(t ,(if (member '&rest args)
`(destructuring-bind ,args
,(transform-arguments macro-args)
,@body)
`(destructuring-bind (,@args &rest ,ignored-rest)
,(transform-arguments macro-args)
(when ,ignored-rest
(m4-warn (format nil "excess arguments to builtin `~a' ignored" ,name)))
,@body)))))))))))
(defun defm4runtimemacro (name expansion &optional (replace t))
(let ((fun (if (macro-token-p expansion)
(macro-token-m4macro expansion)
#'(lambda (macro-name internal-call &rest macro-args)
(if (find internal-call '(:definition :expansion))
expansion
(macro-return
(cl-ppcre:regex-replace-all "\\$(\\d+|#|\\*|@)" expansion
(replace-with-region
#'(lambda (match)
(cond ((string= "#" match)
(write-to-string (length macro-args)))
((string= "*" match)
(format nil "~{~a~^,~}" macro-args))
((string= "@" match)
(format nil
(concatenate 'string "~{" (m4-quote-string "~a") "~^,~}")
macro-args))
(t (let ((num (parse-integer match)))
(if (= 0 num)
macro-name
(or (nth (1- num) macro-args) ""))))))))))))))
(pushm4macro name fun replace)))
(defm4macro "define" (name &optional (expansion "")) (:minimum-arguments 1 :accept-macro-tokens t)
(if (stringp name)
(prog1 ""
(when (string/= "" name)
(defm4runtimemacro name expansion)))
(prog1 "" (m4-warn "define: invalid macro name ignored"))))
(defm4macro "undefine" (&rest args) ()
(prog1 ""
(mapc #'(lambda (name)
(remhash name *m4-runtime-lib*))
args)))
(defm4macro "defn" (&rest args) ()
(cond ((= 0 (length args))
"")
((and (= 1 (length args))
(signal 'macro-defn-invocation-condition
:macro (make-macro-token (m4-macro (car args) t) (car args))))
(t (macro-return
(apply #'concatenate 'string
(mapcar #'(lambda (name)
(let ((macro (m4-macro name)))
(if macro
(if (m4-macro name t)
(prog1 ""
(m4-warn (format nil "cannot concatenate builtin `~a'" name)))
(m4-quote-string (funcall macro name :expansion)))
"")))
args))))))
(defm4macro "pushdef" (name &optional (expansion "")) (:minimum-arguments 1)
(prog1 ""
(when (string/= "" name)
(defm4runtimemacro name expansion nil))))
(defm4macro "popdef" (&rest args) ()
(prog1 ""
(mapc #'popm4macro args)))
(defm4macro "indir" (name &rest args) (:minimum-arguments 1 :accept-macro-tokens t)
(if (stringp name)
(let ((macro (m4-macro name)))
(cond ((null macro)
(m4-warn (format nil "undefined macro `~a'" name))
"")
((null args)
(funcall macro name t))
(t (apply macro t name args))))
(prog1 "" (m4-warn "indir: invalid macro name ignored"))))
(defm4macro "builtin" (name &rest args) (:minimum-arguments 1 :accept-macro-tokens t)
(if (stringp name)
(let ((macro (m4-macro name t)))
(cond ((null macro)
(m4-warn (format nil "undefined builtin `~a'" name))
"")
((null args)
(funcall macro name t))
(t (apply macro name t args))))
(prog1 "" (m4-warn "builtin: invalid macro name ignored"))))
(defm4macro "ifdef" (name string-1 &optional (string-2 "")) (:minimum-arguments 2)
(macro-return
(if (m4-macro name)
string-1
string-2)))
(defm4macro "ifelse" (&rest args) ()
(labels ((ifelse (string-1 string-2 then &rest else)
(cond ((string= string-1 string-2)
(macro-return then))
((= 2 (list-length else))
(m4-warn "excess arguments to builtin `ifelse' ignored")
(macro-return (car else)))
((> (list-length else) 1)
(apply #'ifelse else))
(t (macro-return (car else))))))
(let ((num-args (list-length args)))
" Used with only one argument , the ifelse
((= 2 num-args)
(m4-warn "too few arguments to builtin `ifelse'")
"")
((< num-args 5)
(ifelse (car args) (cadr args) (caddr args) (or (cadddr args) "")))
" If called with three or four arguments ... A final
fifth argument is ignored , after triggering a warning "
(m4-warn "excess arguments to builtin `ifelse' ignored")
(ifelse (car args) (cadr args) (caddr args) (cadddr args)))
(t (apply #'ifelse (car args) (cadr args) (caddr args) (cdddr args)))))))
(defm4macro "shift" (&rest args) ()
(macro-return (format nil (concatenate 'string "~{" (m4-quote-string "~a") "~^,~}") (cdr args))))
(defm4macro "dumpdef" (&rest args) (:arguments-only nil)
(prog1 ""
(dolist (name (sort (mapcar #'(lambda (name)
(let ((macro (m4-macro name)))
(if macro
(format nil "~a:~a~a" name #\tab (funcall macro name :definition))
(progn
(m4-warn (format nil "undefined macro `~a'" name))
""))))
(or args
(alexandria:hash-table-keys *m4-runtime-lib*)))
#'string<))
(format *error-output* "~a~%" name))))
TODO debugmode , debugfile
(defm4macro "traceon" (&rest args) (:arguments-only nil)
(prog1 "" (setq *m4-traced-macros* (append args *m4-traced-macros*))))
(defm4macro "traceoff" (&rest args) (:arguments-only nil)
(prog1 "" (setq *m4-traced-macros* (nset-difference *m4-traced-macros* args))))
(defm4macro "dnl" () (:arguments-only nil)
(signal 'macro-dnl-invocation-condition))
(defm4macro "changequote" (&optional (start "`") (end "'")) (:arguments-only nil)
(prog1 ""
(let ((end (if (string= "" end) "'" end)))
(setq *m4-quote-start* (quote-regexp start)
*m4-quote-end* (quote-regexp end)))))
(defm4macro "changecom" (&optional (start "") (end (string #\newline))) (:arguments-only nil)
(prog1 ""
(let ((end (if (string= "" end) (string #\newline) end)))
(setq *m4-comment-start* (quote-regexp start)
*m4-comment-end* (quote-regexp end)))))
(defm4macro "m4wrap" (&rest strings) (:minimum-arguments 1)
(prog1 ""
(push (format nil "~{~a~^ ~}" strings) *m4-wrap-stack*)))
(labels ((m4-include-file (file original-arg)
(cond ((or (string= "" original-arg)
(not (cl-fad:file-exists-p file)))
(format nil "cannot open `~a': No such file or directory" original-arg))
((cl-fad:directory-exists-p file)
(format nil "cannot open `~a': Is a directory" original-arg))
(t (handler-case (macro-return (with-open-file (stream file)
(let ((string (make-string (file-length stream))))
(read-sequence string stream)
string)))
(macro-invocation-condition (condition)
(signal condition))
(condition ()
(format nil "cannot open `~a': Permission denied" original-arg))))))
(m4-include (path warnfn)
(prog1 ""
(funcall warnfn
(if (eql :absolute (car (pathname-directory path)))
(m4-include-file path path)
(or (some #'(lambda (include-path)
(prog1 nil (m4-include-file (merge-pathnames path include-path) path)))
*m4-include-path*)
(m4-include-file (merge-pathnames path) path)))))))
(defm4macro "include" (file) (:minimum-arguments 1)
(m4-include file #'m4-warn))
(defm4macro "sinclude" (file) (:minimum-arguments 1)
(m4-include file #'identity))
(defm4macro "undivert" (&rest diversions) (:arguments-only nil)
(apply #'concatenate 'string
(if diversions
(mapcar #'(lambda (diversion)
(handler-case
(let ((parsed-number (if (string= "" diversion)
(parse-integer diversion :junk-allowed nil))))
(car (flush-m4-diversions parsed-number)))
(condition ()
(handler-case (m4-include diversion #'m4-warn)
(macro-invocation-condition (condition)
(macro-invocation-result condition))))))
diversions)
(flush-m4-diversions)))))
(defm4macro "divert" (&optional (number "0")) (:arguments-only nil)
(flet ((set-diversion (string)
(handler-case
(let ((parsed-number (parse-integer string :junk-allowed nil)))
(unless (minusp parsed-number)
(set-m4-diversion parsed-number))
(setq *m4-diversion* parsed-number))
(condition ()
(m4-warn "non-numeric argument to builtin `divert'")))))
(prog1 ""
(set-diversion (if (or (not (stringp number))
(string= "" number))
(prog1 "0" (m4-warn "empty string treated as 0 in builtin `divert'"))
number)))))
(defm4macro "divnum" () (:arguments-only nil)
(defm4macro "len" (string) (:minimum-arguments 1)
(write-to-string (length string)))
(defm4macro "index" (string &optional substring) (:minimum-arguments 1)
(if substring
(write-to-string (or (search substring string) -1))
(prog1 "0" (m4-warn "too few arguments to builtin `index'"))))
(defm4macro "regexp" (string &optional regexp replacement) (:minimum-arguments 1)
(if regexp
(with-regex-search-handler regexp
(multiple-value-bind (startpos registers)
(regex-search regexp string)
(if startpos
(if replacement
(let ((replace-result (m4-regex-replace replacement string registers)))
(macro-return (sanitize-m4-regex-replacement replace-result)))
(write-to-string startpos))
(if replacement "" "-1"))))
(prog1 "0" (m4-warn "too few arguments to builtin `regexp'"))))
(defm4macro "substr" (string &optional from length) (:minimum-arguments 1)
(if from
(flet ((string-or-0 (string)
(if (string= "" string)
(prog1 "0"
(m4-warn "empty string treated as 0 in builtin `substr'"))
string)))
(handler-case
(let* ((start (parse-integer (string-or-0 from) :junk-allowed nil))
(parsed-length (and length
(parse-integer (string-or-0 length) :junk-allowed nil)))
(end (if (or (not parsed-length)
(> (+ start parsed-length) (length string)))
(length string)
(+ start parsed-length))))
(if (< -1 start end)
(macro-return (subseq string start end))
""))
(macro-invocation-condition (condition)
(signal condition))
(condition ()
(m4-warn "non-numeric argument to builtin `substr'")
"")))
(progn
(m4-warn "too few arguments to builtin `substr'")
(macro-return string))))
(defm4macro "translit" (string &optional chars replacement) (:minimum-arguments 1)
(if chars
(macro-return (translate string chars replacement))
(progn
(m4-warn "too few arguments to builtin `translit'")
(macro-return string))))
(defm4macro "patsubst" (string &optional regexp (replacement "")) (:minimum-arguments 1)
(if regexp
(with-regex-search-handler regexp
(macro-return
(m4-regex-replace-all (sanitize-m4-regex-replacement replacement)
string (mapcar #'cdr (regex-search-all regexp string)))))
(prog1 string (m4-warn "too few arguments to builtin `patsubst'"))))
|
52227f03ab93cc6fa970317b107132da67e040c0ef1858935f52b583797f9de1 | lambdaisland/kaocha | kaocha_integration.clj | (ns features.steps.kaocha-integration
^{:clojure.tools.namespace.repl/load false
:clojure.tools.namespace.repl/unload false}
(:require [clojure.edn :as edn]
[clojure.java.io :as io]
[clojure.java.shell :as shell]
[clojure.string :as str]
[clojure.test :as t :refer :all]
[kaocha.integration-helpers :refer :all]
[kaocha.output :as output]
[kaocha.shellwords :refer [shellwords]]
[lambdaisland.cucumber.dsl :refer :all]
[me.raynes.fs :as fs]))
(require 'kaocha.assertions)
(Given "a file named {string} with:" [m path contents]
(spit-file m path contents))
(def last-cpcache-dir (atom nil))
(When "I run `(.*)`" [m args]
(let [{:keys [config-file dir] :as m} (test-dir-setup m)]
(when-let [cache @last-cpcache-dir]
(let [target (join dir ".cpcache")]
(when-not (.isDirectory (io/file target))
(mkdir target)
(run! #(fs/copy % (io/file (join target (.getName %)))) (fs/glob cache "*")))))
(let [result (apply shell/sh (conj (shellwords args)
:dir dir))]
;; By default these are hidden unless the test fails
(when (seq (:out result))
(println (str dir) "$" args)
(println (str (output/colored :underline "stdout") ":\n" (:out result))))
(when (seq (:err result))
(println (str (output/colored :underline "stderr") ":\n" (:err result))))
(let [cpcache (io/file (join dir ".cpcache"))]
(when (.exists cpcache)
(reset! last-cpcache-dir cpcache)))
(merge m result))))
(Then "the exit-code is non-zero" [{:keys [exit] :as m}]
(is (not= "0" exit))
m)
(Then "the exit-code should be {int}" [{:keys [exit] :as m} code]
(is (= code (Integer. exit)))
m)
(Then "the output should contain:" [m output]
(is (substring? output (:out m)))
m)
(Then "stderr should contain:" [m output]
(is (substring? output (:err m)))
m)
(Then "the output should be" [m output]
(is (= (str/trim output) (str/trim (:out m))))
m)
(Then "the output should not contain" [m output]
(is (not (str/includes? (:out m) output)))
m)
(Then "the EDN output should contain:" [m output]
(let [actual (edn/read-string (:out m))
expected (edn/read-string output)]
(is (= (select-keys actual (keys expected)) expected)))
m)
(Then "stderr should contain" [m output]
(is (substring? output (:err m)))
m)
(Then "print output" [m]
(t/with-test-out
(println "----out---------------------------------------")
(println (:out m))
(println "----err---------------------------------------")
(println (:err m)))
m)
#_
(do
(require 'kaocha.repl)
(kaocha.repl/run :plugins.version-filter {:kaocha.plugin.capture-output/capture-output? false
}
))
| null | https://raw.githubusercontent.com/lambdaisland/kaocha/77334edf536a3b39b9fcc27e5b67e3011ee40a94/test/step_definitions/kaocha_integration.clj | clojure | By default these are hidden unless the test fails | (ns features.steps.kaocha-integration
^{:clojure.tools.namespace.repl/load false
:clojure.tools.namespace.repl/unload false}
(:require [clojure.edn :as edn]
[clojure.java.io :as io]
[clojure.java.shell :as shell]
[clojure.string :as str]
[clojure.test :as t :refer :all]
[kaocha.integration-helpers :refer :all]
[kaocha.output :as output]
[kaocha.shellwords :refer [shellwords]]
[lambdaisland.cucumber.dsl :refer :all]
[me.raynes.fs :as fs]))
(require 'kaocha.assertions)
(Given "a file named {string} with:" [m path contents]
(spit-file m path contents))
(def last-cpcache-dir (atom nil))
(When "I run `(.*)`" [m args]
(let [{:keys [config-file dir] :as m} (test-dir-setup m)]
(when-let [cache @last-cpcache-dir]
(let [target (join dir ".cpcache")]
(when-not (.isDirectory (io/file target))
(mkdir target)
(run! #(fs/copy % (io/file (join target (.getName %)))) (fs/glob cache "*")))))
(let [result (apply shell/sh (conj (shellwords args)
:dir dir))]
(when (seq (:out result))
(println (str dir) "$" args)
(println (str (output/colored :underline "stdout") ":\n" (:out result))))
(when (seq (:err result))
(println (str (output/colored :underline "stderr") ":\n" (:err result))))
(let [cpcache (io/file (join dir ".cpcache"))]
(when (.exists cpcache)
(reset! last-cpcache-dir cpcache)))
(merge m result))))
(Then "the exit-code is non-zero" [{:keys [exit] :as m}]
(is (not= "0" exit))
m)
(Then "the exit-code should be {int}" [{:keys [exit] :as m} code]
(is (= code (Integer. exit)))
m)
(Then "the output should contain:" [m output]
(is (substring? output (:out m)))
m)
(Then "stderr should contain:" [m output]
(is (substring? output (:err m)))
m)
(Then "the output should be" [m output]
(is (= (str/trim output) (str/trim (:out m))))
m)
(Then "the output should not contain" [m output]
(is (not (str/includes? (:out m) output)))
m)
(Then "the EDN output should contain:" [m output]
(let [actual (edn/read-string (:out m))
expected (edn/read-string output)]
(is (= (select-keys actual (keys expected)) expected)))
m)
(Then "stderr should contain" [m output]
(is (substring? output (:err m)))
m)
(Then "print output" [m]
(t/with-test-out
(println "----out---------------------------------------")
(println (:out m))
(println "----err---------------------------------------")
(println (:err m)))
m)
#_
(do
(require 'kaocha.repl)
(kaocha.repl/run :plugins.version-filter {:kaocha.plugin.capture-output/capture-output? false
}
))
|
6ede27f9ad91f1d6a495eee6a4db42665396777ea09e037305ec1b9e3fb416eb | kmi/irs | original-rdfs-ontology.lisp | Mode : Lisp ; Package :
(in-package "OCML")
(in-ontology rdfs-ontology)
Automatically translated from RDF file " freaky : rdf - files;rdfs.rdf "
at 13:46:49 , on 27/3/2003
(def-class RESOURCE ()
((Value )
(Isdefinedby
:type resource)
(Seealso
:type resource)
(Label
:type literal)
(Comment
:type literal)
))
(def-class LITERAL ()
())
(def-class CLASS ()
())
(def-class PROPERTY ()
((Range
:type class)
(Domain
:type class)
(Subpropertyof
:type property)
))
(def-class STATEMENT ()
((Object )
(Predicate
:type property)
(Subject
:type resource)
))
(def-class CONTAINER ()
((Member )
))
(def-class BAG ()
())
(def-class SEQ ()
())
(def-class ALT ()
())
(def-class CONTAINERMEMBERSHIPPROPERTY ()
())
(def-instance CLASS-CONTAINERMEMBERSHIPPROPERTY-AS-INSTANCE CLASS
((Isdefinedby "-schema#")
(Label "containermembershipproperty")
(Comment "the container membership properties, rdf:1, rdf:2, ..., all of which are sub-properties of 'member'.")
(Subclassof property)
(Subclassof resource)
))
(def-instance CLASS-ALT-AS-INSTANCE CLASS
((Isdefinedby "-rdf-syntax-ns#")
(Label "alt")
(Comment "a collection of alternatives.")
(Subclassof container)
(Subclassof resource)
))
(def-instance CLASS-SEQ-AS-INSTANCE CLASS
((Isdefinedby "-rdf-syntax-ns#")
(Label "seq")
(Comment "an ordered collection.")
(Subclassof container)
(Subclassof resource)
))
(def-instance CLASS-BAG-AS-INSTANCE CLASS
((Isdefinedby "-rdf-syntax-ns#")
(Label "bag")
(Comment "an unordered collection.")
(Subclassof container)
(Subclassof resource)
))
(def-instance CLASS-CONTAINER-AS-INSTANCE CLASS
((Isdefinedby "-schema#")
(Label "container")
(Subclassof resource)
(Comment "this represents the set containers.")
))
(def-instance CLASS-STATEMENT-AS-INSTANCE CLASS
((Isdefinedby "-rdf-syntax-ns#")
(Label "statement")
(Subclassof resource)
(Comment "the class of rdf statements.")
))
(def-instance CLASS-PROPERTY-AS-INSTANCE CLASS
((Isdefinedby "-rdf-syntax-ns#")
(Label "property")
(Comment "the concept of a property.")
(Subclassof resource)
))
(def-instance CLASS-CLASS-AS-INSTANCE CLASS
((Isdefinedby "-schema#")
(Label "class")
(Comment "the concept of class")
(Subclassof resource)
))
(def-instance CLASS-LITERAL-AS-INSTANCE CLASS
((Isdefinedby "-schema#")
(Label "literal")
(Comment "this represents the set of atomic values, eg. textual strings.")
))
(def-instance CLASS-RESOURCE-AS-INSTANCE CLASS
((Isdefinedby "-schema#")
(Label "resource")
(Comment "the class resource, everything.")
))
(def-relation TYPE (?x ?y)
)
(def-instance TYPE property
((Isdefinedby "-rdf-syntax-ns#")
(Label "type")
(Comment "indicates membership of a class")
(Range class)
(Domain resource)
))
(def-relation SUBCLASSOF (?x ?y)
)
(def-instance SUBCLASSOF property
((Isdefinedby "-schema#")
(Label "subclassof")
(Comment "indicates membership of a class")
(Range class)
(Domain class)
))
(def-relation SUBPROPERTYOF (?x ?y)
)
(def-instance SUBPROPERTYOF property
((Isdefinedby "-schema#")
(Label "subpropertyof")
(Comment "indicates specialization of properties")
(Range property)
(Domain property)
))
(def-relation COMMENT (?x ?y)
)
(def-instance COMMENT property
((Isdefinedby "-schema#")
(Label "comment")
(Comment "use this for descriptions")
(Domain resource)
(Range literal)
))
(def-relation LABEL (?x ?y)
)
(def-instance LABEL property
((Isdefinedby "-schema#")
(Label "label")
(Comment "provides a human-readable version of a resource name.")
(Domain resource)
(Range literal)
))
(def-relation DOMAIN (?x ?y)
)
(def-instance DOMAIN property
((Isdefinedby "-schema#")
(Label "domain")
(Comment "a domain class for a property type")
(Range class)
(Domain property)
))
(def-relation RANGE (?x ?y)
)
(def-instance RANGE property
((Isdefinedby "-schema#")
(Label "range")
(Comment "a range class for a property type")
(Range class)
(Domain property)
))
(def-relation SEEALSO (?x ?y)
)
(def-instance SEEALSO property
((Isdefinedby "-schema#")
(Label "seealso")
(Comment "a resource that provides information about the subject resource")
(Range resource)
(Domain resource)
))
(def-relation ISDEFINEDBY (?x ?y)
)
(def-instance ISDEFINEDBY property
((Isdefinedby "-schema#")
(Subpropertyof seealso)
(Label "isdefinedby")
(Comment "indicates the namespace of a resource")
(Range resource)
(Domain resource)
))
(def-relation SUBJECT (?x ?y)
)
(def-instance SUBJECT property
((Isdefinedby "-rdf-syntax-ns#")
(Label "subject")
(Comment "the subject of an rdf statement.")
(Domain statement)
(Range resource)
))
(def-relation PREDICATE (?x ?y)
)
(def-instance PREDICATE property
((Isdefinedby "-rdf-syntax-ns#")
(Label "predicate")
(Comment "the predicate of an rdf statement.")
(Domain statement)
(Range property)
))
(def-relation OBJECT (?x ?y)
)
(def-instance OBJECT property
((Isdefinedby "-rdf-syntax-ns#")
(Label "object")
(Comment "the object of an rdf statement.")
(Domain statement)
))
(def-relation MEMBER (?x ?y)
)
(def-instance MEMBER property
((Isdefinedby "-schema#")
(Label "member")
(Comment "a member of a container")
(Domain container)
))
(def-relation VALUE (?x ?y)
)
(def-instance VALUE property
((Isdefinedby "-rdf-syntax-ns#")
(Label "value")
(Comment "identifies the principal value (usually a string) of a property when the property value is a structured resource")
(Domain resource)
))
(def-instance "HTTP-SCHEMA#" resource
((Seealso //www.w3.org/2000/01/rdf-schema-more)
)) | null | https://raw.githubusercontent.com/kmi/irs/e1b8d696f61c6b6878c0e92d993ed549fee6e7dd/ontologies/domains/rdfs-ontology/original-rdfs-ontology.lisp | lisp | Package : |
(in-package "OCML")
(in-ontology rdfs-ontology)
Automatically translated from RDF file " freaky : rdf - files;rdfs.rdf "
at 13:46:49 , on 27/3/2003
(def-class RESOURCE ()
((Value )
(Isdefinedby
:type resource)
(Seealso
:type resource)
(Label
:type literal)
(Comment
:type literal)
))
(def-class LITERAL ()
())
(def-class CLASS ()
())
(def-class PROPERTY ()
((Range
:type class)
(Domain
:type class)
(Subpropertyof
:type property)
))
(def-class STATEMENT ()
((Object )
(Predicate
:type property)
(Subject
:type resource)
))
(def-class CONTAINER ()
((Member )
))
(def-class BAG ()
())
(def-class SEQ ()
())
(def-class ALT ()
())
(def-class CONTAINERMEMBERSHIPPROPERTY ()
())
(def-instance CLASS-CONTAINERMEMBERSHIPPROPERTY-AS-INSTANCE CLASS
((Isdefinedby "-schema#")
(Label "containermembershipproperty")
(Comment "the container membership properties, rdf:1, rdf:2, ..., all of which are sub-properties of 'member'.")
(Subclassof property)
(Subclassof resource)
))
(def-instance CLASS-ALT-AS-INSTANCE CLASS
((Isdefinedby "-rdf-syntax-ns#")
(Label "alt")
(Comment "a collection of alternatives.")
(Subclassof container)
(Subclassof resource)
))
(def-instance CLASS-SEQ-AS-INSTANCE CLASS
((Isdefinedby "-rdf-syntax-ns#")
(Label "seq")
(Comment "an ordered collection.")
(Subclassof container)
(Subclassof resource)
))
(def-instance CLASS-BAG-AS-INSTANCE CLASS
((Isdefinedby "-rdf-syntax-ns#")
(Label "bag")
(Comment "an unordered collection.")
(Subclassof container)
(Subclassof resource)
))
(def-instance CLASS-CONTAINER-AS-INSTANCE CLASS
((Isdefinedby "-schema#")
(Label "container")
(Subclassof resource)
(Comment "this represents the set containers.")
))
(def-instance CLASS-STATEMENT-AS-INSTANCE CLASS
((Isdefinedby "-rdf-syntax-ns#")
(Label "statement")
(Subclassof resource)
(Comment "the class of rdf statements.")
))
(def-instance CLASS-PROPERTY-AS-INSTANCE CLASS
((Isdefinedby "-rdf-syntax-ns#")
(Label "property")
(Comment "the concept of a property.")
(Subclassof resource)
))
(def-instance CLASS-CLASS-AS-INSTANCE CLASS
((Isdefinedby "-schema#")
(Label "class")
(Comment "the concept of class")
(Subclassof resource)
))
(def-instance CLASS-LITERAL-AS-INSTANCE CLASS
((Isdefinedby "-schema#")
(Label "literal")
(Comment "this represents the set of atomic values, eg. textual strings.")
))
(def-instance CLASS-RESOURCE-AS-INSTANCE CLASS
((Isdefinedby "-schema#")
(Label "resource")
(Comment "the class resource, everything.")
))
(def-relation TYPE (?x ?y)
)
(def-instance TYPE property
((Isdefinedby "-rdf-syntax-ns#")
(Label "type")
(Comment "indicates membership of a class")
(Range class)
(Domain resource)
))
(def-relation SUBCLASSOF (?x ?y)
)
(def-instance SUBCLASSOF property
((Isdefinedby "-schema#")
(Label "subclassof")
(Comment "indicates membership of a class")
(Range class)
(Domain class)
))
(def-relation SUBPROPERTYOF (?x ?y)
)
(def-instance SUBPROPERTYOF property
((Isdefinedby "-schema#")
(Label "subpropertyof")
(Comment "indicates specialization of properties")
(Range property)
(Domain property)
))
(def-relation COMMENT (?x ?y)
)
(def-instance COMMENT property
((Isdefinedby "-schema#")
(Label "comment")
(Comment "use this for descriptions")
(Domain resource)
(Range literal)
))
(def-relation LABEL (?x ?y)
)
(def-instance LABEL property
((Isdefinedby "-schema#")
(Label "label")
(Comment "provides a human-readable version of a resource name.")
(Domain resource)
(Range literal)
))
(def-relation DOMAIN (?x ?y)
)
(def-instance DOMAIN property
((Isdefinedby "-schema#")
(Label "domain")
(Comment "a domain class for a property type")
(Range class)
(Domain property)
))
(def-relation RANGE (?x ?y)
)
(def-instance RANGE property
((Isdefinedby "-schema#")
(Label "range")
(Comment "a range class for a property type")
(Range class)
(Domain property)
))
(def-relation SEEALSO (?x ?y)
)
(def-instance SEEALSO property
((Isdefinedby "-schema#")
(Label "seealso")
(Comment "a resource that provides information about the subject resource")
(Range resource)
(Domain resource)
))
(def-relation ISDEFINEDBY (?x ?y)
)
(def-instance ISDEFINEDBY property
((Isdefinedby "-schema#")
(Subpropertyof seealso)
(Label "isdefinedby")
(Comment "indicates the namespace of a resource")
(Range resource)
(Domain resource)
))
(def-relation SUBJECT (?x ?y)
)
(def-instance SUBJECT property
((Isdefinedby "-rdf-syntax-ns#")
(Label "subject")
(Comment "the subject of an rdf statement.")
(Domain statement)
(Range resource)
))
(def-relation PREDICATE (?x ?y)
)
(def-instance PREDICATE property
((Isdefinedby "-rdf-syntax-ns#")
(Label "predicate")
(Comment "the predicate of an rdf statement.")
(Domain statement)
(Range property)
))
(def-relation OBJECT (?x ?y)
)
(def-instance OBJECT property
((Isdefinedby "-rdf-syntax-ns#")
(Label "object")
(Comment "the object of an rdf statement.")
(Domain statement)
))
(def-relation MEMBER (?x ?y)
)
(def-instance MEMBER property
((Isdefinedby "-schema#")
(Label "member")
(Comment "a member of a container")
(Domain container)
))
(def-relation VALUE (?x ?y)
)
(def-instance VALUE property
((Isdefinedby "-rdf-syntax-ns#")
(Label "value")
(Comment "identifies the principal value (usually a string) of a property when the property value is a structured resource")
(Domain resource)
))
(def-instance "HTTP-SCHEMA#" resource
((Seealso //www.w3.org/2000/01/rdf-schema-more)
)) |
052fcea11b5bdad8f9d67d8fde78245c99061ecc87f6f401c958eb655bcc620f | B-Lang-org/bsc | SimPackage.hs | # LANGUAGE CPP #
module SimPackage(
-- types
SimSystem(..),
PackageMap,
InstModMap,
SimPackage(..),
DefMap,
AVInstMap,
MethodOrderMap,
SimSchedule(..),
SchedNode(..), getSchedNodeId,
DisjointRulesDB,
-- utilities
findPkg,
findSubPkg,
findDef,
findAVInst,
findMethodOrderSet,
findInstMod,
getSimPackageInputs,
getPortInfo,
exclRulesDBToDisjRulesDB
) where
#if defined(__GLASGOW_HASKELL__) && (__GLASGOW_HASKELL__ >= 804)
import Prelude hiding ((<>))
#endif
import Eval
import ErrorUtil(internalError)
import PPrint
import Id
import IdPrint
import VModInfo
import Wires
import Pragma
import ASyntax
import ASyntaxUtil
import AScheduleInfo
import ABinUtil(InstModMap,ABinMap)
import SimDomainInfo
import ForeignFunctions(ForeignFuncMap)
import Control.Monad(when)
import Data.List(groupBy)
import qualified Data.Map as M
import qualified Data.Set as S
-- import Debug.Trace
-- This is a map from AId to the ADef which defines the value for that AId
type DefMap = M.Map AId ADef
-- This is a map from AId of an instantiated submodule to its information
type AVInstMap = M.Map AId AVInst
-- map from submodule instance name to a set of pairs of method names
where the first method must execute before the second
( when executed sequentially for atomic execution in one action )
type MethodOrderMap = M.Map AId (S.Set (AId, AId))
map from package Ids to SimPackages
type PackageMap = M.Map Id SimPackage
data SimSystem =
SimSystem { ssys_packages :: PackageMap
, ssys_schedules :: [SimSchedule]
, ssys_top :: Id -- name of top package
, ssys_instmap :: InstModMap
, ssys_ffuncmap :: ForeignFuncMap
, ssys_filemap :: ABinMap
, ssys_default_clk :: Maybe String
, ssys_default_rst :: Maybe String
}
deriving (Show)
data SimPackage =
SimPackage { sp_name :: Id
, sp_is_wrapped :: Bool -- carryover
from ABin
from
, sp_size_params :: [AId] -- carryover
, sp_inputs :: [AAbstractInput] -- carryover
, sp_clock_domains :: [AClockDomain] -- carryover?
, sp_external_wires :: VWireInfo -- carryover?
, sp_reset_list :: [(ResetId, AReset)] -- carryover?
, sp_state_instances :: AVInstMap
-- inst and mod name of noinline functions as modules
, sp_noinline_instances :: [(String,String)]
, sp_method_order_map :: MethodOrderMap
, sp_local_defs :: DefMap
, sp_rules :: [ARule]
, sp_interface :: [AIFace]
, sp_schedule :: AScheduleInfo
, sp_pathinfo :: VPathInfo
Assign numbers to the gates in a module , for codegen
, sp_gate_map :: [AExpr] -- order is [0..]
-- if these are handled earlier, then not needed here:
, sp_schedule_pragmas :: [ASchedulePragma] -- carryover?
could include user - comments ( generated in RTL )
}
deriving (Show)
Trimmed version of ExclusiveRulesDB , to hold just the disjoint info
type DisjointRulesDB = M.Map ARuleId (S.Set ARuleId)
data SimSchedule = SimSchedule
{ ss_clock :: AClock
, ss_posedge :: Bool
, ss_schedule :: ASchedule
, ss_disjoint_rules_db :: DisjointRulesDB
, ss_sched_graph :: [(SchedNode, [SchedNode])]
, ss_sched_order :: [SchedNode]
, ss_domain_info_map :: DomainInfoMap
, ss_early_rules :: [ARuleId]
}
deriving (Show)
-- -----
instance PPrint SimSystem where
pPrint d _ ssys =
(text "SimSystem") $+$
text "-- Packages" $+$
pPrint d 0 (ssys_packages ssys) $+$
text "-- Schedules" $+$
pPrint d 0 (ssys_schedules ssys) $+$
text "-- Top module" $+$
ppId d (ssys_top ssys)
instance PPrint SimPackage where
pPrint d _ spkg =
(text "SimPackage" <+> ppId d (sp_name spkg) <>
if (sp_is_wrapped spkg) then text " -- function" else empty) $+$
text (sp_version spkg) $+$
text "-- SimPackage parameters" $+$
pPrint d 0 (sp_size_params spkg) $+$
text "-- SimPackage arguments" $+$
foldr ($+$) (text "") (map (pPrint d 0) (sp_inputs spkg)) $+$
text "-- SimPackage wire info" $+$
pPrint d 0 (sp_external_wires spkg) $+$
text "-- SimPackage clock domains" $+$
pPrint d 0 (sp_clock_domains spkg) $+$
text "-- SimPackage resets" $+$
pPrint d 0 (sp_reset_list spkg) $+$
text "-- SP state elements" $+$
foldr ($+$) (text "")
(map (pPrint d 0) (M.elems (sp_state_instances spkg))) $+$
text "-- SP noinline elements" $+$
foldr ($+$) (text "")
(map (pPrint d 0) (sp_noinline_instances spkg)) $+$
text "-- SP method order map" $+$
ppMethodOrderMap d (sp_method_order_map spkg) $+$
text "-- SP local definitions" $+$
foldr ($+$) (text "")
(map (pPrint d 0) (M.elems (sp_local_defs spkg))) $+$
text "-- SP rules" $+$
foldr ($+$) (text "") (map (pPrint d 0) (sp_rules spkg)) $+$
text "-- SP scheduling pragmas" $+$
pPrint d 0 (sp_schedule_pragmas spkg) $+$
text "-- SP interface" $+$
foldr ($+$) empty
[(text "-- SP sp_interface def" <+> pPrint d 0 (sp_name spkg)) $+$
pPrint d 0 i | i <- sp_interface spkg] $+$
text "-- SP schedule" $+$
pPrint d 0 (asi_schedule (sp_schedule spkg)) $+$
text "-- SP path info" $+$
pPrint d 0 (sp_pathinfo spkg) $+$
text "-- SP gate map" $+$
pPrint d 0 (sp_gate_map spkg)
ppMethodOrderMap :: PDetail -> MethodOrderMap -> Doc
ppMethodOrderMap d mmap =
let ppOneInst (i, mset) = ppId d i $+$
nest 4 (foldr ($+$) (text "")
(map (pPrint d 0) (S.toList mset)))
in foldr ($+$) (text "")
(map ppOneInst (M.toList mmap))
instance PPrint SimSchedule where
pPrint d _ simschedule =
let label = text "SimSchedule"
edge = text (if (ss_posedge simschedule)
then "posedge"
else "negedge")
domain = text (show (ss_clock simschedule))
in label $+$
(nest 2 ((text "-- clock") $+$
edge <+> domain $+$
(text "-- schedule") $+$
pPrint d 0 (ss_schedule simschedule) $+$
(text "-- seq graph") $+$
pPrint d 0 (ss_sched_graph simschedule) $+$
(text "-- seq order") $+$
pPrint d 0 (ss_sched_order simschedule) $+$
(text "-- domain info map") $+$
pPrint d 0 (ss_domain_info_map simschedule) $+$
(text "-- early rules") $+$
pPrint d 0 (ss_early_rules simschedule)
))
-- -----
instance Hyper SimSystem where
hyper ssim y = hyper3 (ssys_packages ssim)
(ssys_schedules ssim)
(ssys_top ssim)
y
instance Eq SimPackage where
sp1 == sp2 =
(
-- for the scheduleinfo, just check the schedule
(asi_schedule (sp_schedule sp1) ==
asi_schedule (sp_schedule sp2)) &&
-- for the rest, use equality
(sp_name sp1 == sp_name sp2) &&
(sp_is_wrapped sp1 == sp_is_wrapped sp2) &&
(sp_version sp1 == sp_version sp2) &&
(sp_size_params sp1 == sp_size_params sp2) &&
(sp_inputs sp1 == sp_inputs sp2) &&
(sp_clock_domains sp1 == sp_clock_domains sp2) &&
(sp_external_wires sp1 == sp_external_wires sp2) &&
(sp_reset_list sp1 == sp_reset_list sp2) &&
(sp_state_instances sp1 == sp_state_instances sp2) &&
(sp_noinline_instances sp1 == sp_noinline_instances sp2) &&
(sp_method_order_map sp1 == sp_method_order_map sp2) &&
(sp_local_defs sp1 == sp_local_defs sp2) &&
(sp_rules sp1 == sp_rules sp2) &&
(sp_interface sp1 == sp_interface sp2) &&
(sp_pathinfo sp1 == sp_pathinfo sp2) &&
(sp_gate_map sp1 == sp_gate_map sp2) &&
(sp_schedule_pragmas sp1 == sp_schedule_pragmas sp2)
)
instance Hyper SimPackage where
hyper spkg y = (spkg == spkg) `seq` y
instance Hyper SimSchedule where
hyper ssched y =
--- we only care about certain fields
(
(ss_clock ssched == ss_clock ssched)
&& (ss_posedge ssched == ss_posedge ssched)
&& (ss_schedule ssched == ss_schedule ssched)
&& (ss_sched_graph ssched == ss_sched_graph ssched)
&& (ss_sched_order ssched == ss_sched_order ssched)
&& (ss_domain_info_map ssched == ss_domain_info_map ssched)
&& (ss_early_rules ssched == ss_early_rules ssched)
) `seq` y
-- -----
instance (Ord a, AExprs b) => AExprs (M.Map a b) where
mapAExprs f m = let (ks,vs) = unzip (M.toList m)
vs' = mapAExprs f vs
in M.fromList (zip ks vs')
-- monadic
mapMAExprs f m =
do let (ks,vs) = unzip (M.toList m)
vs' <- mapMAExprs f vs
return $ M.fromList (zip ks vs')
-- find
findAExprs f m = findAExprs f (M.elems m)
instance AExprs SimPackage where
mapAExprs f pack = pack {
sp_interface = mapAExprs f (sp_interface pack),
sp_rules = mapAExprs f (sp_rules pack),
sp_state_instances = mapAExprs f (sp_state_instances pack),
sp_local_defs = mapAExprs f (sp_local_defs pack) }
-- monadic
mapMAExprs f pack@(SimPackage { sp_interface = ifc,
sp_rules = rs,
sp_state_instances = insts,
sp_local_defs = defs })
= do ifc' <- mapMAExprs f ifc
rs' <- mapMAExprs f rs
insts' <- mapMAExprs f insts
defs' <- mapMAExprs f defs
return (pack { sp_interface = ifc',
sp_rules = rs',
sp_state_instances = insts',
sp_local_defs = defs' })
-- find
findAExprs f pack =
findAExprs f (sp_interface pack) ++
findAExprs f (sp_rules pack) ++
findAExprs f (sp_state_instances pack) ++
findAExprs f (sp_local_defs pack)
-- -----
Utilities
findPkg :: PackageMap -> Id -> SimPackage
findPkg pkg_map id =
case M.lookup id pkg_map of
Just pkg -> pkg
Nothing -> internalError ("SimPackage.findPkg: cannot find " ++
ppReadable id)
findSubPkg :: SimSystem -> SimPackage -> AId -> Maybe SimPackage
findSubPkg ss parent path =
let segments = filter (/=".") $ groupBy (\x y -> x /= '.' && y /= '.') (getIdString path)
in findIt parent (map mk_homeless_id segments)
where findIt p [] = Just p
findIt p (x:xs) = let avi = findAVInst (sp_state_instances p) x
mod_name = vName_to_id (vName (avi_vmi avi))
sub = M.lookup mod_name (ssys_packages ss)
in case sub of
(Just s) -> findIt s xs
Nothing -> Nothing
findDef :: DefMap -> AId -> ADef
findDef def_map id =
case M.lookup id def_map of
Just def -> def
Nothing -> internalError ("SimPackage.findDef: cannot find " ++
ppReadable id)
findAVInst :: AVInstMap -> AId -> AVInst
findAVInst avinst_map id =
case M.lookup id avinst_map of
Just avi -> avi
Nothing -> internalError ("SimPackage.findAVInst: cannot find " ++
ppReadable id)
findMethodOrderSet :: MethodOrderMap -> AId -> S.Set (AId, AId)
findMethodOrderSet mmap id =
case M.lookup id mmap of
Just mset -> mset
Nothing -> internalError ("SimPackage.findMethodOrderSet: " ++
"cannot find " ++ ppReadable id)
findInstMod :: InstModMap -> String -> String
findInstMod inst_map inst =
case M.lookup inst inst_map of
Just mod -> mod
Nothing -> internalError ("SimPackage.findInstMod: cannot find " ++
ppReadable inst)
-- -----
-- XXX This wouldn't be needed if we called "getAPackageInputs" on
XXX the APackage and stored the result in SimPackage
getSimPackageInputs :: SimPackage -> [(AAbstractInput, VArgInfo)]
getSimPackageInputs spkg =
let
get the two fields
inputs = sp_inputs spkg
arginfos = wArgs (sp_external_wires spkg)
-- check that they are the same length
inputs_length = length (sp_inputs spkg)
arginfos_length = length arginfos
args_with_info = zip inputs arginfos
in
if (inputs_length /= arginfos_length)
then internalError ("getSimPackageInputs: " ++
"length inputs != length arginfos: " ++
ppReadable (inputs, arginfos))
else args_with_info
-- -----
getPortInfo :: [PProp] -> AIFace
-> Maybe (AId, (Maybe VName, [(AType,AId,VName)], Maybe (AType,VName), Bool, [AId]))
getPortInfo pps aif =
let name = aIfaceName aif
vfi = aif_fieldinfo aif
en = do e <- vf_enable vfi
-- always enabled implies enabled when ready
when (isEnWhenRdy pps name) (fail "no enable port")
return (fst e)
args = aIfaceArgs aif
ps = map fst (vf_inputs vfi)
ins = [ (t,i,vn) | ((i,t),vn) <- zip args ps ]
rt = aIfaceResType aif
ret = case (vf_output vfi) of
(Just (vn,_)) -> Just (rt,vn)
Nothing -> Nothing
isAction = case aif of
(AIAction {}) -> True
(AIActionValue {}) -> True
otherwise -> False
rules = map aRuleName (aIfaceRules aif)
in case vfi of
(Method {}) -> Just (name, (en, ins, ret, isAction, rules))
otherwise -> Nothing
-- -----
exclRulesDBToDisjRulesDB :: ExclusiveRulesDB -> DisjointRulesDB
exclRulesDBToDisjRulesDB (ExclusiveRulesDB emap) =
let e_edges = M.toList emap
convEdge (r,(ds,es)) = (r, ds)
d_edges = map convEdge e_edges
in M.fromList d_edges
-- -----
| null | https://raw.githubusercontent.com/B-Lang-org/bsc/bd141b505394edc5a4bdd3db442a9b0a8c101f0f/src/comp/SimPackage.hs | haskell | types
utilities
import Debug.Trace
This is a map from AId to the ADef which defines the value for that AId
This is a map from AId of an instantiated submodule to its information
map from submodule instance name to a set of pairs of method names
name of top package
carryover
carryover
carryover
carryover?
carryover?
carryover?
inst and mod name of noinline functions as modules
order is [0..]
if these are handled earlier, then not needed here:
carryover?
-----
-----
for the scheduleinfo, just check the schedule
for the rest, use equality
- we only care about certain fields
-----
monadic
find
monadic
find
-----
-----
XXX This wouldn't be needed if we called "getAPackageInputs" on
check that they are the same length
-----
always enabled implies enabled when ready
-----
----- | # LANGUAGE CPP #
module SimPackage(
SimSystem(..),
PackageMap,
InstModMap,
SimPackage(..),
DefMap,
AVInstMap,
MethodOrderMap,
SimSchedule(..),
SchedNode(..), getSchedNodeId,
DisjointRulesDB,
findPkg,
findSubPkg,
findDef,
findAVInst,
findMethodOrderSet,
findInstMod,
getSimPackageInputs,
getPortInfo,
exclRulesDBToDisjRulesDB
) where
#if defined(__GLASGOW_HASKELL__) && (__GLASGOW_HASKELL__ >= 804)
import Prelude hiding ((<>))
#endif
import Eval
import ErrorUtil(internalError)
import PPrint
import Id
import IdPrint
import VModInfo
import Wires
import Pragma
import ASyntax
import ASyntaxUtil
import AScheduleInfo
import ABinUtil(InstModMap,ABinMap)
import SimDomainInfo
import ForeignFunctions(ForeignFuncMap)
import Control.Monad(when)
import Data.List(groupBy)
import qualified Data.Map as M
import qualified Data.Set as S
type DefMap = M.Map AId ADef
type AVInstMap = M.Map AId AVInst
where the first method must execute before the second
( when executed sequentially for atomic execution in one action )
type MethodOrderMap = M.Map AId (S.Set (AId, AId))
map from package Ids to SimPackages
type PackageMap = M.Map Id SimPackage
data SimSystem =
SimSystem { ssys_packages :: PackageMap
, ssys_schedules :: [SimSchedule]
, ssys_instmap :: InstModMap
, ssys_ffuncmap :: ForeignFuncMap
, ssys_filemap :: ABinMap
, ssys_default_clk :: Maybe String
, ssys_default_rst :: Maybe String
}
deriving (Show)
data SimPackage =
SimPackage { sp_name :: Id
from ABin
from
, sp_state_instances :: AVInstMap
, sp_noinline_instances :: [(String,String)]
, sp_method_order_map :: MethodOrderMap
, sp_local_defs :: DefMap
, sp_rules :: [ARule]
, sp_interface :: [AIFace]
, sp_schedule :: AScheduleInfo
, sp_pathinfo :: VPathInfo
Assign numbers to the gates in a module , for codegen
could include user - comments ( generated in RTL )
}
deriving (Show)
Trimmed version of ExclusiveRulesDB , to hold just the disjoint info
type DisjointRulesDB = M.Map ARuleId (S.Set ARuleId)
data SimSchedule = SimSchedule
{ ss_clock :: AClock
, ss_posedge :: Bool
, ss_schedule :: ASchedule
, ss_disjoint_rules_db :: DisjointRulesDB
, ss_sched_graph :: [(SchedNode, [SchedNode])]
, ss_sched_order :: [SchedNode]
, ss_domain_info_map :: DomainInfoMap
, ss_early_rules :: [ARuleId]
}
deriving (Show)
instance PPrint SimSystem where
pPrint d _ ssys =
(text "SimSystem") $+$
text "-- Packages" $+$
pPrint d 0 (ssys_packages ssys) $+$
text "-- Schedules" $+$
pPrint d 0 (ssys_schedules ssys) $+$
text "-- Top module" $+$
ppId d (ssys_top ssys)
instance PPrint SimPackage where
pPrint d _ spkg =
(text "SimPackage" <+> ppId d (sp_name spkg) <>
if (sp_is_wrapped spkg) then text " -- function" else empty) $+$
text (sp_version spkg) $+$
text "-- SimPackage parameters" $+$
pPrint d 0 (sp_size_params spkg) $+$
text "-- SimPackage arguments" $+$
foldr ($+$) (text "") (map (pPrint d 0) (sp_inputs spkg)) $+$
text "-- SimPackage wire info" $+$
pPrint d 0 (sp_external_wires spkg) $+$
text "-- SimPackage clock domains" $+$
pPrint d 0 (sp_clock_domains spkg) $+$
text "-- SimPackage resets" $+$
pPrint d 0 (sp_reset_list spkg) $+$
text "-- SP state elements" $+$
foldr ($+$) (text "")
(map (pPrint d 0) (M.elems (sp_state_instances spkg))) $+$
text "-- SP noinline elements" $+$
foldr ($+$) (text "")
(map (pPrint d 0) (sp_noinline_instances spkg)) $+$
text "-- SP method order map" $+$
ppMethodOrderMap d (sp_method_order_map spkg) $+$
text "-- SP local definitions" $+$
foldr ($+$) (text "")
(map (pPrint d 0) (M.elems (sp_local_defs spkg))) $+$
text "-- SP rules" $+$
foldr ($+$) (text "") (map (pPrint d 0) (sp_rules spkg)) $+$
text "-- SP scheduling pragmas" $+$
pPrint d 0 (sp_schedule_pragmas spkg) $+$
text "-- SP interface" $+$
foldr ($+$) empty
[(text "-- SP sp_interface def" <+> pPrint d 0 (sp_name spkg)) $+$
pPrint d 0 i | i <- sp_interface spkg] $+$
text "-- SP schedule" $+$
pPrint d 0 (asi_schedule (sp_schedule spkg)) $+$
text "-- SP path info" $+$
pPrint d 0 (sp_pathinfo spkg) $+$
text "-- SP gate map" $+$
pPrint d 0 (sp_gate_map spkg)
ppMethodOrderMap :: PDetail -> MethodOrderMap -> Doc
ppMethodOrderMap d mmap =
let ppOneInst (i, mset) = ppId d i $+$
nest 4 (foldr ($+$) (text "")
(map (pPrint d 0) (S.toList mset)))
in foldr ($+$) (text "")
(map ppOneInst (M.toList mmap))
instance PPrint SimSchedule where
pPrint d _ simschedule =
let label = text "SimSchedule"
edge = text (if (ss_posedge simschedule)
then "posedge"
else "negedge")
domain = text (show (ss_clock simschedule))
in label $+$
(nest 2 ((text "-- clock") $+$
edge <+> domain $+$
(text "-- schedule") $+$
pPrint d 0 (ss_schedule simschedule) $+$
(text "-- seq graph") $+$
pPrint d 0 (ss_sched_graph simschedule) $+$
(text "-- seq order") $+$
pPrint d 0 (ss_sched_order simschedule) $+$
(text "-- domain info map") $+$
pPrint d 0 (ss_domain_info_map simschedule) $+$
(text "-- early rules") $+$
pPrint d 0 (ss_early_rules simschedule)
))
instance Hyper SimSystem where
hyper ssim y = hyper3 (ssys_packages ssim)
(ssys_schedules ssim)
(ssys_top ssim)
y
instance Eq SimPackage where
sp1 == sp2 =
(
(asi_schedule (sp_schedule sp1) ==
asi_schedule (sp_schedule sp2)) &&
(sp_name sp1 == sp_name sp2) &&
(sp_is_wrapped sp1 == sp_is_wrapped sp2) &&
(sp_version sp1 == sp_version sp2) &&
(sp_size_params sp1 == sp_size_params sp2) &&
(sp_inputs sp1 == sp_inputs sp2) &&
(sp_clock_domains sp1 == sp_clock_domains sp2) &&
(sp_external_wires sp1 == sp_external_wires sp2) &&
(sp_reset_list sp1 == sp_reset_list sp2) &&
(sp_state_instances sp1 == sp_state_instances sp2) &&
(sp_noinline_instances sp1 == sp_noinline_instances sp2) &&
(sp_method_order_map sp1 == sp_method_order_map sp2) &&
(sp_local_defs sp1 == sp_local_defs sp2) &&
(sp_rules sp1 == sp_rules sp2) &&
(sp_interface sp1 == sp_interface sp2) &&
(sp_pathinfo sp1 == sp_pathinfo sp2) &&
(sp_gate_map sp1 == sp_gate_map sp2) &&
(sp_schedule_pragmas sp1 == sp_schedule_pragmas sp2)
)
instance Hyper SimPackage where
hyper spkg y = (spkg == spkg) `seq` y
instance Hyper SimSchedule where
hyper ssched y =
(
(ss_clock ssched == ss_clock ssched)
&& (ss_posedge ssched == ss_posedge ssched)
&& (ss_schedule ssched == ss_schedule ssched)
&& (ss_sched_graph ssched == ss_sched_graph ssched)
&& (ss_sched_order ssched == ss_sched_order ssched)
&& (ss_domain_info_map ssched == ss_domain_info_map ssched)
&& (ss_early_rules ssched == ss_early_rules ssched)
) `seq` y
instance (Ord a, AExprs b) => AExprs (M.Map a b) where
mapAExprs f m = let (ks,vs) = unzip (M.toList m)
vs' = mapAExprs f vs
in M.fromList (zip ks vs')
mapMAExprs f m =
do let (ks,vs) = unzip (M.toList m)
vs' <- mapMAExprs f vs
return $ M.fromList (zip ks vs')
findAExprs f m = findAExprs f (M.elems m)
instance AExprs SimPackage where
mapAExprs f pack = pack {
sp_interface = mapAExprs f (sp_interface pack),
sp_rules = mapAExprs f (sp_rules pack),
sp_state_instances = mapAExprs f (sp_state_instances pack),
sp_local_defs = mapAExprs f (sp_local_defs pack) }
mapMAExprs f pack@(SimPackage { sp_interface = ifc,
sp_rules = rs,
sp_state_instances = insts,
sp_local_defs = defs })
= do ifc' <- mapMAExprs f ifc
rs' <- mapMAExprs f rs
insts' <- mapMAExprs f insts
defs' <- mapMAExprs f defs
return (pack { sp_interface = ifc',
sp_rules = rs',
sp_state_instances = insts',
sp_local_defs = defs' })
findAExprs f pack =
findAExprs f (sp_interface pack) ++
findAExprs f (sp_rules pack) ++
findAExprs f (sp_state_instances pack) ++
findAExprs f (sp_local_defs pack)
Utilities
findPkg :: PackageMap -> Id -> SimPackage
findPkg pkg_map id =
case M.lookup id pkg_map of
Just pkg -> pkg
Nothing -> internalError ("SimPackage.findPkg: cannot find " ++
ppReadable id)
findSubPkg :: SimSystem -> SimPackage -> AId -> Maybe SimPackage
findSubPkg ss parent path =
let segments = filter (/=".") $ groupBy (\x y -> x /= '.' && y /= '.') (getIdString path)
in findIt parent (map mk_homeless_id segments)
where findIt p [] = Just p
findIt p (x:xs) = let avi = findAVInst (sp_state_instances p) x
mod_name = vName_to_id (vName (avi_vmi avi))
sub = M.lookup mod_name (ssys_packages ss)
in case sub of
(Just s) -> findIt s xs
Nothing -> Nothing
findDef :: DefMap -> AId -> ADef
findDef def_map id =
case M.lookup id def_map of
Just def -> def
Nothing -> internalError ("SimPackage.findDef: cannot find " ++
ppReadable id)
findAVInst :: AVInstMap -> AId -> AVInst
findAVInst avinst_map id =
case M.lookup id avinst_map of
Just avi -> avi
Nothing -> internalError ("SimPackage.findAVInst: cannot find " ++
ppReadable id)
findMethodOrderSet :: MethodOrderMap -> AId -> S.Set (AId, AId)
findMethodOrderSet mmap id =
case M.lookup id mmap of
Just mset -> mset
Nothing -> internalError ("SimPackage.findMethodOrderSet: " ++
"cannot find " ++ ppReadable id)
findInstMod :: InstModMap -> String -> String
findInstMod inst_map inst =
case M.lookup inst inst_map of
Just mod -> mod
Nothing -> internalError ("SimPackage.findInstMod: cannot find " ++
ppReadable inst)
XXX the APackage and stored the result in SimPackage
getSimPackageInputs :: SimPackage -> [(AAbstractInput, VArgInfo)]
getSimPackageInputs spkg =
let
get the two fields
inputs = sp_inputs spkg
arginfos = wArgs (sp_external_wires spkg)
inputs_length = length (sp_inputs spkg)
arginfos_length = length arginfos
args_with_info = zip inputs arginfos
in
if (inputs_length /= arginfos_length)
then internalError ("getSimPackageInputs: " ++
"length inputs != length arginfos: " ++
ppReadable (inputs, arginfos))
else args_with_info
getPortInfo :: [PProp] -> AIFace
-> Maybe (AId, (Maybe VName, [(AType,AId,VName)], Maybe (AType,VName), Bool, [AId]))
getPortInfo pps aif =
let name = aIfaceName aif
vfi = aif_fieldinfo aif
en = do e <- vf_enable vfi
when (isEnWhenRdy pps name) (fail "no enable port")
return (fst e)
args = aIfaceArgs aif
ps = map fst (vf_inputs vfi)
ins = [ (t,i,vn) | ((i,t),vn) <- zip args ps ]
rt = aIfaceResType aif
ret = case (vf_output vfi) of
(Just (vn,_)) -> Just (rt,vn)
Nothing -> Nothing
isAction = case aif of
(AIAction {}) -> True
(AIActionValue {}) -> True
otherwise -> False
rules = map aRuleName (aIfaceRules aif)
in case vfi of
(Method {}) -> Just (name, (en, ins, ret, isAction, rules))
otherwise -> Nothing
exclRulesDBToDisjRulesDB :: ExclusiveRulesDB -> DisjointRulesDB
exclRulesDBToDisjRulesDB (ExclusiveRulesDB emap) =
let e_edges = M.toList emap
convEdge (r,(ds,es)) = (r, ds)
d_edges = map convEdge e_edges
in M.fromList d_edges
|
e38118624e21031b3c971618aba4bb19dac3b1be7080d61766b206a462e850b2 | AntidoteDB/gingko | ct_redirect_handler.erl | %% redirects log messages to ct:log
-module(ct_redirect_handler).
-include("gingko.hrl").
%% API
-export([log/2]).
log(LogEvent, _Config) ->
CtMaster = application:get_env(?GINGKO_APP_NAME, ct_master, undefined),
#{msg := Message} = LogEvent,
case Message of
{Msg, Format} -> _ = rpc:call(CtMaster, ct, log, [Msg, Format]);
_ -> _ = rpc:call(CtMaster, ct, log, ["~p", [Message]])
end.
| null | https://raw.githubusercontent.com/AntidoteDB/gingko/a965979aefb2868abcd0b3bf5ed1b5e4f9fdd163/test/utils/ct_redirect_handler.erl | erlang | redirects log messages to ct:log
API |
-module(ct_redirect_handler).
-include("gingko.hrl").
-export([log/2]).
log(LogEvent, _Config) ->
CtMaster = application:get_env(?GINGKO_APP_NAME, ct_master, undefined),
#{msg := Message} = LogEvent,
case Message of
{Msg, Format} -> _ = rpc:call(CtMaster, ct, log, [Msg, Format]);
_ -> _ = rpc:call(CtMaster, ct, log, ["~p", [Message]])
end.
|
07c25f23fa2db6dd9429d78fc2b55ddd36c6390a9c9b0482ea69115a52d193ac | hidaris/thinking-dumps | chap3.rkt | #lang racket/base
;; Load the J-Bob language:
(require "j-bob/j-bob-lang.rkt")
;; Load J-Bob, our little proof assistant:
(require "j-bob/j-bob.rkt")
;;; What's in a name?
(defun pair (x y)
(cons x (cons y '())))
(defun first-of (x)
(car x))
(defun second-of (x)
(car (cdr x)))
(dethm first-of-pair (a b) ; a claim of therom
(equal (first-of (pair a b)) a))
The Law of Defun ( initial )
;;; Given the non-recursive function
;;; (defun name (x1 ... xn) body),
;;; (name e1 ... en) = body where x1 is e1, ..., xn is en
(dethm second-of-pair (a b)
(equal (second-of (pair a b)) b))
(defun in-pair? (xs)
(if (equal (first-of xs) '?)
't
(equal (second-of xs) '?)))
(dethm in-first-of-pair (b)
(equal (in-pair? (pair '? b)) 't))
(dethm in-second-of-pair (a)
(equal (in-pair? (pair a '?)) 't))
;;; Insight: Skip Irrelevant Expressions
;;; Rewriting a claim to 't does not have to go in
;;; any particular order. Some parts of the expression
;;; might be skipped entirely. For example, if-same can
;;; simplify many if expressions to 't regardless of the
;;; if question.
| null | https://raw.githubusercontent.com/hidaris/thinking-dumps/3fceaf9e6195ab99c8315749814a7377ef8baf86/the-little-series/the-little-prover/chap3.rkt | racket | Load the J-Bob language:
Load J-Bob, our little proof assistant:
What's in a name?
a claim of therom
Given the non-recursive function
(defun name (x1 ... xn) body),
(name e1 ... en) = body where x1 is e1, ..., xn is en
Insight: Skip Irrelevant Expressions
Rewriting a claim to 't does not have to go in
any particular order. Some parts of the expression
might be skipped entirely. For example, if-same can
simplify many if expressions to 't regardless of the
if question. | #lang racket/base
(require "j-bob/j-bob-lang.rkt")
(require "j-bob/j-bob.rkt")
(defun pair (x y)
(cons x (cons y '())))
(defun first-of (x)
(car x))
(defun second-of (x)
(car (cdr x)))
(equal (first-of (pair a b)) a))
The Law of Defun ( initial )
(dethm second-of-pair (a b)
(equal (second-of (pair a b)) b))
(defun in-pair? (xs)
(if (equal (first-of xs) '?)
't
(equal (second-of xs) '?)))
(dethm in-first-of-pair (b)
(equal (in-pair? (pair '? b)) 't))
(dethm in-second-of-pair (a)
(equal (in-pair? (pair a '?)) 't))
|
d74198d97a715c453310f1ae6d561c105e14bbd84be04245fb0edf2d971e3982 | ermine/sulci | scheduler.mli |
* ( c ) 2005 - 2008
* (c) 2005-2008 Anastasia Gornostaeva
*)
type elt = {
mutable time : float;
repeat : unit -> float;
callback : unit -> unit;
mutable cancelled : bool;
}
module TimerOrdered : sig type t = elt val compare : elt -> elt -> int end
module TimerQueue :
sig
exception Empty
type 'a t =
'a Heapqueue.HeapQueue(TimerOrdered).t = {
mutable n : int;
a : TimerOrdered.t option array;
}
val is_empty : 'a t -> bool
val create : unit -> 'a t
val swap : 'a array -> int -> int -> unit
val lt : 'a t -> int -> int -> bool
val sift_down : 'a t -> int -> unit
val sift_up : 'a t -> int -> unit
val add : 'a t -> TimerOrdered.t -> unit
val remove : 'a t -> int -> unit
val peek : 'a t -> TimerOrdered.t
val take : 'a t -> TimerOrdered.t
end
type t = {
reader : Unix.file_descr;
writer : Unix.file_descr;
queue : elt TimerQueue.t;
mutex : Mutex.t;
mutable input_wrote : bool;
}
val create : unit -> t
val add_task : t -> (unit -> unit) -> float -> (unit -> float) -> elt
val run : t -> Thread.t
| null | https://raw.githubusercontent.com/ermine/sulci/3ee4bd609b01e2093a6d37bf74579728d0a93b70/libs/scheduler/scheduler.mli | ocaml |
* ( c ) 2005 - 2008
* (c) 2005-2008 Anastasia Gornostaeva
*)
type elt = {
mutable time : float;
repeat : unit -> float;
callback : unit -> unit;
mutable cancelled : bool;
}
module TimerOrdered : sig type t = elt val compare : elt -> elt -> int end
module TimerQueue :
sig
exception Empty
type 'a t =
'a Heapqueue.HeapQueue(TimerOrdered).t = {
mutable n : int;
a : TimerOrdered.t option array;
}
val is_empty : 'a t -> bool
val create : unit -> 'a t
val swap : 'a array -> int -> int -> unit
val lt : 'a t -> int -> int -> bool
val sift_down : 'a t -> int -> unit
val sift_up : 'a t -> int -> unit
val add : 'a t -> TimerOrdered.t -> unit
val remove : 'a t -> int -> unit
val peek : 'a t -> TimerOrdered.t
val take : 'a t -> TimerOrdered.t
end
type t = {
reader : Unix.file_descr;
writer : Unix.file_descr;
queue : elt TimerQueue.t;
mutex : Mutex.t;
mutable input_wrote : bool;
}
val create : unit -> t
val add_task : t -> (unit -> unit) -> float -> (unit -> float) -> elt
val run : t -> Thread.t
|
|
71b07d8b1e32f286cd2d7b737e555dc11856c0575a60ddc6770c5e623c9a3444 | mk270/archipelago | lexicon.ml |
Archipelago , a multi - user dungeon ( MUD ) server , by ( C ) 2009 - 2012
This programme is free software ; you may redistribute and/or modify
it under the terms of the GNU Affero General Public Licence as published by
the Free Software Foundation , either version 3 of said Licence , or
( at your option ) any later version .
Archipelago, a multi-user dungeon (MUD) server, by Martin Keegan
Copyright (C) 2009-2012 Martin Keegan
This programme is free software; you may redistribute and/or modify
it under the terms of the GNU Affero General Public Licence as published by
the Free Software Foundation, either version 3 of said Licence, or
(at your option) any later version.
*)
type verb_forms = {
vf_base : string;
vf_past_simple : string;
vf_past_participle : string;
vf_pres_3p : string;
vf_pres_participle : string;
}
let irregulars = [
("have", "has", "having", "had", "had");
("go", "goes", "going", "went", "gone");
("log", "logs", "logging", "logged", "logged");
("rise", "rises", "rising", "rose", "risen");
("fall", "falls", "falling", "fell", "fallen");
FIXME
("drop", "drops", "dropping", "dropped", "dropped");
]
# #
type verb_schemes =
| E
| IE
| EE
| S
| Sibilant
| VY
| Y
| VC
| VStrongC
| I
| O
| A
| U
type verb_schemes =
| E
| IE
| EE
| S
| Sibilant
| VY
| Y
| VC
| VStrongC
| I
| O
| A
| U
*)
# #
let matchers = [
( " ee " , EE ) ;
( " ie " , IE ) ;
( " e " , E ) ;
( " [ ^s]s " , S ) ;
( " \\(x\\|ch\\|sh\\|\\ss\\ ) " , ) ;
( " [ aeou]y " , ) ;
( " y " , Y ) ;
( " [ aeoiu][bcdfgjklmnptvz ] " , VC ) ;
( " [ aeoiu][hqrw ] " , VStrongC ) ;
( " i " , I ) ;
( " o " , O ) ;
( " a " , A ) ;
( " u " , U ) ;
]
let matchers = List.map ( fun ( pat , vs ) - > ( Str.regexp ( pat ^ " $ " ) , vs ) ) matchers
let matchers = [
("ee", EE);
("ie", IE);
("e", E);
("[^s]s", S);
("\\(x\\|ch\\|sh\\|\\ss\\)", Sibilant);
("[aeou]y", VY);
("y", Y);
("[aeoiu][bcdfgjklmnptvz]", VC);
("[aeoiu][hqrw]", VStrongC);
("i", I);
("o", O);
("a", A);
("u", U);
]
let matchers = List.map (fun (pat, vs) -> (Str.regexp (pat ^ "$"), vs)) matchers
*)
let verbs = Hashtbl.create 50
let make_verb base =
{
vf_base = base;
vf_past_simple = base ^ "ed";
vf_past_participle = base ^ "ed";
vf_pres_3p = base ^ "s";
vf_pres_participle = base ^ "ing";
}
let init () =
List.iter (
fun (base, pres3p, presp, pasts, pastp) ->
Hashtbl.replace verbs base {
vf_base = base;
vf_past_simple = pasts;
vf_past_participle = pastp;
vf_pres_3p = pres3p;
vf_pres_participle = presp;
}
) irregulars;
()
let fini () =
Hashtbl.clear verbs
let get_verb base =
try Hashtbl.find verbs base
with Not_found ->
let v = make_verb base in
Hashtbl.replace verbs base v;
v
let get_verb_base base =
let v = get_verb base in
v.vf_base
let get_verb_past_simple base =
let v = get_verb base in
v.vf_past_simple
let get_verb_past_participle base =
let v = get_verb base in
v.vf_past_participle
let get_verb_pres_participle base =
let v = get_verb base in
v.vf_pres_participle
let get_verb_pres_3p base =
let v = get_verb base in
v.vf_pres_3p
| null | https://raw.githubusercontent.com/mk270/archipelago/4241bdc994da6d846637bcc079051405ee905c9b/src/server/lexicon.ml | ocaml |
Archipelago , a multi - user dungeon ( MUD ) server , by ( C ) 2009 - 2012
This programme is free software ; you may redistribute and/or modify
it under the terms of the GNU Affero General Public Licence as published by
the Free Software Foundation , either version 3 of said Licence , or
( at your option ) any later version .
Archipelago, a multi-user dungeon (MUD) server, by Martin Keegan
Copyright (C) 2009-2012 Martin Keegan
This programme is free software; you may redistribute and/or modify
it under the terms of the GNU Affero General Public Licence as published by
the Free Software Foundation, either version 3 of said Licence, or
(at your option) any later version.
*)
type verb_forms = {
vf_base : string;
vf_past_simple : string;
vf_past_participle : string;
vf_pres_3p : string;
vf_pres_participle : string;
}
let irregulars = [
("have", "has", "having", "had", "had");
("go", "goes", "going", "went", "gone");
("log", "logs", "logging", "logged", "logged");
("rise", "rises", "rising", "rose", "risen");
("fall", "falls", "falling", "fell", "fallen");
FIXME
("drop", "drops", "dropping", "dropped", "dropped");
]
# #
type verb_schemes =
| E
| IE
| EE
| S
| Sibilant
| VY
| Y
| VC
| VStrongC
| I
| O
| A
| U
type verb_schemes =
| E
| IE
| EE
| S
| Sibilant
| VY
| Y
| VC
| VStrongC
| I
| O
| A
| U
*)
# #
let matchers = [
( " ee " , EE ) ;
( " ie " , IE ) ;
( " e " , E ) ;
( " [ ^s]s " , S ) ;
( " \\(x\\|ch\\|sh\\|\\ss\\ ) " , ) ;
( " [ aeou]y " , ) ;
( " y " , Y ) ;
( " [ aeoiu][bcdfgjklmnptvz ] " , VC ) ;
( " [ aeoiu][hqrw ] " , VStrongC ) ;
( " i " , I ) ;
( " o " , O ) ;
( " a " , A ) ;
( " u " , U ) ;
]
let matchers = List.map ( fun ( pat , vs ) - > ( Str.regexp ( pat ^ " $ " ) , vs ) ) matchers
let matchers = [
("ee", EE);
("ie", IE);
("e", E);
("[^s]s", S);
("\\(x\\|ch\\|sh\\|\\ss\\)", Sibilant);
("[aeou]y", VY);
("y", Y);
("[aeoiu][bcdfgjklmnptvz]", VC);
("[aeoiu][hqrw]", VStrongC);
("i", I);
("o", O);
("a", A);
("u", U);
]
let matchers = List.map (fun (pat, vs) -> (Str.regexp (pat ^ "$"), vs)) matchers
*)
let verbs = Hashtbl.create 50
let make_verb base =
{
vf_base = base;
vf_past_simple = base ^ "ed";
vf_past_participle = base ^ "ed";
vf_pres_3p = base ^ "s";
vf_pres_participle = base ^ "ing";
}
let init () =
List.iter (
fun (base, pres3p, presp, pasts, pastp) ->
Hashtbl.replace verbs base {
vf_base = base;
vf_past_simple = pasts;
vf_past_participle = pastp;
vf_pres_3p = pres3p;
vf_pres_participle = presp;
}
) irregulars;
()
let fini () =
Hashtbl.clear verbs
let get_verb base =
try Hashtbl.find verbs base
with Not_found ->
let v = make_verb base in
Hashtbl.replace verbs base v;
v
let get_verb_base base =
let v = get_verb base in
v.vf_base
let get_verb_past_simple base =
let v = get_verb base in
v.vf_past_simple
let get_verb_past_participle base =
let v = get_verb base in
v.vf_past_participle
let get_verb_pres_participle base =
let v = get_verb base in
v.vf_pres_participle
let get_verb_pres_3p base =
let v = get_verb base in
v.vf_pres_3p
|
|
72aa6377c37edb662ec17464fc2ffd75567a048b285e148626e748d743371d1e | nikita-volkov/rerebase | Strict.hs | module Control.Monad.Writer.Strict
(
module Rebase.Control.Monad.Writer.Strict
)
where
import Rebase.Control.Monad.Writer.Strict
| null | https://raw.githubusercontent.com/nikita-volkov/rerebase/25895e6d8b0c515c912c509ad8dd8868780a74b6/library/Control/Monad/Writer/Strict.hs | haskell | module Control.Monad.Writer.Strict
(
module Rebase.Control.Monad.Writer.Strict
)
where
import Rebase.Control.Monad.Writer.Strict
|
|
3d43c939a28394c3ceae4d0a474e0f8d1dd684d9e0cba21349efbfdbfc9a93b1 | quchen/generative-art | Billard.hs | module Geometry.Processes.Billard (
billard
) where
import Algebra.VectorSpace
import Control.Monad
import Data.List
import Data.Maybe
import Geometry.Core
| Shoot a ball , and record its trajectory as it is reflected off the
-- edges of a provided geometry.
--
-- <<docs/billard/3_lambda.svg>>
billard
:: [Line] -- ^ Geometry; typically involves the edges of a bounding polygon.
-> Line -- ^ Initial velocity vector of the ball. Only start and direction,
-- not length, are relevant for the algorithm.
-> [Vec2] -- ^ List of collision points. Finite iff the ball escapes the
-- geometry.
billard edges = go (const True)
where
-- The predicate is used to exclude the line just mirrored off of, otherwise
-- we get rays stuck in a single line due to numerical shenanigans. Note
-- that this is a valid use case for equality of Double (contained in
-- Line/Vec2). :-)
go :: (Line -> Bool) -> Line -> [Vec2]
go considerEdge ballVec@(Line ballStart _)
= let reflectionRays :: [(Line, Line)]
reflectionRays = do
edge <- edges
(Line _ reflectionEnd, incidentPoint, ty) <- maybeToList (reflection ballVec edge)
guard $ case ty of
IntersectionReal _ -> True
IntersectionVirtualInsideR _ -> True
_otherwise -> False
guard (incidentPoint `liesAheadOf` ballVec)
guard (considerEdge edge)
pure (edge, Line incidentPoint reflectionEnd)
in case reflectionRays of
[] -> let Line _ end = ballVec in [end]
_ ->
let (edgeReflectedOn, reflectionRay@(Line reflectionStart _))
= minimumBy
(\(_, Line p _) (_, Line q _) -> distanceFrom ballStart p q)
reflectionRays
in reflectionStart : go (/= edgeReflectedOn) reflectionRay
liesAheadOf :: Vec2 -> Line -> Bool
liesAheadOf point (Line rayStart rayEnd)
= dotProduct (point -. rayStart) (rayEnd -. rayStart) > 0
distanceFrom :: Vec2 -> Vec2 -> Vec2 -> Ordering
distanceFrom start p q
= let pDistance = lineLength (Line start p)
qDistance = lineLength (Line start q)
in compare pDistance qDistance
| null | https://raw.githubusercontent.com/quchen/generative-art/c2ea1b0bfc4128aed5fc5bc82002a63fa0d874e3/src/Geometry/Processes/Billard.hs | haskell | edges of a provided geometry.
<<docs/billard/3_lambda.svg>>
^ Geometry; typically involves the edges of a bounding polygon.
^ Initial velocity vector of the ball. Only start and direction,
not length, are relevant for the algorithm.
^ List of collision points. Finite iff the ball escapes the
geometry.
The predicate is used to exclude the line just mirrored off of, otherwise
we get rays stuck in a single line due to numerical shenanigans. Note
that this is a valid use case for equality of Double (contained in
Line/Vec2). :-) | module Geometry.Processes.Billard (
billard
) where
import Algebra.VectorSpace
import Control.Monad
import Data.List
import Data.Maybe
import Geometry.Core
| Shoot a ball , and record its trajectory as it is reflected off the
billard
billard edges = go (const True)
where
go :: (Line -> Bool) -> Line -> [Vec2]
go considerEdge ballVec@(Line ballStart _)
= let reflectionRays :: [(Line, Line)]
reflectionRays = do
edge <- edges
(Line _ reflectionEnd, incidentPoint, ty) <- maybeToList (reflection ballVec edge)
guard $ case ty of
IntersectionReal _ -> True
IntersectionVirtualInsideR _ -> True
_otherwise -> False
guard (incidentPoint `liesAheadOf` ballVec)
guard (considerEdge edge)
pure (edge, Line incidentPoint reflectionEnd)
in case reflectionRays of
[] -> let Line _ end = ballVec in [end]
_ ->
let (edgeReflectedOn, reflectionRay@(Line reflectionStart _))
= minimumBy
(\(_, Line p _) (_, Line q _) -> distanceFrom ballStart p q)
reflectionRays
in reflectionStart : go (/= edgeReflectedOn) reflectionRay
liesAheadOf :: Vec2 -> Line -> Bool
liesAheadOf point (Line rayStart rayEnd)
= dotProduct (point -. rayStart) (rayEnd -. rayStart) > 0
distanceFrom :: Vec2 -> Vec2 -> Vec2 -> Ordering
distanceFrom start p q
= let pDistance = lineLength (Line start p)
qDistance = lineLength (Line start q)
in compare pDistance qDistance
|
e8aafbb5b0d274e45bc6c5204177fbcf97660fcfe365b765e7bdf051f44d5ead | mbg/hoop | StateEnv.hs | # LANGUAGE FlexibleContexts #
module Language.Hoop.StateEnv where
--------------------------------------------------------------------------------
import Control.Monad.Except
import Data.Graph
import Data.List (intersperse)
import qualified Data.Map as M
import Language.Haskell.TH.Syntax
import Language.Hoop.StateDecl
import Language.Hoop.Pretty
--------------------------------------------------------------------------------
-- | Represents different errors that can arise during the construction of
-- a class graph.
data StateGraphError
= ClassNotFound String
| CyclicInheritance [String]
instance Show StateGraphError where
show (ClassNotFound cls) = "`" ++ cls ++ "' is not in scope."
show (CyclicInheritance cs) =
"The following state classes form a cyclic inheritance hierarchy: " ++
concat (intersperse ", " cs)
--------------------------------------------------------------------------------
type StateEnv = M.Map String StateDecl
ppStateEnv :: StateEnv -> String
ppStateEnv env = render $ vcat $ map (\(k,d) -> pp d) $ M.toList env
--------------------------------------------------------------------------------
-- | `preProcessMethods' @ds builds a method table from a list of decls that
-- make up an object class.
preProcessMethods : : [ Dec ] - > MethodTable
preProcessMethods ds = go emptyMethodTable ds
where
go tbl [ ] = tbl
go ( d@(SigD name ) : ds ) = go ( addMethodSig name d tbl ) ds
go ( d@(FunD name cs ) : ds ) = go ( addMethodDef name d tbl ) ds
go ( d@(ValD ( VarP name ) body wh ) : ds ) = go ( addMethodDef name d tbl ) ds
go ( d : ds ) = go tbl ds
preProcessMethods ds = go emptyMethodTable ds
where
go tbl [] = tbl
go tbl (d@(SigD name ty) : ds) = go (addMethodSig name d tbl) ds
go tbl (d@(FunD name cs) : ds) = go (addMethodDef name d tbl) ds
go tbl (d@(ValD (VarP name) body wh) : ds) = go (addMethodDef name d tbl) ds
go tbl (d : ds) = go tbl ds-}
-- | `inherit` @decl@ extracts the method table from @decl@ (the parent of
-- another state class) and marks all method table entries as inherited.
inherit :: StateDecl -> MethodTable
inherit StateDecl{..} = go stateMethods
where
go (MkMethodTable methods) =
MkMethodTable (M.mapWithKey transform methods)
if @n@ originated in the parent , we inherit it ( possibly abstract )
transform n (GenesisMethod a (Just d) mdef) = InheritedMethod a d mdef
if @n@ was overriden in the parent , we inherit it ( never abstract )
transform n (OverridenMethod dec def) = InheritedMethod False dec (Just def)
otherwise @n@ was inherited by the parent and we continue to inherit it
transform n d = d
-- | `buildMethodTable` @decl@ builds a method table for @decl@.
buildMethodTable :: StateDecl -> StateDecl
buildMethodTable s@StateDecl{..} =
s { stateMethods = checkMethodTable s (go initialTable stateBody) }
where
initialTable :: MethodTable
initialTable = case stateParent of
Just p -> inherit p
Nothing -> emptyMethodTable
go :: MethodTable -> [Dec] -> MethodTable
go tbl [] = tbl
-- is this a function signature?
go tbl (d@(SigD name ty) : ds)
| declByParent name s = error $
"Method typing for inherited method `" ++ nameBase name ++ "`"
| otherwise = go (addMethodSig name d tbl) ds
is this a function / value definition ( annoyingly : two different
-- constructors)
go tbl (d@(FunD name cs) : ds)
| declByParent name s = go (addOverride name d tbl) ds
| otherwise = go (addGenesisDef name d tbl) ds
go tbl (d@(ValD (VarP name) body wh) : ds)
| declByParent name s = go (addOverride name d tbl) ds
| otherwise = go (addGenesisDef name d tbl) ds
otherwise it is some type of definition we do n't care about ;
-- just ignore it
go tbl (d : ds) = go tbl ds
--------------------------------------------------------------------------------
-- | `checkMethodTable` @decl tbl@ performs sanity checks on @tbl@ for @decl@:
-- this function fails if @tbl@ contains abstract methods and @decl@ is not
-- marked as abstract
checkMethodTable :: StateDecl -> MethodTable -> MethodTable
checkMethodTable s tbl =
MkMethodTable $ M.mapWithKey check (methods tbl)
where check k v | abstractEntry v && not (isAbstractClass s) =
error $ "Abstract member `" ++ k ++
"` in non-abstract class `" ++
stateName s ++ "`"
| otherwise = v
--------------------------------------------------------------------------------
| ` buildStateGraph ` @env@ constructs a strongly - connected graph from @env@.
buildStateGraph :: StateEnv -> Except StateGraphError StateEnv
throwError . ClassNotFound . show . toGraph
go M.empty . stronglyConnCompR . toGraph
where
-- nothing more to add
go env [] = return env
-- we found a cyclic dependency group, raise an error
go env (CyclicSCC cs : ds) =
throwError $ CyclicInheritance [c | (_,c,_) <- cs]
-- we found an acyclic node without dependencies, so
-- we just construct the method table for it
go env (AcyclicSCC (dec,n,[]) : ds) =
go (M.insert n (buildMethodTable dec) env) ds
-- we found an acyclic node with dependencies, try to resolve
-- the parent or throw an error if it cannot be found
go env (AcyclicSCC (dec,n,[p]) : ds) = case M.lookup p env of
Nothing -> throwError (ClassNotFound p)
(Just pd) -> go (M.insert n (buildMethodTable dec') env) ds
where dec' = dec { stateParent = Just pd }
| ` toGraph ` @env@ turns into a suitable graph for the SCC algorithm .
toGraph :: StateEnv -> [(StateDecl, String, [String])]
toGraph = map (\(k,v) -> (v, k, dep v)) . M.toList
where
a state class either has zero dependencies if it is a base class ,
-- or exactly one dependency if it inherits from another class
dep StateDecl{ stateParentN = Nothing } = []
dep StateDecl{ stateParentN = Just p } = [p]
--------------------------------------------------------------------------------
| null | https://raw.githubusercontent.com/mbg/hoop/98a53bb1db66b06f9b5d3e5242eed336f908ad18/src/Language/Hoop/StateEnv.hs | haskell | ------------------------------------------------------------------------------
------------------------------------------------------------------------------
| Represents different errors that can arise during the construction of
a class graph.
------------------------------------------------------------------------------
------------------------------------------------------------------------------
| `preProcessMethods' @ds builds a method table from a list of decls that
make up an object class.
| `inherit` @decl@ extracts the method table from @decl@ (the parent of
another state class) and marks all method table entries as inherited.
| `buildMethodTable` @decl@ builds a method table for @decl@.
is this a function signature?
constructors)
just ignore it
------------------------------------------------------------------------------
| `checkMethodTable` @decl tbl@ performs sanity checks on @tbl@ for @decl@:
this function fails if @tbl@ contains abstract methods and @decl@ is not
marked as abstract
------------------------------------------------------------------------------
nothing more to add
we found a cyclic dependency group, raise an error
we found an acyclic node without dependencies, so
we just construct the method table for it
we found an acyclic node with dependencies, try to resolve
the parent or throw an error if it cannot be found
or exactly one dependency if it inherits from another class
------------------------------------------------------------------------------ | # LANGUAGE FlexibleContexts #
module Language.Hoop.StateEnv where
import Control.Monad.Except
import Data.Graph
import Data.List (intersperse)
import qualified Data.Map as M
import Language.Haskell.TH.Syntax
import Language.Hoop.StateDecl
import Language.Hoop.Pretty
data StateGraphError
= ClassNotFound String
| CyclicInheritance [String]
instance Show StateGraphError where
show (ClassNotFound cls) = "`" ++ cls ++ "' is not in scope."
show (CyclicInheritance cs) =
"The following state classes form a cyclic inheritance hierarchy: " ++
concat (intersperse ", " cs)
type StateEnv = M.Map String StateDecl
ppStateEnv :: StateEnv -> String
ppStateEnv env = render $ vcat $ map (\(k,d) -> pp d) $ M.toList env
preProcessMethods : : [ Dec ] - > MethodTable
preProcessMethods ds = go emptyMethodTable ds
where
go tbl [ ] = tbl
go ( d@(SigD name ) : ds ) = go ( addMethodSig name d tbl ) ds
go ( d@(FunD name cs ) : ds ) = go ( addMethodDef name d tbl ) ds
go ( d@(ValD ( VarP name ) body wh ) : ds ) = go ( addMethodDef name d tbl ) ds
go ( d : ds ) = go tbl ds
preProcessMethods ds = go emptyMethodTable ds
where
go tbl [] = tbl
go tbl (d@(SigD name ty) : ds) = go (addMethodSig name d tbl) ds
go tbl (d@(FunD name cs) : ds) = go (addMethodDef name d tbl) ds
go tbl (d@(ValD (VarP name) body wh) : ds) = go (addMethodDef name d tbl) ds
go tbl (d : ds) = go tbl ds-}
inherit :: StateDecl -> MethodTable
inherit StateDecl{..} = go stateMethods
where
go (MkMethodTable methods) =
MkMethodTable (M.mapWithKey transform methods)
if @n@ originated in the parent , we inherit it ( possibly abstract )
transform n (GenesisMethod a (Just d) mdef) = InheritedMethod a d mdef
if @n@ was overriden in the parent , we inherit it ( never abstract )
transform n (OverridenMethod dec def) = InheritedMethod False dec (Just def)
otherwise @n@ was inherited by the parent and we continue to inherit it
transform n d = d
buildMethodTable :: StateDecl -> StateDecl
buildMethodTable s@StateDecl{..} =
s { stateMethods = checkMethodTable s (go initialTable stateBody) }
where
initialTable :: MethodTable
initialTable = case stateParent of
Just p -> inherit p
Nothing -> emptyMethodTable
go :: MethodTable -> [Dec] -> MethodTable
go tbl [] = tbl
go tbl (d@(SigD name ty) : ds)
| declByParent name s = error $
"Method typing for inherited method `" ++ nameBase name ++ "`"
| otherwise = go (addMethodSig name d tbl) ds
is this a function / value definition ( annoyingly : two different
go tbl (d@(FunD name cs) : ds)
| declByParent name s = go (addOverride name d tbl) ds
| otherwise = go (addGenesisDef name d tbl) ds
go tbl (d@(ValD (VarP name) body wh) : ds)
| declByParent name s = go (addOverride name d tbl) ds
| otherwise = go (addGenesisDef name d tbl) ds
otherwise it is some type of definition we do n't care about ;
go tbl (d : ds) = go tbl ds
checkMethodTable :: StateDecl -> MethodTable -> MethodTable
checkMethodTable s tbl =
MkMethodTable $ M.mapWithKey check (methods tbl)
where check k v | abstractEntry v && not (isAbstractClass s) =
error $ "Abstract member `" ++ k ++
"` in non-abstract class `" ++
stateName s ++ "`"
| otherwise = v
| ` buildStateGraph ` @env@ constructs a strongly - connected graph from @env@.
buildStateGraph :: StateEnv -> Except StateGraphError StateEnv
throwError . ClassNotFound . show . toGraph
go M.empty . stronglyConnCompR . toGraph
where
go env [] = return env
go env (CyclicSCC cs : ds) =
throwError $ CyclicInheritance [c | (_,c,_) <- cs]
go env (AcyclicSCC (dec,n,[]) : ds) =
go (M.insert n (buildMethodTable dec) env) ds
go env (AcyclicSCC (dec,n,[p]) : ds) = case M.lookup p env of
Nothing -> throwError (ClassNotFound p)
(Just pd) -> go (M.insert n (buildMethodTable dec') env) ds
where dec' = dec { stateParent = Just pd }
| ` toGraph ` @env@ turns into a suitable graph for the SCC algorithm .
toGraph :: StateEnv -> [(StateDecl, String, [String])]
toGraph = map (\(k,v) -> (v, k, dep v)) . M.toList
where
a state class either has zero dependencies if it is a base class ,
dep StateDecl{ stateParentN = Nothing } = []
dep StateDecl{ stateParentN = Just p } = [p]
|
0d2128ed6a16d4e58ffbac30ed1fb407481599d57163f7615dfeed9d140d4bfe | status-im/status-electron | react.cljs | (ns cljsjs.react)
| null | https://raw.githubusercontent.com/status-im/status-electron/aad18c34c0ee0304071e984f21d5622735ec5bef/src_front/cljsjs/react.cljs | clojure | (ns cljsjs.react)
|
|
ee515a650df57e4d0573c301aeb62dd4c063f2f020a590ab2ed375c48ad55b2c | parof/wstat | ProgramPoints.hs | module SyntacticStructure.ProgramPoints (
getProgramPoints,
chooseWideningPoints) where
import Interfaces.AbstractStateDomain
import SyntacticStructure.ControlFlowGraph
import SyntacticStructure.WhileGrammar
import Tools.StateTransitions
import Tools.Utilities
import Tools.MonadicBuilder
getProgramPoints :: AbstractStateDomain d => ControlFlowGraph (d -> d) -> [Label]
getProgramPoints controlFlowGraph =
removeDuplicates $
[ initialLabel | (initialLabel, function, finalLabel) <- controlFlowGraph ] ++
[ finalLabel | (initialLabel, function, finalLabel) <- controlFlowGraph ]
-- choose the entry program point for each loop
chooseWideningPoints :: Stmt -> [Label]
chooseWideningPoints s =
let (ws, _) = applyST (chooseWideningPointsMonadic s) startingLabel in ws
chooseWideningPointsMonadic :: Stmt -> ST [Label]
chooseWideningPointsMonadic stmt = cfgBuilderWithArgs stmt chooseWideningPointsFactory id ()
chooseWideningPointsFactory :: CfgFactoryWithArgs [Label] ()
chooseWideningPointsFactory = [
ASSIGN emptyFunc,
ASSERT emptyFunc,
SKIP emptyFunc,
SEQ seqFunc,
IF ifFunc,
WHILE whileFunc
]
emptyFunc _ _ _ _ = []
seqFunc _ _ = (++)
ifFunc _ _ _ _ trueBlock _ _ falseBlock _ _ = trueBlock ++ falseBlock
whileFunc _ _ _ wideningPoint _ whileBody _ _ = wideningPoint:whileBody | null | https://raw.githubusercontent.com/parof/wstat/369cf5d1d92ef235049c29ad2f1cc6fd53747754/src/SyntacticStructure/ProgramPoints.hs | haskell | choose the entry program point for each loop | module SyntacticStructure.ProgramPoints (
getProgramPoints,
chooseWideningPoints) where
import Interfaces.AbstractStateDomain
import SyntacticStructure.ControlFlowGraph
import SyntacticStructure.WhileGrammar
import Tools.StateTransitions
import Tools.Utilities
import Tools.MonadicBuilder
getProgramPoints :: AbstractStateDomain d => ControlFlowGraph (d -> d) -> [Label]
getProgramPoints controlFlowGraph =
removeDuplicates $
[ initialLabel | (initialLabel, function, finalLabel) <- controlFlowGraph ] ++
[ finalLabel | (initialLabel, function, finalLabel) <- controlFlowGraph ]
chooseWideningPoints :: Stmt -> [Label]
chooseWideningPoints s =
let (ws, _) = applyST (chooseWideningPointsMonadic s) startingLabel in ws
chooseWideningPointsMonadic :: Stmt -> ST [Label]
chooseWideningPointsMonadic stmt = cfgBuilderWithArgs stmt chooseWideningPointsFactory id ()
chooseWideningPointsFactory :: CfgFactoryWithArgs [Label] ()
chooseWideningPointsFactory = [
ASSIGN emptyFunc,
ASSERT emptyFunc,
SKIP emptyFunc,
SEQ seqFunc,
IF ifFunc,
WHILE whileFunc
]
emptyFunc _ _ _ _ = []
seqFunc _ _ = (++)
ifFunc _ _ _ _ trueBlock _ _ falseBlock _ _ = trueBlock ++ falseBlock
whileFunc _ _ _ wideningPoint _ whileBody _ _ = wideningPoint:whileBody |
1ebe2749ec8b60dba4dce8fe9c4bfd43193063ba43a594454d7c3b48e1fda022 | BinaryAnalysisPlatform/bap | primus_round_robin_main.ml | open Core_kernel[@@warning "-D"]
open Bap.Std
open Monads.Std
open Bap_primus.Std
open Format
include Self()
module Mid = Monad.State.Multi.Id
type t = {
pending : Mid.t Fqueue.t;
finished : Mid.Set.t
}
let state = Primus.Machine.State.declare
~uuid:"d1b33e16-bf5d-48d5-a174-3901dff3d123"
~name:"round-robin-scheduler"
(fun _ -> {
pending = Fqueue.empty;
finished = Mid.Set.empty;
})
module RR(Machine : Primus.Machine.S) = struct
open Machine.Syntax
let rec schedule t = match Fqueue.dequeue t.pending with
| None ->
Machine.forks () >>| Seq.filter ~f:(fun id ->
not (Set.mem t.finished id)) >>= fun fs ->
if Seq.is_empty fs
then Machine.return ()
else schedule {
t with
pending = Seq.fold fs ~init:Fqueue.empty ~f:Fqueue.enqueue
}
| Some (next,pending) ->
Machine.status next >>= function
| `Dead ->
schedule {pending; finished = Set.add t.finished next}
| _ ->
Machine.Global.put state {t with pending} >>= fun () ->
Machine.switch next >>= fun () ->
Machine.Global.get state >>= schedule
let step _ =
Machine.Global.get state >>= schedule
let finish () =
Machine.current () >>= fun id ->
Machine.Global.update state ~f:(fun t ->
{t with finished = Set.add t.finished id}) >>= fun () ->
step ()
let init () =
Machine.sequence [
Primus.Interpreter.leave_blk >>> step;
Primus.System.fini >>> finish;
]
end
let register enabled =
if enabled
then Primus.Machine.add_component (module RR) [@warning "-D"];
Primus.Components.register_generic "round-robin-scheduler" (module RR)
~package:"bap"
~desc:"Enables the round-robin scheduler (experimental)."
open Config;;
manpage [
`S "DESCRIPTION";
`P
"The round-robin scheduler will try to distribute machine time
equally between competing clones. The state tree will be traversed
in an order that is close to the bread-first search order";
`P
"The round-robin scheduler will switch the context after each basic block."
];;
let enabled = flag "scheduler" ~doc:"Enable the scheduler."
let () = declare_extension
~doc:"schedules Primus machines in the BFS order"
~provides:["primus"; "scheduler"]
(fun {get=(!!)} -> register !!enabled)
| null | https://raw.githubusercontent.com/BinaryAnalysisPlatform/bap/cbdf732d46c8e38df79d9942fc49bcb97915c657/plugins/primus_round_robin/primus_round_robin_main.ml | ocaml | open Core_kernel[@@warning "-D"]
open Bap.Std
open Monads.Std
open Bap_primus.Std
open Format
include Self()
module Mid = Monad.State.Multi.Id
type t = {
pending : Mid.t Fqueue.t;
finished : Mid.Set.t
}
let state = Primus.Machine.State.declare
~uuid:"d1b33e16-bf5d-48d5-a174-3901dff3d123"
~name:"round-robin-scheduler"
(fun _ -> {
pending = Fqueue.empty;
finished = Mid.Set.empty;
})
module RR(Machine : Primus.Machine.S) = struct
open Machine.Syntax
let rec schedule t = match Fqueue.dequeue t.pending with
| None ->
Machine.forks () >>| Seq.filter ~f:(fun id ->
not (Set.mem t.finished id)) >>= fun fs ->
if Seq.is_empty fs
then Machine.return ()
else schedule {
t with
pending = Seq.fold fs ~init:Fqueue.empty ~f:Fqueue.enqueue
}
| Some (next,pending) ->
Machine.status next >>= function
| `Dead ->
schedule {pending; finished = Set.add t.finished next}
| _ ->
Machine.Global.put state {t with pending} >>= fun () ->
Machine.switch next >>= fun () ->
Machine.Global.get state >>= schedule
let step _ =
Machine.Global.get state >>= schedule
let finish () =
Machine.current () >>= fun id ->
Machine.Global.update state ~f:(fun t ->
{t with finished = Set.add t.finished id}) >>= fun () ->
step ()
let init () =
Machine.sequence [
Primus.Interpreter.leave_blk >>> step;
Primus.System.fini >>> finish;
]
end
let register enabled =
if enabled
then Primus.Machine.add_component (module RR) [@warning "-D"];
Primus.Components.register_generic "round-robin-scheduler" (module RR)
~package:"bap"
~desc:"Enables the round-robin scheduler (experimental)."
open Config;;
manpage [
`S "DESCRIPTION";
`P
"The round-robin scheduler will try to distribute machine time
equally between competing clones. The state tree will be traversed
in an order that is close to the bread-first search order";
`P
"The round-robin scheduler will switch the context after each basic block."
];;
let enabled = flag "scheduler" ~doc:"Enable the scheduler."
let () = declare_extension
~doc:"schedules Primus machines in the BFS order"
~provides:["primus"; "scheduler"]
(fun {get=(!!)} -> register !!enabled)
|
|
669641d12121d617328bbf54f26f5c38264714446cb3a4707dd7788e8f6b6591 | appleshan/cl-http | tcp-interface-mp.lisp | ;;;; Server network interface.
;;;
This code was written by , has been placed in
;;; the public domain, and is provides 'as-is'.
;;;
Ideas from the other ports , and public domain CMUCL source .
(in-package :http)
;;;-------------------------------------------------------------------
;;;
(defparameter *number-of-listening-processes* 1
"The number of threads simultaneously listening for HTTP connections.")
5 minutes in 60ths of a second .
(setq *server-timeout* (the fixnum (* 60 60 5)))
;;;-------------------------------------------------------------------
;;;
;;;
;;; SET LISP ENVIRONMENT VARIABLES
Resource arg required from server;server
;;;
(resources:defresource
http-server (stream host address)
:constructor make-server
:initializer initialize-resourced-server
:deinitializer deinitialize-resourced-server
:initial-copies 0)
;;;-------------------------------------------------------------------
;;;
;;; LISTENING STREAMS
;;;
(defvar *listener-processes* nil
"An alist of processes awaiting incoming http connections on each port.")
(defvar *verbose-connections* nil)
(defun %start-listening-for-connections (&optional (port *STANDARD-HTTP-PORT*)
(timeout *server-timeout*))
(declare (ignore timeout)
(optimize (speed 3)))
"Primitive to begin listening for HTTP connections on PORT with server
timeout, TIMEOUT."
(flet ((listener ()
(declare (optimize (speed 3)))
(let ((fd nil))
(unwind-protect
(progn
;; Try to start the listener - sleep until available.
(do ((retry-wait 10 (* 2 retry-wait)))
(fd)
(declare (fixnum retry-wait))
(handler-case
(setf fd (ext:create-inet-listener port :stream
:reuse-address t))
(error (condition)
(format t "~&Warning: unable to create listener on ~
retry in ~d seconds ( ~a).~% "
port retry-wait condition)
(sleep retry-wait))))
(loop
;; Wait until input ready.
(mp:process-wait-until-fd-usable fd :input)
;; All connections are accepted here. If they are
;; over the limit then they are quickly closed by
;; listen-for-connection.
(let ((new-fd (ext:accept-tcp-connection fd)))
(when *verbose-connections*
(format t "* accept new connection fd=~s ~
new-fd=~s port-~s~%" fd new-fd port))
(let ((stream (www-utils::make-tcp-stream new-fd port)))
;; Make it non-blocking.
(unix:unix-fcntl new-fd unix:f-setfl unix:fndelay)
(listen-for-connection stream port)))))
;; Close the listener stream.
(when fd
(unix:unix-close fd))))))
;; Make the listening thread.
(let ((listener-process
(mp:make-process
#'listener :name (format nil "HTTP Listener on port ~d" port))))
(push (cons port listener-process) *listener-processes*))))
(defun %provide-service (stream client-domain-name client-address)
(flet ((log-dropped-connection (server)
(www-utils:abort-http-stream stream)
client timeout status code changed from 504 -- JCMa 5/29/1995 .
(log-access server))
(handle-unhandled-error (server error)
(handler-case
(progn
(set-server-status server 500)
(log-access server)
(report-status-unhandled-error error stream
(server-request server))
(close stream)) ; force output
(error ()
;; Make sure it's closed.
(www-utils:abort-http-stream stream)))
;; Log the access after the output has been forced.
(log-access server)))
Initialise the streams ' process .
(setf (www-utils::http-stream-process stream) mp:*current-process*)
(resources:using-resource
(server http-server stream client-domain-name client-address)
(let ((*server* server))
(handler-case-if (not *debug-server*)
(provide-service server)
;; Catch aborts anywhere within server.
(http-abort () (www-utils::abort-http-stream stream))
(connection-lost () (log-dropped-connection server))
(http-stream-error () (log-dropped-connection server))
(sys:io-timeout () (log-dropped-connection server))
(error (error) (handle-unhandled-error server error)))))))
(defun listen-for-connection (stream port)
(declare (values control-keyword))
(flet ((accept-connection-p ()
(< *number-of-connections* *reject-connection-threshold*))
(reject-connection (stream string)
(when string
(write-string string stream)
(force-output stream))
(close stream :abort t))
(process-namestring (client-domain-name port)
(declare (type simple-base-string client-domain-name))
(concatenate 'string "HTTP Server [" (write-to-string port :base 10.)
"] (" client-domain-name ")")))
(declare (inline accept-connection-p reject-connection process-namestring))
(cond ((accept-connection-p)
(let* ((client-address (www-utils::foreign-host stream))
(client-domain-name (host-domain-name client-address)))
;; set the timeout to the connected value
;; Provide http service
(mp:make-process
#'(lambda ()
(%provide-service stream client-domain-name client-address))
:name (process-namestring client-domain-name port))
#+mp (mp:process-yield)))
(t (reject-connection stream *reject-connection-message*)
(close stream)))))
;;;-------------------------------------------------------------------
;;;
;;; HIGH LEVEL OPERATIONS TO CONTROL HTTP SERVICE
;;;
Typically defaults to standard port , which is normally 8000 .
(defvar *http-ports* nil
"The ports over which http service is provided.")
(define listening-on-http-ports ()
"Returns the ports on which the server is listening for http connections."
(declare (values http-port-numbers))
(or *http-ports*
(setq *http-ports* (list *standard-http-port*))))
(export 'listening-on-http-ports :http)
(defun set-listening-on-http-ports (http-port-numbers)
(cond ((every #'integerp http-port-numbers)
(unless (eq http-port-numbers *http-ports*)
(setq *http-ports* http-port-numbers))
*http-ports*)
(t (error "Every listening port must be a number."))))
(defsetf listening-on-http-ports set-listening-on-http-ports)
(define enable-http-service (&key (on-ports (listening-on-http-ports)))
"Top-level method for starting up HTTP servers."
;; Shutdown any listeners that may be awake.
(disable-http-service on-ports)
;; before starting a new batch
(dolist (port (setf (listening-on-http-ports) (ensure-list on-ports)))
(ensure-http-protocol-on-port port)
;; Advise the user.
(expose-log-window)
(notify-log-window "HTTP service enabled for: http://~A:~D/"
(www-utils:local-host-domain-name) port))
on-ports)
(defun ensure-http-protocol-on-port (port)
(unless (assoc port *listener-processes*)
(%start-listening-for-connections port 0)))
(defun disable-http-service (&optional ports)
;; Disable all listeners.
(let ((rem-listeners nil))
(dolist (port-process-cons *listener-processes*)
(cond ((or (null ports) (member (first port-process-cons) ports))
(mp:destroy-process (cdr port-process-cons)))
(t
(push port-process-cons rem-listeners))))
(setf *listener-processes* rem-listeners)))
(define http-service-enabled-p (&optional (ports `(8000)))
"Returns the ports on which HTTP service is enabled or NIL if HTTP is
enabled on none of PORTS. PORTS is a list of port numbers. :ANY matches
any port."
(cond ((null ports)
(error "No ports specified in ports."))
((and (member :any ports) *listener-processes*)
ports)
(t (loop for port in ports
for (p . proc) = (assoc port *listener-processes*)
unless (and p proc)
return nil
finally (return ports)))))
;;;-------------------------------------------------------------------
;;;
SPECIALIZED HTTP STREAM POLLING
;;;
(defmethod http-input-data-available-p (stream &optional timeout-seconds)
(declare (type (or null fixnum) timeout-seconds)
(optimize (speed 3)))
(loop
(cond ((not (www-utils:live-connection-p stream))
(return nil))
((listen stream)
Clear any dangling White Space due to buggy clients .
(let ((char (peek-char nil stream nil)))
(cond ((and char (member char '(#\return #\linefeed #\space #\tab)
:test #'eql))
(read-char stream t))
(char (return t))
(t (return nil)))))
((and timeout-seconds (not (zerop timeout-seconds))
(mp:process-wait-until-fd-usable
(www-utils::http-stream-fd stream)
:input timeout-seconds)))
(t (return nil)))))
| null | https://raw.githubusercontent.com/appleshan/cl-http/a7ec6bf51e260e9bb69d8e180a103daf49aa0ac2/cmucl/server/tcp-interface-mp.lisp | lisp | Server network interface.
the public domain, and is provides 'as-is'.
-------------------------------------------------------------------
-------------------------------------------------------------------
SET LISP ENVIRONMENT VARIABLES
server
-------------------------------------------------------------------
LISTENING STREAMS
Try to start the listener - sleep until available.
Wait until input ready.
All connections are accepted here. If they are
over the limit then they are quickly closed by
listen-for-connection.
Make it non-blocking.
Close the listener stream.
Make the listening thread.
force output
Make sure it's closed.
Log the access after the output has been forced.
Catch aborts anywhere within server.
set the timeout to the connected value
Provide http service
-------------------------------------------------------------------
HIGH LEVEL OPERATIONS TO CONTROL HTTP SERVICE
Shutdown any listeners that may be awake.
before starting a new batch
Advise the user.
Disable all listeners.
-------------------------------------------------------------------
|
This code was written by , has been placed in
Ideas from the other ports , and public domain CMUCL source .
(in-package :http)
(defparameter *number-of-listening-processes* 1
"The number of threads simultaneously listening for HTTP connections.")
5 minutes in 60ths of a second .
(setq *server-timeout* (the fixnum (* 60 60 5)))
(resources:defresource
http-server (stream host address)
:constructor make-server
:initializer initialize-resourced-server
:deinitializer deinitialize-resourced-server
:initial-copies 0)
(defvar *listener-processes* nil
"An alist of processes awaiting incoming http connections on each port.")
(defvar *verbose-connections* nil)
(defun %start-listening-for-connections (&optional (port *STANDARD-HTTP-PORT*)
(timeout *server-timeout*))
(declare (ignore timeout)
(optimize (speed 3)))
"Primitive to begin listening for HTTP connections on PORT with server
timeout, TIMEOUT."
(flet ((listener ()
(declare (optimize (speed 3)))
(let ((fd nil))
(unwind-protect
(progn
(do ((retry-wait 10 (* 2 retry-wait)))
(fd)
(declare (fixnum retry-wait))
(handler-case
(setf fd (ext:create-inet-listener port :stream
:reuse-address t))
(error (condition)
(format t "~&Warning: unable to create listener on ~
retry in ~d seconds ( ~a).~% "
port retry-wait condition)
(sleep retry-wait))))
(loop
(mp:process-wait-until-fd-usable fd :input)
(let ((new-fd (ext:accept-tcp-connection fd)))
(when *verbose-connections*
(format t "* accept new connection fd=~s ~
new-fd=~s port-~s~%" fd new-fd port))
(let ((stream (www-utils::make-tcp-stream new-fd port)))
(unix:unix-fcntl new-fd unix:f-setfl unix:fndelay)
(listen-for-connection stream port)))))
(when fd
(unix:unix-close fd))))))
(let ((listener-process
(mp:make-process
#'listener :name (format nil "HTTP Listener on port ~d" port))))
(push (cons port listener-process) *listener-processes*))))
(defun %provide-service (stream client-domain-name client-address)
(flet ((log-dropped-connection (server)
(www-utils:abort-http-stream stream)
client timeout status code changed from 504 -- JCMa 5/29/1995 .
(log-access server))
(handle-unhandled-error (server error)
(handler-case
(progn
(set-server-status server 500)
(log-access server)
(report-status-unhandled-error error stream
(server-request server))
(error ()
(www-utils:abort-http-stream stream)))
(log-access server)))
Initialise the streams ' process .
(setf (www-utils::http-stream-process stream) mp:*current-process*)
(resources:using-resource
(server http-server stream client-domain-name client-address)
(let ((*server* server))
(handler-case-if (not *debug-server*)
(provide-service server)
(http-abort () (www-utils::abort-http-stream stream))
(connection-lost () (log-dropped-connection server))
(http-stream-error () (log-dropped-connection server))
(sys:io-timeout () (log-dropped-connection server))
(error (error) (handle-unhandled-error server error)))))))
(defun listen-for-connection (stream port)
(declare (values control-keyword))
(flet ((accept-connection-p ()
(< *number-of-connections* *reject-connection-threshold*))
(reject-connection (stream string)
(when string
(write-string string stream)
(force-output stream))
(close stream :abort t))
(process-namestring (client-domain-name port)
(declare (type simple-base-string client-domain-name))
(concatenate 'string "HTTP Server [" (write-to-string port :base 10.)
"] (" client-domain-name ")")))
(declare (inline accept-connection-p reject-connection process-namestring))
(cond ((accept-connection-p)
(let* ((client-address (www-utils::foreign-host stream))
(client-domain-name (host-domain-name client-address)))
(mp:make-process
#'(lambda ()
(%provide-service stream client-domain-name client-address))
:name (process-namestring client-domain-name port))
#+mp (mp:process-yield)))
(t (reject-connection stream *reject-connection-message*)
(close stream)))))
Typically defaults to standard port , which is normally 8000 .
(defvar *http-ports* nil
"The ports over which http service is provided.")
(define listening-on-http-ports ()
"Returns the ports on which the server is listening for http connections."
(declare (values http-port-numbers))
(or *http-ports*
(setq *http-ports* (list *standard-http-port*))))
(export 'listening-on-http-ports :http)
(defun set-listening-on-http-ports (http-port-numbers)
(cond ((every #'integerp http-port-numbers)
(unless (eq http-port-numbers *http-ports*)
(setq *http-ports* http-port-numbers))
*http-ports*)
(t (error "Every listening port must be a number."))))
(defsetf listening-on-http-ports set-listening-on-http-ports)
(define enable-http-service (&key (on-ports (listening-on-http-ports)))
"Top-level method for starting up HTTP servers."
(disable-http-service on-ports)
(dolist (port (setf (listening-on-http-ports) (ensure-list on-ports)))
(ensure-http-protocol-on-port port)
(expose-log-window)
(notify-log-window "HTTP service enabled for: http://~A:~D/"
(www-utils:local-host-domain-name) port))
on-ports)
(defun ensure-http-protocol-on-port (port)
(unless (assoc port *listener-processes*)
(%start-listening-for-connections port 0)))
(defun disable-http-service (&optional ports)
(let ((rem-listeners nil))
(dolist (port-process-cons *listener-processes*)
(cond ((or (null ports) (member (first port-process-cons) ports))
(mp:destroy-process (cdr port-process-cons)))
(t
(push port-process-cons rem-listeners))))
(setf *listener-processes* rem-listeners)))
(define http-service-enabled-p (&optional (ports `(8000)))
"Returns the ports on which HTTP service is enabled or NIL if HTTP is
enabled on none of PORTS. PORTS is a list of port numbers. :ANY matches
any port."
(cond ((null ports)
(error "No ports specified in ports."))
((and (member :any ports) *listener-processes*)
ports)
(t (loop for port in ports
for (p . proc) = (assoc port *listener-processes*)
unless (and p proc)
return nil
finally (return ports)))))
SPECIALIZED HTTP STREAM POLLING
(defmethod http-input-data-available-p (stream &optional timeout-seconds)
(declare (type (or null fixnum) timeout-seconds)
(optimize (speed 3)))
(loop
(cond ((not (www-utils:live-connection-p stream))
(return nil))
((listen stream)
Clear any dangling White Space due to buggy clients .
(let ((char (peek-char nil stream nil)))
(cond ((and char (member char '(#\return #\linefeed #\space #\tab)
:test #'eql))
(read-char stream t))
(char (return t))
(t (return nil)))))
((and timeout-seconds (not (zerop timeout-seconds))
(mp:process-wait-until-fd-usable
(www-utils::http-stream-fd stream)
:input timeout-seconds)))
(t (return nil)))))
|
2674c1204cada41944587bcb7fa97184bad7a8ddc7fb197957cd08eac2ce9286 | guildhall/guile-sly | repl.scm |
Copyright ( C ) 2014 >
;;;
;;; 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
;;; </>.
;;; Commentary:
;;
Cooperative REPL server extension .
;;
;;; Code:
(define-module (sly repl)
#:use-module (system repl coop-server)
#:use-module (system repl server)
#:use-module (sly agenda)
#:use-module (sly game)
#:export (start-sly-repl
resume-game-loop))
(define* (start-sly-repl #:optional (port (make-tcp-server-socket #:port 37146)))
"Start a cooperative REPL server that listens on the given PORT. By
default, this port is 37146. Additionally, a process is scheduled to
poll the REPL server upon every tick of the game loop."
(let ((server (spawn-coop-repl-server port))
(error-agenda (make-agenda)))
(schedule-each
(lambda ()
(poll-coop-repl-server server)))
;; Pause game and handle errors when they occur.
(add-hook! after-game-loop-error-hook
(lambda ()
(call-with-prompt
'sly-repl-error-prompt
(lambda ()
(with-agenda error-agenda
(while #t
(poll-coop-repl-server server)
(agenda-tick!)
(usleep 10))))
(lambda (cont)
;; Discard the continuation
#f))))))
(define (resume-game-loop)
"Abort from the error handling loop prompt and resume the game
loop."
;; We need to use the agenda so that the prompt is not aborted
within the REPL , which would break the client session .
(schedule
(lambda ()
(abort-to-prompt 'sly-repl-error-prompt))))
| null | https://raw.githubusercontent.com/guildhall/guile-sly/92f5f21da76986c5b606b36afc4bb984cc63da5b/sly/repl.scm | scheme |
This program is free software: you can redistribute it and/or
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
along with this program. If not, see
</>.
Commentary:
Code:
Pause game and handle errors when they occur.
Discard the continuation
We need to use the agenda so that the prompt is not aborted |
Copyright ( C ) 2014 >
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation , either version 3 of the
You should have received a copy of the GNU General Public License
Cooperative REPL server extension .
(define-module (sly repl)
#:use-module (system repl coop-server)
#:use-module (system repl server)
#:use-module (sly agenda)
#:use-module (sly game)
#:export (start-sly-repl
resume-game-loop))
(define* (start-sly-repl #:optional (port (make-tcp-server-socket #:port 37146)))
"Start a cooperative REPL server that listens on the given PORT. By
default, this port is 37146. Additionally, a process is scheduled to
poll the REPL server upon every tick of the game loop."
(let ((server (spawn-coop-repl-server port))
(error-agenda (make-agenda)))
(schedule-each
(lambda ()
(poll-coop-repl-server server)))
(add-hook! after-game-loop-error-hook
(lambda ()
(call-with-prompt
'sly-repl-error-prompt
(lambda ()
(with-agenda error-agenda
(while #t
(poll-coop-repl-server server)
(agenda-tick!)
(usleep 10))))
(lambda (cont)
#f))))))
(define (resume-game-loop)
"Abort from the error handling loop prompt and resume the game
loop."
within the REPL , which would break the client session .
(schedule
(lambda ()
(abort-to-prompt 'sly-repl-error-prompt))))
|
f8c591b298ed761391e01f23ec11a12f1f66f149b63aefa46ccadd63043aec0b | cardmagic/lucash | read-form.scm | Copyright ( c ) 1993 - 1999 by and . See file COPYING .
; The value of $NOTE-FILE-PACKAGE is called whenever a file is loaded into
; a package. env/debug.scm uses this to associate packages with files so
that code stuffed to the REPL will be eval'ed in the correct package .
;
; Is there any point in having this be a fluid?
(define $note-file-package
(make-fluid (lambda (filename package)
(values))))
(define (read-forms pathname package)
(let* ((filename (namestring pathname #f *scheme-file-type*))
(truename (translate filename))
(port (open-input-file truename)))
(dynamic-wind
(lambda ()
(if (not port)
(error "attempt to throw back into a file read"))) ; message needs work
(lambda ()
((fluid $note-file-package) filename package)
(let ((o-port (current-noise-port)))
(display truename o-port)
(force-output o-port)
(read-forms-from-port port)))
(lambda ()
(close-input-port port)
(set! port #f)))))
(define (read-forms-from-port port)
(let loop ((forms '()))
(let ((form (read port)))
(if (eof-object? form)
(reverse forms)
(loop (cons form forms))))))
| null | https://raw.githubusercontent.com/cardmagic/lucash/0452d410430d12140c14948f7f583624f819cdad/reference/scsh-0.6.6/scheme/bcomp/read-form.scm | scheme | The value of $NOTE-FILE-PACKAGE is called whenever a file is loaded into
a package. env/debug.scm uses this to associate packages with files so
Is there any point in having this be a fluid?
message needs work | Copyright ( c ) 1993 - 1999 by and . See file COPYING .
that code stuffed to the REPL will be eval'ed in the correct package .
(define $note-file-package
(make-fluid (lambda (filename package)
(values))))
(define (read-forms pathname package)
(let* ((filename (namestring pathname #f *scheme-file-type*))
(truename (translate filename))
(port (open-input-file truename)))
(dynamic-wind
(lambda ()
(if (not port)
(lambda ()
((fluid $note-file-package) filename package)
(let ((o-port (current-noise-port)))
(display truename o-port)
(force-output o-port)
(read-forms-from-port port)))
(lambda ()
(close-input-port port)
(set! port #f)))))
(define (read-forms-from-port port)
(let loop ((forms '()))
(let ((form (read port)))
(if (eof-object? form)
(reverse forms)
(loop (cons form forms))))))
|
2c725828935f1b6aae0d439b01a3af27d4e1d1f9c436c9885051b61d01d9fbc3 | serokell/ariadne | Generic.hs | # LANGUAGE AllowAmbiguousTypes , DefaultSignatures , ExistentialQuantification ,
, LambdaCase , NoImplicitPrelude ,
TypeFamilyDependencies #
GeneralizedNewtypeDeriving, LambdaCase, NoImplicitPrelude,
TypeFamilyDependencies #-}
module Ariadne.Wallet.Cardano.Kernel.CoinSelection.Generic (
-- * Domain
IsValue(..)
, CoinSelDom(..)
, StandardDom
, Rounding(..)
, Fee(..)
, adjustFee
, unsafeFeeSum
, utxoEntryVal
, sizeOfEntries
, unsafeValueAdd
, unsafeValueSub
, unsafeValueSum
, unsafeValueAdjust
-- * Addresses
, HasAddress(..)
, utxoEntryAddr
-- * Monad
, CoinSelT -- opaque
, coinSelLiftExcept
, mapCoinSelErr
, mapCoinSelUtxo
, unwrapCoinSelT
, wrapCoinSelT
-- * Errors
, CoinSelHardErr(..)
, CoinSelSoftErr(..)
, CoinSelErr(..)
, catchJustSoft
-- * Policy
, CoinSelPolicy
-- * Coin selection result
, CoinSelResult(..)
, defCoinSelResult
, coinSelInputSet
, coinSelInputSize
, coinSelOutputs
, coinSelRemoveDust
, coinSelPerGoal
* Generalization over representations
, StandardUtxo
, PickFromUtxo(..)
-- * Defining policies
, SelectedUtxo(..)
, emptySelection
, select
, selectedInputs
-- * Helper functions
, mapRandom
, nLargestFromMapBy
, nLargestFromListBy
, divvyFee
-- * Convenience re-exports
, MonadError(..)
, MonadRandom
, withoutKeys
) where
import Universum
import qualified Universum as U
import Control.Monad.Except (Except, MonadError(..))
import Crypto.Number.Generate (generateBetween)
import Crypto.Random (MonadRandom(..))
import Data.Coerce (coerce)
import qualified Data.Map.Strict as Map
import qualified Data.Set as Set
import Data.Text.Buildable (build)
import Formatting (bprint, (%))
import qualified Formatting as F
import Test.QuickCheck (Arbitrary(..))
import Ariadne.Wallet.Cardano.Kernel.Util (withoutKeys)
import Ariadne.Wallet.Cardano.Kernel.Util.StrictStateT
{-------------------------------------------------------------------------------
Abstract domain
-------------------------------------------------------------------------------}
data Rounding = RoundUp | RoundDown
class Ord v => IsValue v where
valueZero :: v -- ^ @0@
valueAdd :: v -> v -> Maybe v -- ^ @a + b@
valueSub :: v -> v -> Maybe v -- ^ @a - b@
valueDist :: v -> v -> v -- ^ @|a - b|@
valueRatio :: v -> v -> Double -- ^ @a / b@
valueAdjust :: Rounding -> Double -> v -> Maybe v -- ^ @a * b@
class ( Ord (Input dom)
, IsValue (Value dom)
-- Buildable and Show instances to aid debugging and testing
, Buildable (Input dom)
, Buildable (Output dom)
, Buildable (Value dom)
, Show (Value dom)
) => CoinSelDom dom where
type Input dom = i | i -> dom
type Output dom = o | o -> dom
type UtxoEntry dom = e | e -> dom
type Value dom = v | v -> dom
-- | Size of a UTxO
--
-- It is important to keep this abstract: when we introduce grouped domains,
-- then we need to be careful not to accidentally exceed the maximum number
-- of transaction inputs because we counted the /groups/ of inputs.
--
We therefore do /not/ want a ' sizeFromInt ' method .
data Size dom :: *
outVal :: Output dom -> Value dom
outSubFee :: Fee dom -> Output dom -> Maybe (Output dom)
utxoEntryInp :: UtxoEntry dom -> Input dom
utxoEntryOut :: UtxoEntry dom -> Output dom
sizeZero :: Size dom
sizeIncr :: UtxoEntry dom -> Size dom -> Size dom
sizeToWord :: Size dom -> Word64
-- default implementations
default utxoEntryInp :: StandardDom dom => UtxoEntry dom -> Input dom
utxoEntryInp = fst
default utxoEntryOut :: StandardDom dom => UtxoEntry dom -> Output dom
utxoEntryOut = snd
default sizeZero :: StandardDom dom => Size dom
sizeZero = coerce (0 :: Word64)
default sizeIncr :: StandardDom dom => UtxoEntry dom -> Size dom -> Size dom
sizeIncr _ = coerce . ((+ 1) :: Word64 -> Word64) . coerce
default sizeToWord :: StandardDom dom => Size dom -> Word64
sizeToWord = coerce
-- | Standard domain
class ( CoinSelDom dom
, UtxoEntry dom ~ (Input dom, Output dom)
, Coercible (Size dom) Word64
, Coercible Word64 (Size dom)
) => StandardDom dom where
| for ' Value '
newtype Fee dom = Fee { getFee :: Value dom }
adjustFee :: (Value dom -> Value dom) -> Fee dom -> Fee dom
adjustFee f = Fee . f . getFee
unsafeFeeSum :: CoinSelDom dom => [Fee dom] -> Fee dom
unsafeFeeSum = Fee . unsafeValueSum . map getFee
utxoEntryVal :: CoinSelDom dom => UtxoEntry dom -> Value dom
utxoEntryVal = outVal . utxoEntryOut
sizeOfEntries :: CoinSelDom dom => [UtxoEntry dom] -> Size dom
sizeOfEntries = foldl' (flip sizeIncr) sizeZero
unsafeValueAdd :: CoinSelDom dom => Value dom -> Value dom -> Value dom
unsafeValueAdd x y = fromMaybe (error "unsafeValueAdd: overflow") $
valueAdd x y
unsafeValueSub :: CoinSelDom dom => Value dom -> Value dom -> Value dom
unsafeValueSub x y = fromMaybe (error "unsafeValueSub: underflow") $
valueSub x y
unsafeValueSum :: CoinSelDom dom => [Value dom] -> Value dom
unsafeValueSum = foldl' unsafeValueAdd valueZero
unsafeValueAdjust :: CoinSelDom dom
=> Rounding -> Double -> Value dom -> Value dom
unsafeValueAdjust r x y = fromMaybe (error "unsafeValueAdjust: out of range") $
valueAdjust r x y
{-------------------------------------------------------------------------------
Describing domains which have addresses
-------------------------------------------------------------------------------}
class ( CoinSelDom dom
, Buildable (Address dom)
, Ord (Address dom)
) => HasAddress dom where
type Address dom :: *
outAddr :: Output dom -> Address dom
utxoEntryAddr :: HasAddress dom => UtxoEntry dom -> Address dom
utxoEntryAddr = outAddr . utxoEntryOut
{-------------------------------------------------------------------------------
Coin selection monad
-------------------------------------------------------------------------------}
| Monad that can be to define input selection policies
--
-- NOTE: This stack is carefully defined so that if an error occurs, we do
/not/ get a final state value . This means that when we catch errors and
-- provide error handlers, those error handlers will run with the state as it
-- was /before/ the action they wrapped.
newtype CoinSelT utxo e m a = CoinSelT {
unCoinSelT :: StrictStateT utxo (ExceptT e m) a
}
deriving ( Functor
, Applicative
, Monad
, MonadState utxo
, MonadError e
)
instance MonadTrans (CoinSelT utxo e) where
lift = CoinSelT . lift . lift
instance MonadRandom m => MonadRandom (CoinSelT utxo e m) where
getRandomBytes = lift . getRandomBytes
coinSelLiftExcept :: Monad m => Except e a -> CoinSelT utxo e m a
coinSelLiftExcept (ExceptT (Identity (Left err))) = throwError err
coinSelLiftExcept (ExceptT (Identity (Right a))) = return a
-- | Change errors
mapCoinSelErr :: Monad m
=> (e -> e')
-> CoinSelT utxo e m a
-> CoinSelT utxo e' m a
mapCoinSelErr f act = wrapCoinSelT $ \st ->
bimap f identity <$> unwrapCoinSelT act st
-- | Temporarily work with a different UTxO representation
mapCoinSelUtxo :: Monad m
=> (utxo' -> utxo)
-> (utxo -> utxo')
-> CoinSelT utxo e m a
-> CoinSelT utxo' e m a
mapCoinSelUtxo inj proj act = wrapCoinSelT $ \st ->
bimap identity (bimap identity proj) <$> unwrapCoinSelT act (inj st)
| Unwrap the ' CoinSelT ' stack
unwrapCoinSelT :: CoinSelT utxo e m a -> utxo -> m (Either e (a, utxo))
unwrapCoinSelT act = U.runExceptT . runStrictStateT (unCoinSelT act)
-- | Inverse of 'unwrapCoinSelT'
wrapCoinSelT :: Monad m
=> (utxo -> m (Either e (a, utxo))) -> CoinSelT utxo e m a
wrapCoinSelT f = CoinSelT $ strictStateT $ ExceptT . f
-- | Catch only certain errors
--
-- The signature of 'catchJust' is more general than the usual one, because
-- we make it clear /in the types/ that errors of a certain type /must/ be
-- caught.
catchJust :: Monad m
=> (e -> Either e1 e2)
-> CoinSelT utxo e m a
-> (e2 -> CoinSelT utxo e1 m a)
-> CoinSelT utxo e1 m a
catchJust classify act handler = wrapCoinSelT $ \st -> do
ma <- unwrapCoinSelT act st
case ma of
Right (a, st') -> return $ Right (a, st')
Left err -> case classify err of
Left e1 -> return $ Left e1
Right e2 -> unwrapCoinSelT (handler e2) st
{-------------------------------------------------------------------------------
Errors
-------------------------------------------------------------------------------}
-- | This input selection request is unsatisfiable
--
-- These are errors we cannot recover from.
data CoinSelHardErr =
-- | Payment to receiver insufficient to cover fee
--
-- We record the original output and the fee it needed to cover.
--
-- Only applicable using 'ReceiverPaysFees' regulation
forall dom. CoinSelDom dom =>
CoinSelHardErrOutputCannotCoverFee (Output dom) (Fee dom)
-- | Attempt to pay into a redeem-only address
| forall dom. CoinSelDom dom =>
CoinSelHardErrOutputIsRedeemAddress (Output dom)
-- | UTxO exhausted whilst trying to pick inputs to cover remaining fee
| CoinSelHardErrCannotCoverFee
| When trying to construct a transaction , the number of allowed
-- inputs was reached.
| CoinSelHardErrMaxInputsReached Word64
-- | UTxO exhausted during input selection
--
We record the balance of the UTxO as well as the size of the payment
-- we tried to make.
--
-- See also 'CoinSelHardErrCannotCoverFee'
| forall dom. CoinSelDom dom =>
CoinSelHardErrUtxoExhausted (Value dom) (Value dom)
-- | UTxO depleted using input selection
| CoinSelHardErrUtxoDepleted
-- | This wallet does not \"own\" the input address
| forall dom. HasAddress dom =>
CoinSelHardErrAddressNotOwned (Proxy dom) (Address dom)
-- ^ We need a proxy here due to the fact that 'Address' is not
-- injective.
instance Arbitrary CoinSelHardErr where
arbitrary = pure CoinSelHardErrUtxoDepleted
-- | The input selection request failed
--
-- The algorithm failed to find a solution, but that doesn't necessarily mean
-- that there isn't one.
data CoinSelSoftErr = CoinSelSoftErr
| Union of the two kinds of input selection failures
data CoinSelErr =
CoinSelErrHard CoinSelHardErr
| CoinSelErrSoft CoinSelSoftErr
-- | Specialization of 'catchJust'
catchJustSoft :: Monad m
=> CoinSelT utxo CoinSelErr m a
-> (CoinSelSoftErr -> CoinSelT utxo CoinSelHardErr m a)
-> CoinSelT utxo CoinSelHardErr m a
catchJustSoft = catchJust $ \case CoinSelErrHard e' -> Left e'
CoinSelErrSoft e' -> Right e'
{-------------------------------------------------------------------------------
Policy
-------------------------------------------------------------------------------}
-- | Coin selection policy returning result of type @a@
--
-- We are polymorphic in the result because instantiations of this framework
-- for different domains will return different kinds of results (signed
-- transaction, DSL transaction along with statistics, etc.)
type CoinSelPolicy utxo m a =
NonEmpty (Output (Dom utxo))
^ Available
-> m (Either CoinSelHardErr a)
{-------------------------------------------------------------------------------
Coin selection result
-------------------------------------------------------------------------------}
-- | The result of coin selection for a single output
data CoinSelResult dom = CoinSelResult {
-- | The output as it was requested
coinSelRequest :: Output dom
-- | The output as it should appear in the final tranasction
--
-- This may be different from the requested output if recipient pays fees.
, coinSelOutput :: Output dom
-- | Change outputs (if any)
--
-- These are not outputs, to keep this agnostic to a choice of change addr
, coinSelChange :: [Value dom]
| The entries that were used for this output
, coinSelInputs :: SelectedUtxo dom
}
-- | Default 'CoinSelResult' where 'CoinSelOutput = coinSelRequest',
defCoinSelResult :: CoinSelDom dom
=> Output dom -> SelectedUtxo dom -> CoinSelResult dom
defCoinSelResult goal selected = CoinSelResult {
coinSelRequest = goal
, coinSelOutput = goal
, coinSelChange = [change]
, coinSelInputs = selected
}
where
change = unsafeValueSub (selectedBalance selected) (outVal goal)
coinSelInputSize :: CoinSelResult dom -> Size dom
coinSelInputSize = selectedSize . coinSelInputs
coinSelInputSet :: CoinSelDom dom => CoinSelResult dom -> Set (Input dom)
coinSelInputSet = selectedInputs . coinSelInputs
coinSelOutputs :: CoinSelDom dom => CoinSelResult dom -> [Value dom]
coinSelOutputs cs = outVal (coinSelOutput cs) : coinSelChange cs
-- | Filter out any outputs from the coin selection that are smaller than
-- or equal to the dust threshold
coinSelRemoveDust :: CoinSelDom dom
=> Value dom -> CoinSelResult dom -> CoinSelResult dom
coinSelRemoveDust dust cs = cs {
coinSelChange = filter (> dust) (coinSelChange cs)
}
-- | Do coin selection per goal
--
-- Coin selection per goal simplifies the algorithm, but is not without loss
of generality , as it can not reuse a single UTxO entry for multiple goals .
--
NOTE : This is basically ' mapM ' , except that we thread the maximum nmber of
-- inputs through.
coinSelPerGoal :: forall m a dom. (Monad m, CoinSelDom dom)
=> (Word64 -> a -> m (CoinSelResult dom))
-> (Word64 -> [a] -> m [CoinSelResult dom])
coinSelPerGoal f = go []
where
go :: [CoinSelResult dom] -> Word64 -> [a] -> m [CoinSelResult dom]
go acc _ [] = return acc
go acc maxNumInputs (goal:goals) = do
cs <- f maxNumInputs goal
go (cs:acc) (maxNumInputs - sizeToWord (coinSelInputSize cs)) goals
------------------------------------------------------------------------------
Helper data structture for defining coin selection policies
------------------------------------------------------------------------------
Helper data structture for defining coin selection policies
-------------------------------------------------------------------------------}
-- | Selection of UTxO entries
--
-- This is convenient for defining coin selection policies
--
-- Invariants:
--
-- > selectedSize == sizeOfEntries selectedEntries
> = = unsafeValueSum selectedEntries
data SelectedUtxo dom = SelectedUtxo {
selectedEntries :: ![UtxoEntry dom]
, selectedBalance :: !(Value dom)
, selectedSize :: !(Size dom)
}
emptySelection :: CoinSelDom dom => SelectedUtxo dom
emptySelection = SelectedUtxo {
selectedEntries = []
, selectedBalance = valueZero
, selectedSize = sizeZero
}
-- | Select an entry and prepend it to `selectedEntries`
--
NOTE : We assume that these entries are selected from a well - formed UTxO ,
-- and hence that this cannot overflow `selectedBalance`.
select :: CoinSelDom dom
=> UtxoEntry dom -> SelectedUtxo dom -> SelectedUtxo dom
select io SelectedUtxo{..} = SelectedUtxo {
selectedEntries = io : selectedEntries
, selectedBalance = unsafeValueAdd selectedBalance (utxoEntryVal io)
, selectedSize = sizeIncr io selectedSize
}
selectedInputs :: CoinSelDom dom => SelectedUtxo dom -> Set (Input dom)
selectedInputs = Set.fromList . map utxoEntryInp . selectedEntries
------------------------------------------------------------------------------
Generalization over representations
------------------------------------------------------------------------------
Generalization over UTxO representations
-------------------------------------------------------------------------------}
-- | Shape of standard UTxO (map)
class ( StandardDom (Dom utxo)
, Coercible utxo (Map (Input (Dom utxo)) (Output (Dom utxo)))
) => StandardUtxo utxo where
| Abstraction over selecting entries from a UTxO
class CoinSelDom (Dom utxo) => PickFromUtxo utxo where
| The domain that this representation lives in
--
NOTE : This type family is /not/ injective ( a domain may have more than
one possible UTxO representation ) .
type Dom utxo :: *
| Pick a random element from the UTxO
pickRandom :: MonadRandom m => utxo -> m (Maybe (UtxoEntry (Dom utxo), utxo))
| Return the N largest elements from the UTxO
--
This returns a list of pairs of entries and utxos ; the second component
-- in each pair is the utxo after the entries in the list /so far/ have
-- been removed. The coin selection policy should decide for each entry
in the list , in order , whether or not to use it , and use the UTxO
-- associated with the last used entry as the new UTxO. Only this final
-- UTxO should be forced.
pickLargest :: Word64 -> utxo -> [(UtxoEntry (Dom utxo), utxo)]
-- | Compute UTxO balance
--
-- This is used only for error reporting.
utxoBalance :: utxo -> Value (Dom utxo)
-- default definitions for maps
default pickRandom :: forall m. (StandardUtxo utxo, MonadRandom m)
=> utxo -> m (Maybe (UtxoEntry (Dom utxo), utxo))
pickRandom = fmap (fmap (bimap identity coerce))
. mapRandom
. coerce
default pickLargest :: StandardUtxo utxo
=> Word64 -> utxo -> [(UtxoEntry (Dom utxo), utxo)]
pickLargest n = fmap (bimap identity coerce)
. nLargestFromMapBy outVal n
. coerce
default utxoBalance :: StandardUtxo utxo => utxo -> Value (Dom utxo)
utxoBalance = unsafeValueSum . map outVal . elems @(Map _ _). coerce
{-------------------------------------------------------------------------------
Helper functions for defining instances
-------------------------------------------------------------------------------}
-- | Pick a random element from a map
--
-- Returns 'Nothing' if the map is empty
mapRandom :: forall m k a. MonadRandom m
=> Map k a -> m (Maybe ((k, a), Map k a))
mapRandom m
| Map.null m = return Nothing
| otherwise = withIx . fromIntegral <$>
generateBetween 0 (fromIntegral (Map.size m - 1))
where
withIx :: Int -> Maybe ((k, a), Map k a)
withIx ix = Just (Map.elemAt ix m, Map.deleteAt ix m)
nLargestFromMapBy :: forall k a b. (Ord b, Ord k)
=> (a -> b) -> Word64 -> Map k a -> [((k, a), Map k a)]
nLargestFromMapBy f n m =
aux Set.empty $ nLargestFromListBy (f . snd) n (toPairs m)
where
aux :: Set k -> [(k, a)] -> [((k, a), Map k a)]
aux _ [] = []
aux deleted ((k, a) : kas) = ((k, a), m `withoutKeys` deleted')
: aux deleted' kas
where
deleted' = Set.insert k deleted
| Return the @n@ largest elements of the list , from large to small .
--
-- @O(n)@
nLargestFromListBy :: forall a b. Ord b => (a -> b) -> Word64 -> [a] -> [a]
nLargestFromListBy f n = \xs ->
-- If the map resulting from manipulating @xs@ is empty, we need to
-- return straight away as otherwise the call to 'Map.findMin' later
-- would fail.
let (firstN, rest) = splitAt (fromIntegral n) xs
acc = Map.fromListWith (++) $ map (\a -> (f a, [a])) firstN
in if Map.null acc then [] else go acc rest
where
-- We cache the minimum element in the accumulator, since looking this up
-- is an @O(log n)@ operation.
--
-- Invariants:
--
* Map must contain exactly @n@ elements
-- * No list in the codomain of the map can be empty
--
NOTE : Using a PSQ here does n't really gain us very much . Sure , we can
lookup the minimum element in @O(1)@ time , but /replacing/ the minimum
-- element still requires @O(log n)@ time. Thus, if we cache the minimum
-- value we have the same complexity, and avoid an additional depenedency.
go :: Map b [a] -> [a] -> [a]
go acc = go' acc (fst (Map.findMin acc))
Inherits invariants from @go@
-- Precondition: @accMin == fst (Map.findMin acc)@
go' :: Map b [a] -> b -> [a] -> [a]
go' acc _ [] = concatMap snd $ Map.toDescList acc
go' acc accMin (a:as)
| b > accMin = go (replaceMin accMin b a acc) as
| otherwise = go' acc accMin as
where
b :: b
b = f a
-- Replace the minimum entry in the map
--
-- Precondition: @accMin@ should be the minimum key of the map.
replaceMin :: b -> b -> a -> Map b [a] -> Map b [a]
replaceMin accMin b a = Map.insertWith (++) b [a] . Map.alter dropOne accMin
-- Remove one entry from the map
--
All of the entries in these lists have the same " size " ( @b@ ) ,
so we just drop the first .
dropOne :: Maybe [a] -> Maybe [a]
dropOne Nothing = error "nLargest': precondition violation"
dropOne (Just []) = error "nLargest': invariant violation"
dropOne (Just [_]) = Nothing
dropOne (Just (_:as)) = Just as
-- | Proportionally divide the fee over each output
divvyFee :: forall dom a. CoinSelDom dom
=> (a -> Value dom) -> Fee dom -> [a] -> [(Fee dom, a)]
divvyFee _ _ [] = error "divvyFee: empty list"
divvyFee f fee as = map (\a -> (feeForOut a, a)) as
where
All outputs are selected from well - formed UTxO , so their sum can not
-- overflow
totalOut :: Value dom
totalOut = unsafeValueSum (map f as)
The ratio will be between 0 and 1 so can not overflow
feeForOut :: a -> Fee dom
feeForOut a =
adjustFee (unsafeValueAdjust RoundUp (valueRatio (f a) totalOut)) fee
{-------------------------------------------------------------------------------
Pretty-printing
-------------------------------------------------------------------------------}
instance Buildable CoinSelHardErr where
build (CoinSelHardErrOutputCannotCoverFee out val) = bprint
( "CoinSelHardErrOutputCannotCoverFee"
% "{ output: " % F.build
% ", value: " % F.build
% "}"
)
out
val
build (CoinSelHardErrOutputIsRedeemAddress out) = bprint
( "CoinSelHardErrOutputIsRedeemAddress"
% "{ output: " % F.build
% "}"
)
out
build (CoinSelHardErrMaxInputsReached inputs) = bprint
( "CoinSelHardErrMaxInputsReached"
% "{ inputs: " % F.build
% "}"
)
inputs
build (CoinSelHardErrCannotCoverFee) = bprint
( "CoinSelHardErrCannotCoverFee" )
build (CoinSelHardErrUtxoExhausted bal val) = bprint
( "CoinSelHardErrUtxoExhausted"
% "{ balance: " % F.build
% ", value: " % F.build
% "}"
)
bal
val
build (CoinSelHardErrUtxoDepleted) = bprint
( "CoinSelHardErrUtxoDepleted" )
build (CoinSelHardErrAddressNotOwned _ addr) = bprint
( "CoinSelHardErrAddressNotOwned { address: " % F.build % " } ") addr
instance CoinSelDom dom => Buildable (Fee dom) where
build = bprint F.build . getFee
| null | https://raw.githubusercontent.com/serokell/ariadne/5f49ee53b6bbaf332cb6f110c75f7b971acdd452/ariadne/cardano/src/Ariadne/Wallet/Cardano/Kernel/CoinSelection/Generic.hs | haskell | * Domain
* Addresses
* Monad
opaque
* Errors
* Policy
* Coin selection result
* Defining policies
* Helper functions
* Convenience re-exports
------------------------------------------------------------------------------
Abstract domain
------------------------------------------------------------------------------
^ @0@
^ @a + b@
^ @a - b@
^ @|a - b|@
^ @a / b@
^ @a * b@
Buildable and Show instances to aid debugging and testing
| Size of a UTxO
It is important to keep this abstract: when we introduce grouped domains,
then we need to be careful not to accidentally exceed the maximum number
of transaction inputs because we counted the /groups/ of inputs.
default implementations
| Standard domain
------------------------------------------------------------------------------
Describing domains which have addresses
------------------------------------------------------------------------------
------------------------------------------------------------------------------
Coin selection monad
------------------------------------------------------------------------------
NOTE: This stack is carefully defined so that if an error occurs, we do
provide error handlers, those error handlers will run with the state as it
was /before/ the action they wrapped.
| Change errors
| Temporarily work with a different UTxO representation
| Inverse of 'unwrapCoinSelT'
| Catch only certain errors
The signature of 'catchJust' is more general than the usual one, because
we make it clear /in the types/ that errors of a certain type /must/ be
caught.
------------------------------------------------------------------------------
Errors
------------------------------------------------------------------------------
| This input selection request is unsatisfiable
These are errors we cannot recover from.
| Payment to receiver insufficient to cover fee
We record the original output and the fee it needed to cover.
Only applicable using 'ReceiverPaysFees' regulation
| Attempt to pay into a redeem-only address
| UTxO exhausted whilst trying to pick inputs to cover remaining fee
inputs was reached.
| UTxO exhausted during input selection
we tried to make.
See also 'CoinSelHardErrCannotCoverFee'
| UTxO depleted using input selection
| This wallet does not \"own\" the input address
^ We need a proxy here due to the fact that 'Address' is not
injective.
| The input selection request failed
The algorithm failed to find a solution, but that doesn't necessarily mean
that there isn't one.
| Specialization of 'catchJust'
------------------------------------------------------------------------------
Policy
------------------------------------------------------------------------------
| Coin selection policy returning result of type @a@
We are polymorphic in the result because instantiations of this framework
for different domains will return different kinds of results (signed
transaction, DSL transaction along with statistics, etc.)
------------------------------------------------------------------------------
Coin selection result
------------------------------------------------------------------------------
| The result of coin selection for a single output
| The output as it was requested
| The output as it should appear in the final tranasction
This may be different from the requested output if recipient pays fees.
| Change outputs (if any)
These are not outputs, to keep this agnostic to a choice of change addr
| Default 'CoinSelResult' where 'CoinSelOutput = coinSelRequest',
| Filter out any outputs from the coin selection that are smaller than
or equal to the dust threshold
| Do coin selection per goal
Coin selection per goal simplifies the algorithm, but is not without loss
inputs through.
----------------------------------------------------------------------------
----------------------------------------------------------------------------
-----------------------------------------------------------------------------}
| Selection of UTxO entries
This is convenient for defining coin selection policies
Invariants:
> selectedSize == sizeOfEntries selectedEntries
| Select an entry and prepend it to `selectedEntries`
and hence that this cannot overflow `selectedBalance`.
----------------------------------------------------------------------------
----------------------------------------------------------------------------
-----------------------------------------------------------------------------}
| Shape of standard UTxO (map)
in each pair is the utxo after the entries in the list /so far/ have
been removed. The coin selection policy should decide for each entry
associated with the last used entry as the new UTxO. Only this final
UTxO should be forced.
| Compute UTxO balance
This is used only for error reporting.
default definitions for maps
------------------------------------------------------------------------------
Helper functions for defining instances
------------------------------------------------------------------------------
| Pick a random element from a map
Returns 'Nothing' if the map is empty
@O(n)@
If the map resulting from manipulating @xs@ is empty, we need to
return straight away as otherwise the call to 'Map.findMin' later
would fail.
We cache the minimum element in the accumulator, since looking this up
is an @O(log n)@ operation.
Invariants:
* No list in the codomain of the map can be empty
element still requires @O(log n)@ time. Thus, if we cache the minimum
value we have the same complexity, and avoid an additional depenedency.
Precondition: @accMin == fst (Map.findMin acc)@
Replace the minimum entry in the map
Precondition: @accMin@ should be the minimum key of the map.
Remove one entry from the map
| Proportionally divide the fee over each output
overflow
------------------------------------------------------------------------------
Pretty-printing
------------------------------------------------------------------------------ | # LANGUAGE AllowAmbiguousTypes , DefaultSignatures , ExistentialQuantification ,
, LambdaCase , NoImplicitPrelude ,
TypeFamilyDependencies #
GeneralizedNewtypeDeriving, LambdaCase, NoImplicitPrelude,
TypeFamilyDependencies #-}
module Ariadne.Wallet.Cardano.Kernel.CoinSelection.Generic (
IsValue(..)
, CoinSelDom(..)
, StandardDom
, Rounding(..)
, Fee(..)
, adjustFee
, unsafeFeeSum
, utxoEntryVal
, sizeOfEntries
, unsafeValueAdd
, unsafeValueSub
, unsafeValueSum
, unsafeValueAdjust
, HasAddress(..)
, utxoEntryAddr
, coinSelLiftExcept
, mapCoinSelErr
, mapCoinSelUtxo
, unwrapCoinSelT
, wrapCoinSelT
, CoinSelHardErr(..)
, CoinSelSoftErr(..)
, CoinSelErr(..)
, catchJustSoft
, CoinSelPolicy
, CoinSelResult(..)
, defCoinSelResult
, coinSelInputSet
, coinSelInputSize
, coinSelOutputs
, coinSelRemoveDust
, coinSelPerGoal
* Generalization over representations
, StandardUtxo
, PickFromUtxo(..)
, SelectedUtxo(..)
, emptySelection
, select
, selectedInputs
, mapRandom
, nLargestFromMapBy
, nLargestFromListBy
, divvyFee
, MonadError(..)
, MonadRandom
, withoutKeys
) where
import Universum
import qualified Universum as U
import Control.Monad.Except (Except, MonadError(..))
import Crypto.Number.Generate (generateBetween)
import Crypto.Random (MonadRandom(..))
import Data.Coerce (coerce)
import qualified Data.Map.Strict as Map
import qualified Data.Set as Set
import Data.Text.Buildable (build)
import Formatting (bprint, (%))
import qualified Formatting as F
import Test.QuickCheck (Arbitrary(..))
import Ariadne.Wallet.Cardano.Kernel.Util (withoutKeys)
import Ariadne.Wallet.Cardano.Kernel.Util.StrictStateT
data Rounding = RoundUp | RoundDown
class Ord v => IsValue v where
class ( Ord (Input dom)
, IsValue (Value dom)
, Buildable (Input dom)
, Buildable (Output dom)
, Buildable (Value dom)
, Show (Value dom)
) => CoinSelDom dom where
type Input dom = i | i -> dom
type Output dom = o | o -> dom
type UtxoEntry dom = e | e -> dom
type Value dom = v | v -> dom
We therefore do /not/ want a ' sizeFromInt ' method .
data Size dom :: *
outVal :: Output dom -> Value dom
outSubFee :: Fee dom -> Output dom -> Maybe (Output dom)
utxoEntryInp :: UtxoEntry dom -> Input dom
utxoEntryOut :: UtxoEntry dom -> Output dom
sizeZero :: Size dom
sizeIncr :: UtxoEntry dom -> Size dom -> Size dom
sizeToWord :: Size dom -> Word64
default utxoEntryInp :: StandardDom dom => UtxoEntry dom -> Input dom
utxoEntryInp = fst
default utxoEntryOut :: StandardDom dom => UtxoEntry dom -> Output dom
utxoEntryOut = snd
default sizeZero :: StandardDom dom => Size dom
sizeZero = coerce (0 :: Word64)
default sizeIncr :: StandardDom dom => UtxoEntry dom -> Size dom -> Size dom
sizeIncr _ = coerce . ((+ 1) :: Word64 -> Word64) . coerce
default sizeToWord :: StandardDom dom => Size dom -> Word64
sizeToWord = coerce
class ( CoinSelDom dom
, UtxoEntry dom ~ (Input dom, Output dom)
, Coercible (Size dom) Word64
, Coercible Word64 (Size dom)
) => StandardDom dom where
| for ' Value '
newtype Fee dom = Fee { getFee :: Value dom }
adjustFee :: (Value dom -> Value dom) -> Fee dom -> Fee dom
adjustFee f = Fee . f . getFee
unsafeFeeSum :: CoinSelDom dom => [Fee dom] -> Fee dom
unsafeFeeSum = Fee . unsafeValueSum . map getFee
utxoEntryVal :: CoinSelDom dom => UtxoEntry dom -> Value dom
utxoEntryVal = outVal . utxoEntryOut
sizeOfEntries :: CoinSelDom dom => [UtxoEntry dom] -> Size dom
sizeOfEntries = foldl' (flip sizeIncr) sizeZero
unsafeValueAdd :: CoinSelDom dom => Value dom -> Value dom -> Value dom
unsafeValueAdd x y = fromMaybe (error "unsafeValueAdd: overflow") $
valueAdd x y
unsafeValueSub :: CoinSelDom dom => Value dom -> Value dom -> Value dom
unsafeValueSub x y = fromMaybe (error "unsafeValueSub: underflow") $
valueSub x y
unsafeValueSum :: CoinSelDom dom => [Value dom] -> Value dom
unsafeValueSum = foldl' unsafeValueAdd valueZero
unsafeValueAdjust :: CoinSelDom dom
=> Rounding -> Double -> Value dom -> Value dom
unsafeValueAdjust r x y = fromMaybe (error "unsafeValueAdjust: out of range") $
valueAdjust r x y
class ( CoinSelDom dom
, Buildable (Address dom)
, Ord (Address dom)
) => HasAddress dom where
type Address dom :: *
outAddr :: Output dom -> Address dom
utxoEntryAddr :: HasAddress dom => UtxoEntry dom -> Address dom
utxoEntryAddr = outAddr . utxoEntryOut
| Monad that can be to define input selection policies
/not/ get a final state value . This means that when we catch errors and
newtype CoinSelT utxo e m a = CoinSelT {
unCoinSelT :: StrictStateT utxo (ExceptT e m) a
}
deriving ( Functor
, Applicative
, Monad
, MonadState utxo
, MonadError e
)
instance MonadTrans (CoinSelT utxo e) where
lift = CoinSelT . lift . lift
instance MonadRandom m => MonadRandom (CoinSelT utxo e m) where
getRandomBytes = lift . getRandomBytes
coinSelLiftExcept :: Monad m => Except e a -> CoinSelT utxo e m a
coinSelLiftExcept (ExceptT (Identity (Left err))) = throwError err
coinSelLiftExcept (ExceptT (Identity (Right a))) = return a
mapCoinSelErr :: Monad m
=> (e -> e')
-> CoinSelT utxo e m a
-> CoinSelT utxo e' m a
mapCoinSelErr f act = wrapCoinSelT $ \st ->
bimap f identity <$> unwrapCoinSelT act st
mapCoinSelUtxo :: Monad m
=> (utxo' -> utxo)
-> (utxo -> utxo')
-> CoinSelT utxo e m a
-> CoinSelT utxo' e m a
mapCoinSelUtxo inj proj act = wrapCoinSelT $ \st ->
bimap identity (bimap identity proj) <$> unwrapCoinSelT act (inj st)
| Unwrap the ' CoinSelT ' stack
unwrapCoinSelT :: CoinSelT utxo e m a -> utxo -> m (Either e (a, utxo))
unwrapCoinSelT act = U.runExceptT . runStrictStateT (unCoinSelT act)
wrapCoinSelT :: Monad m
=> (utxo -> m (Either e (a, utxo))) -> CoinSelT utxo e m a
wrapCoinSelT f = CoinSelT $ strictStateT $ ExceptT . f
catchJust :: Monad m
=> (e -> Either e1 e2)
-> CoinSelT utxo e m a
-> (e2 -> CoinSelT utxo e1 m a)
-> CoinSelT utxo e1 m a
catchJust classify act handler = wrapCoinSelT $ \st -> do
ma <- unwrapCoinSelT act st
case ma of
Right (a, st') -> return $ Right (a, st')
Left err -> case classify err of
Left e1 -> return $ Left e1
Right e2 -> unwrapCoinSelT (handler e2) st
data CoinSelHardErr =
forall dom. CoinSelDom dom =>
CoinSelHardErrOutputCannotCoverFee (Output dom) (Fee dom)
| forall dom. CoinSelDom dom =>
CoinSelHardErrOutputIsRedeemAddress (Output dom)
| CoinSelHardErrCannotCoverFee
| When trying to construct a transaction , the number of allowed
| CoinSelHardErrMaxInputsReached Word64
We record the balance of the UTxO as well as the size of the payment
| forall dom. CoinSelDom dom =>
CoinSelHardErrUtxoExhausted (Value dom) (Value dom)
| CoinSelHardErrUtxoDepleted
| forall dom. HasAddress dom =>
CoinSelHardErrAddressNotOwned (Proxy dom) (Address dom)
instance Arbitrary CoinSelHardErr where
arbitrary = pure CoinSelHardErrUtxoDepleted
data CoinSelSoftErr = CoinSelSoftErr
| Union of the two kinds of input selection failures
data CoinSelErr =
CoinSelErrHard CoinSelHardErr
| CoinSelErrSoft CoinSelSoftErr
catchJustSoft :: Monad m
=> CoinSelT utxo CoinSelErr m a
-> (CoinSelSoftErr -> CoinSelT utxo CoinSelHardErr m a)
-> CoinSelT utxo CoinSelHardErr m a
catchJustSoft = catchJust $ \case CoinSelErrHard e' -> Left e'
CoinSelErrSoft e' -> Right e'
type CoinSelPolicy utxo m a =
NonEmpty (Output (Dom utxo))
^ Available
-> m (Either CoinSelHardErr a)
data CoinSelResult dom = CoinSelResult {
coinSelRequest :: Output dom
, coinSelOutput :: Output dom
, coinSelChange :: [Value dom]
| The entries that were used for this output
, coinSelInputs :: SelectedUtxo dom
}
defCoinSelResult :: CoinSelDom dom
=> Output dom -> SelectedUtxo dom -> CoinSelResult dom
defCoinSelResult goal selected = CoinSelResult {
coinSelRequest = goal
, coinSelOutput = goal
, coinSelChange = [change]
, coinSelInputs = selected
}
where
change = unsafeValueSub (selectedBalance selected) (outVal goal)
coinSelInputSize :: CoinSelResult dom -> Size dom
coinSelInputSize = selectedSize . coinSelInputs
coinSelInputSet :: CoinSelDom dom => CoinSelResult dom -> Set (Input dom)
coinSelInputSet = selectedInputs . coinSelInputs
coinSelOutputs :: CoinSelDom dom => CoinSelResult dom -> [Value dom]
coinSelOutputs cs = outVal (coinSelOutput cs) : coinSelChange cs
coinSelRemoveDust :: CoinSelDom dom
=> Value dom -> CoinSelResult dom -> CoinSelResult dom
coinSelRemoveDust dust cs = cs {
coinSelChange = filter (> dust) (coinSelChange cs)
}
of generality , as it can not reuse a single UTxO entry for multiple goals .
NOTE : This is basically ' mapM ' , except that we thread the maximum nmber of
coinSelPerGoal :: forall m a dom. (Monad m, CoinSelDom dom)
=> (Word64 -> a -> m (CoinSelResult dom))
-> (Word64 -> [a] -> m [CoinSelResult dom])
coinSelPerGoal f = go []
where
go :: [CoinSelResult dom] -> Word64 -> [a] -> m [CoinSelResult dom]
go acc _ [] = return acc
go acc maxNumInputs (goal:goals) = do
cs <- f maxNumInputs goal
go (cs:acc) (maxNumInputs - sizeToWord (coinSelInputSize cs)) goals
Helper data structture for defining coin selection policies
Helper data structture for defining coin selection policies
> = = unsafeValueSum selectedEntries
data SelectedUtxo dom = SelectedUtxo {
selectedEntries :: ![UtxoEntry dom]
, selectedBalance :: !(Value dom)
, selectedSize :: !(Size dom)
}
emptySelection :: CoinSelDom dom => SelectedUtxo dom
emptySelection = SelectedUtxo {
selectedEntries = []
, selectedBalance = valueZero
, selectedSize = sizeZero
}
NOTE : We assume that these entries are selected from a well - formed UTxO ,
select :: CoinSelDom dom
=> UtxoEntry dom -> SelectedUtxo dom -> SelectedUtxo dom
select io SelectedUtxo{..} = SelectedUtxo {
selectedEntries = io : selectedEntries
, selectedBalance = unsafeValueAdd selectedBalance (utxoEntryVal io)
, selectedSize = sizeIncr io selectedSize
}
selectedInputs :: CoinSelDom dom => SelectedUtxo dom -> Set (Input dom)
selectedInputs = Set.fromList . map utxoEntryInp . selectedEntries
Generalization over representations
Generalization over UTxO representations
class ( StandardDom (Dom utxo)
, Coercible utxo (Map (Input (Dom utxo)) (Output (Dom utxo)))
) => StandardUtxo utxo where
| Abstraction over selecting entries from a UTxO
class CoinSelDom (Dom utxo) => PickFromUtxo utxo where
| The domain that this representation lives in
NOTE : This type family is /not/ injective ( a domain may have more than
one possible UTxO representation ) .
type Dom utxo :: *
| Pick a random element from the UTxO
pickRandom :: MonadRandom m => utxo -> m (Maybe (UtxoEntry (Dom utxo), utxo))
| Return the N largest elements from the UTxO
This returns a list of pairs of entries and utxos ; the second component
in the list , in order , whether or not to use it , and use the UTxO
pickLargest :: Word64 -> utxo -> [(UtxoEntry (Dom utxo), utxo)]
utxoBalance :: utxo -> Value (Dom utxo)
default pickRandom :: forall m. (StandardUtxo utxo, MonadRandom m)
=> utxo -> m (Maybe (UtxoEntry (Dom utxo), utxo))
pickRandom = fmap (fmap (bimap identity coerce))
. mapRandom
. coerce
default pickLargest :: StandardUtxo utxo
=> Word64 -> utxo -> [(UtxoEntry (Dom utxo), utxo)]
pickLargest n = fmap (bimap identity coerce)
. nLargestFromMapBy outVal n
. coerce
default utxoBalance :: StandardUtxo utxo => utxo -> Value (Dom utxo)
utxoBalance = unsafeValueSum . map outVal . elems @(Map _ _). coerce
mapRandom :: forall m k a. MonadRandom m
=> Map k a -> m (Maybe ((k, a), Map k a))
mapRandom m
| Map.null m = return Nothing
| otherwise = withIx . fromIntegral <$>
generateBetween 0 (fromIntegral (Map.size m - 1))
where
withIx :: Int -> Maybe ((k, a), Map k a)
withIx ix = Just (Map.elemAt ix m, Map.deleteAt ix m)
nLargestFromMapBy :: forall k a b. (Ord b, Ord k)
=> (a -> b) -> Word64 -> Map k a -> [((k, a), Map k a)]
nLargestFromMapBy f n m =
aux Set.empty $ nLargestFromListBy (f . snd) n (toPairs m)
where
aux :: Set k -> [(k, a)] -> [((k, a), Map k a)]
aux _ [] = []
aux deleted ((k, a) : kas) = ((k, a), m `withoutKeys` deleted')
: aux deleted' kas
where
deleted' = Set.insert k deleted
| Return the @n@ largest elements of the list , from large to small .
nLargestFromListBy :: forall a b. Ord b => (a -> b) -> Word64 -> [a] -> [a]
nLargestFromListBy f n = \xs ->
let (firstN, rest) = splitAt (fromIntegral n) xs
acc = Map.fromListWith (++) $ map (\a -> (f a, [a])) firstN
in if Map.null acc then [] else go acc rest
where
* Map must contain exactly @n@ elements
NOTE : Using a PSQ here does n't really gain us very much . Sure , we can
lookup the minimum element in @O(1)@ time , but /replacing/ the minimum
go :: Map b [a] -> [a] -> [a]
go acc = go' acc (fst (Map.findMin acc))
Inherits invariants from @go@
go' :: Map b [a] -> b -> [a] -> [a]
go' acc _ [] = concatMap snd $ Map.toDescList acc
go' acc accMin (a:as)
| b > accMin = go (replaceMin accMin b a acc) as
| otherwise = go' acc accMin as
where
b :: b
b = f a
replaceMin :: b -> b -> a -> Map b [a] -> Map b [a]
replaceMin accMin b a = Map.insertWith (++) b [a] . Map.alter dropOne accMin
All of the entries in these lists have the same " size " ( @b@ ) ,
so we just drop the first .
dropOne :: Maybe [a] -> Maybe [a]
dropOne Nothing = error "nLargest': precondition violation"
dropOne (Just []) = error "nLargest': invariant violation"
dropOne (Just [_]) = Nothing
dropOne (Just (_:as)) = Just as
divvyFee :: forall dom a. CoinSelDom dom
=> (a -> Value dom) -> Fee dom -> [a] -> [(Fee dom, a)]
divvyFee _ _ [] = error "divvyFee: empty list"
divvyFee f fee as = map (\a -> (feeForOut a, a)) as
where
All outputs are selected from well - formed UTxO , so their sum can not
totalOut :: Value dom
totalOut = unsafeValueSum (map f as)
The ratio will be between 0 and 1 so can not overflow
feeForOut :: a -> Fee dom
feeForOut a =
adjustFee (unsafeValueAdjust RoundUp (valueRatio (f a) totalOut)) fee
instance Buildable CoinSelHardErr where
build (CoinSelHardErrOutputCannotCoverFee out val) = bprint
( "CoinSelHardErrOutputCannotCoverFee"
% "{ output: " % F.build
% ", value: " % F.build
% "}"
)
out
val
build (CoinSelHardErrOutputIsRedeemAddress out) = bprint
( "CoinSelHardErrOutputIsRedeemAddress"
% "{ output: " % F.build
% "}"
)
out
build (CoinSelHardErrMaxInputsReached inputs) = bprint
( "CoinSelHardErrMaxInputsReached"
% "{ inputs: " % F.build
% "}"
)
inputs
build (CoinSelHardErrCannotCoverFee) = bprint
( "CoinSelHardErrCannotCoverFee" )
build (CoinSelHardErrUtxoExhausted bal val) = bprint
( "CoinSelHardErrUtxoExhausted"
% "{ balance: " % F.build
% ", value: " % F.build
% "}"
)
bal
val
build (CoinSelHardErrUtxoDepleted) = bprint
( "CoinSelHardErrUtxoDepleted" )
build (CoinSelHardErrAddressNotOwned _ addr) = bprint
( "CoinSelHardErrAddressNotOwned { address: " % F.build % " } ") addr
instance CoinSelDom dom => Buildable (Fee dom) where
build = bprint F.build . getFee
|
f01bc9b2d5862f7406e72cf1cd343fbd80a30e790098458fe097c215bf3f32cc | xh4/web-toolkit | features.lisp | :abcl1.6.0
#| all features implemented |#
:allegro8.2-9.0
((:class-default-initargs)
(:class-direct-default-initargs)
(:default-superclass-for-funcallable-standard-class-is-funcallable-standard-object)
(:defgeneric-calls-find-method-combination)
(:defmethod-calls-make-method-lambda fixed)
(:dependent-protocol-for-generic-functions fixed)
(:extensible-allocation fixed)
(:function-invocation-calls-compute-applicable-methods fixed)
(:function-invocation-calls-compute-applicable-methods-using-classes fixed)
(:function-invocation-calls-compute-effective-method fixed)
(:generic-function-argument-precedence-order-returns-required-arguments fixed)
(:make-method-lambda fixed)
(:method-functions-take-processed-parameters fixed)
(:method-lambdas-are-processed fixed)
(:reinitialize-instance-calls-compute-discriminating-function fixed)
(:setf-class-name-calls-reinitialize-instance)
(:setf-generic-function-name-calls-reinitialize-instance)
(:slot-makunbound-using-class-specialized-on-slot-definition fixed)
(:standard-class-and-funcallable-standard-class-are-compatible)
(:subclasses-of-built-in-class-do-not-inherit-exported-slots)
(:subclasses-of-forward-referenced-class-do-not-inherit-exported-slots)
(:subclasses-of-funcallable-standard-class-do-not-inherit-exported-slots)
(:subclasses-of-method-combination-do-not-inherit-exported-slots)
(:subclasses-of-standard-accessor-method-do-not-inherit-exported-slots)
(:subclasses-of-standard-class-do-not-inherit-exported-slots)
(:subclasses-of-standard-direct-slot-definition-do-not-inherit-exported-slots)
(:subclasses-of-standard-effective-slot-definition-do-not-inherit-exported-slots)
(:subclasses-of-standard-generic-function-do-not-inherit-exported-slots)
(:subclasses-of-standard-method-do-not-inherit-exported-slots)
(:subclasses-of-standard-reader-method-do-not-inherit-exported-slots)
(:subclasses-of-standard-slot-definition-do-not-inherit-exported-slots)
(:subclasses-of-standard-writer-method-do-not-inherit-exported-slots)
(:t-is-always-a-valid-superclass))
:allegro10.0-10.1
((:class-default-initargs)
(:class-direct-default-initargs)
(:defgeneric-calls-find-method-combination)
(:defmethod-calls-make-method-lambda fixed)
(:dependent-protocol-for-generic-functions fixed)
(:extensible-allocation fixed)
(:function-invocation-calls-compute-applicable-methods fixed)
(:function-invocation-calls-compute-applicable-methods-using-classes fixed)
(:function-invocation-calls-compute-effective-method fixed)
(:generic-function-argument-precedence-order-returns-required-arguments fixed)
(:make-method-lambda fixed)
(:method-functions-take-processed-parameters fixed)
(:method-lambdas-are-processed fixed)
(:reinitialize-instance-calls-compute-discriminating-function fixed)
(:setf-class-name-calls-reinitialize-instance)
(:setf-generic-function-name-calls-reinitialize-instance)
(:slot-makunbound-using-class-specialized-on-slot-definition fixed)
(:subclasses-of-built-in-class-do-not-inherit-exported-slots)
(:subclasses-of-forward-referenced-class-do-not-inherit-exported-slots)
(:subclasses-of-funcallable-standard-class-do-not-inherit-exported-slots)
(:subclasses-of-method-combination-do-not-inherit-exported-slots)
(:subclasses-of-standard-accessor-method-do-not-inherit-exported-slots)
(:subclasses-of-standard-class-do-not-inherit-exported-slots)
(:subclasses-of-standard-direct-slot-definition-do-not-inherit-exported-slots)
(:subclasses-of-standard-effective-slot-definition-do-not-inherit-exported-slots)
(:subclasses-of-standard-generic-function-do-not-inherit-exported-slots)
(:subclasses-of-standard-method-do-not-inherit-exported-slots)
(:subclasses-of-standard-reader-method-do-not-inherit-exported-slots)
(:subclasses-of-standard-slot-definition-do-not-inherit-exported-slots)
(:subclasses-of-standard-writer-method-do-not-inherit-exported-slots)
(:t-is-always-a-valid-superclass))
:clisp2.49
((:accessor-method-initialized-with-function)
(:add-method-calls-compute-discriminating-function)
(:compute-slots-requested-slot-order-honoured)
(:defmethod-calls-make-method-lambda fixed)
(:forward-referenced-class-changed-by-change-class)
(:initialize-instance-calls-compute-discriminating-function)
(:make-method-lambda fixed)
(:method-initialized-with-function)
(:method-lambdas-are-processed fixed)
(:reinitialize-instance-calls-compute-discriminating-function)
(:remove-method-calls-compute-discriminating-function)
(:subclasses-of-method-combination-do-not-inherit-exported-slots))
:clozure-common-lisp1.11.6
((:add-method-calls-compute-discriminating-function fixed)
(:compute-slots-requested-slot-order-honoured)
(:defmethod-calls-generic-function-method-class fixed)
(:defmethod-calls-make-method-lambda fixed)
(:discriminating-functions-can-be-closures fixed)
(:discriminating-functions-can-be-funcalled fixed)
(:function-invocation-calls-compute-applicable-methods fixed)
(:function-invocation-calls-compute-applicable-methods-using-classes fixed)
(:function-invocation-calls-compute-effective-method fixed)
(:generic-functions-can-be-empty fixed)
(:initialize-instance-calls-compute-discriminating-function fixed)
(:make-method-lambda fixed)
(:method-functions-take-processed-parameters fixed)
(:method-lambdas-are-processed fixed)
(:reinitialize-instance-calls-compute-discriminating-function fixed)
(:reinitialize-instance-calls-finalize-inheritance fixed)
(:reinitialize-lambda-list-reinitializes-argument-precedence-order fixed)
(:remove-method-calls-compute-discriminating-function fixed)
(:slot-definition-documentation fixed)
(:subclasses-of-direct-slot-definition-do-not-inherit-exported-slots)
(:subclasses-of-effective-slot-definition-do-not-inherit-exported-slots)
(:subclasses-of-generic-function-do-not-inherit-exported-slots)
(:subclasses-of-slot-definition-do-not-inherit-exported-slots)
(:subclasses-of-standard-accessor-method-do-not-inherit-exported-slot)
(:subclasses-of-standard-direct-slot-definition-do-not-inherit-exported-slots)
(:subclasses-of-standard-effective-slot-definition-do-not-inherit-exported-slots)
(:subclasses-of-standard-generic-function-do-not-inherit-exported-slots)
(:subclasses-of-standard-method-do-not-inherit-exported-slots)
(:subclasses-of-standard-reader-method-do-not-inherit-exported-slots)
(:subclasses-of-standard-slot-definition-do-not-inherit-exported-slots)
(:subclasses-of-standard-accessor-method-do-not-inherit-exported-slots)
(:subclasses-of-standard-writer-method-do-not-inherit-exported-slots))
:cmu21d
((:accessor-method-initialized-with-function fixed)
(:accessor-method-initialized-with-lambda-list fixed)
(:accessor-method-initialized-with-slot-definition fixed)
(:accessor-method-initialized-with-specializers fixed)
(:anonymous-classes fixed)
(:class-default-initargs)
(:class-direct-default-initargs)
(:class-initialization-calls-reader-method-class fixed)
(:class-initialization-calls-writer-method-class fixed)
(:discriminating-functions-can-be-closures)
(:discriminating-functions-can-be-funcalled)
(:documentation-passed-to-effective-slot-definition-class)
(:effective-slot-definition-initialized-with-documentation)
(:extensible-allocation)
(:method-initialized-with-function)
(:multiple-slot-options-passed-as-list-to-direct-slot-definition-class) ; fix with fix-slot-initargs
(:reinitialize-instance-calls-compute-discriminating-function fixed)
(:reinitialize-instance-calls-finalize-inheritance)
(:setf-class-name-calls-reinitialize-instance)
(:setf-generic-function-name-calls-reinitialize-instance)
(:slot-definition-documentation fixed)
(:standard-class-and-funcallable-standard-class-are-compatible)
(:subclasses-of-built-in-class-do-not-inherit-exported-slots)
(:subclasses-of-class-do-not-inherit-exported-slots)
(:subclasses-of-direct-slot-definition-do-not-inherit-exported-slots)
(:subclasses-of-effective-slot-definition-do-not-inherit-exported-slots)
(:subclasses-of-eql-specializer-do-not-inherit-exported-slots)
(:subclasses-of-forward-referenced-class-do-not-inherit-exported-slots)
(:subclasses-of-funcallable-standard-class-do-not-inherit-exported-slots)
(:subclasses-of-slot-definition-do-not-inherit-exported-slots)
(:subclasses-of-specializer-do-not-inherit-exported-slots)
(:subclasses-of-standard-accessor-method-do-not-inherit-exported-slots)
(:subclasses-of-standard-class-do-not-inherit-exported-slots)
(:subclasses-of-standard-direct-slot-definition-do-not-inherit-exported-slots)
(:subclasses-of-standard-effective-slot-definition-do-not-inherit-exported-slots)
(:subclasses-of-standard-generic-function-do-not-inherit-exported-slots)
(:subclasses-of-standard-method-do-not-inherit-exported-slots)
(:subclasses-of-standard-reader-method-do-not-inherit-exported-slots)
(:subclasses-of-standard-slot-definition-do-not-inherit-exported-slots)
(:subclasses-of-standard-writer-method-do-not-inherit-exported-slots))
:ecl16.1.3
((:class-initialization-calls-reader-method-class)
(:class-initialization-calls-writer-method-class)
(:subclasses-of-built-in-class-do-not-inherit-exported-slots fixed)
(:subclasses-of-class-do-not-inherit-exported-slots fixed)
(:subclasses-of-direct-slot-definition-do-not-inherit-exported-slots fixed)
(:subclasses-of-effective-slot-definition-do-not-inherit-exported-slots fixed)
(:subclasses-of-forward-referenced-class-do-not-inherit-exported-slots fixed)
(:subclasses-of-funcallable-standard-class-do-not-inherit-exported-slots fixed)
(:subclasses-of-slot-definition-do-not-inherit-exported-slots fixed)
(:subclasses-of-standard-accessor-method-do-not-inherit-exported-slots)
(:subclasses-of-standard-class-do-not-inherit-exported-slots fixed)
(:subclasses-of-standard-direct-slot-definition-do-not-inherit-exported-slots fixed)
(:subclasses-of-standard-effective-slot-definition-do-not-inherit-exported-slots fixed)
(:subclasses-of-standard-generic-function-do-not-inherit-exported-slots)
(:subclasses-of-standard-method-do-not-inherit-exported-slots fixed)
(:subclasses-of-standard-reader-method-do-not-inherit-exported-slots)
(:subclasses-of-standard-slot-definition-do-not-inherit-exported-slots fixed)
(:subclasses-of-standard-writer-method-do-not-inherit-exported-slots))
:lispworks5.1-5.1.2
((:add-method-calls-compute-discriminating-function)
(:add-method-updates-specializer-direct-generic-functions fixed)
(:class-default-initargs)
(:class-direct-default-initargs)
(:compute-applicable-methods-using-classes fixed)
(:compute-default-initargs)
(:defgeneric-calls-find-method-combination)
(:eql-specializer) ; partially fixed
(:eql-specializer-object fixed)
(:eql-specializers-are-objects)
(:finalize-inheritance-calls-compute-default-initargs)
(:find-method-combination fixed) ; partially
(:funcallable-standard-instance-access fixed)
(:function-invocation-calls-compute-applicable-methods fixed)
(:function-invocation-calls-compute-applicable-methods-using-classes fixed)
(:initialize-instance-calls-compute-discriminating-function)
(:intern-eql-specializer fixed) ; partially
(:make-method-lambda fixed)
(:method-functions-take-processed-parameters fixed)
(:reinitialize-instance-calls-compute-discriminating-function)
(:remove-method-calls-compute-discriminating-function)
(:setf-slot-value-using-class-specialized-on-slot-definition fixed)
(:slot-boundp-using-class-specialized-on-slot-definition fixed)
(:slot-makunbound-using-class-specialized-on-slot-definition fixed)
(:slot-reader-calls-slot-value-using-class fixed)
(:slot-value-using-class-specialized-on-slot-definition fixed)
(:slot-writer-calls-slot-value-using-class fixed)
(:specializer)
(:specializer-direct-generic-functions fixed)
(:standard-class-and-funcallable-standard-class-are-compatible)
(:standard-instance-access fixed)
(:subclasses-of-built-in-class-do-not-inherit-exported-slots fixed)
(:subclasses-of-class-do-not-inherit-exported-slots fixed)
(:subclasses-of-direct-slot-definition-do-not-inherit-exported-slots)
(:subclasses-of-effective-slot-definition-do-not-inherit-exported-slots)
(:subclasses-of-forward-referenced-class-do-not-inherit-exported-slots fixed)
(:subclasses-of-funcallable-standard-class-do-not-inherit-exported-slots fixed)
(:subclasses-of-slot-definition-do-not-inherit-exported-slots)
(:subclasses-of-standard-accessor-method-do-not-inherit-exported-slots)
(:subclasses-of-standard-class-do-not-inherit-exported-slots fixed)
(:subclasses-of-standard-direct-slot-definition-do-not-inherit-exported-slots)
(:subclasses-of-standard-effective-slot-definition-do-not-inherit-exported-slots)
(:subclasses-of-standard-generic-function-do-not-inherit-exported-slots)
(:subclasses-of-standard-method-do-not-inherit-exported-slots)
(:subclasses-of-standard-reader-method-do-not-inherit-exported-slots)
(:subclasses-of-standard-slot-definition-do-not-inherit-exported-slots)
(:subclasses-of-standard-writer-method-do-not-inherit-exported-slots))
:lispworks6.0.1-7.0.0
((:add-method-calls-compute-discriminating-function)
(:add-method-updates-specializer-direct-generic-functions fixed)
(:class-default-initargs)
(:class-direct-default-initargs)
(:compute-applicable-methods-using-classes fixed)
(:defgeneric-calls-find-method-combination)
(:eql-specializer) ; partially fixed
(:eql-specializer-object fixed)
(:eql-specializers-are-objects)
(:find-method-combination fixed) ; partially
(:funcallable-standard-instance-access fixed)
(:function-invocation-calls-compute-applicable-methods fixed)
(:function-invocation-calls-compute-applicable-methods-using-classes fixed)
(:initialize-instance-calls-compute-discriminating-function)
(:intern-eql-specializer fixed) ; partially
(:make-method-lambda fixed)
(:method-functions-take-processed-parameters fixed)
(:reinitialize-instance-calls-compute-discriminating-function)
(:remove-method-calls-compute-discriminating-function)
(:setf-slot-value-using-class-specialized-on-slot-definition fixed)
(:slot-boundp-using-class-specialized-on-slot-definition fixed)
(:slot-makunbound-using-class-specialized-on-slot-definition fixed)
(:slot-reader-calls-slot-value-using-class fixed)
(:slot-value-using-class-specialized-on-slot-definition fixed)
(:slot-writer-calls-slot-value-using-class fixed)
(:specializer-direct-generic-functions fixed)
(:standard-class-and-funcallable-standard-class-are-compatible)
(:standard-instance-access fixed)
(:subclasses-of-built-in-class-do-not-inherit-exported-slots fixed)
(:subclasses-of-class-do-not-inherit-exported-slots fixed)
(:subclasses-of-direct-slot-definition-do-not-inherit-exported-slots)
(:subclasses-of-effective-slot-definition-do-not-inherit-exported-slots)
(:subclasses-of-forward-referenced-class-do-not-inherit-exported-slots fixed)
(:subclasses-of-funcallable-standard-class-do-not-inherit-exported-slots fixed)
(:subclasses-of-slot-definition-do-not-inherit-exported-slots)
(:subclasses-of-standard-accessor-method-do-not-inherit-exported-slots)
(:subclasses-of-standard-class-do-not-inherit-exported-slots fixed)
(:subclasses-of-standard-direct-slot-definition-do-not-inherit-exported-slots)
(:subclasses-of-standard-effective-slot-definition-do-not-inherit-exported-slots)
(:subclasses-of-standard-generic-function-do-not-inherit-exported-slots)
(:subclasses-of-standard-method-do-not-inherit-exported-slots)
(:subclasses-of-standard-reader-method-do-not-inherit-exported-slots)
(:subclasses-of-standard-slot-definition-do-not-inherit-exported-slots)
(:subclasses-of-standard-writer-method-do-not-inherit-exported-slots))
:mcl5.2.1
((:add-method-calls-compute-discriminating-function)
(:compute-applicable-methods-using-classes)
(:compute-slots-requested-slot-order-honoured)
(:default-superclass-for-funcallable-standard-class-is-funcallable-standard-object fixed)
(:defmethod-calls-generic-function-method-class)
(:defmethod-calls-make-method-lambda)
(:discriminating-functions-can-be-closures)
(:discriminating-functions-can-be-funcalled)
(:funcallable-instance-functions-can-be-closures)
(:funcallable-standard-object fixed)
(:function-invocation-calls-compute-applicable-methods)
(:function-invocation-calls-compute-applicable-methods-using-classes)
(:function-invocation-calls-compute-effective-method)
(:generic-function-declarations)
(:generic-function-initialized-with-declarations)
(:generic-functions-can-be-empty)
(:initialize-instance-calls-compute-discriminating-function)
(:make-method-lambda)
(:method-functions-take-processed-parameters)
(:method-lambdas-are-processed)
(:reinitialize-instance-calls-compute-discriminating-function)
(:reinitialize-instance-calls-finalize-inheritance)
(:reinitialize-lambda-list-reinitializes-argument-precedence-order)
(:remove-method-calls-compute-discriminating-function)
(:set-funcallable-instance-function)
(:setf-generic-function-name)
(:setf-generic-function-name-calls-reinitialize-instance)
(:slot-reader-calls-slot-value-using-class fixed)
(:slot-writer-calls-slot-value-using-class fixed)
(:subclasses-of-direct-slot-definition-do-not-inherit-exported-slots)
(:subclasses-of-effective-slot-definition-do-not-inherit-exported-slots)
(:subclasses-of-slot-definition-do-not-inherit-exported-slots)
(:subclasses-of-standard-accessor-method-do-not-inherit-exported-slots)
(:subclasses-of-standard-direct-slot-definition-do-not-inherit-exported-slots)
(:subclasses-of-standard-effective-slot-definition-do-not-inherit-exported-slots)
(:subclasses-of-standard-generic-function-do-not-inherit-exported-slots)
(:subclasses-of-standard-method-do-not-inherit-exported-slots)
(:subclasses-of-standard-reader-method-do-not-inherit-exported-slots)
(:subclasses-of-standard-slot-definition-do-not-inherit-exported-slots)
(:subclasses-of-standard-writer-method-do-not-inherit-exported-slots))
:sbcl1.5.9
#| all features implemented |#
:scl1.3.9
((:add-direct-method fixed)
(:add-method-calls-add-direct-method fixed)
(:class-default-initargs)
(:class-direct-default-initargs)
(:compute-effective-method)
(:compute-effective-method-is-generic)
(:defmethod-calls-make-method-lambda)
(:dependent-protocol-for-classes fixed)
(:dependent-protocol-for-generic-functions fixed)
(:discriminating-functions-can-be-funcalled)
(:eql-specializer)
(:extensible-allocation)
(:funcallable-standard-instance-access)
(:function-invocation-calls-compute-applicable-methods)
(:function-invocation-calls-compute-effective-method)
(:make-method-lambda)
(:method-lambdas-are-processed)
(:multiple-slot-options-passed-as-list-to-direct-slot-definition-class)
(:reinitialize-instance-calls-compute-discriminating-function)
(:remove-direct-method fixed)
(:remove-method-calls-remove-direct-method fixed)
(:setf-class-name-calls-reinitialize-instance)
(:setf-generic-function-name-calls-reinitialize-instance)
(:specializer)
(:standard-class-and-funcallable-standard-class-are-compatible)
(:standard-instance-access)
(:subclasses-of-built-in-class-do-not-inherit-exported-slots)
(:subclasses-of-class-do-not-inherit-exported-slots)
(:subclasses-of-forward-referenced-class-do-not-inherit-exported-slots)
(:subclasses-of-funcallable-standard-class-do-not-inherit-exported-slots)
(:subclasses-of-method-combination-do-not-inherit-exported-slots)
(:subclasses-of-standard-accessor-method-do-not-inherit-exported-slots)
(:subclasses-of-standard-class-do-not-inherit-exported-slots)
(:subclasses-of-standard-direct-slot-definition-do-not-inherit-exported-slots)
(:subclasses-of-standard-effective-slot-definition-do-not-inherit-exported-slots)
(:subclasses-of-standard-generic-function-do-not-inherit-exported-slots)
(:subclasses-of-standard-method-do-not-inherit-exported-slots)
(:subclasses-of-standard-reader-method-do-not-inherit-exported-slots)
(:subclasses-of-standard-slot-definition-do-not-inherit-exported-slots)
(:subclasses-of-standard-writer-method-do-not-inherit-exported-slots))
| null | https://raw.githubusercontent.com/xh4/web-toolkit/e510d44a25b36ca8acd66734ed1ee9f5fe6ecd09/vendor/closer-mop-20191227-git/features.lisp | lisp | all features implemented
fix with fix-slot-initargs
partially fixed
partially
partially
partially fixed
partially
partially
all features implemented | :abcl1.6.0
:allegro8.2-9.0
((:class-default-initargs)
(:class-direct-default-initargs)
(:default-superclass-for-funcallable-standard-class-is-funcallable-standard-object)
(:defgeneric-calls-find-method-combination)
(:defmethod-calls-make-method-lambda fixed)
(:dependent-protocol-for-generic-functions fixed)
(:extensible-allocation fixed)
(:function-invocation-calls-compute-applicable-methods fixed)
(:function-invocation-calls-compute-applicable-methods-using-classes fixed)
(:function-invocation-calls-compute-effective-method fixed)
(:generic-function-argument-precedence-order-returns-required-arguments fixed)
(:make-method-lambda fixed)
(:method-functions-take-processed-parameters fixed)
(:method-lambdas-are-processed fixed)
(:reinitialize-instance-calls-compute-discriminating-function fixed)
(:setf-class-name-calls-reinitialize-instance)
(:setf-generic-function-name-calls-reinitialize-instance)
(:slot-makunbound-using-class-specialized-on-slot-definition fixed)
(:standard-class-and-funcallable-standard-class-are-compatible)
(:subclasses-of-built-in-class-do-not-inherit-exported-slots)
(:subclasses-of-forward-referenced-class-do-not-inherit-exported-slots)
(:subclasses-of-funcallable-standard-class-do-not-inherit-exported-slots)
(:subclasses-of-method-combination-do-not-inherit-exported-slots)
(:subclasses-of-standard-accessor-method-do-not-inherit-exported-slots)
(:subclasses-of-standard-class-do-not-inherit-exported-slots)
(:subclasses-of-standard-direct-slot-definition-do-not-inherit-exported-slots)
(:subclasses-of-standard-effective-slot-definition-do-not-inherit-exported-slots)
(:subclasses-of-standard-generic-function-do-not-inherit-exported-slots)
(:subclasses-of-standard-method-do-not-inherit-exported-slots)
(:subclasses-of-standard-reader-method-do-not-inherit-exported-slots)
(:subclasses-of-standard-slot-definition-do-not-inherit-exported-slots)
(:subclasses-of-standard-writer-method-do-not-inherit-exported-slots)
(:t-is-always-a-valid-superclass))
:allegro10.0-10.1
((:class-default-initargs)
(:class-direct-default-initargs)
(:defgeneric-calls-find-method-combination)
(:defmethod-calls-make-method-lambda fixed)
(:dependent-protocol-for-generic-functions fixed)
(:extensible-allocation fixed)
(:function-invocation-calls-compute-applicable-methods fixed)
(:function-invocation-calls-compute-applicable-methods-using-classes fixed)
(:function-invocation-calls-compute-effective-method fixed)
(:generic-function-argument-precedence-order-returns-required-arguments fixed)
(:make-method-lambda fixed)
(:method-functions-take-processed-parameters fixed)
(:method-lambdas-are-processed fixed)
(:reinitialize-instance-calls-compute-discriminating-function fixed)
(:setf-class-name-calls-reinitialize-instance)
(:setf-generic-function-name-calls-reinitialize-instance)
(:slot-makunbound-using-class-specialized-on-slot-definition fixed)
(:subclasses-of-built-in-class-do-not-inherit-exported-slots)
(:subclasses-of-forward-referenced-class-do-not-inherit-exported-slots)
(:subclasses-of-funcallable-standard-class-do-not-inherit-exported-slots)
(:subclasses-of-method-combination-do-not-inherit-exported-slots)
(:subclasses-of-standard-accessor-method-do-not-inherit-exported-slots)
(:subclasses-of-standard-class-do-not-inherit-exported-slots)
(:subclasses-of-standard-direct-slot-definition-do-not-inherit-exported-slots)
(:subclasses-of-standard-effective-slot-definition-do-not-inherit-exported-slots)
(:subclasses-of-standard-generic-function-do-not-inherit-exported-slots)
(:subclasses-of-standard-method-do-not-inherit-exported-slots)
(:subclasses-of-standard-reader-method-do-not-inherit-exported-slots)
(:subclasses-of-standard-slot-definition-do-not-inherit-exported-slots)
(:subclasses-of-standard-writer-method-do-not-inherit-exported-slots)
(:t-is-always-a-valid-superclass))
:clisp2.49
((:accessor-method-initialized-with-function)
(:add-method-calls-compute-discriminating-function)
(:compute-slots-requested-slot-order-honoured)
(:defmethod-calls-make-method-lambda fixed)
(:forward-referenced-class-changed-by-change-class)
(:initialize-instance-calls-compute-discriminating-function)
(:make-method-lambda fixed)
(:method-initialized-with-function)
(:method-lambdas-are-processed fixed)
(:reinitialize-instance-calls-compute-discriminating-function)
(:remove-method-calls-compute-discriminating-function)
(:subclasses-of-method-combination-do-not-inherit-exported-slots))
:clozure-common-lisp1.11.6
((:add-method-calls-compute-discriminating-function fixed)
(:compute-slots-requested-slot-order-honoured)
(:defmethod-calls-generic-function-method-class fixed)
(:defmethod-calls-make-method-lambda fixed)
(:discriminating-functions-can-be-closures fixed)
(:discriminating-functions-can-be-funcalled fixed)
(:function-invocation-calls-compute-applicable-methods fixed)
(:function-invocation-calls-compute-applicable-methods-using-classes fixed)
(:function-invocation-calls-compute-effective-method fixed)
(:generic-functions-can-be-empty fixed)
(:initialize-instance-calls-compute-discriminating-function fixed)
(:make-method-lambda fixed)
(:method-functions-take-processed-parameters fixed)
(:method-lambdas-are-processed fixed)
(:reinitialize-instance-calls-compute-discriminating-function fixed)
(:reinitialize-instance-calls-finalize-inheritance fixed)
(:reinitialize-lambda-list-reinitializes-argument-precedence-order fixed)
(:remove-method-calls-compute-discriminating-function fixed)
(:slot-definition-documentation fixed)
(:subclasses-of-direct-slot-definition-do-not-inherit-exported-slots)
(:subclasses-of-effective-slot-definition-do-not-inherit-exported-slots)
(:subclasses-of-generic-function-do-not-inherit-exported-slots)
(:subclasses-of-slot-definition-do-not-inherit-exported-slots)
(:subclasses-of-standard-accessor-method-do-not-inherit-exported-slot)
(:subclasses-of-standard-direct-slot-definition-do-not-inherit-exported-slots)
(:subclasses-of-standard-effective-slot-definition-do-not-inherit-exported-slots)
(:subclasses-of-standard-generic-function-do-not-inherit-exported-slots)
(:subclasses-of-standard-method-do-not-inherit-exported-slots)
(:subclasses-of-standard-reader-method-do-not-inherit-exported-slots)
(:subclasses-of-standard-slot-definition-do-not-inherit-exported-slots)
(:subclasses-of-standard-accessor-method-do-not-inherit-exported-slots)
(:subclasses-of-standard-writer-method-do-not-inherit-exported-slots))
:cmu21d
((:accessor-method-initialized-with-function fixed)
(:accessor-method-initialized-with-lambda-list fixed)
(:accessor-method-initialized-with-slot-definition fixed)
(:accessor-method-initialized-with-specializers fixed)
(:anonymous-classes fixed)
(:class-default-initargs)
(:class-direct-default-initargs)
(:class-initialization-calls-reader-method-class fixed)
(:class-initialization-calls-writer-method-class fixed)
(:discriminating-functions-can-be-closures)
(:discriminating-functions-can-be-funcalled)
(:documentation-passed-to-effective-slot-definition-class)
(:effective-slot-definition-initialized-with-documentation)
(:extensible-allocation)
(:method-initialized-with-function)
(:reinitialize-instance-calls-compute-discriminating-function fixed)
(:reinitialize-instance-calls-finalize-inheritance)
(:setf-class-name-calls-reinitialize-instance)
(:setf-generic-function-name-calls-reinitialize-instance)
(:slot-definition-documentation fixed)
(:standard-class-and-funcallable-standard-class-are-compatible)
(:subclasses-of-built-in-class-do-not-inherit-exported-slots)
(:subclasses-of-class-do-not-inherit-exported-slots)
(:subclasses-of-direct-slot-definition-do-not-inherit-exported-slots)
(:subclasses-of-effective-slot-definition-do-not-inherit-exported-slots)
(:subclasses-of-eql-specializer-do-not-inherit-exported-slots)
(:subclasses-of-forward-referenced-class-do-not-inherit-exported-slots)
(:subclasses-of-funcallable-standard-class-do-not-inherit-exported-slots)
(:subclasses-of-slot-definition-do-not-inherit-exported-slots)
(:subclasses-of-specializer-do-not-inherit-exported-slots)
(:subclasses-of-standard-accessor-method-do-not-inherit-exported-slots)
(:subclasses-of-standard-class-do-not-inherit-exported-slots)
(:subclasses-of-standard-direct-slot-definition-do-not-inherit-exported-slots)
(:subclasses-of-standard-effective-slot-definition-do-not-inherit-exported-slots)
(:subclasses-of-standard-generic-function-do-not-inherit-exported-slots)
(:subclasses-of-standard-method-do-not-inherit-exported-slots)
(:subclasses-of-standard-reader-method-do-not-inherit-exported-slots)
(:subclasses-of-standard-slot-definition-do-not-inherit-exported-slots)
(:subclasses-of-standard-writer-method-do-not-inherit-exported-slots))
:ecl16.1.3
((:class-initialization-calls-reader-method-class)
(:class-initialization-calls-writer-method-class)
(:subclasses-of-built-in-class-do-not-inherit-exported-slots fixed)
(:subclasses-of-class-do-not-inherit-exported-slots fixed)
(:subclasses-of-direct-slot-definition-do-not-inherit-exported-slots fixed)
(:subclasses-of-effective-slot-definition-do-not-inherit-exported-slots fixed)
(:subclasses-of-forward-referenced-class-do-not-inherit-exported-slots fixed)
(:subclasses-of-funcallable-standard-class-do-not-inherit-exported-slots fixed)
(:subclasses-of-slot-definition-do-not-inherit-exported-slots fixed)
(:subclasses-of-standard-accessor-method-do-not-inherit-exported-slots)
(:subclasses-of-standard-class-do-not-inherit-exported-slots fixed)
(:subclasses-of-standard-direct-slot-definition-do-not-inherit-exported-slots fixed)
(:subclasses-of-standard-effective-slot-definition-do-not-inherit-exported-slots fixed)
(:subclasses-of-standard-generic-function-do-not-inherit-exported-slots)
(:subclasses-of-standard-method-do-not-inherit-exported-slots fixed)
(:subclasses-of-standard-reader-method-do-not-inherit-exported-slots)
(:subclasses-of-standard-slot-definition-do-not-inherit-exported-slots fixed)
(:subclasses-of-standard-writer-method-do-not-inherit-exported-slots))
:lispworks5.1-5.1.2
((:add-method-calls-compute-discriminating-function)
(:add-method-updates-specializer-direct-generic-functions fixed)
(:class-default-initargs)
(:class-direct-default-initargs)
(:compute-applicable-methods-using-classes fixed)
(:compute-default-initargs)
(:defgeneric-calls-find-method-combination)
(:eql-specializer-object fixed)
(:eql-specializers-are-objects)
(:finalize-inheritance-calls-compute-default-initargs)
(:funcallable-standard-instance-access fixed)
(:function-invocation-calls-compute-applicable-methods fixed)
(:function-invocation-calls-compute-applicable-methods-using-classes fixed)
(:initialize-instance-calls-compute-discriminating-function)
(:make-method-lambda fixed)
(:method-functions-take-processed-parameters fixed)
(:reinitialize-instance-calls-compute-discriminating-function)
(:remove-method-calls-compute-discriminating-function)
(:setf-slot-value-using-class-specialized-on-slot-definition fixed)
(:slot-boundp-using-class-specialized-on-slot-definition fixed)
(:slot-makunbound-using-class-specialized-on-slot-definition fixed)
(:slot-reader-calls-slot-value-using-class fixed)
(:slot-value-using-class-specialized-on-slot-definition fixed)
(:slot-writer-calls-slot-value-using-class fixed)
(:specializer)
(:specializer-direct-generic-functions fixed)
(:standard-class-and-funcallable-standard-class-are-compatible)
(:standard-instance-access fixed)
(:subclasses-of-built-in-class-do-not-inherit-exported-slots fixed)
(:subclasses-of-class-do-not-inherit-exported-slots fixed)
(:subclasses-of-direct-slot-definition-do-not-inherit-exported-slots)
(:subclasses-of-effective-slot-definition-do-not-inherit-exported-slots)
(:subclasses-of-forward-referenced-class-do-not-inherit-exported-slots fixed)
(:subclasses-of-funcallable-standard-class-do-not-inherit-exported-slots fixed)
(:subclasses-of-slot-definition-do-not-inherit-exported-slots)
(:subclasses-of-standard-accessor-method-do-not-inherit-exported-slots)
(:subclasses-of-standard-class-do-not-inherit-exported-slots fixed)
(:subclasses-of-standard-direct-slot-definition-do-not-inherit-exported-slots)
(:subclasses-of-standard-effective-slot-definition-do-not-inherit-exported-slots)
(:subclasses-of-standard-generic-function-do-not-inherit-exported-slots)
(:subclasses-of-standard-method-do-not-inherit-exported-slots)
(:subclasses-of-standard-reader-method-do-not-inherit-exported-slots)
(:subclasses-of-standard-slot-definition-do-not-inherit-exported-slots)
(:subclasses-of-standard-writer-method-do-not-inherit-exported-slots))
:lispworks6.0.1-7.0.0
((:add-method-calls-compute-discriminating-function)
(:add-method-updates-specializer-direct-generic-functions fixed)
(:class-default-initargs)
(:class-direct-default-initargs)
(:compute-applicable-methods-using-classes fixed)
(:defgeneric-calls-find-method-combination)
(:eql-specializer-object fixed)
(:eql-specializers-are-objects)
(:funcallable-standard-instance-access fixed)
(:function-invocation-calls-compute-applicable-methods fixed)
(:function-invocation-calls-compute-applicable-methods-using-classes fixed)
(:initialize-instance-calls-compute-discriminating-function)
(:make-method-lambda fixed)
(:method-functions-take-processed-parameters fixed)
(:reinitialize-instance-calls-compute-discriminating-function)
(:remove-method-calls-compute-discriminating-function)
(:setf-slot-value-using-class-specialized-on-slot-definition fixed)
(:slot-boundp-using-class-specialized-on-slot-definition fixed)
(:slot-makunbound-using-class-specialized-on-slot-definition fixed)
(:slot-reader-calls-slot-value-using-class fixed)
(:slot-value-using-class-specialized-on-slot-definition fixed)
(:slot-writer-calls-slot-value-using-class fixed)
(:specializer-direct-generic-functions fixed)
(:standard-class-and-funcallable-standard-class-are-compatible)
(:standard-instance-access fixed)
(:subclasses-of-built-in-class-do-not-inherit-exported-slots fixed)
(:subclasses-of-class-do-not-inherit-exported-slots fixed)
(:subclasses-of-direct-slot-definition-do-not-inherit-exported-slots)
(:subclasses-of-effective-slot-definition-do-not-inherit-exported-slots)
(:subclasses-of-forward-referenced-class-do-not-inherit-exported-slots fixed)
(:subclasses-of-funcallable-standard-class-do-not-inherit-exported-slots fixed)
(:subclasses-of-slot-definition-do-not-inherit-exported-slots)
(:subclasses-of-standard-accessor-method-do-not-inherit-exported-slots)
(:subclasses-of-standard-class-do-not-inherit-exported-slots fixed)
(:subclasses-of-standard-direct-slot-definition-do-not-inherit-exported-slots)
(:subclasses-of-standard-effective-slot-definition-do-not-inherit-exported-slots)
(:subclasses-of-standard-generic-function-do-not-inherit-exported-slots)
(:subclasses-of-standard-method-do-not-inherit-exported-slots)
(:subclasses-of-standard-reader-method-do-not-inherit-exported-slots)
(:subclasses-of-standard-slot-definition-do-not-inherit-exported-slots)
(:subclasses-of-standard-writer-method-do-not-inherit-exported-slots))
:mcl5.2.1
((:add-method-calls-compute-discriminating-function)
(:compute-applicable-methods-using-classes)
(:compute-slots-requested-slot-order-honoured)
(:default-superclass-for-funcallable-standard-class-is-funcallable-standard-object fixed)
(:defmethod-calls-generic-function-method-class)
(:defmethod-calls-make-method-lambda)
(:discriminating-functions-can-be-closures)
(:discriminating-functions-can-be-funcalled)
(:funcallable-instance-functions-can-be-closures)
(:funcallable-standard-object fixed)
(:function-invocation-calls-compute-applicable-methods)
(:function-invocation-calls-compute-applicable-methods-using-classes)
(:function-invocation-calls-compute-effective-method)
(:generic-function-declarations)
(:generic-function-initialized-with-declarations)
(:generic-functions-can-be-empty)
(:initialize-instance-calls-compute-discriminating-function)
(:make-method-lambda)
(:method-functions-take-processed-parameters)
(:method-lambdas-are-processed)
(:reinitialize-instance-calls-compute-discriminating-function)
(:reinitialize-instance-calls-finalize-inheritance)
(:reinitialize-lambda-list-reinitializes-argument-precedence-order)
(:remove-method-calls-compute-discriminating-function)
(:set-funcallable-instance-function)
(:setf-generic-function-name)
(:setf-generic-function-name-calls-reinitialize-instance)
(:slot-reader-calls-slot-value-using-class fixed)
(:slot-writer-calls-slot-value-using-class fixed)
(:subclasses-of-direct-slot-definition-do-not-inherit-exported-slots)
(:subclasses-of-effective-slot-definition-do-not-inherit-exported-slots)
(:subclasses-of-slot-definition-do-not-inherit-exported-slots)
(:subclasses-of-standard-accessor-method-do-not-inherit-exported-slots)
(:subclasses-of-standard-direct-slot-definition-do-not-inherit-exported-slots)
(:subclasses-of-standard-effective-slot-definition-do-not-inherit-exported-slots)
(:subclasses-of-standard-generic-function-do-not-inherit-exported-slots)
(:subclasses-of-standard-method-do-not-inherit-exported-slots)
(:subclasses-of-standard-reader-method-do-not-inherit-exported-slots)
(:subclasses-of-standard-slot-definition-do-not-inherit-exported-slots)
(:subclasses-of-standard-writer-method-do-not-inherit-exported-slots))
:sbcl1.5.9
:scl1.3.9
((:add-direct-method fixed)
(:add-method-calls-add-direct-method fixed)
(:class-default-initargs)
(:class-direct-default-initargs)
(:compute-effective-method)
(:compute-effective-method-is-generic)
(:defmethod-calls-make-method-lambda)
(:dependent-protocol-for-classes fixed)
(:dependent-protocol-for-generic-functions fixed)
(:discriminating-functions-can-be-funcalled)
(:eql-specializer)
(:extensible-allocation)
(:funcallable-standard-instance-access)
(:function-invocation-calls-compute-applicable-methods)
(:function-invocation-calls-compute-effective-method)
(:make-method-lambda)
(:method-lambdas-are-processed)
(:multiple-slot-options-passed-as-list-to-direct-slot-definition-class)
(:reinitialize-instance-calls-compute-discriminating-function)
(:remove-direct-method fixed)
(:remove-method-calls-remove-direct-method fixed)
(:setf-class-name-calls-reinitialize-instance)
(:setf-generic-function-name-calls-reinitialize-instance)
(:specializer)
(:standard-class-and-funcallable-standard-class-are-compatible)
(:standard-instance-access)
(:subclasses-of-built-in-class-do-not-inherit-exported-slots)
(:subclasses-of-class-do-not-inherit-exported-slots)
(:subclasses-of-forward-referenced-class-do-not-inherit-exported-slots)
(:subclasses-of-funcallable-standard-class-do-not-inherit-exported-slots)
(:subclasses-of-method-combination-do-not-inherit-exported-slots)
(:subclasses-of-standard-accessor-method-do-not-inherit-exported-slots)
(:subclasses-of-standard-class-do-not-inherit-exported-slots)
(:subclasses-of-standard-direct-slot-definition-do-not-inherit-exported-slots)
(:subclasses-of-standard-effective-slot-definition-do-not-inherit-exported-slots)
(:subclasses-of-standard-generic-function-do-not-inherit-exported-slots)
(:subclasses-of-standard-method-do-not-inherit-exported-slots)
(:subclasses-of-standard-reader-method-do-not-inherit-exported-slots)
(:subclasses-of-standard-slot-definition-do-not-inherit-exported-slots)
(:subclasses-of-standard-writer-method-do-not-inherit-exported-slots))
|
ee6f5f6716a48194bd79df137876c164835383c02d140e3e5687c9dea4adc821 | RyanGlScott/text-show | Generic.hs | {-# LANGUAGE CPP #-}
# LANGUAGE DeriveGeneric #
# LANGUAGE StandaloneDeriving #
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
#if __GLASGOW_HASKELL__ >= 806
# LANGUAGE DerivingVia #
#endif
# OPTIONS_GHC -fno - warn - orphans #
|
Module : Instances . Generic
Copyright : ( C ) 2014 - 2017
License : BSD - style ( see the file LICENSE )
Maintainer :
Stability : Provisional
Portability : GHC
Provides instances for ' GenericExample ' , and an ' Arbitrary ' instance for ' ' .
Module: Instances.Generic
Copyright: (C) 2014-2017 Ryan Scott
License: BSD-style (see the file LICENSE)
Maintainer: Ryan Scott
Stability: Provisional
Portability: GHC
Provides instances for 'GenericExample', and an 'Arbitrary' instance for 'ConType'.
-}
module Instances.Generic () where
import GHC.Generics (Generic, Generic1)
import Instances.Data.Text ()
import Instances.Utils (GenericExample(..))
import Instances.Utils.GenericArbitrary (genericArbitrary)
import Test.QuickCheck (Arbitrary(..))
import Text.Show.Deriving (deriveShow1)
import TextShow (TextShow(..), TextShow1(..))
import TextShow.Generic ( ConType(..)
#if __GLASGOW_HASKELL__ >= 806
, FromGeneric(..), FromGeneric1(..)
#else
, genericShowbPrec, genericLiftShowbPrec
#endif
)
deriving instance Show a => Show (GenericExample a)
$(deriveShow1 ''GenericExample)
instance Arbitrary a => Arbitrary (GenericExample a) where
arbitrary = genericArbitrary
deriving instance Generic (GenericExample a)
deriving instance Generic1 GenericExample
#if __GLASGOW_HASKELL__ >= 806
deriving via FromGeneric (GenericExample a)
instance TextShow a => TextShow (GenericExample a)
deriving via FromGeneric1 GenericExample
instance TextShow1 GenericExample
#else
instance TextShow a => TextShow (GenericExample a) where
showbPrec = genericShowbPrec
instance TextShow1 GenericExample where
liftShowbPrec = genericLiftShowbPrec
#endif
instance Arbitrary ConType where
arbitrary = genericArbitrary
| null | https://raw.githubusercontent.com/RyanGlScott/text-show/cede44e2bc357db54a7e2ad17de200708b9331cc/tests/Instances/Generic.hs | haskell | # LANGUAGE CPP #
# LANGUAGE TemplateHaskell #
# LANGUAGE TypeFamilies # | # LANGUAGE DeriveGeneric #
# LANGUAGE StandaloneDeriving #
#if __GLASGOW_HASKELL__ >= 806
# LANGUAGE DerivingVia #
#endif
# OPTIONS_GHC -fno - warn - orphans #
|
Module : Instances . Generic
Copyright : ( C ) 2014 - 2017
License : BSD - style ( see the file LICENSE )
Maintainer :
Stability : Provisional
Portability : GHC
Provides instances for ' GenericExample ' , and an ' Arbitrary ' instance for ' ' .
Module: Instances.Generic
Copyright: (C) 2014-2017 Ryan Scott
License: BSD-style (see the file LICENSE)
Maintainer: Ryan Scott
Stability: Provisional
Portability: GHC
Provides instances for 'GenericExample', and an 'Arbitrary' instance for 'ConType'.
-}
module Instances.Generic () where
import GHC.Generics (Generic, Generic1)
import Instances.Data.Text ()
import Instances.Utils (GenericExample(..))
import Instances.Utils.GenericArbitrary (genericArbitrary)
import Test.QuickCheck (Arbitrary(..))
import Text.Show.Deriving (deriveShow1)
import TextShow (TextShow(..), TextShow1(..))
import TextShow.Generic ( ConType(..)
#if __GLASGOW_HASKELL__ >= 806
, FromGeneric(..), FromGeneric1(..)
#else
, genericShowbPrec, genericLiftShowbPrec
#endif
)
deriving instance Show a => Show (GenericExample a)
$(deriveShow1 ''GenericExample)
instance Arbitrary a => Arbitrary (GenericExample a) where
arbitrary = genericArbitrary
deriving instance Generic (GenericExample a)
deriving instance Generic1 GenericExample
#if __GLASGOW_HASKELL__ >= 806
deriving via FromGeneric (GenericExample a)
instance TextShow a => TextShow (GenericExample a)
deriving via FromGeneric1 GenericExample
instance TextShow1 GenericExample
#else
instance TextShow a => TextShow (GenericExample a) where
showbPrec = genericShowbPrec
instance TextShow1 GenericExample where
liftShowbPrec = genericLiftShowbPrec
#endif
instance Arbitrary ConType where
arbitrary = genericArbitrary
|
c2080fb6b8068e4e9f06285d7650fce8fc6ac5f1841ab463db2c130544f41095 | smart-chain-fr/tokenomia | LocalRepository.hs | {-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE RecordWildCards #-}
module Tokenomia.TokenDistribution.Wallet.ChildAddress.LocalRepository
( deriveMissingChildAddresses
, fetchAddressesByWallet
, fetchAddressByWalletAtIndex
, fetchAddressesByWalletAtIndexes
, fetchAddressesByWalletWithIndexFilter
, fetchAddressesByWalletWithNonZeroIndex
, fetchAddressesByWalletWithIndexInRange
) where
import Control.Monad.Reader ( MonadIO, MonadReader )
import Control.Monad.Except ( MonadError )
import Data.List.NonEmpty ( NonEmpty, filter, toList )
import Data.List ( (\\) )
import Data.Maybe ( listToMaybe )
import Prelude hiding ( filter, max )
import Tokenomia.Common.Address ( Address )
import Tokenomia.Common.Error ( TokenomiaError )
import Tokenomia.Common.Environment ( Environment )
import Tokenomia.Wallet.Type ( WalletName )
import Tokenomia.Wallet.ChildAddress.ChildAddressRef
( ChildAddressRef(..)
, ChildAddressIndex(..)
)
import Tokenomia.Wallet.ChildAddress.LocalRepository
( ChildAddress(..)
, fetchDerivedChildAddressIndexes
, fetchById
, deriveChildAddress
)
missingChildAddressIndex ::
( MonadIO m
, MonadReader Environment m
, MonadError TokenomiaError m
)
=> WalletName -> ChildAddressIndex -> m [ChildAddressIndex]
missingChildAddressIndex walletName max = do
derivedChildAddressIndexes <- fetchDerivedChildAddressIndexes walletName
return $ missingUntil max $ toList derivedChildAddressIndexes
where
missingUntil :: (Enum a, Num a, Ord a) => a -> [a] -> [a]
missingUntil n xs = [0..n] \\ xs
missingChildAddressRef ::
( MonadIO m
, MonadReader Environment m
, MonadError TokenomiaError m
)
=> WalletName -> ChildAddressIndex -> m [ChildAddressRef]
missingChildAddressRef walletName max =
(fmap . fmap)
(ChildAddressRef walletName)
(missingChildAddressIndex walletName max)
deriveMissingChildAddresses ::
( MonadIO m
, MonadReader Environment m
, MonadError TokenomiaError m
)
=> WalletName -> ChildAddressIndex -> m ()
deriveMissingChildAddresses walletName max =
missingChildAddressRef walletName max >>= mapM_ deriveChildAddress
fetchAddressByChildAddressRef ::
( MonadIO m
, MonadReader Environment m
)
=> ChildAddressRef -> m Address
fetchAddressByChildAddressRef childAddressRef =
address <$> fetchById childAddressRef
fetchAddressByWalletAtIndex ::
( MonadIO m
, MonadReader Environment m
)
=> ChildAddressIndex -> WalletName -> m (Maybe Address)
fetchAddressByWalletAtIndex index walletName =
listToMaybe <$> fetchAddressesByWalletAtIndexes [index] walletName
fetchAddressesByWalletAtIndexes ::
( MonadIO m
, MonadReader Environment m
, Traversable t
)
=> t ChildAddressIndex -> WalletName -> m (t Address)
fetchAddressesByWalletAtIndexes indexes walletName =
mapM fetchAddressByChildAddressRef (ChildAddressRef walletName <$> indexes)
fetchAddressesByWallet ::
( MonadIO m
, MonadReader Environment m
, MonadError TokenomiaError m
)
=> WalletName -> m (NonEmpty Address)
fetchAddressesByWallet walletName = do
indexes <- fetchDerivedChildAddressIndexes walletName
fetchAddressesByWalletAtIndexes indexes walletName
fetchAddressesByWalletWithIndexFilter ::
( MonadIO m
, MonadReader Environment m
, MonadError TokenomiaError m
)
=> (ChildAddressIndex -> Bool) -> WalletName -> m [Address]
fetchAddressesByWalletWithIndexFilter predicate walletName = do
indexes <- filter predicate <$> fetchDerivedChildAddressIndexes walletName
fetchAddressesByWalletAtIndexes indexes walletName
fetchAddressesByWalletWithNonZeroIndex ::
( MonadIO m
, MonadReader Environment m
, MonadError TokenomiaError m
)
=> WalletName -> m [Address]
fetchAddressesByWalletWithNonZeroIndex =
fetchAddressesByWalletWithIndexFilter (/= 0)
fetchAddressesByWalletWithIndexInRange ::
( MonadIO m
, MonadReader Environment m
, MonadError TokenomiaError m
, Integral a
)
=> [a] -> WalletName -> m [Address]
fetchAddressesByWalletWithIndexInRange range =
fetchAddressesByWalletWithIndexFilter (`elem` childAddressIndexRange range)
where
childAddressIndexRange :: Integral a => [a] -> [ChildAddressIndex]
childAddressIndexRange = fmap (ChildAddressIndex . toInteger)
| null | https://raw.githubusercontent.com/smart-chain-fr/tokenomia/eacde8e851a2e107c8a4a09ffe85cabaa4f52953/src/Tokenomia/TokenDistribution/Wallet/ChildAddress/LocalRepository.hs | haskell | # LANGUAGE FlexibleContexts #
# LANGUAGE RecordWildCards # |
module Tokenomia.TokenDistribution.Wallet.ChildAddress.LocalRepository
( deriveMissingChildAddresses
, fetchAddressesByWallet
, fetchAddressByWalletAtIndex
, fetchAddressesByWalletAtIndexes
, fetchAddressesByWalletWithIndexFilter
, fetchAddressesByWalletWithNonZeroIndex
, fetchAddressesByWalletWithIndexInRange
) where
import Control.Monad.Reader ( MonadIO, MonadReader )
import Control.Monad.Except ( MonadError )
import Data.List.NonEmpty ( NonEmpty, filter, toList )
import Data.List ( (\\) )
import Data.Maybe ( listToMaybe )
import Prelude hiding ( filter, max )
import Tokenomia.Common.Address ( Address )
import Tokenomia.Common.Error ( TokenomiaError )
import Tokenomia.Common.Environment ( Environment )
import Tokenomia.Wallet.Type ( WalletName )
import Tokenomia.Wallet.ChildAddress.ChildAddressRef
( ChildAddressRef(..)
, ChildAddressIndex(..)
)
import Tokenomia.Wallet.ChildAddress.LocalRepository
( ChildAddress(..)
, fetchDerivedChildAddressIndexes
, fetchById
, deriveChildAddress
)
missingChildAddressIndex ::
( MonadIO m
, MonadReader Environment m
, MonadError TokenomiaError m
)
=> WalletName -> ChildAddressIndex -> m [ChildAddressIndex]
missingChildAddressIndex walletName max = do
derivedChildAddressIndexes <- fetchDerivedChildAddressIndexes walletName
return $ missingUntil max $ toList derivedChildAddressIndexes
where
missingUntil :: (Enum a, Num a, Ord a) => a -> [a] -> [a]
missingUntil n xs = [0..n] \\ xs
missingChildAddressRef ::
( MonadIO m
, MonadReader Environment m
, MonadError TokenomiaError m
)
=> WalletName -> ChildAddressIndex -> m [ChildAddressRef]
missingChildAddressRef walletName max =
(fmap . fmap)
(ChildAddressRef walletName)
(missingChildAddressIndex walletName max)
deriveMissingChildAddresses ::
( MonadIO m
, MonadReader Environment m
, MonadError TokenomiaError m
)
=> WalletName -> ChildAddressIndex -> m ()
deriveMissingChildAddresses walletName max =
missingChildAddressRef walletName max >>= mapM_ deriveChildAddress
fetchAddressByChildAddressRef ::
( MonadIO m
, MonadReader Environment m
)
=> ChildAddressRef -> m Address
fetchAddressByChildAddressRef childAddressRef =
address <$> fetchById childAddressRef
fetchAddressByWalletAtIndex ::
( MonadIO m
, MonadReader Environment m
)
=> ChildAddressIndex -> WalletName -> m (Maybe Address)
fetchAddressByWalletAtIndex index walletName =
listToMaybe <$> fetchAddressesByWalletAtIndexes [index] walletName
fetchAddressesByWalletAtIndexes ::
( MonadIO m
, MonadReader Environment m
, Traversable t
)
=> t ChildAddressIndex -> WalletName -> m (t Address)
fetchAddressesByWalletAtIndexes indexes walletName =
mapM fetchAddressByChildAddressRef (ChildAddressRef walletName <$> indexes)
fetchAddressesByWallet ::
( MonadIO m
, MonadReader Environment m
, MonadError TokenomiaError m
)
=> WalletName -> m (NonEmpty Address)
fetchAddressesByWallet walletName = do
indexes <- fetchDerivedChildAddressIndexes walletName
fetchAddressesByWalletAtIndexes indexes walletName
fetchAddressesByWalletWithIndexFilter ::
( MonadIO m
, MonadReader Environment m
, MonadError TokenomiaError m
)
=> (ChildAddressIndex -> Bool) -> WalletName -> m [Address]
fetchAddressesByWalletWithIndexFilter predicate walletName = do
indexes <- filter predicate <$> fetchDerivedChildAddressIndexes walletName
fetchAddressesByWalletAtIndexes indexes walletName
fetchAddressesByWalletWithNonZeroIndex ::
( MonadIO m
, MonadReader Environment m
, MonadError TokenomiaError m
)
=> WalletName -> m [Address]
fetchAddressesByWalletWithNonZeroIndex =
fetchAddressesByWalletWithIndexFilter (/= 0)
fetchAddressesByWalletWithIndexInRange ::
( MonadIO m
, MonadReader Environment m
, MonadError TokenomiaError m
, Integral a
)
=> [a] -> WalletName -> m [Address]
fetchAddressesByWalletWithIndexInRange range =
fetchAddressesByWalletWithIndexFilter (`elem` childAddressIndexRange range)
where
childAddressIndexRange :: Integral a => [a] -> [ChildAddressIndex]
childAddressIndexRange = fmap (ChildAddressIndex . toInteger)
|
bb1819c88e0193102493c4b336eee5e46fd4413e6365cbec87b97539163466f2 | nomaddo/loop | intf_mod.ml | open Tident
open Batteries
type intf_mod =
(Tident.path * Ast.typ) list
let rec mangling = function
| Tident ident -> Tident { ident with id = Btypes.gen_sym () }
let search_file path =
let file = List.find (fun s ->
Sys.file_exists (s ^ path.name)) !Flags.search_path in
file ^ path.name
let load_mod path =
try
let file = search_file path in
let inc = open_in file in
let (intf_mod : intf_mod) = Marshal.input inc in
List.fold_left (fun acc (p, ty) -> (mangling p, ty) :: acc) [] intf_mod
|> List.rev
with
| Not_found -> begin
exit 1
end
| null | https://raw.githubusercontent.com/nomaddo/loop/cd2204208b67b7e1f386b730c953404482ca36d6/typing/intf_mod.ml | ocaml | open Tident
open Batteries
type intf_mod =
(Tident.path * Ast.typ) list
let rec mangling = function
| Tident ident -> Tident { ident with id = Btypes.gen_sym () }
let search_file path =
let file = List.find (fun s ->
Sys.file_exists (s ^ path.name)) !Flags.search_path in
file ^ path.name
let load_mod path =
try
let file = search_file path in
let inc = open_in file in
let (intf_mod : intf_mod) = Marshal.input inc in
List.fold_left (fun acc (p, ty) -> (mangling p, ty) :: acc) [] intf_mod
|> List.rev
with
| Not_found -> begin
exit 1
end
|
|
139e44a5635e56305410fbd12a687a015cecdfccdc48c055e235b3002dd45b91 | Ericson2314/lighthouse | Id.hs | -- #hide
-----------------------------------------------------------------------------
-- |
-- Module : Id
Copyright : ( c ) 2002
-- License : BSD-style
--
-- Maintainer :
-- Stability : provisional
-- Portability : portable
--
-- Id defines the various kinds of identification values that identify GUI
objects . In addition , an ( implemented as ' FiniteMap ' ) is defined
-- in which all bound GUI objects are administered.
--
-----------------------------------------------------------------------------
module Graphics.UI.ObjectIO.Id
( Id, RId, R2Id, IdTable
, IdParent (..)
, toId, toRId, toR2Id
, r2IdtoId, rIdtoId
, getRIdIn, getR2IdIn, getR2IdOut
, okMembersIdTable
, module Graphics.UI.ObjectIO.Device.Types
, module Graphics.UI.ObjectIO.SystemId
) where
import Graphics.UI.ObjectIO.Device.Types
import Graphics.UI.ObjectIO.SystemId
import Data.IORef
import Data.Unique
import qualified Data.Map as Map
type Id = Unique
data RId mess -- The identification of bi-directional receivers:
= RId
{ rid :: !Unique -- The identification value
, ridIn :: !(IORef [mess]) -- The message input channel
}
data R2Id mess resp -- The identification of bi-directional receivers:
= R2Id
{ r2id :: !Unique -- The identification value
, r2idIn :: !(IORef mess) -- The message input
, r2idOut :: !(IORef resp) -- The message output
}
type IdTable = Map.Map Unique IdParent -- all Id entries
data IdParent
= IdParent
{ idpIOId :: !SystemId -- Id of parent process
, idpDevice :: !Device -- Device kind of parent GUI object
, idpId :: !Id -- Id of parent GUI object
}
toId :: Unique -> Id
toId i = i
toRId :: Unique -> IORef [mess] -> RId mess
toRId i cIn = RId {rid=i,ridIn=cIn}
toR2Id :: Unique -> IORef mess -> IORef resp -> R2Id mess resp
toR2Id i cIn cOut = R2Id {r2id=i,r2idIn=cIn,r2idOut=cOut}
instance Eq (RId mess) where
(==) rid1 rid2 = rid rid1 == rid rid2
instance Eq (R2Id mess resp) where
(==) rid1 rid2 = r2id rid1 == r2id rid2
rIdtoId :: RId mess -> Id
rIdtoId id = rid id
r2IdtoId :: R2Id mess resp -> Id
r2IdtoId id = r2id id
instance Show Id where
show id = "Id"
{- Additional R(2)Id access operations:
-}
getRIdIn :: RId msg -> IORef [msg]
getRIdIn id = ridIn id
getR2IdIn :: R2Id msg resp -> IORef msg
getR2IdIn id = r2idIn id
getR2IdOut :: R2Id msg resp -> IORef resp
getR2IdOut id = r2idOut id
operations :
okMembersIdTable :: [Id] -> IdTable -> Bool
okMembersIdTable ids tbl
= noDuplicates ids && not (any (\key -> elem key $ Map.keys tbl) ids)
where
noDuplicates :: (Eq x) => [x] -> Bool
noDuplicates (x:xs) = not (x `elem` xs) && noDuplicates xs
noDuplicates _ = True
| null | https://raw.githubusercontent.com/Ericson2314/lighthouse/210078b846ebd6c43b89b5f0f735362a01a9af02/ghc-6.8.2/libraries/ObjectIO/Graphics/UI/ObjectIO/Id.hs | haskell | #hide
---------------------------------------------------------------------------
|
Module : Id
License : BSD-style
Maintainer :
Stability : provisional
Portability : portable
Id defines the various kinds of identification values that identify GUI
in which all bound GUI objects are administered.
---------------------------------------------------------------------------
The identification of bi-directional receivers:
The identification value
The message input channel
The identification of bi-directional receivers:
The identification value
The message input
The message output
all Id entries
Id of parent process
Device kind of parent GUI object
Id of parent GUI object
Additional R(2)Id access operations:
| Copyright : ( c ) 2002
objects . In addition , an ( implemented as ' FiniteMap ' ) is defined
module Graphics.UI.ObjectIO.Id
( Id, RId, R2Id, IdTable
, IdParent (..)
, toId, toRId, toR2Id
, r2IdtoId, rIdtoId
, getRIdIn, getR2IdIn, getR2IdOut
, okMembersIdTable
, module Graphics.UI.ObjectIO.Device.Types
, module Graphics.UI.ObjectIO.SystemId
) where
import Graphics.UI.ObjectIO.Device.Types
import Graphics.UI.ObjectIO.SystemId
import Data.IORef
import Data.Unique
import qualified Data.Map as Map
type Id = Unique
= RId
}
= R2Id
}
data IdParent
= IdParent
}
toId :: Unique -> Id
toId i = i
toRId :: Unique -> IORef [mess] -> RId mess
toRId i cIn = RId {rid=i,ridIn=cIn}
toR2Id :: Unique -> IORef mess -> IORef resp -> R2Id mess resp
toR2Id i cIn cOut = R2Id {r2id=i,r2idIn=cIn,r2idOut=cOut}
instance Eq (RId mess) where
(==) rid1 rid2 = rid rid1 == rid rid2
instance Eq (R2Id mess resp) where
(==) rid1 rid2 = r2id rid1 == r2id rid2
rIdtoId :: RId mess -> Id
rIdtoId id = rid id
r2IdtoId :: R2Id mess resp -> Id
r2IdtoId id = r2id id
instance Show Id where
show id = "Id"
getRIdIn :: RId msg -> IORef [msg]
getRIdIn id = ridIn id
getR2IdIn :: R2Id msg resp -> IORef msg
getR2IdIn id = r2idIn id
getR2IdOut :: R2Id msg resp -> IORef resp
getR2IdOut id = r2idOut id
operations :
okMembersIdTable :: [Id] -> IdTable -> Bool
okMembersIdTable ids tbl
= noDuplicates ids && not (any (\key -> elem key $ Map.keys tbl) ids)
where
noDuplicates :: (Eq x) => [x] -> Bool
noDuplicates (x:xs) = not (x `elem` xs) && noDuplicates xs
noDuplicates _ = True
|
b38ac70e17cfe41cfe8dfd2340a492ed8de47155821e52a08b46af21655b487e | jacekschae/learn-pedestal-course-files | conversations_tests.clj | (ns cheffy.conversations-tests
(:require [clojure.test :refer :all]
[io.pedestal.test :as pt]
[io.pedestal.http :as http]
[cheffy.test-system :as ts]
[com.stuartsierra.component.repl :as cr]))
(def service-fn (-> cr/system :api-server :service ::http/service-fn))
(def conversation-id (atom nil))
(deftest conversation-tests
(testing "create-messages"
(testing "without-conversation-id"
(let [{:keys [status body]} (-> (pt/response-for
service-fn
:post "/conversations"
:headers {"Authorization" "auth|5fbf7db6271d5e0076903601"
"Content-Type" "application/transit+json"}
:body (ts/transit-write {:to ""
:message-body "new message"}))
(update :body ts/transit-read))]
(reset! conversation-id (:conversation-id body))
(is (= 201 status))))
(testing "with-conversation-id"
(let [{:keys [status body]} (-> (pt/response-for
service-fn
:post (str "/conversations/" @conversation-id)
:headers {"Authorization" "auth|5fbf7db6271d5e0076903601"
"Content-Type" "application/transit+json"}
:body (ts/transit-write {:to ""
:message-body "second message"}))
(update :body ts/transit-read))]
(is (= 201 status)))))
(testing "list-conversations"
(let [{:keys [status body]} (-> (pt/response-for
service-fn
:get "/conversations"
:headers {"Authorization" "auth|5fbf7db6271d5e0076903601"})
(update :body ts/transit-read))]
(is (= 200 status))))
(testing "list-messages"
(let [{:keys [status body]} (-> (pt/response-for
service-fn
:get (str "/conversations/" @conversation-id)
:headers {"Authorization" "auth|5fbf7db6271d5e0076903601"})
(update :body ts/transit-read))]
(is (= 200 status))))) | null | https://raw.githubusercontent.com/jacekschae/learn-pedestal-course-files/54431873708f11a497abd2795e02d0934f019c68/increments/50-clear-notifications-tests/src/test/cheffy/conversations_tests.clj | clojure | (ns cheffy.conversations-tests
(:require [clojure.test :refer :all]
[io.pedestal.test :as pt]
[io.pedestal.http :as http]
[cheffy.test-system :as ts]
[com.stuartsierra.component.repl :as cr]))
(def service-fn (-> cr/system :api-server :service ::http/service-fn))
(def conversation-id (atom nil))
(deftest conversation-tests
(testing "create-messages"
(testing "without-conversation-id"
(let [{:keys [status body]} (-> (pt/response-for
service-fn
:post "/conversations"
:headers {"Authorization" "auth|5fbf7db6271d5e0076903601"
"Content-Type" "application/transit+json"}
:body (ts/transit-write {:to ""
:message-body "new message"}))
(update :body ts/transit-read))]
(reset! conversation-id (:conversation-id body))
(is (= 201 status))))
(testing "with-conversation-id"
(let [{:keys [status body]} (-> (pt/response-for
service-fn
:post (str "/conversations/" @conversation-id)
:headers {"Authorization" "auth|5fbf7db6271d5e0076903601"
"Content-Type" "application/transit+json"}
:body (ts/transit-write {:to ""
:message-body "second message"}))
(update :body ts/transit-read))]
(is (= 201 status)))))
(testing "list-conversations"
(let [{:keys [status body]} (-> (pt/response-for
service-fn
:get "/conversations"
:headers {"Authorization" "auth|5fbf7db6271d5e0076903601"})
(update :body ts/transit-read))]
(is (= 200 status))))
(testing "list-messages"
(let [{:keys [status body]} (-> (pt/response-for
service-fn
:get (str "/conversations/" @conversation-id)
:headers {"Authorization" "auth|5fbf7db6271d5e0076903601"})
(update :body ts/transit-read))]
(is (= 200 status))))) |
|
2344ddacf62095dce7d5ab984a8063196ab659cea659d74c43e9daac9f3ffe8a | sboehler/beans | Include.hs | module Beans.Include (Include (Include)) where
import Data.Text.Prettyprint.Doc (Pretty (pretty), (<+>))
import qualified Text.Megaparsec.Pos as P
data Include = Include
{ position :: P.SourcePos,
filePath :: FilePath
}
deriving (Eq, Ord, Show)
instance Pretty Include where
pretty (Include _ filePath) = "include" <+> pretty filePath
| null | https://raw.githubusercontent.com/sboehler/beans/897fc30a602f49906eb952c4fd5c8c0bf05a6beb/src/Beans/Include.hs | haskell | module Beans.Include (Include (Include)) where
import Data.Text.Prettyprint.Doc (Pretty (pretty), (<+>))
import qualified Text.Megaparsec.Pos as P
data Include = Include
{ position :: P.SourcePos,
filePath :: FilePath
}
deriving (Eq, Ord, Show)
instance Pretty Include where
pretty (Include _ filePath) = "include" <+> pretty filePath
|
|
b086c65053dadb4a893500604d2df9d07271d03e97e342268e926271e4a01b4e | larrychristensen/orcpub | feats.cljc | (ns orcpub.dnd.e5.feats
(:require #?(:clj [clojure.spec.alpha :as spec])
#?(:cljs [cljs.spec.alpha :as spec])
[orcpub.common :as common]))
(spec/def ::name (spec/and string? common/starts-with-letter?))
(spec/def ::key (spec/and keyword? common/keyword-starts-with-letter?))
(spec/def ::option-pack string?)
(spec/def ::homebrew-feat (spec/keys :req-un [::name ::key ::option-pack]))
| null | https://raw.githubusercontent.com/larrychristensen/orcpub/e83995857f7e64af1798009a45a0b03abcd3a4be/src/cljc/orcpub/dnd/e5/feats.cljc | clojure | (ns orcpub.dnd.e5.feats
(:require #?(:clj [clojure.spec.alpha :as spec])
#?(:cljs [cljs.spec.alpha :as spec])
[orcpub.common :as common]))
(spec/def ::name (spec/and string? common/starts-with-letter?))
(spec/def ::key (spec/and keyword? common/keyword-starts-with-letter?))
(spec/def ::option-pack string?)
(spec/def ::homebrew-feat (spec/keys :req-un [::name ::key ::option-pack]))
|
|
8cc470817210b4985fcc6b8e5522506d7f5248eb8e7ba0fcc5d03683903d6a27 | VictorCMiraldo/generics-mrsop | SimpTH.hs | # LANGUAGE TypeApplications #
{-# LANGUAGE RankNTypes #-}
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
{-# LANGUAGE GADTs #-}
{-# LANGUAGE TypeOperators #-}
# LANGUAGE DataKinds #
# LANGUAGE PolyKinds #
{-# LANGUAGE ScopedTypeVariables #-}
# LANGUAGE FunctionalDependencies #
{-# LANGUAGE TemplateHaskell #-}
# LANGUAGE LambdaCase #
{-# LANGUAGE PatternSynonyms #-}
{-# OPTIONS_HADDOCK hide, prune, ignore-exports #-}
# OPTIONS_GHC -Wno - missing - pattern - synonym - signatures #
# OPTIONS_GHC -Wno - missing - signatures #
# OPTIONS_GHC -Wno - incomplete - patterns #
# OPTIONS_GHC -Wno - orphans #
-- |Uses a more involved example to test some
of the functionalities of @generics - mrsop@.
module Generics.MRSOP.Examples.SimpTH where
import Data.Function (on)
import Data.Functor.Const
import Generics.MRSOP.Base
import Generics.MRSOP.Holes
import Generics.MRSOP.Opaque
import Generics.MRSOP.Zipper
import Generics.MRSOP.Examples.LambdaAlphaEqTH hiding (FIX, alphaEq)
import Generics.MRSOP.TH
import Control.Monad
-- * Simple IMPerative Language:
data Stmt var
= SAssign var (Exp var)
| SIf (Exp var) (Stmt var) (Stmt var)
| SSeq (Stmt var) (Stmt var)
| SReturn (Exp var)
| SDecl (Decl var)
| SSkip
deriving Show
-- Below is a little type synonym fun, to make sure
-- generation is working
data ODecl var
= DVar var
| DFun var var (Stmt var)
deriving Show
-- Note that since we use 'Decl' directly in the family;
-- there won't be pattern-synonyms generated for 'ODecl' or 'TDecl'
type Decl x = TDecl x
type TDecl x = ODecl x
data Exp var
= EVar var
| ECall var (Exp var)
| EAdd (Exp var) (Exp var)
| ESub (Exp var) (Exp var)
| ELit Int
deriving Show
deriveFamily [t| Stmt String |]
type FIX = Fix Singl CodesStmtString
-- * Alpha Equality Functionality
alphaEqD :: Decl String -> Decl String -> Bool
alphaEqD = (galphaEq IdxDeclString) `on` (deep @FamStmtString)
where
Generic programming boilerplate ;
could be removed . WE are just passing SNat
-- and Proxies around.
galphaEq :: forall iy . (IsNat iy)
=> SNat iy -> FIX iy -> FIX iy -> Bool
galphaEq iy x y = runAlpha (galphaEq' iy x y)
galphaEqT :: forall iy m . (MonadAlphaEq m , IsNat iy)
=> FIX iy -> FIX iy -> m Bool
galphaEqT x y = galphaEq' (getSNat' @iy) x y
galphaEq' :: forall iy m . (MonadAlphaEq m , IsNat iy)
=> SNat iy -> FIX iy -> FIX iy -> m Bool
galphaEq' iy (Fix x)
= maybe (return False) (go iy) . zipRep x . unFix
Performs one default ste by eliminating the topmost Rep
using galphaEqT on the recursive positions and isEqv
-- on the atoms.
step :: forall m c . (MonadAlphaEq m)
=> Rep (Singl :*: Singl) (FIX :*: FIX) c
-> m Bool
step = elimRepM (return . uncurry' eqSingl)
(uncurry' galphaEqT)
(return . and)
-- The actual important 'patterns'; everything
-- else is done by 'step'.
go :: forall iy m . (MonadAlphaEq m)
=> SNat iy
-> Rep (Singl :*: Singl) (FIX :*: FIX)
(Lkup iy CodesStmtString)
-> m Bool
go IdxStmtString x
= case sop x of
StmtStringSAssign_ (SString v1 :*: SString v2) e1e2
-> addRule v1 v2 >> uncurry' (galphaEq' IdxExpString) e1e2
_ -> step x
go IdxDeclString x
= case sop x of
DeclStringDVar_ (SString v1 :*: SString v2)
-> addRule v1 v2 >> return True
DeclStringDFun_ (SString f1 :*: SString f2) (SString x1 :*: SString x2) s
-> addRule f1 f2 >> onNewScope (addRule x1 x2 >> uncurry' galphaEqT s)
_ -> step x
go IdxExpString x
= case sop x of
ExpStringEVar_ (SString v1 :*: SString v2)
-> v1 =~= v2
ExpStringECall_ (SString f1 :*: SString f2) e
-> (&&) <$> (f1 =~= f2) <*> uncurry' galphaEqT e
_ -> step x
go _ x = step x
EXAMPLE
decl fib(n ):
aux = fib(n-1 ) + fib(n-2 ) ;
return aux ;
is alpha eq to
fib(x ):
r = fib(x-1 ) + fib(x-2 ) ;
return r ;
decl fib(n):
aux = fib(n-1) + fib(n-2);
return aux;
is alpha eq to
decl fib(x):
r = fib(x-1) + fib(x-2);
return r;
-}
test1 :: String -> String -> String -> Decl String
test1 fib n aux = DFun fib n
$ (SAssign aux (EAdd (ECall fib (ESub (EVar n) (ELit 1)))
(ECall fib (ESub (EVar n) (ELit 2)))))
`SSeq` (SReturn (EVar aux))
test2 :: String -> String -> String -> Decl String
test2 fib n aux = DFun fib n
$ (SAssign aux (EAdd (ECall fib (ESub (EVar n) (ELit 2)))
(ECall fib (ESub (EVar n) (ELit 1)))))
`SSeq` (SReturn (EVar aux))
EXAMPLE
):
decl g(n ):
z = n + 1
return z
return g(n )
decl f(n):
decl g(n):
z = n + 1
return z
return g(n)
-}
test3 :: String -> String -> String -> Decl String
test3 n1 n2 z = DFun "f" n1
$ SDecl (DFun "g" n2
$ SAssign z (EAdd (EVar n2) (ELit 1))
`SSeq` (SReturn $ EVar z))
`SSeq` (SReturn $ ECall "g" (EVar n1))
-- ** Zipper test
infixr 4 >>>
(>>>) :: (a -> b) -> (b -> c) -> a -> c
(>>>) = flip (.)
test4 :: Int -> Decl String
test4 n = DFun "test" "n"
$ (SAssign "x" (EAdd (ELit 10) (ELit n)))
`SSeq` (SReturn (EVar "x"))
test5 :: Maybe (Decl String)
test5 = enter
>>> down
>=> down
>=> down
>=> down
>=> right
>=> update mk42
>>> leave
>>> return . unEl
$ into @FamStmtString (test4 10)
where
mk42 :: SNat ix -> El FamStmtString ix -> El FamStmtString ix
mk42 IdxExpString _ = El $ ELit 42
mk42 _ x = x
-- ** Holes test
test6 :: Holes Singl CodesStmtString (Const Int) ('I ('S 'Z))
test6 = HPeel' (CS (CS CZ))
( (HPeel' CZ (HOpq' (SString "lol") :* Nil))
:* (Hole' (Const 42))
:* Nil)
test7 :: HolesAnn (Const Int) Singl CodesStmtString (Const Int) ('I ('S 'Z))
test7 = HPeel (Const 1) (CS (CS CZ))
( (HPeel (Const 2) CZ (HOpq (Const 4) (SString "lol") :* Nil))
:* (Hole (Const 3) (Const 42))
:* Nil)
| null | https://raw.githubusercontent.com/VictorCMiraldo/generics-mrsop/b66bb6c651297cdb71655663e34ab35812b38f72/src/Generics/MRSOP/Examples/SimpTH.hs | haskell | # LANGUAGE RankNTypes #
# LANGUAGE GADTs #
# LANGUAGE TypeOperators #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TemplateHaskell #
# LANGUAGE PatternSynonyms #
# OPTIONS_HADDOCK hide, prune, ignore-exports #
|Uses a more involved example to test some
* Simple IMPerative Language:
Below is a little type synonym fun, to make sure
generation is working
Note that since we use 'Decl' directly in the family;
there won't be pattern-synonyms generated for 'ODecl' or 'TDecl'
* Alpha Equality Functionality
and Proxies around.
on the atoms.
The actual important 'patterns'; everything
else is done by 'step'.
** Zipper test
** Holes test | # LANGUAGE TypeApplications #
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE DataKinds #
# LANGUAGE PolyKinds #
# LANGUAGE FunctionalDependencies #
# LANGUAGE LambdaCase #
# OPTIONS_GHC -Wno - missing - pattern - synonym - signatures #
# OPTIONS_GHC -Wno - missing - signatures #
# OPTIONS_GHC -Wno - incomplete - patterns #
# OPTIONS_GHC -Wno - orphans #
of the functionalities of @generics - mrsop@.
module Generics.MRSOP.Examples.SimpTH where
import Data.Function (on)
import Data.Functor.Const
import Generics.MRSOP.Base
import Generics.MRSOP.Holes
import Generics.MRSOP.Opaque
import Generics.MRSOP.Zipper
import Generics.MRSOP.Examples.LambdaAlphaEqTH hiding (FIX, alphaEq)
import Generics.MRSOP.TH
import Control.Monad
data Stmt var
= SAssign var (Exp var)
| SIf (Exp var) (Stmt var) (Stmt var)
| SSeq (Stmt var) (Stmt var)
| SReturn (Exp var)
| SDecl (Decl var)
| SSkip
deriving Show
data ODecl var
= DVar var
| DFun var var (Stmt var)
deriving Show
type Decl x = TDecl x
type TDecl x = ODecl x
data Exp var
= EVar var
| ECall var (Exp var)
| EAdd (Exp var) (Exp var)
| ESub (Exp var) (Exp var)
| ELit Int
deriving Show
deriveFamily [t| Stmt String |]
type FIX = Fix Singl CodesStmtString
alphaEqD :: Decl String -> Decl String -> Bool
alphaEqD = (galphaEq IdxDeclString) `on` (deep @FamStmtString)
where
Generic programming boilerplate ;
could be removed . WE are just passing SNat
galphaEq :: forall iy . (IsNat iy)
=> SNat iy -> FIX iy -> FIX iy -> Bool
galphaEq iy x y = runAlpha (galphaEq' iy x y)
galphaEqT :: forall iy m . (MonadAlphaEq m , IsNat iy)
=> FIX iy -> FIX iy -> m Bool
galphaEqT x y = galphaEq' (getSNat' @iy) x y
galphaEq' :: forall iy m . (MonadAlphaEq m , IsNat iy)
=> SNat iy -> FIX iy -> FIX iy -> m Bool
galphaEq' iy (Fix x)
= maybe (return False) (go iy) . zipRep x . unFix
Performs one default ste by eliminating the topmost Rep
using galphaEqT on the recursive positions and isEqv
step :: forall m c . (MonadAlphaEq m)
=> Rep (Singl :*: Singl) (FIX :*: FIX) c
-> m Bool
step = elimRepM (return . uncurry' eqSingl)
(uncurry' galphaEqT)
(return . and)
go :: forall iy m . (MonadAlphaEq m)
=> SNat iy
-> Rep (Singl :*: Singl) (FIX :*: FIX)
(Lkup iy CodesStmtString)
-> m Bool
go IdxStmtString x
= case sop x of
StmtStringSAssign_ (SString v1 :*: SString v2) e1e2
-> addRule v1 v2 >> uncurry' (galphaEq' IdxExpString) e1e2
_ -> step x
go IdxDeclString x
= case sop x of
DeclStringDVar_ (SString v1 :*: SString v2)
-> addRule v1 v2 >> return True
DeclStringDFun_ (SString f1 :*: SString f2) (SString x1 :*: SString x2) s
-> addRule f1 f2 >> onNewScope (addRule x1 x2 >> uncurry' galphaEqT s)
_ -> step x
go IdxExpString x
= case sop x of
ExpStringEVar_ (SString v1 :*: SString v2)
-> v1 =~= v2
ExpStringECall_ (SString f1 :*: SString f2) e
-> (&&) <$> (f1 =~= f2) <*> uncurry' galphaEqT e
_ -> step x
go _ x = step x
EXAMPLE
decl fib(n ):
aux = fib(n-1 ) + fib(n-2 ) ;
return aux ;
is alpha eq to
fib(x ):
r = fib(x-1 ) + fib(x-2 ) ;
return r ;
decl fib(n):
aux = fib(n-1) + fib(n-2);
return aux;
is alpha eq to
decl fib(x):
r = fib(x-1) + fib(x-2);
return r;
-}
test1 :: String -> String -> String -> Decl String
test1 fib n aux = DFun fib n
$ (SAssign aux (EAdd (ECall fib (ESub (EVar n) (ELit 1)))
(ECall fib (ESub (EVar n) (ELit 2)))))
`SSeq` (SReturn (EVar aux))
test2 :: String -> String -> String -> Decl String
test2 fib n aux = DFun fib n
$ (SAssign aux (EAdd (ECall fib (ESub (EVar n) (ELit 2)))
(ECall fib (ESub (EVar n) (ELit 1)))))
`SSeq` (SReturn (EVar aux))
EXAMPLE
):
decl g(n ):
z = n + 1
return z
return g(n )
decl f(n):
decl g(n):
z = n + 1
return z
return g(n)
-}
test3 :: String -> String -> String -> Decl String
test3 n1 n2 z = DFun "f" n1
$ SDecl (DFun "g" n2
$ SAssign z (EAdd (EVar n2) (ELit 1))
`SSeq` (SReturn $ EVar z))
`SSeq` (SReturn $ ECall "g" (EVar n1))
infixr 4 >>>
(>>>) :: (a -> b) -> (b -> c) -> a -> c
(>>>) = flip (.)
test4 :: Int -> Decl String
test4 n = DFun "test" "n"
$ (SAssign "x" (EAdd (ELit 10) (ELit n)))
`SSeq` (SReturn (EVar "x"))
test5 :: Maybe (Decl String)
test5 = enter
>>> down
>=> down
>=> down
>=> down
>=> right
>=> update mk42
>>> leave
>>> return . unEl
$ into @FamStmtString (test4 10)
where
mk42 :: SNat ix -> El FamStmtString ix -> El FamStmtString ix
mk42 IdxExpString _ = El $ ELit 42
mk42 _ x = x
test6 :: Holes Singl CodesStmtString (Const Int) ('I ('S 'Z))
test6 = HPeel' (CS (CS CZ))
( (HPeel' CZ (HOpq' (SString "lol") :* Nil))
:* (Hole' (Const 42))
:* Nil)
test7 :: HolesAnn (Const Int) Singl CodesStmtString (Const Int) ('I ('S 'Z))
test7 = HPeel (Const 1) (CS (CS CZ))
( (HPeel (Const 2) CZ (HOpq (Const 4) (SString "lol") :* Nil))
:* (Hole (Const 3) (Const 42))
:* Nil)
|
61a095c3b5f811bc33daa9be827476450b81323e3c247956a2a94a01ff4fb9a5 | Engil/Goodboy | utils.ml | open Goodboy
open Notty
open Printf
let msg s = Error (`Msg s)
let a_current = A.(fg black ++ bg green)
let show_hex_i16 i16 = sprintf "0x%04X" i16
let show_hex_i8 i8 = sprintf "0x%02X" i8
let show_instr i = (Instructions.sexp_of_instruction i |> Sexplib.Sexp.to_string)
| null | https://raw.githubusercontent.com/Engil/Goodboy/2e9abc243b929d8bdfb7c5d4874ddb8a07c55fac/debugger/utils.ml | ocaml | open Goodboy
open Notty
open Printf
let msg s = Error (`Msg s)
let a_current = A.(fg black ++ bg green)
let show_hex_i16 i16 = sprintf "0x%04X" i16
let show_hex_i8 i8 = sprintf "0x%02X" i8
let show_instr i = (Instructions.sexp_of_instruction i |> Sexplib.Sexp.to_string)
|
|
25bbf4c482cddf6c6db7abce969854d8e03c937f0e3a461f51dec8601c659f09 | tnoda/rashinban | core.clj | (ns tnoda.rashinban.core
(:refer-clojure :exclude [apply eval])
(:require [clojure.core :as clj]
[clojure.string :as str]
[tnoda.rashinban.protocols :refer [clj->rexp java->clj]])
(:import (org.rosuda.REngine.Rserve RConnection)
(org.rosuda.REngine REXP
REXPDouble
REXPGenericVector
REXPInteger
REXPLogical
REXPNull
REXPString
REXPSymbol
RList)))
(defonce connection (atom nil))
(defn- connect
([]
(reset! connection (RConnection.)))
([^String host]
(reset! connection (RConnection. host)))
([^String host port]
(reset! connection (RConnection. host (int port)))))
(defn- get-conn ^RConnection
[]
(or @connection
(throw (ex-info "Rserve connection has not been established."
{:connection @connection}))))
(defn shutdown
[]
(swap! connection (memfn ^RConnection shutdown)))
(defn eval*
[^String src]
(-> (get-conn) (.eval src) .asNativeJavaObject))
(defn eval
[src]
(java->clj (eval* src)))
(defn apply*
[^String rfn & more]
(let [args (->> (clj/apply list* more)
(map clj->rexp)
(into-array REXP))
what (REXP/asCall rfn ^"[Lorg.rosuda.REngine.REXP;" args)]
(-> (get-conn)
(.eval what nil true)
.asNativeJavaObject)))
(defn apply
[& args]
(java->clj (clj/apply apply* args)))
(defn- rdefn
[rfn]
(let [clojurize #(symbol (str/replace % #"[./]" "-"))]
(intern 'tnoda.rashinban
(clojurize rfn)
#(apply rfn %&))))
(defn- load-builtins
[]
(doseq [rfn (apply "builtins" nil)]
(rdefn rfn)))
(defn- load-attached-package-fns
[]
(doseq [pkg (->> (eval "search()")
(keep #(second (re-find #"^package:(.+)" %))))
rfn (eval (str "ls(getNamespace(\"" pkg "\"))"))]
(rdefn rfn)))
(defn init
[& args]
(connect)
(load-builtins)
(load-attached-package-fns))
| null | https://raw.githubusercontent.com/tnoda/rashinban/a9e6053d2a9cf852d04d594f52e03e045415a2e7/src/tnoda/rashinban/core.clj | clojure | (ns tnoda.rashinban.core
(:refer-clojure :exclude [apply eval])
(:require [clojure.core :as clj]
[clojure.string :as str]
[tnoda.rashinban.protocols :refer [clj->rexp java->clj]])
(:import (org.rosuda.REngine.Rserve RConnection)
(org.rosuda.REngine REXP
REXPDouble
REXPGenericVector
REXPInteger
REXPLogical
REXPNull
REXPString
REXPSymbol
RList)))
(defonce connection (atom nil))
(defn- connect
([]
(reset! connection (RConnection.)))
([^String host]
(reset! connection (RConnection. host)))
([^String host port]
(reset! connection (RConnection. host (int port)))))
(defn- get-conn ^RConnection
[]
(or @connection
(throw (ex-info "Rserve connection has not been established."
{:connection @connection}))))
(defn shutdown
[]
(swap! connection (memfn ^RConnection shutdown)))
(defn eval*
[^String src]
(-> (get-conn) (.eval src) .asNativeJavaObject))
(defn eval
[src]
(java->clj (eval* src)))
(defn apply*
[^String rfn & more]
(let [args (->> (clj/apply list* more)
(map clj->rexp)
(into-array REXP))
what (REXP/asCall rfn ^"[Lorg.rosuda.REngine.REXP;" args)]
(-> (get-conn)
(.eval what nil true)
.asNativeJavaObject)))
(defn apply
[& args]
(java->clj (clj/apply apply* args)))
(defn- rdefn
[rfn]
(let [clojurize #(symbol (str/replace % #"[./]" "-"))]
(intern 'tnoda.rashinban
(clojurize rfn)
#(apply rfn %&))))
(defn- load-builtins
[]
(doseq [rfn (apply "builtins" nil)]
(rdefn rfn)))
(defn- load-attached-package-fns
[]
(doseq [pkg (->> (eval "search()")
(keep #(second (re-find #"^package:(.+)" %))))
rfn (eval (str "ls(getNamespace(\"" pkg "\"))"))]
(rdefn rfn)))
(defn init
[& args]
(connect)
(load-builtins)
(load-attached-package-fns))
|
|
aa36bc78aac2bbcce3f493adab262d942ced9d910c25322fd61c44fee793c4eb | PhDP/Akarui | FOL.hs | {-# LANGUAGE TypeSynonymInstances, FlexibleInstances #-}
| Type and functions for first - order predicate logic .
module Akarui.FOL.FOL where
import qualified Data.Map as Map
import Data.Map (Map)
import qualified Data.Set as Set
import Data.Set (Set)
import Data.List (foldl')
import qualified Data.Text as T
import Akarui.ShowTxt
import Akarui.FOL.Formula
import Akarui.FOL.Predicate (Predicate (Predicate))
import Akarui.FOL.Symbols (symbolic)
import qualified Akarui.FOL.Predicate as Pred
import Akarui.FOL.Term (Term (Constant, Variable, Function))
import qualified Akarui.FOL.Term as Term
import Akarui.FOL.PrettyPrint
import Akarui.FOL.BinT
import Akarui.FOL.QuanT
| A first - order logic formula is simply a formula of predicates .
type FOL = Formula Predicate
-- | Special "Truth", "Top", "True" predicate.
top :: FOL
top = Atom $ Predicate "Top" []
-- | Special "False", "Bot", "Bottom" predicate.
bot :: FOL
bot = Atom $ Predicate "Bot" []
instance Show FOL where
show = T.unpack . prettyPrintFm symbolic
instance ShowTxt FOL where
showTxt = prettyPrintFm symbolic
instance PrettyPrint FOL where
prettyPrint = prettyPrintFm
-- | Extracts predicates from a list of formulas. If a formula is not an atom,
-- it will be ignored.
toPredicates :: [FOL] -> [Predicate]
toPredicates = foldl' (\acc f -> case f of Atom p -> p : acc; _ -> acc) []
-- | Tests if the formula is 'grounded', i.e. if it has no variables.
ground :: FOL -> Bool
ground f = case f of
Atom (Predicate _ ts) -> all Term.ground ts
BinOp _ x y -> ground x || ground y
Quantifier _ _ x -> ground x
_ -> False
| Gathers all the variables in a first - order logic formula .
variables :: FOL -> Set T.Text
variables = gat Set.empty
where
-- Gathers variables from terms
gatT s term = case term of
Function _ ts -> foldl' gatT Set.empty ts
Variable v -> Set.insert v s
Constant _ -> Set.empty
-- Gathers variables from formula
gat s fm = case fm of
Atom (Predicate _ ts) -> foldl' gatT Set.empty ts
Not x -> Set.union (gatE x) s
BinOp _ x y -> Set.unions [gatE x, gatE y, s]
Quantifier _ _ x -> Set.union (gatE x) s
-- Gathers with an empty set
gatE = gat Set.empty
-- | Test for the presence of a predicate in the formula.
hasPred :: Predicate -> FOL -> Bool
hasPred p f = case f of
Atom p' -> p == p'
BinOp _ x y -> hasPred p x || hasPred p y
Quantifier _ _ x -> hasPred p x
_ -> False
-- | Test for the presence of a predicate in the formula using only the name
-- of the predicate.
hasPredName :: FOL -> T.Text -> Bool
hasPredName f n = case f of
Atom (Predicate n' _) -> n == n'
BinOp _ x y -> hasPredName x n || hasPredName y n
Quantifier _ _ x -> hasPredName x n
_ -> False
-- | Returns true if the formula has functions. This is often used in algorithms
-- where we must ensure all functions have been resolved to an object.
hasFun :: FOL -> Bool
hasFun f = case f of
Atom (Predicate _ ts) -> any (\trm -> (Term.numFuns trm :: Int) > 0) ts
BinOp _ x y -> hasFun x || hasFun y
Quantifier _ _ x -> hasFun x
_ -> False
-- | Substitute a term in the formula.
substitute :: Term -> Term -> FOL -> FOL
substitute old new f = case f of
Atom (Predicate n ts)
-> Atom $ Predicate n $ map (Term.substitute old new) ts
Not x -> Not $ substitute old new x
BinOp b x y -> BinOp b (substitute old new x) (substitute old new y)
Quantifier q v x -> Quantifier q v (substitute old new x)
| Shows the internal structure of the first - order logic formula . This is
-- mostly useful for testing and making sure the formula has the correct
-- structure.
showFOLStruct :: FOL -> T.Text
showFOLStruct f = case f of
Atom a -> Pred.showStruct a
Not x -> T.concat ["Not (", showFOLStruct x, ")"]
BinOp b x y -> T.concat [showTxt b, " (", showFOLStruct x, ") (", showFOLStruct y, ")"]
Quantifier q v x -> T.concat [showTxt q, " ", v, "(", showFOLStruct x, ")"]
-- | Resolves universal Quantifiers, substituting the variables in the 'ForAll'
-- for a given term (a constant, generally).
resolveForAll :: T.Text -> Term -> FOL -> FOL
resolveForAll v t f = case f of
Not x -> Not $ resolveForAll v t x
BinOp b x y -> BinOp b (resolveForAll v t x) (resolveForAll v t y)
Quantifier ForAll v' x ->
if v == v' then substitute (Variable v) t x
else Quantifier ForAll v' (resolveForAll v t x)
Quantifier Exists v' x -> Quantifier Exists v' (resolveForAll v t x)
_ -> f
-- | Takes a formula, a map between functions and constants, and a list of
-- constants to produce a set of groundings.
--
-- Reference:
P Domingos and D , : An Interface Layer for Artificial
Intelligence , 2009 , Morgan & Claypool . p. 14 .
groundings :: [Term] -> FOL -> Set FOL
groundings cs f = loopV
where
groundSub v f' = case f' of
Atom p ->
if Pred.hasVar v p then
let as = map (\c -> Atom $ Pred.substitute (Variable v) c p) cs in
foldr1 (BinOp Or) as
else
f'
Not x -> Not $ groundSub v x
BinOp b x y -> BinOp b (groundSub v x) (groundSub v y)
Quantifier q v' x -> Quantifier q v' (groundSub v' x)
existsVar f' = case f' of
Not x -> Not $ existsVar x
BinOp b x y -> BinOp b (existsVar x) (existsVar y)
Quantifier Exists v x -> existsVar $ groundSub v x
Quantifier ForAll v x -> Quantifier ForAll v $ existsVar x
_ -> f'
f0 = existsVar f
g0 = Set.fromList [f0]
vs = uniquanVars f0
loopV = Set.foldr' loopG g0 vs
loopG v g = Set.foldr (\x a -> Set.union a (Set.fromList x)) Set.empty (gr v g)
where
gr v' =
Set.map (\fm -> map (\c -> simplify $ resolveForAll v' c fm) cs)
-- | Returns all possible valuations of a set of formula.
allAss :: Set FOL -> [Map Predicate Bool]
allAss fs = if null as then [] else ms (head as) (tail as)
where
as = Set.toList $ Set.foldr Set.union Set.empty $ Set.map atoms fs
ms atm s =
if null s then
[Map.fromList [(atm, True)], Map.fromList [(atm, False)]]
else
map (Map.insert atm True) (ms (head s) (tail s)) ++
map (Map.insert atm False) (ms (head s) (tail s))
-- | The unary negation operator.
lneg :: FOL -> FOL
lneg (Not y) = y
lneg x
| x == top = bot
| x == bot = top
| otherwise = Not x
-- | The 'and' (conjunction) binary operator.
land :: FOL -> FOL -> FOL
land x y
| x == top && y == top = top
| x == bot || y == bot = bot
| x == top = y
| y == top = x
| otherwise = BinOp And x y
-- | The 'or' (inclusive disjunction) binary operator.
lor :: FOL -> FOL -> FOL
lor x y
| x == top || y == top = top
| x == bot = y
| y == bot = x
| otherwise = BinOp Or x y
-- | The 'exclusive or' (exclusive disjunction) binary operator.
lxor :: FOL -> FOL -> FOL
lxor x y
| y == bot = x
| x == bot = y
| y == top = lneg x
| x == top = lneg y
| otherwise = BinOp Xor x y
-- | The 'implies' (implication) binary operator.
limplies :: FOL -> FOL -> FOL
limplies x y
| x == top = y
| x == bot = top
| y == bot = lneg x
| y == top = top
| otherwise = BinOp Implies x y
-- | The 'if and only if' (equivalence) binary operator.
liff :: FOL -> FOL -> FOL
liff x y
| x == top = y
| x == bot && y == bot = top
| x == bot = lneg y
| y == bot = lneg x
| y == top = x
| otherwise = BinOp Iff x y
-- | Dispatch binary operators to their resolution function.
binOperator :: BinT -> FOL -> FOL -> FOL
binOperator b = case b of
And -> land
Or -> lor
Xor -> lxor
Implies -> limplies
Iff -> liff
| Simplify using ' algorithm .
simplify :: FOL -> FOL
simplify f = case f of
Not x -> lneg $ sim1 $ simplify x
BinOp b x y -> binOperator b (sim1 $ simplify x) (sim1 $ simplify y)
Quantifier q v x -> Quantifier q v $ sim1 $ simplify x
_ -> f
where
sim1 f' = case f' of
Not x -> lneg $ sim1 x
BinOp b x y -> binOperator b (sim1 x) (sim1 y)
Quantifier q v x -> Quantifier q v $ sim1 x
_ -> f'
-- | Evaluates a formula given an assignment to atoms. If the assignment is
-- incomplete, eval with evaluate as much as possible but might not reduce
-- formula to top/bot. This function completely ignores Quantifiers. For
functions that rely on Quantifiers , see the Sphinx . first - order logic
-- module.
eval :: Map Predicate Bool -> FOL -> FOL
eval ass = simplify . eval'
where
eval' f' = case f' of
Atom a -> case Map.lookup a ass of
Just True -> top
Just False -> bot
Nothing -> f'
Not x -> lneg $ eval' x
BinOp b x y -> BinOp b (eval' x) (eval' y)
Quantifier _ _ x -> eval' x
-- | Given an assignment to atoms, test whethers the formula evaluates to 'True'
-- This functions ignores Quantifiers (if present, and they should not be there).
satisfy :: Map Predicate Bool -> FOL -> Bool
satisfy ass f = eval ass f == top
-- | Given an assignment to atoms, test whethers the formula fails to evaluate
-- to true. That is: unsatisfiable means it evaluates to bot or failed to
-- evaluate to top/bot.
unsatisfiable :: Map Predicate Bool -> FOL -> Bool
unsatisfiable ass f = eval ass f /= top
-- | Takes a formula, a list of assignments, and returns how many were true,
-- false, or undefined (could not be reduced to either top or bot).
numTrueFalse :: (Integral n) => FOL -> [Map Predicate Bool] -> (n, n, n)
numTrueFalse f =
foldl'
(\(t, b, u) ass ->
let v = eval ass f in
if v == top then (t + 1, b, u)
else if v == bot then (t, b + 1, u)
else (t, b, u + 1))
(0, 0, 0)
| null | https://raw.githubusercontent.com/PhDP/Akarui/4ad888d011f7115677e8f9ba18887865f5150746/Akarui/FOL/FOL.hs | haskell | # LANGUAGE TypeSynonymInstances, FlexibleInstances #
| Special "Truth", "Top", "True" predicate.
| Special "False", "Bot", "Bottom" predicate.
| Extracts predicates from a list of formulas. If a formula is not an atom,
it will be ignored.
| Tests if the formula is 'grounded', i.e. if it has no variables.
Gathers variables from terms
Gathers variables from formula
Gathers with an empty set
| Test for the presence of a predicate in the formula.
| Test for the presence of a predicate in the formula using only the name
of the predicate.
| Returns true if the formula has functions. This is often used in algorithms
where we must ensure all functions have been resolved to an object.
| Substitute a term in the formula.
mostly useful for testing and making sure the formula has the correct
structure.
| Resolves universal Quantifiers, substituting the variables in the 'ForAll'
for a given term (a constant, generally).
| Takes a formula, a map between functions and constants, and a list of
constants to produce a set of groundings.
Reference:
| Returns all possible valuations of a set of formula.
| The unary negation operator.
| The 'and' (conjunction) binary operator.
| The 'or' (inclusive disjunction) binary operator.
| The 'exclusive or' (exclusive disjunction) binary operator.
| The 'implies' (implication) binary operator.
| The 'if and only if' (equivalence) binary operator.
| Dispatch binary operators to their resolution function.
| Evaluates a formula given an assignment to atoms. If the assignment is
incomplete, eval with evaluate as much as possible but might not reduce
formula to top/bot. This function completely ignores Quantifiers. For
module.
| Given an assignment to atoms, test whethers the formula evaluates to 'True'
This functions ignores Quantifiers (if present, and they should not be there).
| Given an assignment to atoms, test whethers the formula fails to evaluate
to true. That is: unsatisfiable means it evaluates to bot or failed to
evaluate to top/bot.
| Takes a formula, a list of assignments, and returns how many were true,
false, or undefined (could not be reduced to either top or bot). |
| Type and functions for first - order predicate logic .
module Akarui.FOL.FOL where
import qualified Data.Map as Map
import Data.Map (Map)
import qualified Data.Set as Set
import Data.Set (Set)
import Data.List (foldl')
import qualified Data.Text as T
import Akarui.ShowTxt
import Akarui.FOL.Formula
import Akarui.FOL.Predicate (Predicate (Predicate))
import Akarui.FOL.Symbols (symbolic)
import qualified Akarui.FOL.Predicate as Pred
import Akarui.FOL.Term (Term (Constant, Variable, Function))
import qualified Akarui.FOL.Term as Term
import Akarui.FOL.PrettyPrint
import Akarui.FOL.BinT
import Akarui.FOL.QuanT
| A first - order logic formula is simply a formula of predicates .
type FOL = Formula Predicate
top :: FOL
top = Atom $ Predicate "Top" []
bot :: FOL
bot = Atom $ Predicate "Bot" []
instance Show FOL where
show = T.unpack . prettyPrintFm symbolic
instance ShowTxt FOL where
showTxt = prettyPrintFm symbolic
instance PrettyPrint FOL where
prettyPrint = prettyPrintFm
toPredicates :: [FOL] -> [Predicate]
toPredicates = foldl' (\acc f -> case f of Atom p -> p : acc; _ -> acc) []
ground :: FOL -> Bool
ground f = case f of
Atom (Predicate _ ts) -> all Term.ground ts
BinOp _ x y -> ground x || ground y
Quantifier _ _ x -> ground x
_ -> False
| Gathers all the variables in a first - order logic formula .
variables :: FOL -> Set T.Text
variables = gat Set.empty
where
gatT s term = case term of
Function _ ts -> foldl' gatT Set.empty ts
Variable v -> Set.insert v s
Constant _ -> Set.empty
gat s fm = case fm of
Atom (Predicate _ ts) -> foldl' gatT Set.empty ts
Not x -> Set.union (gatE x) s
BinOp _ x y -> Set.unions [gatE x, gatE y, s]
Quantifier _ _ x -> Set.union (gatE x) s
gatE = gat Set.empty
hasPred :: Predicate -> FOL -> Bool
hasPred p f = case f of
Atom p' -> p == p'
BinOp _ x y -> hasPred p x || hasPred p y
Quantifier _ _ x -> hasPred p x
_ -> False
hasPredName :: FOL -> T.Text -> Bool
hasPredName f n = case f of
Atom (Predicate n' _) -> n == n'
BinOp _ x y -> hasPredName x n || hasPredName y n
Quantifier _ _ x -> hasPredName x n
_ -> False
hasFun :: FOL -> Bool
hasFun f = case f of
Atom (Predicate _ ts) -> any (\trm -> (Term.numFuns trm :: Int) > 0) ts
BinOp _ x y -> hasFun x || hasFun y
Quantifier _ _ x -> hasFun x
_ -> False
substitute :: Term -> Term -> FOL -> FOL
substitute old new f = case f of
Atom (Predicate n ts)
-> Atom $ Predicate n $ map (Term.substitute old new) ts
Not x -> Not $ substitute old new x
BinOp b x y -> BinOp b (substitute old new x) (substitute old new y)
Quantifier q v x -> Quantifier q v (substitute old new x)
| Shows the internal structure of the first - order logic formula . This is
showFOLStruct :: FOL -> T.Text
showFOLStruct f = case f of
Atom a -> Pred.showStruct a
Not x -> T.concat ["Not (", showFOLStruct x, ")"]
BinOp b x y -> T.concat [showTxt b, " (", showFOLStruct x, ") (", showFOLStruct y, ")"]
Quantifier q v x -> T.concat [showTxt q, " ", v, "(", showFOLStruct x, ")"]
resolveForAll :: T.Text -> Term -> FOL -> FOL
resolveForAll v t f = case f of
Not x -> Not $ resolveForAll v t x
BinOp b x y -> BinOp b (resolveForAll v t x) (resolveForAll v t y)
Quantifier ForAll v' x ->
if v == v' then substitute (Variable v) t x
else Quantifier ForAll v' (resolveForAll v t x)
Quantifier Exists v' x -> Quantifier Exists v' (resolveForAll v t x)
_ -> f
P Domingos and D , : An Interface Layer for Artificial
Intelligence , 2009 , Morgan & Claypool . p. 14 .
groundings :: [Term] -> FOL -> Set FOL
groundings cs f = loopV
where
groundSub v f' = case f' of
Atom p ->
if Pred.hasVar v p then
let as = map (\c -> Atom $ Pred.substitute (Variable v) c p) cs in
foldr1 (BinOp Or) as
else
f'
Not x -> Not $ groundSub v x
BinOp b x y -> BinOp b (groundSub v x) (groundSub v y)
Quantifier q v' x -> Quantifier q v' (groundSub v' x)
existsVar f' = case f' of
Not x -> Not $ existsVar x
BinOp b x y -> BinOp b (existsVar x) (existsVar y)
Quantifier Exists v x -> existsVar $ groundSub v x
Quantifier ForAll v x -> Quantifier ForAll v $ existsVar x
_ -> f'
f0 = existsVar f
g0 = Set.fromList [f0]
vs = uniquanVars f0
loopV = Set.foldr' loopG g0 vs
loopG v g = Set.foldr (\x a -> Set.union a (Set.fromList x)) Set.empty (gr v g)
where
gr v' =
Set.map (\fm -> map (\c -> simplify $ resolveForAll v' c fm) cs)
allAss :: Set FOL -> [Map Predicate Bool]
allAss fs = if null as then [] else ms (head as) (tail as)
where
as = Set.toList $ Set.foldr Set.union Set.empty $ Set.map atoms fs
ms atm s =
if null s then
[Map.fromList [(atm, True)], Map.fromList [(atm, False)]]
else
map (Map.insert atm True) (ms (head s) (tail s)) ++
map (Map.insert atm False) (ms (head s) (tail s))
lneg :: FOL -> FOL
lneg (Not y) = y
lneg x
| x == top = bot
| x == bot = top
| otherwise = Not x
land :: FOL -> FOL -> FOL
land x y
| x == top && y == top = top
| x == bot || y == bot = bot
| x == top = y
| y == top = x
| otherwise = BinOp And x y
lor :: FOL -> FOL -> FOL
lor x y
| x == top || y == top = top
| x == bot = y
| y == bot = x
| otherwise = BinOp Or x y
lxor :: FOL -> FOL -> FOL
lxor x y
| y == bot = x
| x == bot = y
| y == top = lneg x
| x == top = lneg y
| otherwise = BinOp Xor x y
limplies :: FOL -> FOL -> FOL
limplies x y
| x == top = y
| x == bot = top
| y == bot = lneg x
| y == top = top
| otherwise = BinOp Implies x y
liff :: FOL -> FOL -> FOL
liff x y
| x == top = y
| x == bot && y == bot = top
| x == bot = lneg y
| y == bot = lneg x
| y == top = x
| otherwise = BinOp Iff x y
binOperator :: BinT -> FOL -> FOL -> FOL
binOperator b = case b of
And -> land
Or -> lor
Xor -> lxor
Implies -> limplies
Iff -> liff
| Simplify using ' algorithm .
simplify :: FOL -> FOL
simplify f = case f of
Not x -> lneg $ sim1 $ simplify x
BinOp b x y -> binOperator b (sim1 $ simplify x) (sim1 $ simplify y)
Quantifier q v x -> Quantifier q v $ sim1 $ simplify x
_ -> f
where
sim1 f' = case f' of
Not x -> lneg $ sim1 x
BinOp b x y -> binOperator b (sim1 x) (sim1 y)
Quantifier q v x -> Quantifier q v $ sim1 x
_ -> f'
functions that rely on Quantifiers , see the Sphinx . first - order logic
eval :: Map Predicate Bool -> FOL -> FOL
eval ass = simplify . eval'
where
eval' f' = case f' of
Atom a -> case Map.lookup a ass of
Just True -> top
Just False -> bot
Nothing -> f'
Not x -> lneg $ eval' x
BinOp b x y -> BinOp b (eval' x) (eval' y)
Quantifier _ _ x -> eval' x
satisfy :: Map Predicate Bool -> FOL -> Bool
satisfy ass f = eval ass f == top
unsatisfiable :: Map Predicate Bool -> FOL -> Bool
unsatisfiable ass f = eval ass f /= top
numTrueFalse :: (Integral n) => FOL -> [Map Predicate Bool] -> (n, n, n)
numTrueFalse f =
foldl'
(\(t, b, u) ass ->
let v = eval ass f in
if v == top then (t + 1, b, u)
else if v == bot then (t, b + 1, u)
else (t, b, u + 1))
(0, 0, 0)
|
8faa3a5e9c9472d9eb6558d836a2dbdf70a0b1fc1d37d78186a6e92493912347 | mhayashi1120/Gauche-net-twitter | module.scm | (use gauche.test)
(use gauche.process)
(use file.util)
(use net.favotter)
(use net.twitter)
(use net.twitter.account)
(use net.twitter.auth)
(use net.twitter.block)
(use net.twitter.core)
(use net.twitter.dm)
(use net.twitter.friendship)
(use net.twitter.geo)
(use net.twitter.help)
(use net.twitter.list)
(use net.twitter.saved-search)
(use net.twitter.search)
(use net.twitter.timeline)
(use net.twitter.status)
(use net.twitter.stream)
(use net.twitter.user)
(use net.twitter.favorite)
(use net.twitter.mute)
(use net.twitter.media)
(use net.twitter.media+)
(use net.twitter.trends)
(use net.twitter.snowflake)
(define (main args)
(test-start "Start test all module")
(module-test)
(executable-test)
(test-end :exit-on-failure #t))
(define (executable-test)
(test-script "net/twitauth.scm")
(test-script "net/twitter/app/upload-media.scm"))
(define (module-test)
(test-module 'net.favotter)
(test-module 'net.twitter)
(test-module 'net.twitter.account)
(test-module 'net.twitter.auth)
(test-module 'net.twitter.base)
(test-module 'net.twitter.block)
(test-module 'net.twitter.core)
(test-module 'net.twitter.dm)
(test-module 'net.twitter.favorite)
(test-module 'net.twitter.friendship)
(test-module 'net.twitter.geo)
(test-module 'net.twitter.help)
(test-module 'net.twitter.list)
(test-module 'net.twitter.media)
(test-module 'net.twitter.media+)
(test-module 'net.twitter.mute)
(test-module 'net.twitter.saved-search)
(test-module 'net.twitter.search)
(test-module 'net.twitter.snowflake)
(test-module 'net.twitter.status)
(test-module 'net.twitter.stream)
(test-module 'net.twitter.timeline)
(test-module 'net.twitter.trends)
(test-module 'net.twitter.user)
)
| null | https://raw.githubusercontent.com/mhayashi1120/Gauche-net-twitter/2c6ae5ff15461cb34a86c71e8f9f4eb5b7a7bf87/__tests__/module.scm | scheme | (use gauche.test)
(use gauche.process)
(use file.util)
(use net.favotter)
(use net.twitter)
(use net.twitter.account)
(use net.twitter.auth)
(use net.twitter.block)
(use net.twitter.core)
(use net.twitter.dm)
(use net.twitter.friendship)
(use net.twitter.geo)
(use net.twitter.help)
(use net.twitter.list)
(use net.twitter.saved-search)
(use net.twitter.search)
(use net.twitter.timeline)
(use net.twitter.status)
(use net.twitter.stream)
(use net.twitter.user)
(use net.twitter.favorite)
(use net.twitter.mute)
(use net.twitter.media)
(use net.twitter.media+)
(use net.twitter.trends)
(use net.twitter.snowflake)
(define (main args)
(test-start "Start test all module")
(module-test)
(executable-test)
(test-end :exit-on-failure #t))
(define (executable-test)
(test-script "net/twitauth.scm")
(test-script "net/twitter/app/upload-media.scm"))
(define (module-test)
(test-module 'net.favotter)
(test-module 'net.twitter)
(test-module 'net.twitter.account)
(test-module 'net.twitter.auth)
(test-module 'net.twitter.base)
(test-module 'net.twitter.block)
(test-module 'net.twitter.core)
(test-module 'net.twitter.dm)
(test-module 'net.twitter.favorite)
(test-module 'net.twitter.friendship)
(test-module 'net.twitter.geo)
(test-module 'net.twitter.help)
(test-module 'net.twitter.list)
(test-module 'net.twitter.media)
(test-module 'net.twitter.media+)
(test-module 'net.twitter.mute)
(test-module 'net.twitter.saved-search)
(test-module 'net.twitter.search)
(test-module 'net.twitter.snowflake)
(test-module 'net.twitter.status)
(test-module 'net.twitter.stream)
(test-module 'net.twitter.timeline)
(test-module 'net.twitter.trends)
(test-module 'net.twitter.user)
)
|
|
50eb9fe45ef6d00b755eb5d3373c99f33e3b9d594da195701e1663caf66169ee | crategus/cl-cffi-gtk | rtest-gtk-print-unix-dialog.lisp | (def-suite gtk-print-unix-dialog :in gtk-suite)
(in-suite gtk-print-unix-dialog)
;;; --- Types and Values -------------------------------------------------------
GtkPrintCapabilities
(test gtk-print-capabilities
;; Check the type
(is (g-type-is-flags "GtkPrintCapabilities"))
;; Check the registered name
(is (eq 'gtk-print-capabilities
(registered-flags-type "GtkPrintCapabilities")))
;; Check the type initializer
(is (eq (gtype "GtkPrintCapabilities")
(gtype (foreign-funcall "gtk_print_capabilities_get_type" g-size))))
;; Check the names
(is (equal '("GTK_PRINT_CAPABILITY_PAGE_SET" "GTK_PRINT_CAPABILITY_COPIES"
"GTK_PRINT_CAPABILITY_COLLATE" "GTK_PRINT_CAPABILITY_REVERSE"
"GTK_PRINT_CAPABILITY_SCALE" "GTK_PRINT_CAPABILITY_GENERATE_PDF"
"GTK_PRINT_CAPABILITY_GENERATE_PS" "GTK_PRINT_CAPABILITY_PREVIEW"
"GTK_PRINT_CAPABILITY_NUMBER_UP" "GTK_PRINT_CAPABILITY_NUMBER_UP_LAYOUT")
(mapcar #'flags-item-name
(get-flags-items "GtkPrintCapabilities"))))
;; Check the values
(is (equal '(1 2 4 8 16 32 64 128 256 512)
(mapcar #'flags-item-value
(get-flags-items "GtkPrintCapabilities"))))
Check the nick names
(is (equal '("page-set" "copies" "collate" "reverse" "scale" "generate-pdf"
"generate-ps" "preview" "number-up" "number-up-layout")
(mapcar #'flags-item-nick
(get-flags-items "GtkPrintCapabilities"))))
;; Check the flags definition
(is (equal '(DEFINE-G-FLAGS "GtkPrintCapabilities"
GTK-PRINT-CAPABILITIES
(:EXPORT T
:TYPE-INITIALIZER "gtk_print_capabilities_get_type")
(:PAGE-SET 1)
(:COPIES 2)
(:COLLATE 4)
(:REVERSE 8)
(:SCALE 16)
(:GENERATE-PDF 32)
(:GENERATE-PS 64)
(:PREVIEW 128)
(:NUMBER-UP 256)
(:NUMBER-UP-LAYOUT 512))
(get-g-type-definition "GtkPrintCapabilities"))))
;;; GtkPrintUnixDialog
(test gtk-print-unix-dialog-class
;; Type check
(is (g-type-is-object "GtkPrintUnixDialog"))
;; Check the registered name
(is (eq 'gtk-print-unix-dialog
(registered-object-type-by-name "GtkPrintUnixDialog")))
;; Check the type initializer
(is (eq (gtype "GtkPrintUnixDialog")
(gtype (foreign-funcall "gtk_print_unix_dialog_get_type" g-size))))
;; Check the parent
(is (eq (gtype "GtkDialog") (g-type-parent "GtkPrintUnixDialog")))
;; Check the children
(is (equal '()
(mapcar #'g-type-name (g-type-children "GtkPrintUnixDialog"))))
;; Check the interfaces
(is (equal '("AtkImplementorIface" "GtkBuildable")
(mapcar #'g-type-name (g-type-interfaces "GtkPrintUnixDialog"))))
;; Check the class properties
(is (equal '("accept-focus" "app-paintable" "application" "attached-to"
"border-width" "can-default" "can-focus" "child"
"composite-child" "current-page" "decorated" "default-height"
"default-width" "deletable" "destroy-with-parent"
"double-buffered" "embed-page-setup" "events" "expand"
"focus-on-click" "focus-on-map" "focus-visible" "gravity"
"halign" "has-default" "has-focus" "has-resize-grip"
"has-selection" "has-tooltip" "has-toplevel-focus"
"height-request" "hexpand" "hexpand-set"
"hide-titlebar-when-maximized" "icon" "icon-name" "is-active"
"is-focus" "is-maximized" "manual-capabilities" "margin"
"margin-bottom" "margin-end" "margin-left" "margin-right"
"margin-start" "margin-top" "mnemonics-visible" "modal" "name"
"no-show-all" "opacity" "page-setup" "parent" "print-settings"
"receives-default" "resizable" "resize-grip-visible"
"resize-mode" "role" "scale-factor" "screen" "selected-printer"
"sensitive" "skip-pager-hint" "skip-taskbar-hint" "startup-id"
"style" "support-selection" "title" "tooltip-markup"
"tooltip-text" "transient-for" "type" "type-hint" "urgency-hint"
"use-header-bar" "valign" "vexpand" "vexpand-set" "visible"
"width-request" "window" "window-position")
(stable-sort (mapcar #'g-param-spec-name
(g-object-class-list-properties "GtkPrintUnixDialog"))
#'string-lessp)))
;; Get the names of the style properties.
(is (equal '("cursor-aspect-ratio" "cursor-color" "focus-line-pattern"
"focus-line-width" "focus-padding" "interior-focus" "link-color"
"scroll-arrow-hlength" "scroll-arrow-vlength"
"secondary-cursor-color" "separator-height" "separator-width"
"text-handle-height" "text-handle-width" "visited-link-color"
"wide-separators" "window-dragging" "decoration-button-layout"
"decoration-resize-handle" "action-area-border" "button-spacing"
"content-area-border" "content-area-spacing")
(mapcar #'g-param-spec-name
(gtk-widget-class-list-style-properties "GtkPrintUnixDialog"))))
;; Get the names of the child properties
(is (equal '()
(mapcar #'g-param-spec-name
(gtk-container-class-list-child-properties "GtkPrintUnixDialog"))))
;; Check the class definition
(is (equal '(DEFINE-G-OBJECT-CLASS "GtkPrintUnixDialog" GTK-PRINT-UNIX-DIALOG
(:SUPERCLASS GTK-DIALOG :EXPORT T :INTERFACES
("AtkImplementorIface" "GtkBuildable")
:TYPE-INITIALIZER "gtk_print_unix_dialog_get_type")
((CURRENT-PAGE GTK-PRINT-UNIX-DIALOG-CURRENT-PAGE
"current-page" "gint" T T)
(EMBED-PAGE-SETUP
GTK-PRINT-UNIX-DIALOG-EMBED-PAGE-SETUP
"embed-page-setup" "gboolean" T T)
(HAS-SELECTION GTK-PRINT-UNIX-DIALOG-HAS-SELECTION
"has-selection" "gboolean" T T)
(MANUAL-CAPABILITIES
GTK-PRINT-UNIX-DIALOG-MANUAL-CAPABILITIES
"manual-capabilities" "GtkPrintCapabilities" T T)
(PAGE-SETUP GTK-PRINT-UNIX-DIALOG-PAGE-SETUP
"page-setup" "GtkPageSetup" T T)
(PRINT-SETTINGS GTK-PRINT-UNIX-DIALOG-PRINT-SETTINGS
"print-settings" "GtkPrintSettings" T T)
(SELECTED-PRINTER
GTK-PRINT-UNIX-DIALOG-SELECTED-PRINTER
"selected-printer" "GtkPrinter" T NIL)
(SUPPORT-SELECTION
GTK-PRINT-UNIX-DIALOG-SUPPORT-SELECTION
"support-selection" "gboolean" T T)))
(get-g-type-definition "GtkPrintUnixDialog"))))
;;; --- Properties -------------------------------------------------------------
(test gtk-print-unix-dialog-properties
(let ((dialog (make-instance 'gtk-print-unix-dialog)))
;; current-page
(is (= -1 (gtk-print-unix-dialog-current-page dialog)))
(is (= 10 (setf (gtk-print-unix-dialog-current-page dialog) 10)))
(is (= 10 (gtk-print-unix-dialog-current-page dialog)))
;; embed-page-setup
(is-false (gtk-print-unix-dialog-embed-page-setup dialog))
(is-true (setf (gtk-print-unix-dialog-embed-page-setup dialog) t))
(is-true (gtk-print-unix-dialog-embed-page-setup dialog))
;; has-selection
(is-false (gtk-print-unix-dialog-has-selection dialog))
(is-true (setf (gtk-print-unix-dialog-has-selection dialog) t))
(is-true (gtk-print-unix-dialog-has-selection dialog))
;; manual-capabilities
(is-false (gtk-print-unix-dialog-manual-capabilities dialog))
(is (equal '(:page-set :scale)
(setf (gtk-print-unix-dialog-manual-capabilities dialog) '(:page-set :scale))))
(is (equal '(:page-set :scale) (gtk-print-unix-dialog-manual-capabilities dialog)))
;; page-setup
(is (eq 'gtk-page-setup (type-of (gtk-print-unix-dialog-page-setup dialog))))
(is (eq 'gtk-page-setup
(type-of (setf (gtk-print-unix-dialog-page-setup dialog)
(make-instance 'gtk-page-setup)))))
(is (eq 'gtk-page-setup (type-of (gtk-print-unix-dialog-page-setup dialog))))
;; print-settings
(is (eq 'gtk-print-settings (type-of (gtk-print-unix-dialog-print-settings dialog))))
(is (eq 'gtk-print-settings
(type-of (setf (gtk-print-unix-dialog-print-settings dialog)
(make-instance 'gtk-print-settings)))))
(is (eq 'gtk-print-settings (type-of (gtk-print-unix-dialog-print-settings dialog))))
;; selected-printer
(is-false (gtk-print-unix-dialog-selected-printer dialog))
;; selected-printer is not writeable
(signals (error) (setf (gtk-print-unix-dialog-selected-printer dialog) (make-instance 'gtk-printer)))
;; support-selection
(is-false (gtk-print-unix-dialog-support-selection dialog))
(is-true (setf (gtk-print-unix-dialog-support-selection dialog) t))
(is-true (gtk-print-unix-dialog-support-selection dialog))))
;;; --- Functions --------------------------------------------------------------
;;; gtk_print_unix_dialog_new
(test gtk-print-unix-dialog-new
(let ((window (make-instance 'gtk-window)))
(is (eq 'gtk-print-unix-dialog (type-of (gtk-print-unix-dialog-new nil nil))))
(is (eq 'gtk-print-unix-dialog (type-of (gtk-print-unix-dialog-new "title" window))))
(is (eq 'gtk-print-unix-dialog (type-of (gtk-print-unix-dialog-new nil window))))
(is (eq 'gtk-print-unix-dialog (type-of (gtk-print-unix-dialog-new "title" window))))))
;;; gtk_print_unix_dialog_set_settings
;;; gtk_print_unix_dialog_get_settings
gtk_print_unix_dialog_add_custom_tab
;;; gtk_print_unix_dialog_get_page_setup_set
| null | https://raw.githubusercontent.com/crategus/cl-cffi-gtk/22156e3e2356f71a67231d9868abcab3582356f3/test/rtest-gtk-print-unix-dialog.lisp | lisp | --- Types and Values -------------------------------------------------------
Check the type
Check the registered name
Check the type initializer
Check the names
Check the values
Check the flags definition
GtkPrintUnixDialog
Type check
Check the registered name
Check the type initializer
Check the parent
Check the children
Check the interfaces
Check the class properties
Get the names of the style properties.
Get the names of the child properties
Check the class definition
--- Properties -------------------------------------------------------------
current-page
embed-page-setup
has-selection
manual-capabilities
page-setup
print-settings
selected-printer
selected-printer is not writeable
support-selection
--- Functions --------------------------------------------------------------
gtk_print_unix_dialog_new
gtk_print_unix_dialog_set_settings
gtk_print_unix_dialog_get_settings
gtk_print_unix_dialog_get_page_setup_set | (def-suite gtk-print-unix-dialog :in gtk-suite)
(in-suite gtk-print-unix-dialog)
GtkPrintCapabilities
(test gtk-print-capabilities
(is (g-type-is-flags "GtkPrintCapabilities"))
(is (eq 'gtk-print-capabilities
(registered-flags-type "GtkPrintCapabilities")))
(is (eq (gtype "GtkPrintCapabilities")
(gtype (foreign-funcall "gtk_print_capabilities_get_type" g-size))))
(is (equal '("GTK_PRINT_CAPABILITY_PAGE_SET" "GTK_PRINT_CAPABILITY_COPIES"
"GTK_PRINT_CAPABILITY_COLLATE" "GTK_PRINT_CAPABILITY_REVERSE"
"GTK_PRINT_CAPABILITY_SCALE" "GTK_PRINT_CAPABILITY_GENERATE_PDF"
"GTK_PRINT_CAPABILITY_GENERATE_PS" "GTK_PRINT_CAPABILITY_PREVIEW"
"GTK_PRINT_CAPABILITY_NUMBER_UP" "GTK_PRINT_CAPABILITY_NUMBER_UP_LAYOUT")
(mapcar #'flags-item-name
(get-flags-items "GtkPrintCapabilities"))))
(is (equal '(1 2 4 8 16 32 64 128 256 512)
(mapcar #'flags-item-value
(get-flags-items "GtkPrintCapabilities"))))
Check the nick names
(is (equal '("page-set" "copies" "collate" "reverse" "scale" "generate-pdf"
"generate-ps" "preview" "number-up" "number-up-layout")
(mapcar #'flags-item-nick
(get-flags-items "GtkPrintCapabilities"))))
(is (equal '(DEFINE-G-FLAGS "GtkPrintCapabilities"
GTK-PRINT-CAPABILITIES
(:EXPORT T
:TYPE-INITIALIZER "gtk_print_capabilities_get_type")
(:PAGE-SET 1)
(:COPIES 2)
(:COLLATE 4)
(:REVERSE 8)
(:SCALE 16)
(:GENERATE-PDF 32)
(:GENERATE-PS 64)
(:PREVIEW 128)
(:NUMBER-UP 256)
(:NUMBER-UP-LAYOUT 512))
(get-g-type-definition "GtkPrintCapabilities"))))
(test gtk-print-unix-dialog-class
(is (g-type-is-object "GtkPrintUnixDialog"))
(is (eq 'gtk-print-unix-dialog
(registered-object-type-by-name "GtkPrintUnixDialog")))
(is (eq (gtype "GtkPrintUnixDialog")
(gtype (foreign-funcall "gtk_print_unix_dialog_get_type" g-size))))
(is (eq (gtype "GtkDialog") (g-type-parent "GtkPrintUnixDialog")))
(is (equal '()
(mapcar #'g-type-name (g-type-children "GtkPrintUnixDialog"))))
(is (equal '("AtkImplementorIface" "GtkBuildable")
(mapcar #'g-type-name (g-type-interfaces "GtkPrintUnixDialog"))))
(is (equal '("accept-focus" "app-paintable" "application" "attached-to"
"border-width" "can-default" "can-focus" "child"
"composite-child" "current-page" "decorated" "default-height"
"default-width" "deletable" "destroy-with-parent"
"double-buffered" "embed-page-setup" "events" "expand"
"focus-on-click" "focus-on-map" "focus-visible" "gravity"
"halign" "has-default" "has-focus" "has-resize-grip"
"has-selection" "has-tooltip" "has-toplevel-focus"
"height-request" "hexpand" "hexpand-set"
"hide-titlebar-when-maximized" "icon" "icon-name" "is-active"
"is-focus" "is-maximized" "manual-capabilities" "margin"
"margin-bottom" "margin-end" "margin-left" "margin-right"
"margin-start" "margin-top" "mnemonics-visible" "modal" "name"
"no-show-all" "opacity" "page-setup" "parent" "print-settings"
"receives-default" "resizable" "resize-grip-visible"
"resize-mode" "role" "scale-factor" "screen" "selected-printer"
"sensitive" "skip-pager-hint" "skip-taskbar-hint" "startup-id"
"style" "support-selection" "title" "tooltip-markup"
"tooltip-text" "transient-for" "type" "type-hint" "urgency-hint"
"use-header-bar" "valign" "vexpand" "vexpand-set" "visible"
"width-request" "window" "window-position")
(stable-sort (mapcar #'g-param-spec-name
(g-object-class-list-properties "GtkPrintUnixDialog"))
#'string-lessp)))
(is (equal '("cursor-aspect-ratio" "cursor-color" "focus-line-pattern"
"focus-line-width" "focus-padding" "interior-focus" "link-color"
"scroll-arrow-hlength" "scroll-arrow-vlength"
"secondary-cursor-color" "separator-height" "separator-width"
"text-handle-height" "text-handle-width" "visited-link-color"
"wide-separators" "window-dragging" "decoration-button-layout"
"decoration-resize-handle" "action-area-border" "button-spacing"
"content-area-border" "content-area-spacing")
(mapcar #'g-param-spec-name
(gtk-widget-class-list-style-properties "GtkPrintUnixDialog"))))
(is (equal '()
(mapcar #'g-param-spec-name
(gtk-container-class-list-child-properties "GtkPrintUnixDialog"))))
(is (equal '(DEFINE-G-OBJECT-CLASS "GtkPrintUnixDialog" GTK-PRINT-UNIX-DIALOG
(:SUPERCLASS GTK-DIALOG :EXPORT T :INTERFACES
("AtkImplementorIface" "GtkBuildable")
:TYPE-INITIALIZER "gtk_print_unix_dialog_get_type")
((CURRENT-PAGE GTK-PRINT-UNIX-DIALOG-CURRENT-PAGE
"current-page" "gint" T T)
(EMBED-PAGE-SETUP
GTK-PRINT-UNIX-DIALOG-EMBED-PAGE-SETUP
"embed-page-setup" "gboolean" T T)
(HAS-SELECTION GTK-PRINT-UNIX-DIALOG-HAS-SELECTION
"has-selection" "gboolean" T T)
(MANUAL-CAPABILITIES
GTK-PRINT-UNIX-DIALOG-MANUAL-CAPABILITIES
"manual-capabilities" "GtkPrintCapabilities" T T)
(PAGE-SETUP GTK-PRINT-UNIX-DIALOG-PAGE-SETUP
"page-setup" "GtkPageSetup" T T)
(PRINT-SETTINGS GTK-PRINT-UNIX-DIALOG-PRINT-SETTINGS
"print-settings" "GtkPrintSettings" T T)
(SELECTED-PRINTER
GTK-PRINT-UNIX-DIALOG-SELECTED-PRINTER
"selected-printer" "GtkPrinter" T NIL)
(SUPPORT-SELECTION
GTK-PRINT-UNIX-DIALOG-SUPPORT-SELECTION
"support-selection" "gboolean" T T)))
(get-g-type-definition "GtkPrintUnixDialog"))))
(test gtk-print-unix-dialog-properties
(let ((dialog (make-instance 'gtk-print-unix-dialog)))
(is (= -1 (gtk-print-unix-dialog-current-page dialog)))
(is (= 10 (setf (gtk-print-unix-dialog-current-page dialog) 10)))
(is (= 10 (gtk-print-unix-dialog-current-page dialog)))
(is-false (gtk-print-unix-dialog-embed-page-setup dialog))
(is-true (setf (gtk-print-unix-dialog-embed-page-setup dialog) t))
(is-true (gtk-print-unix-dialog-embed-page-setup dialog))
(is-false (gtk-print-unix-dialog-has-selection dialog))
(is-true (setf (gtk-print-unix-dialog-has-selection dialog) t))
(is-true (gtk-print-unix-dialog-has-selection dialog))
(is-false (gtk-print-unix-dialog-manual-capabilities dialog))
(is (equal '(:page-set :scale)
(setf (gtk-print-unix-dialog-manual-capabilities dialog) '(:page-set :scale))))
(is (equal '(:page-set :scale) (gtk-print-unix-dialog-manual-capabilities dialog)))
(is (eq 'gtk-page-setup (type-of (gtk-print-unix-dialog-page-setup dialog))))
(is (eq 'gtk-page-setup
(type-of (setf (gtk-print-unix-dialog-page-setup dialog)
(make-instance 'gtk-page-setup)))))
(is (eq 'gtk-page-setup (type-of (gtk-print-unix-dialog-page-setup dialog))))
(is (eq 'gtk-print-settings (type-of (gtk-print-unix-dialog-print-settings dialog))))
(is (eq 'gtk-print-settings
(type-of (setf (gtk-print-unix-dialog-print-settings dialog)
(make-instance 'gtk-print-settings)))))
(is (eq 'gtk-print-settings (type-of (gtk-print-unix-dialog-print-settings dialog))))
(is-false (gtk-print-unix-dialog-selected-printer dialog))
(signals (error) (setf (gtk-print-unix-dialog-selected-printer dialog) (make-instance 'gtk-printer)))
(is-false (gtk-print-unix-dialog-support-selection dialog))
(is-true (setf (gtk-print-unix-dialog-support-selection dialog) t))
(is-true (gtk-print-unix-dialog-support-selection dialog))))
(test gtk-print-unix-dialog-new
(let ((window (make-instance 'gtk-window)))
(is (eq 'gtk-print-unix-dialog (type-of (gtk-print-unix-dialog-new nil nil))))
(is (eq 'gtk-print-unix-dialog (type-of (gtk-print-unix-dialog-new "title" window))))
(is (eq 'gtk-print-unix-dialog (type-of (gtk-print-unix-dialog-new nil window))))
(is (eq 'gtk-print-unix-dialog (type-of (gtk-print-unix-dialog-new "title" window))))))
gtk_print_unix_dialog_add_custom_tab
|
46f4afabeac8abf11d0c1b1c26893abda9eeedbf0b95f6fa332322453eb642b2 | bytekid/mkbtt | conversion.ml | (*** SUBMODULES **********************************************************)
module Pos = Rewriting.Position;;
module Term = U.Term;;
module Rule = U.Rule;;
module Trs = U.Trs;;
module Elogic = U.Elogic;;
module Sub = U.Substitution;;
module INode = IndexedNode;;
module W = World;;
(*** OPENS ***************************************************************)
open Types.Node;;
open World;;
open World.Monad;;
open Util;;
(*** TYPES ***************************************************************)
type t =
Empty of Term.t
| Step of Term.t * Nodex.t_rule * Pos.t * Term.t
;;
(*** FUNCTIONS ***********************************************************)
let start_term = function
| Step (s,_,_,_) :: _ -> s
| Empty s :: _-> s
| [] -> failwith "Conversion.start_term: empty list"
let rec end_term = function
| [Step (s,_,_,_)] -> s
| Empty s :: _-> s
| Step _ :: s -> end_term s
| [] -> failwith "Conversion.end_term: empty list"
(*** trace back **********************************************************)
let matcher t1 l1 t2 l2 =
let tau1 = Elogic.match_term t1 l1 in
let tau2 = Elogic.match_term t2 l2 in
Sub.union tau1 tau2
;;
let by_id i =
INode.by_id i >>= function
| None -> failwith "Conversion.by_id: not found"
| Some n -> return n
;;
let is_axiom i =
by_id i >>= fun n -> return (Nodex.is_axiom n)
;;
let rule_rename = World.M.Rule.rename
(* Narrows a term.
t: term to be narrowed
rule: to be used
p: position in t
Returns narrowed term t', substitution sigma *)
let narrow t rule p =
let l', r' = Rule.lhs rule, Rule.rhs rule in
let t' = Term.subterm p t in
let sigma = Elogic.unify t' l' in
let u = Sub.apply_term sigma r' in
let t' = Sub.apply_term sigma t in
Term.replace p u t', sigma, rule
;;
( ( i , b),q,(j , c ) ) is an overlap of rules l1 - > r1 ( i ) and l2 - > r2 ( j )
with substitution \sigma . t contains an instance of r1\sigma , i.e. ,
t = C[r1\sigma\tau]_pos and we want to obtain the term C[l1\sigma\tau ] .
with substitution \sigma. t contains an instance of r1\sigma, i.e.,
t=C[r1\sigma\tau]_pos and we want to obtain the term C[l1\sigma\tau]. *)
let deduce_back t s pos ((i,b),q,(j,c)) =
(* get rules *)
by_id i >>= fun n -> rule_rename (Nodex.brule b n) >>= fun rl1 ->
let l1, r1 = Rule.lhs rl1, Rule.rhs rl1 in
by_id j >>= fun n -> rule_rename (Nodex.brule c n) >>= fun rl2 ->
(* sigma is the used substitution *)
let l1r2sigma, sigma, _ = narrow l1 rl2 q in
let r1sigma = Sub.apply_term sigma r1 in
(* critical pair was l1r2sigma=r1sigma*)
let l1sigma = Sub.apply_term sigma l1 in
let t' = Term.subterm pos t in
let s' = Term.subterm pos s in
( is_matching t ' r1sigma ) & & ( l1r2sigma ) consistent
let tau, o =
try matcher t' r1sigma s' l1r2sigma, true
with Elogic.Not_matchable | Sub.Inconsistent ->
matcher t' l1r2sigma s' r1sigma, false
in
let l1sigmatau = Sub.apply_term tau l1sigma in
let t' = Term.replace pos l1sigmatau t in
let pos' = Pos.append pos q in
let steps =
if o then [Step(t, (i,not b), pos, t'); Step(t', (j,c), pos', s)]
else [Step(t, (j,not c), pos', t'); Step(t', (i,b), pos, s)]
in return steps
;;
let rewrite_back t s pos ((i,b), q, (j,c)) =
(* get rules *)
by_id i >>= fun n -> rule_rename (Nodex.brule (not b) n) >>= fun rl1 ->
let l1, r1 = Rule.lhs rl1, Rule.rhs rl1 in
by_id j >>= fun n -> rule_rename (Nodex.brule c n) >>= fun rl2 ->
W.M.Term.to_stringm t > > = fun t_s - >
s > > = fun s_s - >
W.M.Rule.to_stringm rl1 > > = fun rl1_s - >
W.M.Rule.to_stringm rl2 > > = fun rl2_s - >
Format.printf " % s = % s originates from % s and % s , position % s\n% ! "
t_s s_s rl1_s rl2_s ( Pos.to_string q ) ;
W.M.Term.to_stringm s >>= fun s_s ->
W.M.Rule.to_stringm rl1 >>= fun rl1_s ->
W.M.Rule.to_stringm rl2 >>= fun rl2_s ->
Format.printf "%s = %s originates from %s and %s, position %s\n%!"
t_s s_s rl1_s rl2_s (Pos.to_string q);*)
let l1' = Rule.rewrite l1 q rl2 in
let t', s' = Term.subterm pos t, Term.subterm pos s in
(* check in which order i and j were applied *)
(*(is_matching t' r1) && (is_matching s' l1') consistent *)
try
let tau = matcher t' r1 s' l1' in
let t'' = Term.replace pos (Sub.apply_term tau l1) t in
return [Step(t,(i, b),pos,t''); Step(t'',(j,c),Pos.append pos q,s)]
with Sub.Inconsistent | Elogic.Not_matchable ->
(*(is_matching t' l1') && (is_matching s' r1) consistent *) (
let tau = matcher t' l1' s' r1 in
let t'' = Term.replace pos (Sub.apply_term tau l1) t in
return [Step(t,(j, not c),Pos.append pos q,t''); Step(t'',(i,not b),pos,s)]
)
;;
let rec print' = function
failwith " empty conversion list "
| (Empty t) :: [] ->
W.M.Term.to_stringm t >>= fun ts ->
Format.printf "%s \n%!" ts;
return ()
| (Empty t) :: seq' ->
W.M.Term.to_stringm t >>= fun ts ->
Format.printf "%s \n%!" ts;
print' seq'
| Step (t, (i,b), p, u) :: seq' ->
W.M.Term.to_stringm t >>= fun ts ->
W.M.Term.to_stringm u >>= fun us ->
INode.brule b i >>= fun rl ->
W.M.Rule.to_stringm rl >>= fun rls ->
Format.printf "%s -> (%s (= %i, %i), %s) -> %s \n%!" ts rls i (if b then 1 else 0)(Pos.to_string p) us;
print' seq'
;;
let rec last_term = function
[Step(_,_,_,t)] -> t
| Step (_,_,_,_) :: seq -> last_term seq
| _ -> failwith "last_term: empty sequence"
;;
let add_last seq = seq @ [Empty (last_term seq) ]
let brule rl =
let eqn = Equation.of_rule rl in
let b =
let s', t' = Equation.terms eqn in
let s, t = Rule.to_terms rl in
(Term.equal s' s) && (Term.equal t t')
in
INode.node_by_eqn eqn >>= function
| None -> failwith "Conversion.brule: rule not found"
| Some (i, n) -> return (i,b)
;;
let rec to_nf trs s =
let reduct_with s rl =
let app r p =
match r with
Some _ -> r
| None -> try let t = Rule.rewrite s p rl in Some (rl, p, t) with _ -> None
in List.fold_left app None (Term.funs_pos s)
in
let reduct =
let app r rl = match r with Some _ -> r | None -> reduct_with s rl in
List.fold_left app None trs
in
match reduct with
| None -> return [Empty s]
| Some (rl, p, t) ->
brule rl >>= fun brl ->
to_nf trs t >>= fun seq -> return (Step (s, brl, p, t) :: seq)
;;
let rec rev' = function
| [Empty s] -> []
| [Step (s, (i,b), p, t)] -> [Step (t, (i, not b), p, s)]
| Step (s, (i,b), p, t) :: seq -> let seq' = rev' seq in
seq' @ [Step (t, (i, not b), p, s)]
| [] -> []
;;
let rev seq =
let rec rev' = function
| [Empty s] -> [], s
| [Step (s, (i,b), p, t)] -> [Step (t, (i, not b), p, s)], s
| Step (s, (i,b), p, t) :: seq -> let (seq', t) = rev' seq in
seq' @ [Step (t, (i, not b), p, s)], s
in
let seq', s = rev' seq in seq' @ [Empty s]
;;
let rec append ss ts =
match ss with
| (Empty _) :: _ -> ts
| (Step (_,_,_,_) as s) :: ss' -> s :: (append ss' ts)
| _ -> failwith "Conversion.append: unexpected input"
;;
let traces : (Term.t * (int * bool) * Pos.t * Term.t, t list) Hashtbl.t
= Hashtbl.create 100
let rec trace_step step =
let rec trace (s,(i,b),pos,t) =
History.smallest_occurrence i >>= (function
| Axiom -> failwith "Conversion.trace: no axiom expected"
| Instance ((j,c),_) ->
return [Step(s, (j,(b && c) || (not b && not c)), pos, t)]
" deduce " ;
" rewrite " ;
in
try return (Hashtbl.find traces step)
with Not_found ->
trace step >>= fun steps ->
Hashtbl.add traces step steps;
return steps
;;
let is_lemma i =
is_axiom i >>= fun is_axiom ->
GoalState.false_term () >>= fun f ->
INode.by_id i >>= fun n ->
let s,t = Nodex.data (Option.the n) in
return (not is_axiom && not (Term.equal s f || (Term.equal t f)))
;;
let trace lemmas seq =
let dont_trace i =
is_axiom i >>= fun is_axiom ->
is_lemma i >>= fun is_lemma ->
return (is_axiom || (List.mem i lemmas && is_lemma))
in
let rec trace acc seq =
" in trace : \n% ! " ; print ' seq > >
match seq with
| (Empty _) as e :: _ -> return (List.rev (e :: acc))
| (Step (s,(i,b),pos,t) as step) :: seq ->
dont_trace i >>= fun dont_trace ->
INode.by_id i > > = fun n - >
W.M.Rule.to_stringm ( Nodex.brule b ( Option.the n ) ) > > = fun rs - >
Format.printf " % s is axiom : % i \n " rs ( if is_axiom then 1 else 0 ) ;
W.M.Rule.to_stringm (Nodex.brule b (Option.the n)) >>= fun rs ->
Format.printf "%s is axiom: %i \n" rs (if is_axiom then 1 else 0);*)
if dont_trace then trace (step :: acc) seq
else
trace_step (s,(i,b),pos,t) >>= fun steps ->
(*Format.printf "steps:"; print' steps >>*)
trace acc (steps @ seq)
| [] -> failwith "Conversion.trace: empty list"
in trace [] seq
;;
let lemma_for i =
INode.brule true i >>= fun rl ->
let l,r = Rule.to_terms rl in
trace_step (l,(i,true),Pos.root,r) >>= fun steps ->
return (add_last steps)
;;
let true_false =
W.get_goal_state >>= fun s ->
let (t,f) =
match s.true_symbol, s.false_symbol with
Some t, Some f -> (Term.Fun (t, []), Term.Fun(f, []))
| _ -> failwith "Control.print_proof: no goal found"
in
(INode.node_by_eqn (Equation.of_terms t f) >>= function
| None -> failwith "Conversion.print_goal: rule not found"
| Some (i, n) -> return (i,n)) >>= fun (i,n) ->
let s,t = Nodex.data n in
return (Step(s, (i, true), Pos.root, t) :: [Empty t])
;;
(* given conversion for true = false, constructs conversion
for goal s = t; exploits fact that conversion starts with
true <- eq(u,u) for some term u that is convertible to both s and t *)
let purify seq =
let is_pos_step p = function
Step (s, (i,b), pos, t) -> Pos.is_prefix p pos | _ -> false
in
let project p = function
Step (s, ib, pos,t) ->
let s', t' = Term.subterm p s, Term.subterm p t in
Step (s', ib, Pos.tail pos, t')
| _ -> failwith "take_left: empty not expected"
in
let p0, p1 = Pos.make 0, Pos.make 1 in
let seq_l = List.map (project p0) (List.filter (is_pos_step p0) seq) in
let seq_r = List.map (project p1) (List.filter (is_pos_step p1) seq) in
let seq = (rev' seq_l) @ seq_r in
return (seq @ [Empty (last_term seq)])
;;
let for_goal =
true_false >>=
trace [] >>=
purify >>= fun seq ->
(*print' seq >>*) return seq
;;
let for_goal_with_lemmas =
(* get history of goal *)
GoalState.true_is_false () >>= INode.by_eqn >>= fun i ->
History.joint_history(*_for p*) [] [Option.the i] >>= fun h ->
let is = List.unique (List.map snd h) in
(* create conversions for lemmas *)
filter is_lemma is >>= fun is ->
map lemma_for is >>= fun lemmas ->
(* and conversion for goal *)
true_false >>= fun seq ->
trace is seq >>= fun seq ->
" Final conversion : " ; print ' seq > > = fun _ - >
Format.printf " % i : % s\n% ! " ( lemmas ) ( List.to_string string_of_int " " is ) ;
iter ( fun l - > Format.printf " Lemma:% ! " ; print ' l ) lemmas > > = fun _ - >
Format.printf " now purify:\n% ! " ;
Format.printf "%i Lemmas: %s\n%!" (List.length lemmas) (List.to_string string_of_int " " is );
iter (fun l -> Format.printf "Lemma:%!"; print' l) lemmas >>= fun _ ->
Format.printf "now purify:\n%!";*)
purify seq >>= fun seq ->
(*print' seq >>*)
return (lemmas @ [seq])
;;
let for_trs trs =
let for_rule rl =
W.M.Rule.to_stringm rl >>= fun s ->
Format.printf "for rule %s\n%!";
let l,r = Rule.to_terms rl in
INode.node_by_eqn (Equation.of_rule rl) >>= fun ni ->
let i,n = Option.the ni in
let l',r' = Nodex.data n in
let b = Term.equal l l' && Term.equal r r' in
return [Step (l, (i,b), Pos.root, r); Empty r]
in
map
(fun rl -> for_rule rl >>= trace [] >>= fun c -> return (rl,c))
(Trs.to_list trs) >>= fun seqs ->
Format.printf "convs computed\n%!";
return seqs
;;
| null | https://raw.githubusercontent.com/bytekid/mkbtt/c2f8e0615389b52eabd12655fe48237aa0fe83fd/src/mkbtt/conversion.ml | ocaml | ** SUBMODULES *********************************************************
** OPENS **************************************************************
** TYPES **************************************************************
** FUNCTIONS **********************************************************
** trace back *********************************************************
Narrows a term.
t: term to be narrowed
rule: to be used
p: position in t
Returns narrowed term t', substitution sigma
get rules
sigma is the used substitution
critical pair was l1r2sigma=r1sigma
get rules
check in which order i and j were applied
(is_matching t' r1) && (is_matching s' l1') consistent
(is_matching t' l1') && (is_matching s' r1) consistent
Format.printf "steps:"; print' steps >>
given conversion for true = false, constructs conversion
for goal s = t; exploits fact that conversion starts with
true <- eq(u,u) for some term u that is convertible to both s and t
print' seq >>
get history of goal
_for p
create conversions for lemmas
and conversion for goal
print' seq >> | module Pos = Rewriting.Position;;
module Term = U.Term;;
module Rule = U.Rule;;
module Trs = U.Trs;;
module Elogic = U.Elogic;;
module Sub = U.Substitution;;
module INode = IndexedNode;;
module W = World;;
open Types.Node;;
open World;;
open World.Monad;;
open Util;;
type t =
Empty of Term.t
| Step of Term.t * Nodex.t_rule * Pos.t * Term.t
;;
let start_term = function
| Step (s,_,_,_) :: _ -> s
| Empty s :: _-> s
| [] -> failwith "Conversion.start_term: empty list"
let rec end_term = function
| [Step (s,_,_,_)] -> s
| Empty s :: _-> s
| Step _ :: s -> end_term s
| [] -> failwith "Conversion.end_term: empty list"
let matcher t1 l1 t2 l2 =
let tau1 = Elogic.match_term t1 l1 in
let tau2 = Elogic.match_term t2 l2 in
Sub.union tau1 tau2
;;
let by_id i =
INode.by_id i >>= function
| None -> failwith "Conversion.by_id: not found"
| Some n -> return n
;;
let is_axiom i =
by_id i >>= fun n -> return (Nodex.is_axiom n)
;;
let rule_rename = World.M.Rule.rename
let narrow t rule p =
let l', r' = Rule.lhs rule, Rule.rhs rule in
let t' = Term.subterm p t in
let sigma = Elogic.unify t' l' in
let u = Sub.apply_term sigma r' in
let t' = Sub.apply_term sigma t in
Term.replace p u t', sigma, rule
;;
( ( i , b),q,(j , c ) ) is an overlap of rules l1 - > r1 ( i ) and l2 - > r2 ( j )
with substitution \sigma . t contains an instance of r1\sigma , i.e. ,
t = C[r1\sigma\tau]_pos and we want to obtain the term C[l1\sigma\tau ] .
with substitution \sigma. t contains an instance of r1\sigma, i.e.,
t=C[r1\sigma\tau]_pos and we want to obtain the term C[l1\sigma\tau]. *)
let deduce_back t s pos ((i,b),q,(j,c)) =
by_id i >>= fun n -> rule_rename (Nodex.brule b n) >>= fun rl1 ->
let l1, r1 = Rule.lhs rl1, Rule.rhs rl1 in
by_id j >>= fun n -> rule_rename (Nodex.brule c n) >>= fun rl2 ->
let l1r2sigma, sigma, _ = narrow l1 rl2 q in
let r1sigma = Sub.apply_term sigma r1 in
let l1sigma = Sub.apply_term sigma l1 in
let t' = Term.subterm pos t in
let s' = Term.subterm pos s in
( is_matching t ' r1sigma ) & & ( l1r2sigma ) consistent
let tau, o =
try matcher t' r1sigma s' l1r2sigma, true
with Elogic.Not_matchable | Sub.Inconsistent ->
matcher t' l1r2sigma s' r1sigma, false
in
let l1sigmatau = Sub.apply_term tau l1sigma in
let t' = Term.replace pos l1sigmatau t in
let pos' = Pos.append pos q in
let steps =
if o then [Step(t, (i,not b), pos, t'); Step(t', (j,c), pos', s)]
else [Step(t, (j,not c), pos', t'); Step(t', (i,b), pos, s)]
in return steps
;;
let rewrite_back t s pos ((i,b), q, (j,c)) =
by_id i >>= fun n -> rule_rename (Nodex.brule (not b) n) >>= fun rl1 ->
let l1, r1 = Rule.lhs rl1, Rule.rhs rl1 in
by_id j >>= fun n -> rule_rename (Nodex.brule c n) >>= fun rl2 ->
W.M.Term.to_stringm t > > = fun t_s - >
s > > = fun s_s - >
W.M.Rule.to_stringm rl1 > > = fun rl1_s - >
W.M.Rule.to_stringm rl2 > > = fun rl2_s - >
Format.printf " % s = % s originates from % s and % s , position % s\n% ! "
t_s s_s rl1_s rl2_s ( Pos.to_string q ) ;
W.M.Term.to_stringm s >>= fun s_s ->
W.M.Rule.to_stringm rl1 >>= fun rl1_s ->
W.M.Rule.to_stringm rl2 >>= fun rl2_s ->
Format.printf "%s = %s originates from %s and %s, position %s\n%!"
t_s s_s rl1_s rl2_s (Pos.to_string q);*)
let l1' = Rule.rewrite l1 q rl2 in
let t', s' = Term.subterm pos t, Term.subterm pos s in
try
let tau = matcher t' r1 s' l1' in
let t'' = Term.replace pos (Sub.apply_term tau l1) t in
return [Step(t,(i, b),pos,t''); Step(t'',(j,c),Pos.append pos q,s)]
with Sub.Inconsistent | Elogic.Not_matchable ->
let tau = matcher t' l1' s' r1 in
let t'' = Term.replace pos (Sub.apply_term tau l1) t in
return [Step(t,(j, not c),Pos.append pos q,t''); Step(t'',(i,not b),pos,s)]
)
;;
let rec print' = function
failwith " empty conversion list "
| (Empty t) :: [] ->
W.M.Term.to_stringm t >>= fun ts ->
Format.printf "%s \n%!" ts;
return ()
| (Empty t) :: seq' ->
W.M.Term.to_stringm t >>= fun ts ->
Format.printf "%s \n%!" ts;
print' seq'
| Step (t, (i,b), p, u) :: seq' ->
W.M.Term.to_stringm t >>= fun ts ->
W.M.Term.to_stringm u >>= fun us ->
INode.brule b i >>= fun rl ->
W.M.Rule.to_stringm rl >>= fun rls ->
Format.printf "%s -> (%s (= %i, %i), %s) -> %s \n%!" ts rls i (if b then 1 else 0)(Pos.to_string p) us;
print' seq'
;;
let rec last_term = function
[Step(_,_,_,t)] -> t
| Step (_,_,_,_) :: seq -> last_term seq
| _ -> failwith "last_term: empty sequence"
;;
let add_last seq = seq @ [Empty (last_term seq) ]
let brule rl =
let eqn = Equation.of_rule rl in
let b =
let s', t' = Equation.terms eqn in
let s, t = Rule.to_terms rl in
(Term.equal s' s) && (Term.equal t t')
in
INode.node_by_eqn eqn >>= function
| None -> failwith "Conversion.brule: rule not found"
| Some (i, n) -> return (i,b)
;;
let rec to_nf trs s =
let reduct_with s rl =
let app r p =
match r with
Some _ -> r
| None -> try let t = Rule.rewrite s p rl in Some (rl, p, t) with _ -> None
in List.fold_left app None (Term.funs_pos s)
in
let reduct =
let app r rl = match r with Some _ -> r | None -> reduct_with s rl in
List.fold_left app None trs
in
match reduct with
| None -> return [Empty s]
| Some (rl, p, t) ->
brule rl >>= fun brl ->
to_nf trs t >>= fun seq -> return (Step (s, brl, p, t) :: seq)
;;
let rec rev' = function
| [Empty s] -> []
| [Step (s, (i,b), p, t)] -> [Step (t, (i, not b), p, s)]
| Step (s, (i,b), p, t) :: seq -> let seq' = rev' seq in
seq' @ [Step (t, (i, not b), p, s)]
| [] -> []
;;
let rev seq =
let rec rev' = function
| [Empty s] -> [], s
| [Step (s, (i,b), p, t)] -> [Step (t, (i, not b), p, s)], s
| Step (s, (i,b), p, t) :: seq -> let (seq', t) = rev' seq in
seq' @ [Step (t, (i, not b), p, s)], s
in
let seq', s = rev' seq in seq' @ [Empty s]
;;
let rec append ss ts =
match ss with
| (Empty _) :: _ -> ts
| (Step (_,_,_,_) as s) :: ss' -> s :: (append ss' ts)
| _ -> failwith "Conversion.append: unexpected input"
;;
let traces : (Term.t * (int * bool) * Pos.t * Term.t, t list) Hashtbl.t
= Hashtbl.create 100
let rec trace_step step =
let rec trace (s,(i,b),pos,t) =
History.smallest_occurrence i >>= (function
| Axiom -> failwith "Conversion.trace: no axiom expected"
| Instance ((j,c),_) ->
return [Step(s, (j,(b && c) || (not b && not c)), pos, t)]
" deduce " ;
" rewrite " ;
in
try return (Hashtbl.find traces step)
with Not_found ->
trace step >>= fun steps ->
Hashtbl.add traces step steps;
return steps
;;
let is_lemma i =
is_axiom i >>= fun is_axiom ->
GoalState.false_term () >>= fun f ->
INode.by_id i >>= fun n ->
let s,t = Nodex.data (Option.the n) in
return (not is_axiom && not (Term.equal s f || (Term.equal t f)))
;;
let trace lemmas seq =
let dont_trace i =
is_axiom i >>= fun is_axiom ->
is_lemma i >>= fun is_lemma ->
return (is_axiom || (List.mem i lemmas && is_lemma))
in
let rec trace acc seq =
" in trace : \n% ! " ; print ' seq > >
match seq with
| (Empty _) as e :: _ -> return (List.rev (e :: acc))
| (Step (s,(i,b),pos,t) as step) :: seq ->
dont_trace i >>= fun dont_trace ->
INode.by_id i > > = fun n - >
W.M.Rule.to_stringm ( Nodex.brule b ( Option.the n ) ) > > = fun rs - >
Format.printf " % s is axiom : % i \n " rs ( if is_axiom then 1 else 0 ) ;
W.M.Rule.to_stringm (Nodex.brule b (Option.the n)) >>= fun rs ->
Format.printf "%s is axiom: %i \n" rs (if is_axiom then 1 else 0);*)
if dont_trace then trace (step :: acc) seq
else
trace_step (s,(i,b),pos,t) >>= fun steps ->
trace acc (steps @ seq)
| [] -> failwith "Conversion.trace: empty list"
in trace [] seq
;;
let lemma_for i =
INode.brule true i >>= fun rl ->
let l,r = Rule.to_terms rl in
trace_step (l,(i,true),Pos.root,r) >>= fun steps ->
return (add_last steps)
;;
let true_false =
W.get_goal_state >>= fun s ->
let (t,f) =
match s.true_symbol, s.false_symbol with
Some t, Some f -> (Term.Fun (t, []), Term.Fun(f, []))
| _ -> failwith "Control.print_proof: no goal found"
in
(INode.node_by_eqn (Equation.of_terms t f) >>= function
| None -> failwith "Conversion.print_goal: rule not found"
| Some (i, n) -> return (i,n)) >>= fun (i,n) ->
let s,t = Nodex.data n in
return (Step(s, (i, true), Pos.root, t) :: [Empty t])
;;
let purify seq =
let is_pos_step p = function
Step (s, (i,b), pos, t) -> Pos.is_prefix p pos | _ -> false
in
let project p = function
Step (s, ib, pos,t) ->
let s', t' = Term.subterm p s, Term.subterm p t in
Step (s', ib, Pos.tail pos, t')
| _ -> failwith "take_left: empty not expected"
in
let p0, p1 = Pos.make 0, Pos.make 1 in
let seq_l = List.map (project p0) (List.filter (is_pos_step p0) seq) in
let seq_r = List.map (project p1) (List.filter (is_pos_step p1) seq) in
let seq = (rev' seq_l) @ seq_r in
return (seq @ [Empty (last_term seq)])
;;
let for_goal =
true_false >>=
trace [] >>=
purify >>= fun seq ->
;;
let for_goal_with_lemmas =
GoalState.true_is_false () >>= INode.by_eqn >>= fun i ->
let is = List.unique (List.map snd h) in
filter is_lemma is >>= fun is ->
map lemma_for is >>= fun lemmas ->
true_false >>= fun seq ->
trace is seq >>= fun seq ->
" Final conversion : " ; print ' seq > > = fun _ - >
Format.printf " % i : % s\n% ! " ( lemmas ) ( List.to_string string_of_int " " is ) ;
iter ( fun l - > Format.printf " Lemma:% ! " ; print ' l ) lemmas > > = fun _ - >
Format.printf " now purify:\n% ! " ;
Format.printf "%i Lemmas: %s\n%!" (List.length lemmas) (List.to_string string_of_int " " is );
iter (fun l -> Format.printf "Lemma:%!"; print' l) lemmas >>= fun _ ->
Format.printf "now purify:\n%!";*)
purify seq >>= fun seq ->
return (lemmas @ [seq])
;;
let for_trs trs =
let for_rule rl =
W.M.Rule.to_stringm rl >>= fun s ->
Format.printf "for rule %s\n%!";
let l,r = Rule.to_terms rl in
INode.node_by_eqn (Equation.of_rule rl) >>= fun ni ->
let i,n = Option.the ni in
let l',r' = Nodex.data n in
let b = Term.equal l l' && Term.equal r r' in
return [Step (l, (i,b), Pos.root, r); Empty r]
in
map
(fun rl -> for_rule rl >>= trace [] >>= fun c -> return (rl,c))
(Trs.to_list trs) >>= fun seqs ->
Format.printf "convs computed\n%!";
return seqs
;;
|
066be972ef5d02e54b2511e58cde627c10acfdedaeb5150b3905838dd73e126e | ulrikstrid/ocaml-oidc | PiafOidc.ml | *
* Copyright 2022 . All rights reserved .
* Use of this source code is governed by a BSD - style
* license that can be found in the LICENSE file .
* Copyright 2022 Ulrik Strid. All rights reserved.
* Use of this source code is governed by a BSD-style
* license that can be found in the LICENSE file.
*)
let to_string_body (res : Piaf.Response.t) = Piaf.Body.to_string res.body
let map_piaf_error e = `Msg (Piaf.Error.to_string e)
let request_descr_to_request Oidc.SimpleClient.{ headers; uri; body; meth } =
let open Lwt_result.Infix in
let body = Option.map Piaf.Body.of_string body in
Piaf.Client.Oneshot.request ~headers ?body ~meth uri
>>= to_string_body
|> Lwt_result.map_error map_piaf_error
| null | https://raw.githubusercontent.com/ulrikstrid/ocaml-oidc/3dcd0a258847561c8ce55b9e41b428ae0a99412c/executable/PiafOidc.ml | ocaml | *
* Copyright 2022 . All rights reserved .
* Use of this source code is governed by a BSD - style
* license that can be found in the LICENSE file .
* Copyright 2022 Ulrik Strid. All rights reserved.
* Use of this source code is governed by a BSD-style
* license that can be found in the LICENSE file.
*)
let to_string_body (res : Piaf.Response.t) = Piaf.Body.to_string res.body
let map_piaf_error e = `Msg (Piaf.Error.to_string e)
let request_descr_to_request Oidc.SimpleClient.{ headers; uri; body; meth } =
let open Lwt_result.Infix in
let body = Option.map Piaf.Body.of_string body in
Piaf.Client.Oneshot.request ~headers ?body ~meth uri
>>= to_string_body
|> Lwt_result.map_error map_piaf_error
|
|
4d99a92cd2a5b91b7a553f070d8c3385ac508c49113a9cb67e6aaa39c05cc669 | xapi-project/xen-api | test_unit.ml |
* Copyright ( C ) Citrix Systems Inc.
*
* This program is free software ; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation ; version 2.1 only . with the special
* exception on linking described in file LICENSE .
*
* This program is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
* GNU Lesser General Public License for more details .
* Copyright (C) Citrix Systems Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation; version 2.1 only. with the special
* exception on linking described in file LICENSE.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*)
open OUnit
open Test_common
let test_file_io protocol =
bracket
(fun () ->
let shared_file = make_shared_file () in
let _, writer =
Rrd_writer.FileWriter.create
{Rrd_writer.path= shared_file; shared_page_count= 1}
protocol
in
let reader = Rrd_reader.FileReader.create shared_file protocol in
(writer, reader)
)
(fun (writer, reader) ->
(* Check that writing then reading the shared file gives the expected
* timestamp and datasources. *)
writer.Rrd_writer.write_payload test_payload ;
let received_payload = reader.Rrd_reader.read_payload () in
assert_payloads_equal test_payload received_payload
)
(fun (writer, reader) ->
reader.Rrd_reader.cleanup () ;
writer.Rrd_writer.cleanup ()
)
()
let test_writer_cleanup protocol =
let shared_file = make_shared_file () in
let _, writer =
Rrd_writer.FileWriter.create
{Rrd_writer.path= shared_file; shared_page_count= 1}
protocol
in
writer.Rrd_writer.write_payload test_payload ;
writer.Rrd_writer.cleanup () ;
assert_equal ~msg:"Shared file was not cleaned up"
(Sys.file_exists shared_file)
false ;
assert_raises ~msg:"write_payload should fail after cleanup"
Rrd_io.Resource_closed (fun () ->
writer.Rrd_writer.write_payload test_payload
) ;
assert_raises ~msg:"cleanup should fail after cleanup" Rrd_io.Resource_closed
(fun () -> writer.Rrd_writer.cleanup ()
)
let test_reader_cleanup protocol =
bracket
(fun () ->
let shared_file = make_shared_file () in
let _, writer =
Rrd_writer.FileWriter.create
{Rrd_writer.path= shared_file; shared_page_count= 1}
protocol
in
writer.Rrd_writer.write_payload test_payload ;
(shared_file, writer)
)
(fun (shared_file, _writer) ->
let reader = Rrd_reader.FileReader.create shared_file protocol in
let (_ : Rrd_protocol.payload) = reader.Rrd_reader.read_payload () in
reader.Rrd_reader.cleanup () ;
assert_raises ~msg:"read_payload should fail after cleanup"
Rrd_io.Resource_closed (fun () -> reader.Rrd_reader.read_payload ()
) ;
assert_raises ~msg:"cleanup should fail after cleanup"
Rrd_io.Resource_closed (fun () -> reader.Rrd_reader.cleanup ()
)
)
(fun (_, writer) -> writer.Rrd_writer.cleanup ())
()
let test_reader_state protocol =
bracket
(fun () ->
let shared_file = make_shared_file () in
let _, writer =
Rrd_writer.FileWriter.create
{Rrd_writer.path= shared_file; shared_page_count= 1}
protocol
in
let reader = Rrd_reader.FileReader.create shared_file protocol in
(writer, reader)
)
(fun (writer, reader) ->
writer.Rrd_writer.write_payload test_payload ;
let (_ : Rrd_protocol.payload) = reader.Rrd_reader.read_payload () in
assert_raises
~msg:"read_payload should raise No_update if there has been no update"
Rrd_protocol.No_update (fun () -> reader.Rrd_reader.read_payload ()
) ;
(* After the timestamp has been updated, we should be able to read the
* payload again. *)
let open Rrd_protocol in
writer.Rrd_writer.write_payload
{test_payload with timestamp= Int64.add test_payload.timestamp 5L} ;
let (_ : Rrd_protocol.payload) = reader.Rrd_reader.read_payload () in
()
)
(fun (writer, reader) ->
reader.Rrd_reader.cleanup () ;
writer.Rrd_writer.cleanup ()
)
()
let with_each_protocol prefix_string test_fn =
[
(prefix_string ^ "_v1" >:: fun () -> test_fn Rrd_protocol_v1.protocol)
; (prefix_string ^ "_v2" >:: fun () -> test_fn Rrd_protocol_v2.protocol)
]
let base_suite =
"test_suite"
>::: with_each_protocol "test_file_io" test_file_io
@ with_each_protocol "test_writer_cleanup" test_writer_cleanup
@ with_each_protocol "test_reader_cleanup" test_reader_cleanup
@ with_each_protocol "test_reader_state" test_reader_state
let () =
print_endline "------ Unit tests ------" ;
ounit2_of_ounit1 base_suite |> OUnit2.run_test_tt_main
| null | https://raw.githubusercontent.com/xapi-project/xen-api/47fae74032aa6ade0fc12e867c530eaf2a96bf75/ocaml/xcp-rrdd/test/transport/test_unit.ml | ocaml | Check that writing then reading the shared file gives the expected
* timestamp and datasources.
After the timestamp has been updated, we should be able to read the
* payload again. |
* Copyright ( C ) Citrix Systems Inc.
*
* This program is free software ; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation ; version 2.1 only . with the special
* exception on linking described in file LICENSE .
*
* This program is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
* GNU Lesser General Public License for more details .
* Copyright (C) Citrix Systems Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation; version 2.1 only. with the special
* exception on linking described in file LICENSE.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*)
open OUnit
open Test_common
let test_file_io protocol =
bracket
(fun () ->
let shared_file = make_shared_file () in
let _, writer =
Rrd_writer.FileWriter.create
{Rrd_writer.path= shared_file; shared_page_count= 1}
protocol
in
let reader = Rrd_reader.FileReader.create shared_file protocol in
(writer, reader)
)
(fun (writer, reader) ->
writer.Rrd_writer.write_payload test_payload ;
let received_payload = reader.Rrd_reader.read_payload () in
assert_payloads_equal test_payload received_payload
)
(fun (writer, reader) ->
reader.Rrd_reader.cleanup () ;
writer.Rrd_writer.cleanup ()
)
()
let test_writer_cleanup protocol =
let shared_file = make_shared_file () in
let _, writer =
Rrd_writer.FileWriter.create
{Rrd_writer.path= shared_file; shared_page_count= 1}
protocol
in
writer.Rrd_writer.write_payload test_payload ;
writer.Rrd_writer.cleanup () ;
assert_equal ~msg:"Shared file was not cleaned up"
(Sys.file_exists shared_file)
false ;
assert_raises ~msg:"write_payload should fail after cleanup"
Rrd_io.Resource_closed (fun () ->
writer.Rrd_writer.write_payload test_payload
) ;
assert_raises ~msg:"cleanup should fail after cleanup" Rrd_io.Resource_closed
(fun () -> writer.Rrd_writer.cleanup ()
)
let test_reader_cleanup protocol =
bracket
(fun () ->
let shared_file = make_shared_file () in
let _, writer =
Rrd_writer.FileWriter.create
{Rrd_writer.path= shared_file; shared_page_count= 1}
protocol
in
writer.Rrd_writer.write_payload test_payload ;
(shared_file, writer)
)
(fun (shared_file, _writer) ->
let reader = Rrd_reader.FileReader.create shared_file protocol in
let (_ : Rrd_protocol.payload) = reader.Rrd_reader.read_payload () in
reader.Rrd_reader.cleanup () ;
assert_raises ~msg:"read_payload should fail after cleanup"
Rrd_io.Resource_closed (fun () -> reader.Rrd_reader.read_payload ()
) ;
assert_raises ~msg:"cleanup should fail after cleanup"
Rrd_io.Resource_closed (fun () -> reader.Rrd_reader.cleanup ()
)
)
(fun (_, writer) -> writer.Rrd_writer.cleanup ())
()
let test_reader_state protocol =
bracket
(fun () ->
let shared_file = make_shared_file () in
let _, writer =
Rrd_writer.FileWriter.create
{Rrd_writer.path= shared_file; shared_page_count= 1}
protocol
in
let reader = Rrd_reader.FileReader.create shared_file protocol in
(writer, reader)
)
(fun (writer, reader) ->
writer.Rrd_writer.write_payload test_payload ;
let (_ : Rrd_protocol.payload) = reader.Rrd_reader.read_payload () in
assert_raises
~msg:"read_payload should raise No_update if there has been no update"
Rrd_protocol.No_update (fun () -> reader.Rrd_reader.read_payload ()
) ;
let open Rrd_protocol in
writer.Rrd_writer.write_payload
{test_payload with timestamp= Int64.add test_payload.timestamp 5L} ;
let (_ : Rrd_protocol.payload) = reader.Rrd_reader.read_payload () in
()
)
(fun (writer, reader) ->
reader.Rrd_reader.cleanup () ;
writer.Rrd_writer.cleanup ()
)
()
let with_each_protocol prefix_string test_fn =
[
(prefix_string ^ "_v1" >:: fun () -> test_fn Rrd_protocol_v1.protocol)
; (prefix_string ^ "_v2" >:: fun () -> test_fn Rrd_protocol_v2.protocol)
]
let base_suite =
"test_suite"
>::: with_each_protocol "test_file_io" test_file_io
@ with_each_protocol "test_writer_cleanup" test_writer_cleanup
@ with_each_protocol "test_reader_cleanup" test_reader_cleanup
@ with_each_protocol "test_reader_state" test_reader_state
let () =
print_endline "------ Unit tests ------" ;
ounit2_of_ounit1 base_suite |> OUnit2.run_test_tt_main
|
788f02058e1ecb106819ff4a2e65ea6fb4f48f98dded6bc729a6420de02984d3 | ku-fpg/kansas-lava | Signal.hs | # LANGUAGE TypeFamilies , ExistentialQuantification ,
FlexibleInstances , UndecidableInstances , FlexibleContexts ,
ScopedTypeVariables , MultiParamTypeClasses #
FlexibleInstances, UndecidableInstances, FlexibleContexts,
ScopedTypeVariables, MultiParamTypeClasses #-}
| The Signal module serves as a representation for the combined shallow and
-- deep embeddings of sequential circuits. The shallow portion is reprented as a
-- stream, the deep portion as a (typed) entity. To allow for multiple clock
domains , the Signal type includes an extra type parameter . The type alias ' Seq '
-- is for sequential logic in some implicit global clock domain.
module Language.KansasLava.Signal where
import Control.Applicative
import Control.Monad (liftM, liftM2, liftM3)
import Data.List as List
import Data.Bits
import Data.Array.IArray
import
import Data.Sized.Matrix as M
import Data.Singletons
import Language.KansasLava.Stream (Stream(Cons))
import Language.KansasLava.Rep
import qualified Language.KansasLava.Stream as S
import Language.KansasLava.Types
import Control.Concurrent
import System.IO.Unsafe
-----------------------------------------------------------------------------------------------
-- | These are sequences of values over time.
-- We assume edge triggered logic (checked at (typically) rising edge of clock)
-- This clock is assumed known, based on who is consuming the list.
-- Right now, it is global, but we think we can support multiple clocks with a bit of work.
data Signal (c :: *) a = Signal (S.Stream (X a)) (D a)
-- | Signal in some implicit clock domain.
type Seq a = Signal CLK a
-- | Extract the shallow portion of a 'Signal'.
shallowXS :: Signal c a -> S.Stream (X a)
shallowXS (Signal a _) = a
-- | Extract the shallow portion of a 'Signal'.
shallowS :: (Rep a) => Signal c a -> S.Stream (Maybe a)
shallowS = fmap unX . shallowXS
-- | Extract the deep portion of a 'Signal'.
deepS :: Signal c a -> D a
deepS (Signal _ d) = d
deepMapS :: (D a -> D a) -> Signal c a -> Signal c a
deepMapS f (Signal a d) = (Signal a (f d))
shallowMapXS :: (S.Stream (X a) -> S.Stream (X a)) -> Signal c a -> Signal c a
shallowMapXS f (Signal a d) = (Signal (f a) d)
-- | A pure 'Signal'.
pureS :: (Rep a) => a -> Signal i a
pureS a = Signal (pure (pureX a)) (D $ Lit $ toRep $ pureX a)
-- | A 'Signal' witness identity function. Useful when typing things.
witnessS :: (Rep a) => Witness a -> Signal i a -> Signal i a
witnessS (Witness) = id
| Inject a deep value into a Signal . The shallow portion of the Signal will be an
-- error, if it is every used.
mkDeepS :: D a -> Signal c a
mkDeepS = Signal (error "incorrect use of shallow Signal")
| Inject a shallow value into a Signal . The deep portion of the Signal will be an
-- Error if it is ever used.
mkShallowS :: (Rep a, Clock c) => S.Stream (Maybe a) -> Signal c a
mkShallowS = mkShallowXS . fmap optX
mkShallowXS :: (Clock c) => S.Stream (X a) -> Signal c a
mkShallowXS s = Signal s (D $ Error "incorrect use of deep Signal")
| Create a Signal with undefined for both the deep and shallow elements .
undefinedS :: forall a sig clk . (Rep a, sig ~ Signal clk) => sig a
undefinedS = Signal (pure $ (unknownX :: X a))
(D $ Lit $ toRep (unknownX :: X a))
| Create a Signal which has every value as 0 . Use ' undefinedS '
-- where posssible.
zeroS :: forall a sig clk . (Rep a, sig ~ Signal clk) => sig a
zeroS = Signal (pure $ (zeroX :: X a))
(D $ Lit $ toRep (zeroX :: X a))
-- | Attach a comment to a 'Signal'.
commentS :: forall a sig clk . (Rep a, sig ~ Signal clk) => String -> sig a -> sig a
commentS msg = idS (Comment [msg])
-- | The width in bits of the signal value.
widthS :: forall a c . (Rep a) => Signal c a -> Int
widthS _ = repWidth (Witness :: Witness a)
writeIOS :: Signal i a -> (X a -> IO ()) -> IO ()
writeIOS sig m = do
_ <- ($) forkIO $ loop (shallowXS sig)
return ()
where
loop (Cons x r) = do
m x
case r of
Nothing -> loop (Cons x r)
Just xs -> loop xs
readIOS :: (Clock i) => IO (X a) -> IO (Signal i a)
readIOS m = do
let loop = unsafeInterleaveIO $ do
x <- m -- atomically $ takeTMVar v
xs <- loop
return $ S.cons x xs
xs <- loop
return (mkShallowXS xs)
-----------------------------------------------------------------------
-- primitive builders
-- | 'idS' create an identity function, with a given 'Id' tag.
idS :: forall a sig clk . (Rep a, sig ~ Signal clk) => Id -> sig a -> sig a
idS id' (Signal a ae) = Signal a $ D $ Port "o0" $ E
$ Entity id'
[("o0",repType (Witness :: Witness a))]
[("i0",repType (Witness :: Witness a),unD $ ae)]
| create a zero - arity Signal value from an ' X ' value .
primXS :: (Rep a) => X a -> String -> Signal i a
primXS a nm = Signal (pure a) (entityD nm)
| create an arity-1 Signal function from an ' X ' function .
primXS1 :: forall a b i . (Rep a, Rep b) => (X a -> X b) -> String -> Signal i a -> Signal i b
primXS1 f nm (Signal a1 ae1) = Signal (fmap f a1) (entityD1 nm ae1)
| create an arity-2 Signal function from an ' X ' function .
primXS2 :: forall a b c i . (Rep a, Rep b, Rep c) => (X a -> X b -> X c) -> String -> Signal i a -> Signal i b -> Signal i c
primXS2 f nm (Signal a1 ae1) (Signal a2 ae2)
= Signal (S.zipWith f a1 a2)
(entityD2 nm ae1 ae2)
| create an arity-3 Signal function from an ' X ' function .
primXS3 :: forall a b c d i . (Rep a, Rep b, Rep c, Rep d)
=> (X a -> X b -> X c -> X d) -> String -> Signal i a -> Signal i b -> Signal i c -> Signal i d
primXS3 f nm (Signal a1 ae1) (Signal a2 ae2) (Signal a3 ae3) = Signal (S.zipWith3 f a1 a2 a3)
(entityD3 nm ae1 ae2 ae3)
| create a zero - arity Signal value from a value .
primS :: (Rep a) => a -> String -> Signal i a
primS a nm = primXS (pureX a) nm
| create an arity-1 Signal function from a function .
primS1 :: (Rep a, Rep b) => (a -> b) -> String -> Signal i a -> Signal i b
primS1 f nm = primXS1 (\ a -> optX $ liftM f (unX a)) nm
| create an arity-2 Signal function from a function .
primS2 :: (Rep a, Rep b, Rep c) => (a -> b -> c) -> String -> Signal i a -> Signal i b -> Signal i c
primS2 f nm = primXS2 (\ a b -> optX $ liftM2 f (unX a) (unX b)) nm
| create an arity-3 Signal function from a function .
primS3 :: (Rep a, Rep b, Rep c, Rep d) => (a -> b -> c -> d) -> String -> Signal i a -> Signal i b -> Signal i c -> Signal i d
primS3 f nm = primXS3 (\ a b c -> optX $ liftM3 f (unX a) (unX b) (unX c)) nm
---------------------------------------------------------------------------------
instance (Rep a) => Show (Signal c a) where
show (Signal vs _) = show' "" vs
where
show' end (Cons a opt_as) = showRep a ++ maybe end (\ as -> " | " ++ show' " ." as) opt_as
instance (Rep a, Eq a) => Eq (Signal c a) where
question ; never True ; can be False .
(Signal _ _) == (Signal _ _) = error "undefined: Eq over a Signal"
instance (Num a, Rep a) => Num (Signal i a) where
s1 + s2 = primS2 (+) "+" s1 s2
s1 - s2 = primS2 (-) "-" s1 s2
s1 * s2 = primS2 (*) "*" s1 s2
negate s1 = primS1 (negate) "negate" s1
abs s1 = primS1 (abs) "abs" s1
signum s1 = primS1 (signum) "signum" s1
fromInteger n = pureS (fromInteger n)
instance (Bounded a, Rep a) => Bounded (Signal i a) where
minBound = pureS $ minBound
maxBound = pureS $ maxBound
instance (Show a, Bits a, Rep a) => Bits (Signal i a) where
s1 .&. s2 = primS2 (.&.) "and2" s1 s2
s1 .|. s2 = primS2 (.|.) "or2" s1 s2
s1 `xor` s2 = primS2 (xor) "xor2" s1 s2
s1 `shiftL` n = primS2 (shiftL) ("shiftL" ++ if isSigned s1 then "A" else "") s1 (pureS n)
s1 `shiftR` n = primS2 (shiftR) ("shiftR" ++ if isSigned s1 then "A" else "") s1 (pureS n)
s1 `rotateL` n = primS2 (rotateL) "rotateL" s1 (pureS n)
s1 `rotateR` n = primS2 (rotateR) "rotateR" s1 (pureS n)
complement s = primS1 (complement) "complement" s
bitSize s = typeWidth (typeOfS s)
isSigned s = isTypeSigned (typeOfS s)
bit = pureS . bit
TODO . testBit for Bits ( Signal i a )
testBit = error "testBit for Signal"
TODO . for Bits ( Signal i a )
popCount = error "popCount for Signal"
instance (Eq a, Show a, Fractional a, Rep a) => Fractional (Signal i a) where
s1 / s2 = primS2 (/) "/" s1 s2
recip s1 = primS1 (recip) "recip" s1
-- This should just fold down to the raw bits.
fromRational r = pureS (fromRational r :: a)
instance (Rep a, Enum a) => Enum (Signal i a) where
toEnum = error "toEnum not supported"
fromEnum = error "fromEnum not supported"
instance (Ord a, Rep a) => Ord (Signal i a) where
compare _ _ = error "compare not supported for Comb"
(<) _ _ = error "(<) not supported for Comb"
(>=) _ _ = error "(>=) not supported for Comb"
(>) _ _ = error "(>) not supported for Comb"
(<=)_ _ = error "(<=) not supported for Comb"
s1 `max` s2 = primS2 max "max" s1 s2
s1 `min` s2 = primS2 max "min" s1 s2
instance (Rep a, Real a) => Real (Signal i a) where
toRational = error "toRational not supported for Comb"
instance (Rep a, Integral a) => Integral (Signal i a) where
quot num dom = primS2 quot "quot" num dom
rem num dom = primS2 rem "rem" num dom
div num dom = primS2 div "div" num dom
mod num dom = primS2 mod "mod" num dom
quotRem num dom = (quot num dom, rem num dom)
divMod num dom = (div num dom, mod num dom)
toInteger = error "toInteger (Signal {})"
----------------------------------------------------------------------------------------------------
-- Small DSL's for declaring signals
| Convert a list of values into a Signal . The shallow portion of the resulting
Signal will begin with the input list , then an infinite stream of X unknowns .
toS :: (Clock c, Rep a) => [a] -> Signal c a
toS = toS' . map Just
| Convert a list of values into a Signal . The input list is wrapped with a
-- Maybe, and any Nothing elements are mapped to X's unknowns.
toS' :: (Clock c, Rep a) => [Maybe a] -> Signal c a
toS' = toXS . map optX
| Convert a list of X values to a Signal . Pad the end with an infinite list of X unknowns .
toXS :: forall a c . (Clock c, Rep a) => [X a] -> Signal c a
toXS xs = mkShallowXS (S.fromFiniteList xs unknownX)
| Convert a Signal of values into a list of Maybe values .
fromS :: (Rep a) => Signal c a -> [Maybe a]
fromS = S.toList . shallowS
| Convret a Signal of values into a list of representable values .
fromXS :: (Rep a) => Signal c a -> [X a]
fromXS = S.toList . shallowXS
| take the first n elements of a ' Signal ' ; the rest is undefined .
takeS :: (Rep a, Clock c) => Int -> Signal c a -> Signal c a
takeS n s = mkShallowXS (S.fromFiniteList (take n (S.toList (shallowXS s))) unknownX)
| Compare the first depth elements of two Signals .
cmpSignalRep :: forall a c . (Rep a) => Int -> Signal c a -> Signal c a -> Bool
cmpSignalRep depth s1 s2 = and $ take depth $ S.toList $ S.zipWith cmpRep
(shallowXS s1)
(shallowXS s2)
-----------------------------------------------------------------------------------
-- | Return the Lava type of a representable signal.
typeOfS :: forall w clk sig . (Rep w, sig ~ Signal clk) => sig w -> Type
typeOfS _ = repType (Witness :: Witness w)
-- | The Pack class allows us to move between signals containing compound data
-- and signals containing the elements of the compound data. This is done by
-- commuting the signal type constructor with the type constructor representing
-- the compound data. For example, if we have a value x :: Signal sig => sig
-- (a,b), then 'unpack x' converts this to a (sig a, sig b). Dually, pack takes
-- (sig a,sig b) to sig (a,b).
class Pack clk a where
type Unpacked clk a
-- ^ Pull the sig type *out* of the compound data type.
pack :: Unpacked clk a -> Signal clk a
-- ^ Push the sign type *into* the compound data type.
unpack :: Signal clk a -> Unpacked clk a
-- | Given a function over unpacked (composite) signals, turn it into a function
-- over packed signals.
mapPacked :: (Pack i a, Pack i b, sig ~ Signal i) => (Unpacked i a -> Unpacked i b) -> sig a -> sig b
mapPacked f = pack . f . unpack
-- | Lift a binary function operating over unpacked signals into a function over a pair of packed signals.
zipPacked :: (Pack i a, Pack i b, Pack i c, sig ~ Signal i)
=> (Unpacked i a -> Unpacked i b -> Unpacked i c)
-> sig a -> sig b -> sig c
zipPacked f x y = pack $ f (unpack x) (unpack y)
instance (Rep a, Rep b) => Pack i (a,b) where
type Unpacked i (a,b) = (Signal i a,Signal i b)
pack (a,b) = primS2 (,) "pair" a b
unpack ab = ( primS1 (fst) "fst" ab
, primS1 (snd) "snd" ab
)
instance (Rep a, Rep b, Rep c) => Pack i (a,b,c) where
type Unpacked i (a,b,c) = (Signal i a,Signal i b, Signal i c)
pack (a,b,c) = primS3 (,,) "triple" a b c
unpack abc = ( primS1 (\(x,_,_) -> x) "fst3" abc
, primS1 (\(_,x,_) -> x) "snd3" abc
, primS1 (\(_,_,x) -> x) "thd3" abc
)
instance (Rep a) => Pack i (Maybe a) where
type Unpacked i (Maybe a) = (Signal i Bool, Signal i a)
pack (a,b) = primXS2 (\ a' b' -> case unX a' of
Nothing -> optX Nothing
Just False -> optX $ Just Nothing
Just True -> optX $ case unX b' of
Nothing -> Nothing
Just v -> Just (Just v))
"pair" a b
unpack ma = ( primXS1 (\ a -> case unX a of
Nothing -> optX Nothing
Just Nothing -> optX (Just False)
Just (Just _) -> optX (Just True))
"fst" ma
, primXS1 (\ a -> case unX a of
Nothing -> optX Nothing
Just Nothing -> optX Nothing
Just (Just v) -> optX (Just v))
"snd" ma
)
instance ( Rep a , Rep b , Rep c , Signal sig ) = > Pack sig ( a , b , c ) where
type Unpacked sig ( a , b , c ) = ( sig a , sig b , sig c )
pack ( a , b , c ) = ( \ ( Comb a ' ae ) ( Comb b ' be ) ( Comb c ' ce ) - >
Comb ( XTriple ( a',b',c ' ) )
( ( Prim " triple " ) ae be ce ) )
a b c
unpack abc = ( liftS1 ( \ ( Comb ( XTriple ( a,_b , _ ) ) abce ) - > Comb a ( entity1 ( Prim " fst3 " ) abce ) ) abc
, liftS1 ( \ ( Comb ( XTriple ( _ , b , _ ) ) abce ) - > Comb b ( ( Prim " snd3 " ) abce ) ) abc
, liftS1 ( \ ( Comb ( XTriple ( _ , _ , c ) ) abce ) - > Comb c ( ( Prim " thd3 " ) abce ) ) abc
)
instance (Rep a, Rep b, Rep c, Signal sig) => Pack sig (a,b,c) where
type Unpacked sig (a,b,c) = (sig a, sig b,sig c)
pack (a,b,c) = liftS3 (\ (Comb a' ae) (Comb b' be) (Comb c' ce) ->
Comb (XTriple (a',b',c'))
(entity3 (Prim "triple") ae be ce))
a b c
unpack abc = ( liftS1 (\ (Comb (XTriple (a,_b,_)) abce) -> Comb a (entity1 (Prim "fst3") abce)) abc
, liftS1 (\ (Comb (XTriple (_,b,_)) abce) -> Comb b (entity1 (Prim "snd3") abce)) abc
, liftS1 (\ (Comb (XTriple (_,_,c)) abce) -> Comb c (entity1 (Prim "thd3") abce)) abc
)
-}
unpackMatrix :: (Rep a, SingI x, sig ~ Signal clk) => sig (M.Vector x a) -> M.Vector x (sig a)
unpackMatrix a = unpack a
packMatrix :: (Rep a, SingI x, sig ~ Signal clk) => M.Vector x (sig a) -> sig (M.Vector x a)
packMatrix a = pack a
instance (Rep a, SingI ix) => Pack clk (M.Vector ix a) where
type Unpacked clk (M.Vector ix a) = M.Vector ix (Signal clk a)
pack m = Signal shallow
deep
where
shallow :: (S.Stream (X (M.Vector ix a)))
shallow = id
$ S.fromList -- Stream (X (Matrix ix a))
$ fmap XMatrix -- [(X (Matrix ix a))]
$ fmap M.matrix -- [Matrix ix (X a)]
$ List.transpose -- [[X a]]
$ fmap S.toList -- [[X a]]
$ fmap shallowXS -- [Stream (X a)]
$ elems -- [sig a]
$ m -- Matrix ix (sig a)
deep :: D (M.Vector ix a)
deep = D
$ Port "o0"
$ E
$ Entity (Prim "concat")
[("o0",repType (Witness :: Witness (M.Vector ix a)))]
[ ("i" ++ show i,repType (Witness :: Witness a),unD $ deepS $ x)
| (x,i) <- zip (elems m) ([0..] :: [Int])
]
unpack ms = M.forAll $ \ i -> Signal (shallow i) (deep i)
where mx :: M.Vector ix Integer
mx = forAll $ \ ix -> fromIntegral ix
deep i = D
$ Port "o0"
$ E
$ Entity (Prim "index")
[("o0",repType (Witness :: Witness a))]
[("i0",GenericTy,Generic (mx ! i))
,("i1",repType (Witness :: Witness (M.Vector ix a)),unD $ deepS ms)
]
shallow i = fmap (liftX (! i)) (shallowXS ms)
----------------------------------------------------------------
-- | a delay is a register with no defined default / initial value.
delay :: forall a clk . (Rep a, Clock clk) => Signal clk a -> Signal clk a
delay ~(Signal line eline) = res
where
def = optX $ Nothing
-- rep = toRep def
res = Signal sres1 (D $ Port ("o0") $ E $ entity)
sres0 = line
sres1 = S.Cons def (Just sres0)
entity = Entity (Prim "delay")
[("o0", typeOfS res)]
[("i0", typeOfS res, unD eline),
("clk",ClkTy, Pad "clk"),
("rst",B, Pad "rst")
]
-- | delays generates a serial sequence of n delays.
delays :: forall a clk . (Rep a, Clock clk) => Int -> Signal clk a -> Signal clk a
delays n ss = iterate delay ss !! n
| A register is a state element with a reset . The reset is supplied by the clock domain in the Signal .
register :: forall a clk . (Rep a, Clock clk) => a -> Signal clk a -> Signal clk a
register first ~(Signal line eline) = res
where
def = optX $ Just first
rep = toRep def
res = Signal sres1 (D $ Port ("o0") $ E $ entity)
sres0 = line
sres1 = S.Cons def (Just sres0)
entity = Entity (Prim "register")
[("o0", typeOfS res)]
[("i0", typeOfS res, unD eline),
("def",GenericTy,Generic (fromRepToInteger rep)),
("clk",ClkTy, Pad "clk"),
("rst",B, Pad "rst")
]
-- | registers generates a serial sequence of n registers, all with the same initial value.
registers :: forall a clk . (Rep a, Clock clk) => Int -> a -> Signal clk a -> Signal clk a
registers n def ss = iterate (register def) ss !! n
-----------------------------------------------------------------------------------
-- The 'deep' combinators, used to build the deep part of a signal.
entityD :: forall a . (Rep a) => String -> D a
entityD nm = D $ Port "o0" $ E $ Entity (Prim nm) [("o0",repType (Witness :: Witness a))]
[]
entityD1 :: forall a1 a . (Rep a, Rep a1) => String -> D a1 -> D a
entityD1 nm (D a1)
= D $ Port "o0" $ E $ Entity (Prim nm) [("o0",repType (Witness :: Witness a))]
[("i0",repType (Witness :: Witness a1),a1)]
entityD2 :: forall a1 a2 a . (Rep a, Rep a1, Rep a2) => String -> D a1 -> D a2 -> D a
entityD2 nm (D a1) (D a2)
= D $ Port "o0" $ E $ Entity (Prim nm) [("o0",repType (Witness :: Witness a))]
[("i0",repType (Witness :: Witness a1),a1)
,("i1",repType (Witness :: Witness a2),a2)]
entityD3 :: forall a1 a2 a3 a . (Rep a, Rep a1, Rep a2, Rep a3) => String -> D a1 -> D a2 -> D a3 -> D a
entityD3 nm (D a1) (D a2) (D a3)
= D $ Port "o0" $ E $ Entity (Prim nm) [("o0",repType (Witness :: Witness a))]
[("i0",repType (Witness :: Witness a1),a1)
,("i1",repType (Witness :: Witness a2),a2)
,("i2",repType (Witness :: Witness a3),a3)]
pureD :: (Rep a) => a -> D a
pureD a = pureXD (pureX a)
pureXD :: (Rep a) => X a -> D a
pureXD a = D $ Lit $ toRep a
| null | https://raw.githubusercontent.com/ku-fpg/kansas-lava/cc0be29bd8392b57060c3c11e7f3b799a6d437e1/Language/KansasLava/Signal.hs | haskell | deep embeddings of sequential circuits. The shallow portion is reprented as a
stream, the deep portion as a (typed) entity. To allow for multiple clock
is for sequential logic in some implicit global clock domain.
---------------------------------------------------------------------------------------------
| These are sequences of values over time.
We assume edge triggered logic (checked at (typically) rising edge of clock)
This clock is assumed known, based on who is consuming the list.
Right now, it is global, but we think we can support multiple clocks with a bit of work.
| Signal in some implicit clock domain.
| Extract the shallow portion of a 'Signal'.
| Extract the shallow portion of a 'Signal'.
| Extract the deep portion of a 'Signal'.
| A pure 'Signal'.
| A 'Signal' witness identity function. Useful when typing things.
error, if it is every used.
Error if it is ever used.
where posssible.
| Attach a comment to a 'Signal'.
| The width in bits of the signal value.
atomically $ takeTMVar v
---------------------------------------------------------------------
primitive builders
| 'idS' create an identity function, with a given 'Id' tag.
-------------------------------------------------------------------------------
This should just fold down to the raw bits.
--------------------------------------------------------------------------------------------------
Small DSL's for declaring signals
Maybe, and any Nothing elements are mapped to X's unknowns.
---------------------------------------------------------------------------------
| Return the Lava type of a representable signal.
| The Pack class allows us to move between signals containing compound data
and signals containing the elements of the compound data. This is done by
commuting the signal type constructor with the type constructor representing
the compound data. For example, if we have a value x :: Signal sig => sig
(a,b), then 'unpack x' converts this to a (sig a, sig b). Dually, pack takes
(sig a,sig b) to sig (a,b).
^ Pull the sig type *out* of the compound data type.
^ Push the sign type *into* the compound data type.
| Given a function over unpacked (composite) signals, turn it into a function
over packed signals.
| Lift a binary function operating over unpacked signals into a function over a pair of packed signals.
Stream (X (Matrix ix a))
[(X (Matrix ix a))]
[Matrix ix (X a)]
[[X a]]
[[X a]]
[Stream (X a)]
[sig a]
Matrix ix (sig a)
--------------------------------------------------------------
| a delay is a register with no defined default / initial value.
rep = toRep def
| delays generates a serial sequence of n delays.
| registers generates a serial sequence of n registers, all with the same initial value.
---------------------------------------------------------------------------------
The 'deep' combinators, used to build the deep part of a signal. | # LANGUAGE TypeFamilies , ExistentialQuantification ,
FlexibleInstances , UndecidableInstances , FlexibleContexts ,
ScopedTypeVariables , MultiParamTypeClasses #
FlexibleInstances, UndecidableInstances, FlexibleContexts,
ScopedTypeVariables, MultiParamTypeClasses #-}
| The Signal module serves as a representation for the combined shallow and
domains , the Signal type includes an extra type parameter . The type alias ' Seq '
module Language.KansasLava.Signal where
import Control.Applicative
import Control.Monad (liftM, liftM2, liftM3)
import Data.List as List
import Data.Bits
import Data.Array.IArray
import
import Data.Sized.Matrix as M
import Data.Singletons
import Language.KansasLava.Stream (Stream(Cons))
import Language.KansasLava.Rep
import qualified Language.KansasLava.Stream as S
import Language.KansasLava.Types
import Control.Concurrent
import System.IO.Unsafe
data Signal (c :: *) a = Signal (S.Stream (X a)) (D a)
type Seq a = Signal CLK a
shallowXS :: Signal c a -> S.Stream (X a)
shallowXS (Signal a _) = a
shallowS :: (Rep a) => Signal c a -> S.Stream (Maybe a)
shallowS = fmap unX . shallowXS
deepS :: Signal c a -> D a
deepS (Signal _ d) = d
deepMapS :: (D a -> D a) -> Signal c a -> Signal c a
deepMapS f (Signal a d) = (Signal a (f d))
shallowMapXS :: (S.Stream (X a) -> S.Stream (X a)) -> Signal c a -> Signal c a
shallowMapXS f (Signal a d) = (Signal (f a) d)
pureS :: (Rep a) => a -> Signal i a
pureS a = Signal (pure (pureX a)) (D $ Lit $ toRep $ pureX a)
witnessS :: (Rep a) => Witness a -> Signal i a -> Signal i a
witnessS (Witness) = id
| Inject a deep value into a Signal . The shallow portion of the Signal will be an
mkDeepS :: D a -> Signal c a
mkDeepS = Signal (error "incorrect use of shallow Signal")
| Inject a shallow value into a Signal . The deep portion of the Signal will be an
mkShallowS :: (Rep a, Clock c) => S.Stream (Maybe a) -> Signal c a
mkShallowS = mkShallowXS . fmap optX
mkShallowXS :: (Clock c) => S.Stream (X a) -> Signal c a
mkShallowXS s = Signal s (D $ Error "incorrect use of deep Signal")
| Create a Signal with undefined for both the deep and shallow elements .
undefinedS :: forall a sig clk . (Rep a, sig ~ Signal clk) => sig a
undefinedS = Signal (pure $ (unknownX :: X a))
(D $ Lit $ toRep (unknownX :: X a))
| Create a Signal which has every value as 0 . Use ' undefinedS '
zeroS :: forall a sig clk . (Rep a, sig ~ Signal clk) => sig a
zeroS = Signal (pure $ (zeroX :: X a))
(D $ Lit $ toRep (zeroX :: X a))
commentS :: forall a sig clk . (Rep a, sig ~ Signal clk) => String -> sig a -> sig a
commentS msg = idS (Comment [msg])
widthS :: forall a c . (Rep a) => Signal c a -> Int
widthS _ = repWidth (Witness :: Witness a)
writeIOS :: Signal i a -> (X a -> IO ()) -> IO ()
writeIOS sig m = do
_ <- ($) forkIO $ loop (shallowXS sig)
return ()
where
loop (Cons x r) = do
m x
case r of
Nothing -> loop (Cons x r)
Just xs -> loop xs
readIOS :: (Clock i) => IO (X a) -> IO (Signal i a)
readIOS m = do
let loop = unsafeInterleaveIO $ do
xs <- loop
return $ S.cons x xs
xs <- loop
return (mkShallowXS xs)
idS :: forall a sig clk . (Rep a, sig ~ Signal clk) => Id -> sig a -> sig a
idS id' (Signal a ae) = Signal a $ D $ Port "o0" $ E
$ Entity id'
[("o0",repType (Witness :: Witness a))]
[("i0",repType (Witness :: Witness a),unD $ ae)]
| create a zero - arity Signal value from an ' X ' value .
primXS :: (Rep a) => X a -> String -> Signal i a
primXS a nm = Signal (pure a) (entityD nm)
| create an arity-1 Signal function from an ' X ' function .
primXS1 :: forall a b i . (Rep a, Rep b) => (X a -> X b) -> String -> Signal i a -> Signal i b
primXS1 f nm (Signal a1 ae1) = Signal (fmap f a1) (entityD1 nm ae1)
| create an arity-2 Signal function from an ' X ' function .
primXS2 :: forall a b c i . (Rep a, Rep b, Rep c) => (X a -> X b -> X c) -> String -> Signal i a -> Signal i b -> Signal i c
primXS2 f nm (Signal a1 ae1) (Signal a2 ae2)
= Signal (S.zipWith f a1 a2)
(entityD2 nm ae1 ae2)
| create an arity-3 Signal function from an ' X ' function .
primXS3 :: forall a b c d i . (Rep a, Rep b, Rep c, Rep d)
=> (X a -> X b -> X c -> X d) -> String -> Signal i a -> Signal i b -> Signal i c -> Signal i d
primXS3 f nm (Signal a1 ae1) (Signal a2 ae2) (Signal a3 ae3) = Signal (S.zipWith3 f a1 a2 a3)
(entityD3 nm ae1 ae2 ae3)
| create a zero - arity Signal value from a value .
primS :: (Rep a) => a -> String -> Signal i a
primS a nm = primXS (pureX a) nm
| create an arity-1 Signal function from a function .
primS1 :: (Rep a, Rep b) => (a -> b) -> String -> Signal i a -> Signal i b
primS1 f nm = primXS1 (\ a -> optX $ liftM f (unX a)) nm
| create an arity-2 Signal function from a function .
primS2 :: (Rep a, Rep b, Rep c) => (a -> b -> c) -> String -> Signal i a -> Signal i b -> Signal i c
primS2 f nm = primXS2 (\ a b -> optX $ liftM2 f (unX a) (unX b)) nm
| create an arity-3 Signal function from a function .
primS3 :: (Rep a, Rep b, Rep c, Rep d) => (a -> b -> c -> d) -> String -> Signal i a -> Signal i b -> Signal i c -> Signal i d
primS3 f nm = primXS3 (\ a b c -> optX $ liftM3 f (unX a) (unX b) (unX c)) nm
instance (Rep a) => Show (Signal c a) where
show (Signal vs _) = show' "" vs
where
show' end (Cons a opt_as) = showRep a ++ maybe end (\ as -> " | " ++ show' " ." as) opt_as
instance (Rep a, Eq a) => Eq (Signal c a) where
question ; never True ; can be False .
(Signal _ _) == (Signal _ _) = error "undefined: Eq over a Signal"
instance (Num a, Rep a) => Num (Signal i a) where
s1 + s2 = primS2 (+) "+" s1 s2
s1 - s2 = primS2 (-) "-" s1 s2
s1 * s2 = primS2 (*) "*" s1 s2
negate s1 = primS1 (negate) "negate" s1
abs s1 = primS1 (abs) "abs" s1
signum s1 = primS1 (signum) "signum" s1
fromInteger n = pureS (fromInteger n)
instance (Bounded a, Rep a) => Bounded (Signal i a) where
minBound = pureS $ minBound
maxBound = pureS $ maxBound
instance (Show a, Bits a, Rep a) => Bits (Signal i a) where
s1 .&. s2 = primS2 (.&.) "and2" s1 s2
s1 .|. s2 = primS2 (.|.) "or2" s1 s2
s1 `xor` s2 = primS2 (xor) "xor2" s1 s2
s1 `shiftL` n = primS2 (shiftL) ("shiftL" ++ if isSigned s1 then "A" else "") s1 (pureS n)
s1 `shiftR` n = primS2 (shiftR) ("shiftR" ++ if isSigned s1 then "A" else "") s1 (pureS n)
s1 `rotateL` n = primS2 (rotateL) "rotateL" s1 (pureS n)
s1 `rotateR` n = primS2 (rotateR) "rotateR" s1 (pureS n)
complement s = primS1 (complement) "complement" s
bitSize s = typeWidth (typeOfS s)
isSigned s = isTypeSigned (typeOfS s)
bit = pureS . bit
TODO . testBit for Bits ( Signal i a )
testBit = error "testBit for Signal"
TODO . for Bits ( Signal i a )
popCount = error "popCount for Signal"
instance (Eq a, Show a, Fractional a, Rep a) => Fractional (Signal i a) where
s1 / s2 = primS2 (/) "/" s1 s2
recip s1 = primS1 (recip) "recip" s1
fromRational r = pureS (fromRational r :: a)
instance (Rep a, Enum a) => Enum (Signal i a) where
toEnum = error "toEnum not supported"
fromEnum = error "fromEnum not supported"
instance (Ord a, Rep a) => Ord (Signal i a) where
compare _ _ = error "compare not supported for Comb"
(<) _ _ = error "(<) not supported for Comb"
(>=) _ _ = error "(>=) not supported for Comb"
(>) _ _ = error "(>) not supported for Comb"
(<=)_ _ = error "(<=) not supported for Comb"
s1 `max` s2 = primS2 max "max" s1 s2
s1 `min` s2 = primS2 max "min" s1 s2
instance (Rep a, Real a) => Real (Signal i a) where
toRational = error "toRational not supported for Comb"
instance (Rep a, Integral a) => Integral (Signal i a) where
quot num dom = primS2 quot "quot" num dom
rem num dom = primS2 rem "rem" num dom
div num dom = primS2 div "div" num dom
mod num dom = primS2 mod "mod" num dom
quotRem num dom = (quot num dom, rem num dom)
divMod num dom = (div num dom, mod num dom)
toInteger = error "toInteger (Signal {})"
| Convert a list of values into a Signal . The shallow portion of the resulting
Signal will begin with the input list , then an infinite stream of X unknowns .
toS :: (Clock c, Rep a) => [a] -> Signal c a
toS = toS' . map Just
| Convert a list of values into a Signal . The input list is wrapped with a
toS' :: (Clock c, Rep a) => [Maybe a] -> Signal c a
toS' = toXS . map optX
| Convert a list of X values to a Signal . Pad the end with an infinite list of X unknowns .
toXS :: forall a c . (Clock c, Rep a) => [X a] -> Signal c a
toXS xs = mkShallowXS (S.fromFiniteList xs unknownX)
| Convert a Signal of values into a list of Maybe values .
fromS :: (Rep a) => Signal c a -> [Maybe a]
fromS = S.toList . shallowS
| Convret a Signal of values into a list of representable values .
fromXS :: (Rep a) => Signal c a -> [X a]
fromXS = S.toList . shallowXS
| take the first n elements of a ' Signal ' ; the rest is undefined .
takeS :: (Rep a, Clock c) => Int -> Signal c a -> Signal c a
takeS n s = mkShallowXS (S.fromFiniteList (take n (S.toList (shallowXS s))) unknownX)
| Compare the first depth elements of two Signals .
cmpSignalRep :: forall a c . (Rep a) => Int -> Signal c a -> Signal c a -> Bool
cmpSignalRep depth s1 s2 = and $ take depth $ S.toList $ S.zipWith cmpRep
(shallowXS s1)
(shallowXS s2)
typeOfS :: forall w clk sig . (Rep w, sig ~ Signal clk) => sig w -> Type
typeOfS _ = repType (Witness :: Witness w)
class Pack clk a where
type Unpacked clk a
pack :: Unpacked clk a -> Signal clk a
unpack :: Signal clk a -> Unpacked clk a
mapPacked :: (Pack i a, Pack i b, sig ~ Signal i) => (Unpacked i a -> Unpacked i b) -> sig a -> sig b
mapPacked f = pack . f . unpack
zipPacked :: (Pack i a, Pack i b, Pack i c, sig ~ Signal i)
=> (Unpacked i a -> Unpacked i b -> Unpacked i c)
-> sig a -> sig b -> sig c
zipPacked f x y = pack $ f (unpack x) (unpack y)
instance (Rep a, Rep b) => Pack i (a,b) where
type Unpacked i (a,b) = (Signal i a,Signal i b)
pack (a,b) = primS2 (,) "pair" a b
unpack ab = ( primS1 (fst) "fst" ab
, primS1 (snd) "snd" ab
)
instance (Rep a, Rep b, Rep c) => Pack i (a,b,c) where
type Unpacked i (a,b,c) = (Signal i a,Signal i b, Signal i c)
pack (a,b,c) = primS3 (,,) "triple" a b c
unpack abc = ( primS1 (\(x,_,_) -> x) "fst3" abc
, primS1 (\(_,x,_) -> x) "snd3" abc
, primS1 (\(_,_,x) -> x) "thd3" abc
)
instance (Rep a) => Pack i (Maybe a) where
type Unpacked i (Maybe a) = (Signal i Bool, Signal i a)
pack (a,b) = primXS2 (\ a' b' -> case unX a' of
Nothing -> optX Nothing
Just False -> optX $ Just Nothing
Just True -> optX $ case unX b' of
Nothing -> Nothing
Just v -> Just (Just v))
"pair" a b
unpack ma = ( primXS1 (\ a -> case unX a of
Nothing -> optX Nothing
Just Nothing -> optX (Just False)
Just (Just _) -> optX (Just True))
"fst" ma
, primXS1 (\ a -> case unX a of
Nothing -> optX Nothing
Just Nothing -> optX Nothing
Just (Just v) -> optX (Just v))
"snd" ma
)
instance ( Rep a , Rep b , Rep c , Signal sig ) = > Pack sig ( a , b , c ) where
type Unpacked sig ( a , b , c ) = ( sig a , sig b , sig c )
pack ( a , b , c ) = ( \ ( Comb a ' ae ) ( Comb b ' be ) ( Comb c ' ce ) - >
Comb ( XTriple ( a',b',c ' ) )
( ( Prim " triple " ) ae be ce ) )
a b c
unpack abc = ( liftS1 ( \ ( Comb ( XTriple ( a,_b , _ ) ) abce ) - > Comb a ( entity1 ( Prim " fst3 " ) abce ) ) abc
, liftS1 ( \ ( Comb ( XTriple ( _ , b , _ ) ) abce ) - > Comb b ( ( Prim " snd3 " ) abce ) ) abc
, liftS1 ( \ ( Comb ( XTriple ( _ , _ , c ) ) abce ) - > Comb c ( ( Prim " thd3 " ) abce ) ) abc
)
instance (Rep a, Rep b, Rep c, Signal sig) => Pack sig (a,b,c) where
type Unpacked sig (a,b,c) = (sig a, sig b,sig c)
pack (a,b,c) = liftS3 (\ (Comb a' ae) (Comb b' be) (Comb c' ce) ->
Comb (XTriple (a',b',c'))
(entity3 (Prim "triple") ae be ce))
a b c
unpack abc = ( liftS1 (\ (Comb (XTriple (a,_b,_)) abce) -> Comb a (entity1 (Prim "fst3") abce)) abc
, liftS1 (\ (Comb (XTriple (_,b,_)) abce) -> Comb b (entity1 (Prim "snd3") abce)) abc
, liftS1 (\ (Comb (XTriple (_,_,c)) abce) -> Comb c (entity1 (Prim "thd3") abce)) abc
)
-}
unpackMatrix :: (Rep a, SingI x, sig ~ Signal clk) => sig (M.Vector x a) -> M.Vector x (sig a)
unpackMatrix a = unpack a
packMatrix :: (Rep a, SingI x, sig ~ Signal clk) => M.Vector x (sig a) -> sig (M.Vector x a)
packMatrix a = pack a
instance (Rep a, SingI ix) => Pack clk (M.Vector ix a) where
type Unpacked clk (M.Vector ix a) = M.Vector ix (Signal clk a)
pack m = Signal shallow
deep
where
shallow :: (S.Stream (X (M.Vector ix a)))
shallow = id
deep :: D (M.Vector ix a)
deep = D
$ Port "o0"
$ E
$ Entity (Prim "concat")
[("o0",repType (Witness :: Witness (M.Vector ix a)))]
[ ("i" ++ show i,repType (Witness :: Witness a),unD $ deepS $ x)
| (x,i) <- zip (elems m) ([0..] :: [Int])
]
unpack ms = M.forAll $ \ i -> Signal (shallow i) (deep i)
where mx :: M.Vector ix Integer
mx = forAll $ \ ix -> fromIntegral ix
deep i = D
$ Port "o0"
$ E
$ Entity (Prim "index")
[("o0",repType (Witness :: Witness a))]
[("i0",GenericTy,Generic (mx ! i))
,("i1",repType (Witness :: Witness (M.Vector ix a)),unD $ deepS ms)
]
shallow i = fmap (liftX (! i)) (shallowXS ms)
delay :: forall a clk . (Rep a, Clock clk) => Signal clk a -> Signal clk a
delay ~(Signal line eline) = res
where
def = optX $ Nothing
res = Signal sres1 (D $ Port ("o0") $ E $ entity)
sres0 = line
sres1 = S.Cons def (Just sres0)
entity = Entity (Prim "delay")
[("o0", typeOfS res)]
[("i0", typeOfS res, unD eline),
("clk",ClkTy, Pad "clk"),
("rst",B, Pad "rst")
]
delays :: forall a clk . (Rep a, Clock clk) => Int -> Signal clk a -> Signal clk a
delays n ss = iterate delay ss !! n
| A register is a state element with a reset . The reset is supplied by the clock domain in the Signal .
register :: forall a clk . (Rep a, Clock clk) => a -> Signal clk a -> Signal clk a
register first ~(Signal line eline) = res
where
def = optX $ Just first
rep = toRep def
res = Signal sres1 (D $ Port ("o0") $ E $ entity)
sres0 = line
sres1 = S.Cons def (Just sres0)
entity = Entity (Prim "register")
[("o0", typeOfS res)]
[("i0", typeOfS res, unD eline),
("def",GenericTy,Generic (fromRepToInteger rep)),
("clk",ClkTy, Pad "clk"),
("rst",B, Pad "rst")
]
registers :: forall a clk . (Rep a, Clock clk) => Int -> a -> Signal clk a -> Signal clk a
registers n def ss = iterate (register def) ss !! n
entityD :: forall a . (Rep a) => String -> D a
entityD nm = D $ Port "o0" $ E $ Entity (Prim nm) [("o0",repType (Witness :: Witness a))]
[]
entityD1 :: forall a1 a . (Rep a, Rep a1) => String -> D a1 -> D a
entityD1 nm (D a1)
= D $ Port "o0" $ E $ Entity (Prim nm) [("o0",repType (Witness :: Witness a))]
[("i0",repType (Witness :: Witness a1),a1)]
entityD2 :: forall a1 a2 a . (Rep a, Rep a1, Rep a2) => String -> D a1 -> D a2 -> D a
entityD2 nm (D a1) (D a2)
= D $ Port "o0" $ E $ Entity (Prim nm) [("o0",repType (Witness :: Witness a))]
[("i0",repType (Witness :: Witness a1),a1)
,("i1",repType (Witness :: Witness a2),a2)]
entityD3 :: forall a1 a2 a3 a . (Rep a, Rep a1, Rep a2, Rep a3) => String -> D a1 -> D a2 -> D a3 -> D a
entityD3 nm (D a1) (D a2) (D a3)
= D $ Port "o0" $ E $ Entity (Prim nm) [("o0",repType (Witness :: Witness a))]
[("i0",repType (Witness :: Witness a1),a1)
,("i1",repType (Witness :: Witness a2),a2)
,("i2",repType (Witness :: Witness a3),a3)]
pureD :: (Rep a) => a -> D a
pureD a = pureXD (pureX a)
pureXD :: (Rep a) => X a -> D a
pureXD a = D $ Lit $ toRep a
|
cd637876eb36386ad46fe03bebfd17e2ab8b7e40db2bcdbb48568d43b45457c4 | ocaml-multicore/ocaml-effects-tutorial | echo_async.ml | open Printf
module type Aio = sig
type 'a promise
(** Type of promises *)
val async : (unit -> 'a) -> 'a promise
(** [async f] runs [f] concurrently *)
val await : 'a promise -> 'a
(** [await p] returns the result of the promise. *)
val yield : unit -> unit
(** yields control to another task *)
val accept : Unix.file_descr -> Unix.file_descr * Unix.sockaddr
val recv : Unix.file_descr -> bytes -> int -> int -> Unix.msg_flag list -> int
val send : Unix.file_descr -> bytes -> int -> int -> Unix.msg_flag list -> int
val run : (unit -> 'a) -> unit
(** Runs the scheduler *)
end
module Aio : Aio = struct
open Effect
open Effect.Deep
type 'a _promise =
Waiting of ('a,unit) continuation list
| Done of 'a
type 'a promise = 'a _promise ref
type _ Effect.t += Async : (unit -> 'a) -> 'a promise Effect.t
let async f = perform (Async f)
type _ Effect.t += Yield : unit Effect.t
let yield () = perform Yield
type _ Effect.t += Await : 'a promise -> 'a Effect.t
let await p = perform (Await p)
type file_descr = Unix.file_descr
type sockaddr = Unix.sockaddr
type msg_flag = Unix.msg_flag
type _ Effect.t += Accept : file_descr -> (file_descr * sockaddr) Effect.t
let accept fd = perform (Accept fd)
type _ Effect.t += Recv : file_descr * bytes * int * int * msg_flag list -> int Effect.t
let recv fd buf pos len mode = perform (Recv (fd, buf, pos, len, mode))
type _ Effect.t += Send : file_descr * bytes * int * int * msg_flag list -> int Effect.t
let send fd bus pos len mode = perform (Send (fd, bus, pos, len, mode))
(********************)
let ready_to_read fd =
match Unix.select [fd] [] [] 0. with
| [], _, _ -> false
| _ -> true
let ready_to_write fd =
match Unix.select [] [fd] [] 0. with
| _, [], _ -> false
| _ -> true
let q = Queue.create ()
let enqueue t = Queue.push t q
type blocked = Blocked : 'a Effect.t * ('a, unit) continuation -> blocked
(* tasks blocked on reads *)
let br = Hashtbl.create 13
(* tasks blocked on writes *)
let bw = Hashtbl.create 13
let rec schedule () =
if not (Queue.is_empty q) then
(* runnable tasks available *)
Queue.pop q ()
else if Hashtbl.length br = 0 && Hashtbl.length bw = 0 then
(* no runnable tasks, and no blocked tasks => we're done. *)
()
else begin (* no runnable tasks, but blocked tasks available *)
let rd_fds = Hashtbl.fold (fun fd _ acc -> fd::acc) br [] in
let wr_fds = Hashtbl.fold (fun fd _ acc -> fd::acc) bw [] in
let rdy_rd_fds, rdy_wr_fds, _ = Unix.select rd_fds wr_fds [] (-1.) in
let rec resume ht = function
| [] -> ()
| x::xs ->
begin match Hashtbl.find ht x with
| Blocked (Recv (fd, buf, pos, len, mode), k) ->
enqueue (fun () -> continue k (Unix.recv fd buf pos len mode))
| Blocked (Accept fd, k) ->
enqueue (fun () -> continue k (Unix.accept fd))
| Blocked (Send (fd, buf, pos, len, mode), k) ->
enqueue (fun () -> continue k (Unix.send fd buf pos len mode))
| Blocked _ -> failwith "impossible"
end;
Hashtbl.remove ht x
in
resume br rdy_rd_fds;
resume br rdy_wr_fds;
schedule ()
end
let run main =
let rec fork : 'a. 'a promise -> (unit -> 'a) -> unit =
fun pr main ->
match_with main ()
{ retc = (fun v ->
let l = match !pr with Waiting l -> l | _ -> failwith "impossible" in
List.iter (fun k -> enqueue (fun () -> continue k v)) l;
pr := Done v;
schedule ()
);
exnc = raise;
effc = (fun (type b) (eff: b Effect.t) ->
match eff with
| Async f -> Some (fun (k: (b,_) continuation) ->
let pr = ref (Waiting []) in
enqueue (fun () -> continue k pr);
fork pr f
)
| Yield -> Some (fun (k: (b,_) continuation) ->
enqueue (continue k);
schedule ()
)
| Await p -> Some (fun (k: (b,_) continuation) ->
begin match !p with
| Done v -> continue k v
| Waiting l -> begin
p := Waiting (k::l);
schedule ()
end
end
)
| (Accept fd as e) -> Some (fun (k: (b,_) continuation) ->
if ready_to_read fd then
continue k (Unix.accept fd)
else begin
Hashtbl.add br fd (Blocked (e,k));
schedule ()
end
)
| (Send (fd,buf,pos,len,mode) as e) -> Some (fun (k: (b,_) continuation) ->
if ready_to_write fd then
continue k (Unix.send fd buf pos len mode)
else begin
Hashtbl.add bw fd (Blocked (e,k));
schedule ()
end
)
| (Recv (fd,buf,pos,len,mode) as e) -> Some (fun (k: (b,_) continuation) ->
if ready_to_read fd then
continue k (Unix.recv fd buf pos len mode)
else begin
Hashtbl.add br fd (Blocked (e, k));
schedule ()
end
)
| _ -> None
)}
in
fork (ref (Waiting [])) main
end
module M = Echo.Make(struct
let accept = Aio.accept
let recv = Aio.recv
let send = Aio.send
let fork f = ignore (Aio.async f)
let run f = Aio.run f
let non_blocking_mode = true
end)
let _ = M.start ()
| null | https://raw.githubusercontent.com/ocaml-multicore/ocaml-effects-tutorial/998376931b7fdaed5d54cb96b39b301b993ba995/sources/solved/echo_async.ml | ocaml | * Type of promises
* [async f] runs [f] concurrently
* [await p] returns the result of the promise.
* yields control to another task
* Runs the scheduler
******************
tasks blocked on reads
tasks blocked on writes
runnable tasks available
no runnable tasks, and no blocked tasks => we're done.
no runnable tasks, but blocked tasks available | open Printf
module type Aio = sig
type 'a promise
val async : (unit -> 'a) -> 'a promise
val await : 'a promise -> 'a
val yield : unit -> unit
val accept : Unix.file_descr -> Unix.file_descr * Unix.sockaddr
val recv : Unix.file_descr -> bytes -> int -> int -> Unix.msg_flag list -> int
val send : Unix.file_descr -> bytes -> int -> int -> Unix.msg_flag list -> int
val run : (unit -> 'a) -> unit
end
module Aio : Aio = struct
open Effect
open Effect.Deep
type 'a _promise =
Waiting of ('a,unit) continuation list
| Done of 'a
type 'a promise = 'a _promise ref
type _ Effect.t += Async : (unit -> 'a) -> 'a promise Effect.t
let async f = perform (Async f)
type _ Effect.t += Yield : unit Effect.t
let yield () = perform Yield
type _ Effect.t += Await : 'a promise -> 'a Effect.t
let await p = perform (Await p)
type file_descr = Unix.file_descr
type sockaddr = Unix.sockaddr
type msg_flag = Unix.msg_flag
type _ Effect.t += Accept : file_descr -> (file_descr * sockaddr) Effect.t
let accept fd = perform (Accept fd)
type _ Effect.t += Recv : file_descr * bytes * int * int * msg_flag list -> int Effect.t
let recv fd buf pos len mode = perform (Recv (fd, buf, pos, len, mode))
type _ Effect.t += Send : file_descr * bytes * int * int * msg_flag list -> int Effect.t
let send fd bus pos len mode = perform (Send (fd, bus, pos, len, mode))
let ready_to_read fd =
match Unix.select [fd] [] [] 0. with
| [], _, _ -> false
| _ -> true
let ready_to_write fd =
match Unix.select [] [fd] [] 0. with
| _, [], _ -> false
| _ -> true
let q = Queue.create ()
let enqueue t = Queue.push t q
type blocked = Blocked : 'a Effect.t * ('a, unit) continuation -> blocked
let br = Hashtbl.create 13
let bw = Hashtbl.create 13
let rec schedule () =
if not (Queue.is_empty q) then
Queue.pop q ()
else if Hashtbl.length br = 0 && Hashtbl.length bw = 0 then
()
let rd_fds = Hashtbl.fold (fun fd _ acc -> fd::acc) br [] in
let wr_fds = Hashtbl.fold (fun fd _ acc -> fd::acc) bw [] in
let rdy_rd_fds, rdy_wr_fds, _ = Unix.select rd_fds wr_fds [] (-1.) in
let rec resume ht = function
| [] -> ()
| x::xs ->
begin match Hashtbl.find ht x with
| Blocked (Recv (fd, buf, pos, len, mode), k) ->
enqueue (fun () -> continue k (Unix.recv fd buf pos len mode))
| Blocked (Accept fd, k) ->
enqueue (fun () -> continue k (Unix.accept fd))
| Blocked (Send (fd, buf, pos, len, mode), k) ->
enqueue (fun () -> continue k (Unix.send fd buf pos len mode))
| Blocked _ -> failwith "impossible"
end;
Hashtbl.remove ht x
in
resume br rdy_rd_fds;
resume br rdy_wr_fds;
schedule ()
end
let run main =
let rec fork : 'a. 'a promise -> (unit -> 'a) -> unit =
fun pr main ->
match_with main ()
{ retc = (fun v ->
let l = match !pr with Waiting l -> l | _ -> failwith "impossible" in
List.iter (fun k -> enqueue (fun () -> continue k v)) l;
pr := Done v;
schedule ()
);
exnc = raise;
effc = (fun (type b) (eff: b Effect.t) ->
match eff with
| Async f -> Some (fun (k: (b,_) continuation) ->
let pr = ref (Waiting []) in
enqueue (fun () -> continue k pr);
fork pr f
)
| Yield -> Some (fun (k: (b,_) continuation) ->
enqueue (continue k);
schedule ()
)
| Await p -> Some (fun (k: (b,_) continuation) ->
begin match !p with
| Done v -> continue k v
| Waiting l -> begin
p := Waiting (k::l);
schedule ()
end
end
)
| (Accept fd as e) -> Some (fun (k: (b,_) continuation) ->
if ready_to_read fd then
continue k (Unix.accept fd)
else begin
Hashtbl.add br fd (Blocked (e,k));
schedule ()
end
)
| (Send (fd,buf,pos,len,mode) as e) -> Some (fun (k: (b,_) continuation) ->
if ready_to_write fd then
continue k (Unix.send fd buf pos len mode)
else begin
Hashtbl.add bw fd (Blocked (e,k));
schedule ()
end
)
| (Recv (fd,buf,pos,len,mode) as e) -> Some (fun (k: (b,_) continuation) ->
if ready_to_read fd then
continue k (Unix.recv fd buf pos len mode)
else begin
Hashtbl.add br fd (Blocked (e, k));
schedule ()
end
)
| _ -> None
)}
in
fork (ref (Waiting [])) main
end
module M = Echo.Make(struct
let accept = Aio.accept
let recv = Aio.recv
let send = Aio.send
let fork f = ignore (Aio.async f)
let run f = Aio.run f
let non_blocking_mode = true
end)
let _ = M.start ()
|
0e47dcef8e96549334284cbd08b61b0fb1214a09be3b6080be05f6de96e9009b | craigfe/progress | line.ml | — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —
Copyright ( c ) 2020–2021 < >
Distributed under the MIT license . See terms at the end of this file .
— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —
Copyright (c) 2020–2021 Craig Ferguson <>
Distributed under the MIT license. See terms at the end of this file.
————————————————————————————————————————————————————————————————————————————*)
include Line_intf
module Primitives = Line_primitives
open! Import
(** [Line] is a higher-level wrapper around [Segment] that makes some
simplifying assumptions about progress bar rendering:
- the reported value has a monoid instance, used for initialisation and
accumulation.
- the line is wrapped inside a single box.
It contains its own notion of "accumulated" line segments, and ensures that
this works with conditional rendering of segments (e.g. when rendering with
a minimum interval). *)
module Acc = struct
type 'a t =
{ mutable latest : 'a
; mutable accumulator : 'a
; mutable pending : 'a
; render_start : Mtime.t
; flow_meter : 'a Flow_meter.t
}
let wrap :
type a.
elt:(module Integer.S with type t = a)
-> clock:(unit -> Mtime.t)
-> should_update:(unit -> bool)
-> a t Primitives.t
-> a Primitives.t =
fun ~elt:(module Integer) ~clock ~should_update inner ->
Primitives.stateful (fun () ->
let flow_meter =
Flow_meter.create ~clock ~size:32 ~elt:(module Integer)
in
let render_start = clock () in
let state =
{ latest = Integer.zero
; accumulator = Integer.zero
; pending = Integer.zero
; render_start
; flow_meter
}
in
Primitives.contramap ~f:(fun a ->
Flow_meter.record state.flow_meter a;
state.pending <- Integer.add a state.pending)
@@ Primitives.conditional (fun _ -> should_update ())
(* On finalisation, we must flush the [pending] accumulator to get the
true final value. *)
@@ Primitives.on_finalise ()
@@ Primitives.contramap ~f:(fun () ->
let to_record = state.pending in
state.accumulator <- Integer.add to_record state.accumulator;
state.latest <- to_record;
state.pending <- Integer.zero;
state)
@@ inner)
let accumulator t = t.accumulator
let flow_meter t = t.flow_meter
end
module Timer = struct
type 'a t = { mutable render_latest : Mtime.t }
let should_update ~interval ~clock t =
match interval with
| None -> Staged.inj (fun () -> true)
| Some interval ->
Staged.inj (fun () ->
let now = clock () in
match
Mtime.Span.compare (Mtime.span t.render_latest now) interval >= 0
with
| false -> false
| true ->
t.render_latest <- now;
true)
end
type 'a t =
| Noop
| Primitive of 'a Primitives.t
| Basic of 'a Primitives.t
| Map of ('a Primitives.t -> 'a Primitives.t) * 'a t
| List of 'a t list
| Contramap : ('b t * ('a -> 'b)) -> 'a t
| Pair : 'a t * unit t * 'b t -> ('a * 'b) t
| Acc of
{ segment : 'a Acc.t Primitives.t
; elt : (module Integer.S with type t = 'a)
}
module Integer_independent (Platform : Platform.S) = struct
open struct
module Clock = Platform.Clock
end
let noop () = Noop
let const s =
let len = String.length s and width = Terminal.guess_printed_width s in
let segment =
Primitives.theta ~width (fun buf _ ->
Line_buffer.add_substring buf s ~off:0 ~len)
in
Basic segment
let spacer n = const (String.make n ' ')
(* Like [Format.str_formatter], but with [Fmt] set to use [`Ansi_tty] style rendering. *)
let str_formatter_buf, str_formatter =
let buf = Buffer.create 0 in
let ppf = Format.formatter_of_buffer buf in
Fmt.set_style_renderer ppf `Ansi_tty;
(buf, ppf)
let constf fmt =
Fmt.kpf
(fun ppf ->
Format.pp_print_flush ppf ();
let str = Buffer.contents str_formatter_buf in
Buffer.clear str_formatter_buf;
const str)
str_formatter fmt
let pair ?(sep = noop ()) a b = Pair (a, sep, b)
let list ?(sep = const " ") xs =
let xs =
ListLabels.filter_map xs ~f:(function Noop -> None | x -> Some x)
in
List (List.intersperse ~sep xs)
let ( ++ ) a b = List [ a; b ]
let parens t = const "(" ++ t ++ const ")"
let brackets t = const "[" ++ t ++ const "]"
let braces t = const "{" ++ t ++ const "}"
let using f x = Contramap (x, f)
let string =
let segment =
Primitives.alpha_unsized ~initial:(`Val "") (fun ~width buf _ s ->
let output_len = width () - 1 (* XXX: why is -1 necessary? *) in
if output_len <= 0 then 0
else
let pp =
Staged.prj
@@ Printer.Internals.to_line_printer
(Printer.string ~width:output_len)
in
pp buf s;
output_len)
in
Basic segment
let lpad sz t = Map (Primitives.box_fixed ~pad:`left sz, t)
let rpad sz t = Map (Primitives.box_fixed ~pad:`right sz, t)
(* Spinners *)
let with_color_opt color buf f =
match color with
| None -> f ()
| Some s ->
Line_buffer.add_string buf Terminal.Style.(code (fg s));
let a = f () in
Line_buffer.add_string buf Terminal.Style.(code none);
a
module Modulo_counter : sig
type t
val create : int -> t
val latest : t -> int
val tick : t -> int
end = struct
type t = { modulus : int; mutable latest : int }
let create modulus = { modulus; latest = 0 }
let latest t = t.latest
let tick t =
t.latest <- succ t.latest mod t.modulus;
t.latest
end
let debounce interval s =
Primitives.stateful (fun () ->
let latest = ref (Clock.now ()) in
let should_update () =
let now = Clock.now () in
match Mtime.Span.compare (Mtime.span !latest now) interval >= 0 with
| false -> false
| true ->
latest := now;
true
in
Primitives.conditional (fun _ -> should_update ()) s)
module Spinner = struct
type t = { frames : string array; final_frame : string option; width : int }
let v ~frames ~final_frame ~width = { frames; final_frame; width }
let default =
v ~final_frame:(Some "✔️") ~width:1
~frames:
[| "⠋"
; "⠙"
; "⠹"
; "⠸"
; "⠼"
; "⠴"
; "⠦"
; "⠧"
; "⠇"
; "⠏"
|]
let stage_count t = Array.length t.frames
end
let spinner ?frames ?color ?(min_interval = Some (Duration.of_int_ms 80)) () =
let spinner =
match frames with
| None -> Spinner.default
| Some [] -> Fmt.invalid_arg "spinner must have at least one stage"
| Some (x :: xs as frames) ->
let width = Terminal.guess_printed_width x in
ListLabels.iteri xs ~f:(fun i x ->
let width' = Terminal.guess_printed_width x in
if width <> width' then
Fmt.invalid_arg
"Spinner frames must have the same UTF-8 length. found %d \
(at index 0) and %d (at index %d)"
(i + 1) width width');
Spinner.v ~frames:(Array.of_list frames) ~final_frame:None ~width
in
let apply_debounce = Option.fold min_interval ~none:Fun.id ~some:debounce in
Basic
(Primitives.stateful (fun () ->
let counter = Modulo_counter.create (Spinner.stage_count spinner) in
apply_debounce
@@ Primitives.theta ~width:spinner.Spinner.width (fun buf -> function
| `finish ->
let final_frame =
match spinner.final_frame with
| None -> spinner.frames.(Modulo_counter.tick counter)
| Some x -> x
in
with_color_opt color buf (fun () ->
Line_buffer.add_string buf final_frame)
| (`report | `tick | `rerender) as e ->
let tick =
match e with
| `report | `tick -> Modulo_counter.tick counter
| `rerender -> Modulo_counter.latest counter
in
let frame = spinner.Spinner.frames.(tick) in
with_color_opt color buf (fun () ->
Line_buffer.add_string buf frame))))
end
module Bar_style = struct
type t =
{ delimiters : (string * string) option
; blank_space : string
; full_space : string
; in_progress_stages : string array
; color : Terminal.Color.t option
; color_empty : Terminal.Color.t option
; total_delimiter_width : int
; segment_width : int
}
let ascii =
{ delimiters = Some ("[", "]")
; blank_space = "-"
; full_space = "#"
; in_progress_stages = [||]
; color = None
; color_empty = None
; total_delimiter_width = 2
; segment_width = 1
}
let utf8 =
{ delimiters = Some ("│", "│")
; blank_space = " "
; full_space = "█"
; in_progress_stages =
[| " "; "▏"; "▎"; "▍"; "▌"; "▋"; "▊"; "▉" |]
; color = None
; color_empty = None
; total_delimiter_width = 2
; segment_width = 1
}
let parse_stages ctx = function
| [] -> Fmt.invalid_arg "%s: empty list of bar stages supplied" ctx
| full_space :: xs ->
let segment_width = Terminal.guess_printed_width full_space in
if segment_width = 0 then
Fmt.invalid_arg
"%s: supplied stage '%s' has estimated printed width of 0" ctx
full_space;
let in_progress_stages, blank_space =
match List.rev xs with
| [] -> ([||], String.make segment_width ' ')
| blank_space :: xs -> (Array.of_list xs, blank_space)
in
(full_space, in_progress_stages, blank_space, segment_width)
let guess_delims_width = function
| None -> 0
| Some (l, r) -> Terminal.(guess_printed_width l + guess_printed_width r)
let v ?delims ?color ?color_empty stages =
let full_space, in_progress_stages, blank_space, segment_width =
parse_stages "Bar_styles.v" stages
in
{ delimiters = delims
; blank_space
; full_space
; in_progress_stages
; color
; color_empty
; segment_width
; total_delimiter_width = guess_delims_width delims
}
let with_color color t = { t with color = Some color }
let with_empty_color color_empty t = { t with color_empty = Some color_empty }
let with_delims delimiters t =
{ t with delimiters; total_delimiter_width = guess_delims_width delimiters }
let with_stages stages t =
let full_space, in_progress_stages, blank_space, segment_width =
parse_stages "Bar_styles.with_stages" stages
in
{ t with full_space; blank_space; in_progress_stages; segment_width }
end
module Make (Platform : Platform.S) = struct
open struct
module Clock = Platform.Clock
end
module Integer_independent = Integer_independent (Platform)
include Integer_independent
module Internals = struct
module Line_buffer = Line_buffer
include Primitives
let box_winsize ?max ?(fallback = 80) s =
let get_width () =
let real_width =
Option.value ~default:fallback (Platform.Terminal_width.get ())
in
match max with None -> real_width | Some m -> min m real_width
in
box_dynamic get_width s
let to_line t = Primitive t
end
let to_primitive : type a. Config.t -> a t -> a Primitives.t =
let rec inner : type a. a t -> (unit -> bool) -> a Primitives.t = function
| Noop -> fun _ -> Primitives.noop ()
| Primitive x -> fun _ -> x
| Pair (a, sep, b) ->
let a = inner a in
let sep = inner sep in
let b = inner b in
fun should_update ->
Primitives.pair ~sep:(sep should_update) (a should_update)
(b should_update)
| Contramap (x, f) ->
let x = inner x in
fun y -> Primitives.contramap ~f (x y)
| Map (f, x) -> fun a -> f (inner x a)
| List xs ->
let xs = List.map xs ~f:inner in
fun should_update ->
Primitives.array
(List.map xs ~f:(fun f -> f should_update) |> Array.of_list)
| Basic segment ->
fun should_update ->
Primitives.conditional (fun _ -> should_update ()) @@ segment
| Acc { segment; elt = (module Integer) } ->
fun should_update ->
Acc.wrap ~elt:(module Integer) ~clock:Clock.now ~should_update
@@ segment
in
fun (config : Config.t) -> function
| Primitive x -> x
| t ->
let inner = inner t in
let segment =
Primitives.stateful (fun () ->
let should_update =
let state = { Timer.render_latest = Clock.now () } in
Staged.prj
(Timer.should_update ~clock:Clock.now
~interval:config.min_interval state)
in
let x = ref true in
Primitives.contramap ~f:(fun a ->
x := should_update ();
a)
@@ Internals.box_winsize ?max:config.max_width
@@ inner (fun () -> !x))
in
segment
(* Basic utilities for combining segments *)
module Integer_dependent = struct
module type S =
Integer_dependent
with type 'a t := 'a t
and type color := Terminal.Color.t
and type duration := Duration.t
and type 'a printer := 'a Printer.t
and type bar_style := Bar_style.t
module type Ext =
DSL
with type 'a t := 'a t
and type color := Terminal.Color.t
and type duration := Duration.t
and type 'a printer := 'a Printer.t
and type Bar_style.t := Bar_style.t
module Make_ext (Integer : Integer.S) = struct
let acc segment = Acc { segment; elt = (module Integer) }
let of_printer ?init printer =
let pp = Staged.prj @@ Printer.Internals.to_line_printer printer in
let width = Printer.print_width printer in
let initial =
match init with
| Some v -> `Val v
| None ->
`Theta
(fun buf ->
for _ = 1 to width do
Line_buffer.add_char buf ' '
done)
in
Basic (Primitives.alpha ~width ~initial (fun buf _ x -> pp buf x))
let count_pp printer =
let pp = Staged.prj @@ Printer.Internals.to_line_printer printer in
acc
@@ Primitives.contramap ~f:Acc.accumulator
@@ Primitives.alpha ~width:(Printer.print_width printer)
~initial:(`Val Integer.zero) (fun buf _ x -> pp buf x)
let bytes = count_pp (Units.Bytes.generic (module Integer))
let percentage_of accumulator =
let printer =
Printer.using Units.Percentage.of_float ~f:(fun x ->
Integer.to_float x /. Integer.to_float accumulator)
in
count_pp printer
let sum ?pp ~width () =
let pp =
match pp with
| None -> Printer.Internals.integer ~width (module Integer)
| Some x -> x
in
let pp = Staged.prj (Printer.Internals.to_line_printer pp) in
acc
@@ Primitives.contramap ~f:Acc.accumulator
@@ Primitives.alpha ~initial:(`Val Integer.zero) ~width (fun buf _ x ->
pp buf x)
let count_to ?pp ?(sep = const "/") total =
let total = Integer.to_string total in
let width =
match pp with
| Some pp -> Printer.print_width pp
| None -> String.length total
in
List [ sum ~width (); using (fun _ -> ()) sep; const total ]
let ticker_to ?(sep = const "/") total =
let total = Integer.to_string total in
let width = String.length total in
let pp =
Staged.prj
@@ Printer.Internals.to_line_printer
@@ Printer.Internals.integer ~width (module Integer)
in
let segment =
Primitives.alpha ~width ~initial:(`Val Integer.zero) (fun buf _ x ->
pp buf x)
in
List
[ Contramap
( Acc
{ segment = Primitives.contramap ~f:Acc.accumulator segment
; elt = (module Integer)
}
, fun _ -> Integer.one )
; using (fun _ -> ()) sep
; const total
]
(* Progress bars *)
module Bar_style = Bar_style
let bar (spec : Bar_style.t) width proportion buf =
let final_stage = Array.length spec.in_progress_stages in
let width = width () in
let bar_segments =
(width - spec.total_delimiter_width) / spec.segment_width
in
let squaresf = Float.of_int bar_segments *. proportion in
let squares = Float.to_int squaresf in
let filled = min squares bar_segments in
let not_filled =
bar_segments - filled - if final_stage = 0 then 0 else 1
in
Option.iter (fun (x, _) -> Line_buffer.add_string buf x) spec.delimiters;
with_color_opt spec.color buf (fun () ->
for _ = 1 to filled do
Line_buffer.add_string buf spec.full_space
done);
let () =
if filled <> bar_segments then (
let chunks = Float.to_int (squaresf *. Float.of_int final_stage) in
let index = chunks - (filled * final_stage) in
if index >= 0 && index < final_stage then
with_color_opt spec.color buf (fun () ->
Line_buffer.add_string buf spec.in_progress_stages.(index));
with_color_opt spec.color_empty buf (fun () ->
for _ = 1 to not_filled do
Line_buffer.add_string buf spec.blank_space
done))
in
Option.iter (fun (_, x) -> Line_buffer.add_string buf x) spec.delimiters;
width
let with_prop f v t = match v with None -> t | Some v -> f v t
let bar ~style ~color =
let style =
match style with
| `ASCII -> Bar_style.ascii
| `UTF8 -> Bar_style.utf8
| `Custom style -> style
in
bar (style |> with_prop Bar_style.with_color color)
let bar ?(style = `ASCII) ?color ?(width = `Expand) ?(data = `Sum) total =
let proportion x = Integer.to_float x /. Integer.to_float total in
let proportion_segment =
match width with
| `Fixed width ->
if width < 3 then failwith "Not enough space for a progress bar";
Primitives.alpha ~width ~initial:(`Val 0.) (fun buf _ x ->
ignore (bar ~style ~color (fun _ -> width) x buf : int))
| `Expand ->
Primitives.alpha_unsized ~initial:(`Val 0.) (fun ~width ppf _ x ->
bar ~style ~color width x ppf)
in
match data with
| `Latest ->
Basic (Primitives.contramap proportion_segment ~f:proportion)
| `Sum ->
acc
(Primitives.contramap proportion_segment
~f:(Acc.accumulator >> proportion))
let rate pp_val =
let pp_rate =
let pp_val = Staged.prj (Printer.Internals.to_line_printer pp_val) in
fun buf _ x ->
pp_val buf x;
Line_buffer.add_string buf "/s"
in
let width = Printer.print_width pp_val + 2 in
acc
@@ Primitives.contramap
~f:(Acc.flow_meter >> Flow_meter.per_second >> Integer.to_float)
@@ Primitives.alpha ~width ~initial:(`Val 0.) pp_rate
let bytes_per_sec = rate Units.Bytes.of_float
let eta ?(pp = Units.Duration.mm_ss) total =
let span_segment =
let printer =
let pp = Staged.prj (Printer.Internals.to_line_printer pp) in
fun ppf event x ->
match event with
| `finish -> pp ppf Mtime.Span.max_span (* renders as [--:--] *)
| `report | `rerender | `tick
(* TODO: tick should cause the estimate to be re-evaluated. *) ->
pp ppf x
in
let width = Printer.print_width Units.Duration.mm_ss in
let initial = `Val Mtime.Span.max_span in
Primitives.alpha ~width ~initial printer
in
acc
@@ Primitives.contramap ~f:(fun acc ->
let per_second = Flow_meter.per_second (Acc.flow_meter acc) in
let acc = Acc.accumulator acc in
if Integer.(equal zero) per_second then Mtime.Span.max_span
else
let todo = Integer.(to_float (sub total acc)) in
if Float.(todo <= 0.) then Mtime.Span.zero
else
Mtime.Span.of_uint64_ns
(Int64.of_float
(todo /. Integer.to_float per_second *. 1_000_000_000.)))
@@ span_segment
let elapsed ?(pp = Units.Duration.mm_ss) () =
let print_time = Staged.prj (Printer.Internals.to_line_printer pp) in
let segment =
Primitives.stateful (fun () ->
let elapsed = Clock.counter () in
let latest = ref Mtime.Span.zero in
let finished = ref false in
let pp buf e =
(match e with
| `tick | `report -> latest := Clock.count elapsed
| `finish when not !finished ->
latest := Clock.count elapsed;
finished := true
| `rerender | `finish -> ());
print_time buf !latest
in
Primitives.theta ~width:5 pp)
in
Basic segment
include Integer_independent
end
module Make = Make_ext
end
include Integer_dependent.Make (Integer.Int)
module Using_int32 = Integer_dependent.Make_ext (Integer.Int32)
module Using_int63 = Integer_dependent.Make_ext (Integer.Int63)
module Using_int64 = Integer_dependent.Make_ext (Integer.Int64)
module Using_float = Integer_dependent.Make_ext (Integer.Float)
end
— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —
Copyright ( c ) 2020–2021 < >
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 " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY ,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT . IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM , DAMAGES OR OTHER
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING
FROM , OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE .
— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —
Copyright (c) 2020–2021 Craig Ferguson <>
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", 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.
————————————————————————————————————————————————————————————————————————————*)
| null | https://raw.githubusercontent.com/craigfe/progress/4b5a0a4288cfc66219e48be824bf5d8d9c1e2866/src/progress/engine/line.ml | ocaml | * [Line] is a higher-level wrapper around [Segment] that makes some
simplifying assumptions about progress bar rendering:
- the reported value has a monoid instance, used for initialisation and
accumulation.
- the line is wrapped inside a single box.
It contains its own notion of "accumulated" line segments, and ensures that
this works with conditional rendering of segments (e.g. when rendering with
a minimum interval).
On finalisation, we must flush the [pending] accumulator to get the
true final value.
Like [Format.str_formatter], but with [Fmt] set to use [`Ansi_tty] style rendering.
XXX: why is -1 necessary?
Spinners
Basic utilities for combining segments
Progress bars
renders as [--:--]
TODO: tick should cause the estimate to be re-evaluated. | — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —
Copyright ( c ) 2020–2021 < >
Distributed under the MIT license . See terms at the end of this file .
— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —
Copyright (c) 2020–2021 Craig Ferguson <>
Distributed under the MIT license. See terms at the end of this file.
————————————————————————————————————————————————————————————————————————————*)
include Line_intf
module Primitives = Line_primitives
open! Import
module Acc = struct
type 'a t =
{ mutable latest : 'a
; mutable accumulator : 'a
; mutable pending : 'a
; render_start : Mtime.t
; flow_meter : 'a Flow_meter.t
}
let wrap :
type a.
elt:(module Integer.S with type t = a)
-> clock:(unit -> Mtime.t)
-> should_update:(unit -> bool)
-> a t Primitives.t
-> a Primitives.t =
fun ~elt:(module Integer) ~clock ~should_update inner ->
Primitives.stateful (fun () ->
let flow_meter =
Flow_meter.create ~clock ~size:32 ~elt:(module Integer)
in
let render_start = clock () in
let state =
{ latest = Integer.zero
; accumulator = Integer.zero
; pending = Integer.zero
; render_start
; flow_meter
}
in
Primitives.contramap ~f:(fun a ->
Flow_meter.record state.flow_meter a;
state.pending <- Integer.add a state.pending)
@@ Primitives.conditional (fun _ -> should_update ())
@@ Primitives.on_finalise ()
@@ Primitives.contramap ~f:(fun () ->
let to_record = state.pending in
state.accumulator <- Integer.add to_record state.accumulator;
state.latest <- to_record;
state.pending <- Integer.zero;
state)
@@ inner)
let accumulator t = t.accumulator
let flow_meter t = t.flow_meter
end
module Timer = struct
type 'a t = { mutable render_latest : Mtime.t }
let should_update ~interval ~clock t =
match interval with
| None -> Staged.inj (fun () -> true)
| Some interval ->
Staged.inj (fun () ->
let now = clock () in
match
Mtime.Span.compare (Mtime.span t.render_latest now) interval >= 0
with
| false -> false
| true ->
t.render_latest <- now;
true)
end
type 'a t =
| Noop
| Primitive of 'a Primitives.t
| Basic of 'a Primitives.t
| Map of ('a Primitives.t -> 'a Primitives.t) * 'a t
| List of 'a t list
| Contramap : ('b t * ('a -> 'b)) -> 'a t
| Pair : 'a t * unit t * 'b t -> ('a * 'b) t
| Acc of
{ segment : 'a Acc.t Primitives.t
; elt : (module Integer.S with type t = 'a)
}
module Integer_independent (Platform : Platform.S) = struct
open struct
module Clock = Platform.Clock
end
let noop () = Noop
let const s =
let len = String.length s and width = Terminal.guess_printed_width s in
let segment =
Primitives.theta ~width (fun buf _ ->
Line_buffer.add_substring buf s ~off:0 ~len)
in
Basic segment
let spacer n = const (String.make n ' ')
let str_formatter_buf, str_formatter =
let buf = Buffer.create 0 in
let ppf = Format.formatter_of_buffer buf in
Fmt.set_style_renderer ppf `Ansi_tty;
(buf, ppf)
let constf fmt =
Fmt.kpf
(fun ppf ->
Format.pp_print_flush ppf ();
let str = Buffer.contents str_formatter_buf in
Buffer.clear str_formatter_buf;
const str)
str_formatter fmt
let pair ?(sep = noop ()) a b = Pair (a, sep, b)
let list ?(sep = const " ") xs =
let xs =
ListLabels.filter_map xs ~f:(function Noop -> None | x -> Some x)
in
List (List.intersperse ~sep xs)
let ( ++ ) a b = List [ a; b ]
let parens t = const "(" ++ t ++ const ")"
let brackets t = const "[" ++ t ++ const "]"
let braces t = const "{" ++ t ++ const "}"
let using f x = Contramap (x, f)
let string =
let segment =
Primitives.alpha_unsized ~initial:(`Val "") (fun ~width buf _ s ->
if output_len <= 0 then 0
else
let pp =
Staged.prj
@@ Printer.Internals.to_line_printer
(Printer.string ~width:output_len)
in
pp buf s;
output_len)
in
Basic segment
let lpad sz t = Map (Primitives.box_fixed ~pad:`left sz, t)
let rpad sz t = Map (Primitives.box_fixed ~pad:`right sz, t)
let with_color_opt color buf f =
match color with
| None -> f ()
| Some s ->
Line_buffer.add_string buf Terminal.Style.(code (fg s));
let a = f () in
Line_buffer.add_string buf Terminal.Style.(code none);
a
module Modulo_counter : sig
type t
val create : int -> t
val latest : t -> int
val tick : t -> int
end = struct
type t = { modulus : int; mutable latest : int }
let create modulus = { modulus; latest = 0 }
let latest t = t.latest
let tick t =
t.latest <- succ t.latest mod t.modulus;
t.latest
end
let debounce interval s =
Primitives.stateful (fun () ->
let latest = ref (Clock.now ()) in
let should_update () =
let now = Clock.now () in
match Mtime.Span.compare (Mtime.span !latest now) interval >= 0 with
| false -> false
| true ->
latest := now;
true
in
Primitives.conditional (fun _ -> should_update ()) s)
module Spinner = struct
type t = { frames : string array; final_frame : string option; width : int }
let v ~frames ~final_frame ~width = { frames; final_frame; width }
let default =
v ~final_frame:(Some "✔️") ~width:1
~frames:
[| "⠋"
; "⠙"
; "⠹"
; "⠸"
; "⠼"
; "⠴"
; "⠦"
; "⠧"
; "⠇"
; "⠏"
|]
let stage_count t = Array.length t.frames
end
let spinner ?frames ?color ?(min_interval = Some (Duration.of_int_ms 80)) () =
let spinner =
match frames with
| None -> Spinner.default
| Some [] -> Fmt.invalid_arg "spinner must have at least one stage"
| Some (x :: xs as frames) ->
let width = Terminal.guess_printed_width x in
ListLabels.iteri xs ~f:(fun i x ->
let width' = Terminal.guess_printed_width x in
if width <> width' then
Fmt.invalid_arg
"Spinner frames must have the same UTF-8 length. found %d \
(at index 0) and %d (at index %d)"
(i + 1) width width');
Spinner.v ~frames:(Array.of_list frames) ~final_frame:None ~width
in
let apply_debounce = Option.fold min_interval ~none:Fun.id ~some:debounce in
Basic
(Primitives.stateful (fun () ->
let counter = Modulo_counter.create (Spinner.stage_count spinner) in
apply_debounce
@@ Primitives.theta ~width:spinner.Spinner.width (fun buf -> function
| `finish ->
let final_frame =
match spinner.final_frame with
| None -> spinner.frames.(Modulo_counter.tick counter)
| Some x -> x
in
with_color_opt color buf (fun () ->
Line_buffer.add_string buf final_frame)
| (`report | `tick | `rerender) as e ->
let tick =
match e with
| `report | `tick -> Modulo_counter.tick counter
| `rerender -> Modulo_counter.latest counter
in
let frame = spinner.Spinner.frames.(tick) in
with_color_opt color buf (fun () ->
Line_buffer.add_string buf frame))))
end
module Bar_style = struct
type t =
{ delimiters : (string * string) option
; blank_space : string
; full_space : string
; in_progress_stages : string array
; color : Terminal.Color.t option
; color_empty : Terminal.Color.t option
; total_delimiter_width : int
; segment_width : int
}
let ascii =
{ delimiters = Some ("[", "]")
; blank_space = "-"
; full_space = "#"
; in_progress_stages = [||]
; color = None
; color_empty = None
; total_delimiter_width = 2
; segment_width = 1
}
let utf8 =
{ delimiters = Some ("│", "│")
; blank_space = " "
; full_space = "█"
; in_progress_stages =
[| " "; "▏"; "▎"; "▍"; "▌"; "▋"; "▊"; "▉" |]
; color = None
; color_empty = None
; total_delimiter_width = 2
; segment_width = 1
}
let parse_stages ctx = function
| [] -> Fmt.invalid_arg "%s: empty list of bar stages supplied" ctx
| full_space :: xs ->
let segment_width = Terminal.guess_printed_width full_space in
if segment_width = 0 then
Fmt.invalid_arg
"%s: supplied stage '%s' has estimated printed width of 0" ctx
full_space;
let in_progress_stages, blank_space =
match List.rev xs with
| [] -> ([||], String.make segment_width ' ')
| blank_space :: xs -> (Array.of_list xs, blank_space)
in
(full_space, in_progress_stages, blank_space, segment_width)
let guess_delims_width = function
| None -> 0
| Some (l, r) -> Terminal.(guess_printed_width l + guess_printed_width r)
let v ?delims ?color ?color_empty stages =
let full_space, in_progress_stages, blank_space, segment_width =
parse_stages "Bar_styles.v" stages
in
{ delimiters = delims
; blank_space
; full_space
; in_progress_stages
; color
; color_empty
; segment_width
; total_delimiter_width = guess_delims_width delims
}
let with_color color t = { t with color = Some color }
let with_empty_color color_empty t = { t with color_empty = Some color_empty }
let with_delims delimiters t =
{ t with delimiters; total_delimiter_width = guess_delims_width delimiters }
let with_stages stages t =
let full_space, in_progress_stages, blank_space, segment_width =
parse_stages "Bar_styles.with_stages" stages
in
{ t with full_space; blank_space; in_progress_stages; segment_width }
end
module Make (Platform : Platform.S) = struct
open struct
module Clock = Platform.Clock
end
module Integer_independent = Integer_independent (Platform)
include Integer_independent
module Internals = struct
module Line_buffer = Line_buffer
include Primitives
let box_winsize ?max ?(fallback = 80) s =
let get_width () =
let real_width =
Option.value ~default:fallback (Platform.Terminal_width.get ())
in
match max with None -> real_width | Some m -> min m real_width
in
box_dynamic get_width s
let to_line t = Primitive t
end
let to_primitive : type a. Config.t -> a t -> a Primitives.t =
let rec inner : type a. a t -> (unit -> bool) -> a Primitives.t = function
| Noop -> fun _ -> Primitives.noop ()
| Primitive x -> fun _ -> x
| Pair (a, sep, b) ->
let a = inner a in
let sep = inner sep in
let b = inner b in
fun should_update ->
Primitives.pair ~sep:(sep should_update) (a should_update)
(b should_update)
| Contramap (x, f) ->
let x = inner x in
fun y -> Primitives.contramap ~f (x y)
| Map (f, x) -> fun a -> f (inner x a)
| List xs ->
let xs = List.map xs ~f:inner in
fun should_update ->
Primitives.array
(List.map xs ~f:(fun f -> f should_update) |> Array.of_list)
| Basic segment ->
fun should_update ->
Primitives.conditional (fun _ -> should_update ()) @@ segment
| Acc { segment; elt = (module Integer) } ->
fun should_update ->
Acc.wrap ~elt:(module Integer) ~clock:Clock.now ~should_update
@@ segment
in
fun (config : Config.t) -> function
| Primitive x -> x
| t ->
let inner = inner t in
let segment =
Primitives.stateful (fun () ->
let should_update =
let state = { Timer.render_latest = Clock.now () } in
Staged.prj
(Timer.should_update ~clock:Clock.now
~interval:config.min_interval state)
in
let x = ref true in
Primitives.contramap ~f:(fun a ->
x := should_update ();
a)
@@ Internals.box_winsize ?max:config.max_width
@@ inner (fun () -> !x))
in
segment
module Integer_dependent = struct
module type S =
Integer_dependent
with type 'a t := 'a t
and type color := Terminal.Color.t
and type duration := Duration.t
and type 'a printer := 'a Printer.t
and type bar_style := Bar_style.t
module type Ext =
DSL
with type 'a t := 'a t
and type color := Terminal.Color.t
and type duration := Duration.t
and type 'a printer := 'a Printer.t
and type Bar_style.t := Bar_style.t
module Make_ext (Integer : Integer.S) = struct
let acc segment = Acc { segment; elt = (module Integer) }
let of_printer ?init printer =
let pp = Staged.prj @@ Printer.Internals.to_line_printer printer in
let width = Printer.print_width printer in
let initial =
match init with
| Some v -> `Val v
| None ->
`Theta
(fun buf ->
for _ = 1 to width do
Line_buffer.add_char buf ' '
done)
in
Basic (Primitives.alpha ~width ~initial (fun buf _ x -> pp buf x))
let count_pp printer =
let pp = Staged.prj @@ Printer.Internals.to_line_printer printer in
acc
@@ Primitives.contramap ~f:Acc.accumulator
@@ Primitives.alpha ~width:(Printer.print_width printer)
~initial:(`Val Integer.zero) (fun buf _ x -> pp buf x)
let bytes = count_pp (Units.Bytes.generic (module Integer))
let percentage_of accumulator =
let printer =
Printer.using Units.Percentage.of_float ~f:(fun x ->
Integer.to_float x /. Integer.to_float accumulator)
in
count_pp printer
let sum ?pp ~width () =
let pp =
match pp with
| None -> Printer.Internals.integer ~width (module Integer)
| Some x -> x
in
let pp = Staged.prj (Printer.Internals.to_line_printer pp) in
acc
@@ Primitives.contramap ~f:Acc.accumulator
@@ Primitives.alpha ~initial:(`Val Integer.zero) ~width (fun buf _ x ->
pp buf x)
let count_to ?pp ?(sep = const "/") total =
let total = Integer.to_string total in
let width =
match pp with
| Some pp -> Printer.print_width pp
| None -> String.length total
in
List [ sum ~width (); using (fun _ -> ()) sep; const total ]
let ticker_to ?(sep = const "/") total =
let total = Integer.to_string total in
let width = String.length total in
let pp =
Staged.prj
@@ Printer.Internals.to_line_printer
@@ Printer.Internals.integer ~width (module Integer)
in
let segment =
Primitives.alpha ~width ~initial:(`Val Integer.zero) (fun buf _ x ->
pp buf x)
in
List
[ Contramap
( Acc
{ segment = Primitives.contramap ~f:Acc.accumulator segment
; elt = (module Integer)
}
, fun _ -> Integer.one )
; using (fun _ -> ()) sep
; const total
]
module Bar_style = Bar_style
let bar (spec : Bar_style.t) width proportion buf =
let final_stage = Array.length spec.in_progress_stages in
let width = width () in
let bar_segments =
(width - spec.total_delimiter_width) / spec.segment_width
in
let squaresf = Float.of_int bar_segments *. proportion in
let squares = Float.to_int squaresf in
let filled = min squares bar_segments in
let not_filled =
bar_segments - filled - if final_stage = 0 then 0 else 1
in
Option.iter (fun (x, _) -> Line_buffer.add_string buf x) spec.delimiters;
with_color_opt spec.color buf (fun () ->
for _ = 1 to filled do
Line_buffer.add_string buf spec.full_space
done);
let () =
if filled <> bar_segments then (
let chunks = Float.to_int (squaresf *. Float.of_int final_stage) in
let index = chunks - (filled * final_stage) in
if index >= 0 && index < final_stage then
with_color_opt spec.color buf (fun () ->
Line_buffer.add_string buf spec.in_progress_stages.(index));
with_color_opt spec.color_empty buf (fun () ->
for _ = 1 to not_filled do
Line_buffer.add_string buf spec.blank_space
done))
in
Option.iter (fun (_, x) -> Line_buffer.add_string buf x) spec.delimiters;
width
let with_prop f v t = match v with None -> t | Some v -> f v t
let bar ~style ~color =
let style =
match style with
| `ASCII -> Bar_style.ascii
| `UTF8 -> Bar_style.utf8
| `Custom style -> style
in
bar (style |> with_prop Bar_style.with_color color)
let bar ?(style = `ASCII) ?color ?(width = `Expand) ?(data = `Sum) total =
let proportion x = Integer.to_float x /. Integer.to_float total in
let proportion_segment =
match width with
| `Fixed width ->
if width < 3 then failwith "Not enough space for a progress bar";
Primitives.alpha ~width ~initial:(`Val 0.) (fun buf _ x ->
ignore (bar ~style ~color (fun _ -> width) x buf : int))
| `Expand ->
Primitives.alpha_unsized ~initial:(`Val 0.) (fun ~width ppf _ x ->
bar ~style ~color width x ppf)
in
match data with
| `Latest ->
Basic (Primitives.contramap proportion_segment ~f:proportion)
| `Sum ->
acc
(Primitives.contramap proportion_segment
~f:(Acc.accumulator >> proportion))
let rate pp_val =
let pp_rate =
let pp_val = Staged.prj (Printer.Internals.to_line_printer pp_val) in
fun buf _ x ->
pp_val buf x;
Line_buffer.add_string buf "/s"
in
let width = Printer.print_width pp_val + 2 in
acc
@@ Primitives.contramap
~f:(Acc.flow_meter >> Flow_meter.per_second >> Integer.to_float)
@@ Primitives.alpha ~width ~initial:(`Val 0.) pp_rate
let bytes_per_sec = rate Units.Bytes.of_float
let eta ?(pp = Units.Duration.mm_ss) total =
let span_segment =
let printer =
let pp = Staged.prj (Printer.Internals.to_line_printer pp) in
fun ppf event x ->
match event with
| `report | `rerender | `tick
pp ppf x
in
let width = Printer.print_width Units.Duration.mm_ss in
let initial = `Val Mtime.Span.max_span in
Primitives.alpha ~width ~initial printer
in
acc
@@ Primitives.contramap ~f:(fun acc ->
let per_second = Flow_meter.per_second (Acc.flow_meter acc) in
let acc = Acc.accumulator acc in
if Integer.(equal zero) per_second then Mtime.Span.max_span
else
let todo = Integer.(to_float (sub total acc)) in
if Float.(todo <= 0.) then Mtime.Span.zero
else
Mtime.Span.of_uint64_ns
(Int64.of_float
(todo /. Integer.to_float per_second *. 1_000_000_000.)))
@@ span_segment
let elapsed ?(pp = Units.Duration.mm_ss) () =
let print_time = Staged.prj (Printer.Internals.to_line_printer pp) in
let segment =
Primitives.stateful (fun () ->
let elapsed = Clock.counter () in
let latest = ref Mtime.Span.zero in
let finished = ref false in
let pp buf e =
(match e with
| `tick | `report -> latest := Clock.count elapsed
| `finish when not !finished ->
latest := Clock.count elapsed;
finished := true
| `rerender | `finish -> ());
print_time buf !latest
in
Primitives.theta ~width:5 pp)
in
Basic segment
include Integer_independent
end
module Make = Make_ext
end
include Integer_dependent.Make (Integer.Int)
module Using_int32 = Integer_dependent.Make_ext (Integer.Int32)
module Using_int63 = Integer_dependent.Make_ext (Integer.Int63)
module Using_int64 = Integer_dependent.Make_ext (Integer.Int64)
module Using_float = Integer_dependent.Make_ext (Integer.Float)
end
— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —
Copyright ( c ) 2020–2021 < >
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 " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY ,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT . IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM , DAMAGES OR OTHER
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING
FROM , OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE .
— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —
Copyright (c) 2020–2021 Craig Ferguson <>
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", 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.
————————————————————————————————————————————————————————————————————————————*)
|
d9e2614b0a6aca2220a170a7daae7d7e57003ffcee60a51be15cd7964b2cbb72 | aarkerio/ZentaurLMS | user.clj | (ns user
"Userspace functions you can run by default in your local REPL."
(:require
[zentaur.config :refer [env]]
[clojure.pprint]
[clojure.spec.alpha :as s]
[expound.alpha :as expound]
[mount.core :as mount]
[zentaur.core :refer [start-app]]))
(alter-var-root #'s/*explain-out* (constantly expound/printer))
(add-tap (bound-fn* clojure.pprint/pprint))
| null | https://raw.githubusercontent.com/aarkerio/ZentaurLMS/adb43fb879b88d6a35f7f556cb225f7930d524f9/env/dev/clj/user.clj | clojure | (ns user
"Userspace functions you can run by default in your local REPL."
(:require
[zentaur.config :refer [env]]
[clojure.pprint]
[clojure.spec.alpha :as s]
[expound.alpha :as expound]
[mount.core :as mount]
[zentaur.core :refer [start-app]]))
(alter-var-root #'s/*explain-out* (constantly expound/printer))
(add-tap (bound-fn* clojure.pprint/pprint))
|
|
f068cb757845aecbfb8d7d2092e25292693b1578077b0b98bffcbf5e39f39308 | dpom/clj-duckling | helpers.clj | (ns clj-duckling.util.helpers
"This namespace contains the common helpers used in rules"
(:require
[clj-time.core :as t]
[clj-duckling.util.core :as util]))
(defmacro fn& [dim & args-body]
(let [meta-map (when (-> args-body first map?)
(first args-body))
args-body (if meta-map
(rest args-body)
args-body)]
(merge meta-map
`{:dim ~(keyword dim)
:pred (fn ~@args-body)})))
(defn dim
"Returns a func checking dim of a token and additional preds"
[dim-val & predicates]
(fn [token]
(and (= dim-val (:dim token))
(every? #(% token) predicates))))
(defn integer
"Return a func (duckling pattern) checking that dim=number and integer=true,
optional range (inclusive), and additional preds"
[& [min max & predicates]]
(fn [token]
(and (= :number (:dim token))
(:integer token)
(or (nil? min) (<= min (:val token)))
(or (nil? max) (<= (:val token) max))
(every? #(% token) predicates))))
| null | https://raw.githubusercontent.com/dpom/clj-duckling/8728f9a99b4b002e9ce2ea62b3a82a61b0cdac06/src/clj_duckling/util/helpers.clj | clojure | (ns clj-duckling.util.helpers
"This namespace contains the common helpers used in rules"
(:require
[clj-time.core :as t]
[clj-duckling.util.core :as util]))
(defmacro fn& [dim & args-body]
(let [meta-map (when (-> args-body first map?)
(first args-body))
args-body (if meta-map
(rest args-body)
args-body)]
(merge meta-map
`{:dim ~(keyword dim)
:pred (fn ~@args-body)})))
(defn dim
"Returns a func checking dim of a token and additional preds"
[dim-val & predicates]
(fn [token]
(and (= dim-val (:dim token))
(every? #(% token) predicates))))
(defn integer
"Return a func (duckling pattern) checking that dim=number and integer=true,
optional range (inclusive), and additional preds"
[& [min max & predicates]]
(fn [token]
(and (= :number (:dim token))
(:integer token)
(or (nil? min) (<= min (:val token)))
(or (nil? max) (<= (:val token) max))
(every? #(% token) predicates))))
|
|
bf15034aff5ede3c40b0274d493d10a7eecf4917798d33b67e5a552a895d559d | cacay/regexp | SparseMatrix.hs | {-# LANGUAGE GADTs #-}
# LANGUAGE DataKinds #
# LANGUAGE KindSignatures #
# LANGUAGE TypeApplications #
# LANGUAGE TypeOperators #
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
-- TODO: remove
# LANGUAGE AllowAmbiguousTypes #
-- | A very cruddy implementation of sparse matrices. I couldn't
-- find an existing implementation that had all that I needed, so
-- I cooked this up.
--
-- TODO: find a package or make nicer
module SparseMatrix
( SparseMatrix
, matrix
, fromRows
, (!)
, nthRow
, plus
, times
, transpose
, map
, nonZero
, nonZeroRows
, toList
) where
import Flow
import Prelude hiding (map)
import Data.Function (on)
import Data.List (sortBy, groupBy, intercalate)
import Data.Ord (comparing)
import Data.Finite
import Data.Singletons
import Data.Singletons.Decide
import Data.Singletons.Prelude
import Data.Singletons.TypeLits
import Data.Semiring (Semiring(..), DetectableZero(..))
import Data.KleeneAlgebra
import SparseVector (SparseVector)
import qualified SparseVector as Vector
-- | A sparse matrix with @r@ rows and @c@ columns over
elements of type
newtype SparseMatrix (r :: Nat) (c :: Nat) a =
UnsafeMakeSparseMatrix {
rows :: SparseVector r (SparseVector c a)
}
-- | Value at the given row and column.
(!) :: (DetectableZero a, KnownNat r, KnownNat c)
=> SparseMatrix r c a
-> (Finite r, Finite c)
-> a
m ! (r, c) =
(rows m Vector.! r) Vector.! c
-- | Row with the given index.
nthRow :: (DetectableZero a, KnownNat r, KnownNat c)
=> Finite r
-> SparseMatrix r c a
-> SparseVector c a
nthRow r m =
rows m Vector.! r
-- | Construct a sparse matrix from a list of indexed elements. Indices
that do n't appear in the list are all set to zero . Duplicate indexes
-- are combined with '(<+>)'.
--
We need detectable zeros so we can filter them out .
matrix :: (DetectableZero a, KnownNat r, KnownNat c)
=> [((Finite r, Finite c), a)]
-> SparseMatrix r c a
matrix l =
UnsafeMakeSparseMatrix {
rows =
sortBy (comparing (fst . fst)) l
|> groupBy ((==) `on` (fst . fst))
|> fmap (\l -> (fst $ fst $ head l, fmap dropRow l))
|> fmap (\(r, elements) -> (r, Vector.vector elements))
|> Vector.vector
}
where
dropRow :: ((r, c), a) -> (c, a)
dropRow ((r, c), x)=
(c, x)
-- | Construct a sparse matrix from a list of indexed vectors corresponding
-- to the rows of the matrix.
fromRows :: (DetectableZero a, KnownNat r, KnownNat c)
=> [(Finite r, SparseVector c a)]
-> SparseMatrix r c a
fromRows rows =
UnsafeMakeSparseMatrix {
rows =
Vector.vector rows
}
-- | Matrix addition.
plus :: (DetectableZero a, KnownNat r, KnownNat c)
=> SparseMatrix r c a
-> SparseMatrix r c a
-> SparseMatrix r c a
plus m1 m2 =
UnsafeMakeSparseMatrix {
rows =
rows m1 <+> rows m2
}
-- | Matrix multiplication.
times :: (DetectableZero a, KnownNat r, KnownNat m, KnownNat c)
=> SparseMatrix r m a
-> SparseMatrix m c a
-> SparseMatrix r c a
times m1 m2 =
UnsafeMakeSparseMatrix {
rows =
Vector.map (\r -> Vector.map (\c -> r `cross` c) (rows m2Tr)) (rows m1)
}
where
m2Tr =
transpose m2
cross v1 v2 =
Vector.sum (v1 <.> v2)
-- | Swap the rows of a matrix with its columns.
transpose :: (DetectableZero a, KnownNat r, KnownNat c)
=> SparseMatrix r c a
-> SparseMatrix c r a
transpose m =
UnsafeMakeSparseMatrix {
rows =
Vector.vector [(i, Vector.map (Vector.! i) (rows m)) | i <- finites]
}
| Split a square matrix into four quadrants .
split :: forall s t a. (DetectableZero a, KnownNat s, KnownNat t)
=> SparseMatrix (s + t) (s + t) a
-> ( SparseMatrix s s a
, SparseMatrix s t a
, SparseMatrix t s a
, SparseMatrix t t a
)
split m =
withKnownNat ((sing :: SNat s) %+ (sing :: SNat t)) $
let
(top, bottom) =
Vector.split (rows m)
topSplit =
Vector.map Vector.split top
bottomSplit =
Vector.map Vector.split bottom
a = UnsafeMakeSparseMatrix { rows = Vector.map fst topSplit }
b = UnsafeMakeSparseMatrix { rows = Vector.map snd topSplit }
c = UnsafeMakeSparseMatrix { rows = Vector.map fst bottomSplit }
d = UnsafeMakeSparseMatrix { rows = Vector.map snd bottomSplit }
in
(a, b, c, d)
| Combine four quadrants into a single square matrix .
combine :: forall s t a. (DetectableZero a, KnownNat s, KnownNat t)
=> ( SparseMatrix s s a
, SparseMatrix s t a
, SparseMatrix t s a
, SparseMatrix t t a
)
-> SparseMatrix (s + t) (s + t) a
combine (a, b, c, d) =
withKnownNat ((sing :: SNat s) %+ (sing :: SNat t)) $
let
top =
Vector.zipWith (Vector.++) (rows a) (rows b)
bottom =
Vector.zipWith (Vector.++) (rows c) (rows d)
in
UnsafeMakeSparseMatrix {
rows =
top Vector.++ bottom
}
| We can map from matrices with one type for elements to another given
-- a semiring homomorphism. Note that this does not work for arbitrary
functions . Specifically , this function must map zeros to zeros .
map :: (DetectableZero a, DetectableZero b, KnownNat r, KnownNat c)
=> (a -> b)
-> SparseMatrix r c a
-> SparseMatrix r c b
map f m =
UnsafeMakeSparseMatrix {
rows =
Vector.map (Vector.map f) (rows m)
}
| Iterate over non - zero elements in a matrix .
nonZero :: (KnownNat r, KnownNat c)
=> SparseMatrix r c a
-> [((Finite r, Finite c), a)]
nonZero m =
concatMap
(\(r, row) -> [((r, c), a) | (c, a) <- Vector.nonZero row])
(Vector.nonZero $ rows m)
| Iterate over non - zero elements in a matrix grouped by rows .
nonZeroRows :: (KnownNat r, KnownNat c)
=> SparseMatrix r c a
-> [(Finite r, [(Finite c, a)])]
nonZeroRows m =
fmap
(\(r, row) -> (r, Vector.nonZero row))
(Vector.nonZero $ rows m)
-- | Convert a vector to a list.
toList :: (DetectableZero a, KnownNat r, KnownNat c) => SparseMatrix r c a -> [[a]]
toList m =
fmap Vector.toList (Vector.toList $ rows m)
-- | Square matrices form a semiring.
instance (DetectableZero a, KnownNat n) => Semiring (SparseMatrix n n a) where
| Matrix where all entries are zero .
zero =
matrix []
-- | Matrix where the diagonal is one.
one =
matrix [((i, i), one) | i <- [0..]]
-- | Matrix addition.
(<+>) =
plus
-- | Matrix multiplication.
(<.>) =
times
| We can recognize zero matrices .
instance (DetectableZero a, KnownNat n) => DetectableZero (SparseMatrix n n a) where
isZero m =
isZero (rows m)
| Square matrices over Kleene algebra form a Kleene algebra .
instance (DetectableZero a, KleeneAlgebra a, KnownNat n) => KleeneAlgebra (SparseMatrix n n a) where
star m | Proved Refl <- (sing :: SNat n) %~ (sing :: SNat 0) =
m
star m | Proved Refl <- (sing :: SNat n) %~ (sing :: SNat 1) =
matrix [((0,0), star (m ! (0, 0)))]
star m =
TODO : get rid of ' unsafeCoerce ' or limit it to proving @n = small + large@.
withKnownNat ((sing :: SNat n) `sDiv` (sing :: SNat 2)) $
withKnownNat (((sing :: SNat n) %+ (sing :: SNat 1)) `sDiv` (sing :: SNat 2)) $
withKnownNat (((sing :: SNat n) `sDiv` (sing :: SNat 2))
%+
(((sing :: SNat n) %+ (sing :: SNat 1)) `sDiv` (sing :: SNat 2))
) $
case (sing :: SNat n) %~ (sing :: SNat ((n `Div` 2) + ((n + 1) `Div` 2))) of
Proved Refl ->
combine (a', b', c', d')
where
a :: SparseMatrix (n `Div` 2) (n `Div` 2) a
(a, b, c, d) =
split m
a ' : : SparseMatrix small small a
a' = star (a `plus` (b `times` star d `times` c))
b ' : : SparseMatrix small large a
b' = star (a `plus` (b `times` star d `times` c)) `times` b `times` star d
c ' : : SparseMatrix large small a
c' = star (d `plus` (c `times` star a `times` b)) `times` c `times` star a
d ' : : SparseMatrix large large a
d' = star (d `plus` (c `times` star a `times` b))
Disproved _->
error "impossible"
-- | Equality of matrices is decidable.
deriving instance Eq a => Eq (SparseMatrix r c a)
-- | We can totally order matrices.
deriving instance Ord a => Ord (SparseMatrix r c a)
instance (DetectableZero a, Show a, KnownNat r, KnownNat c) => Show (SparseMatrix r c a) where
show m =
intercalate "\n"
[ intercalate " " (fmap (padded widest) row) | row <- grid ]
where
-- | Matrix as a list of lists.
grid :: [[a]]
grid =
fmap Vector.toList (Vector.toList $ rows m)
-- | Show an element of the matrix.
show :: a -> String
show a =
showsPrec 11 a ""
-- | Width of the widest entry in the matrix.
widest :: Int
widest =
foldr max 0 [ length (show a) | a <- concat grid ]
-- | Show with a constant width.
padded :: Int -> a -> String
padded width a =
let
s = show a
in
s ++ take (width - length s) (repeat ' ') | null | https://raw.githubusercontent.com/cacay/regexp/25fd123edb00ce0dbd8b6fd6732a7aeca37e4a47/src/SparseMatrix.hs | haskell | # LANGUAGE GADTs #
TODO: remove
| A very cruddy implementation of sparse matrices. I couldn't
find an existing implementation that had all that I needed, so
I cooked this up.
TODO: find a package or make nicer
| A sparse matrix with @r@ rows and @c@ columns over
| Value at the given row and column.
| Row with the given index.
| Construct a sparse matrix from a list of indexed elements. Indices
are combined with '(<+>)'.
| Construct a sparse matrix from a list of indexed vectors corresponding
to the rows of the matrix.
| Matrix addition.
| Matrix multiplication.
| Swap the rows of a matrix with its columns.
a semiring homomorphism. Note that this does not work for arbitrary
| Convert a vector to a list.
| Square matrices form a semiring.
| Matrix where the diagonal is one.
| Matrix addition.
| Matrix multiplication.
| Equality of matrices is decidable.
| We can totally order matrices.
| Matrix as a list of lists.
| Show an element of the matrix.
| Width of the widest entry in the matrix.
| Show with a constant width. | # LANGUAGE DataKinds #
# LANGUAGE KindSignatures #
# LANGUAGE TypeApplications #
# LANGUAGE TypeOperators #
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE AllowAmbiguousTypes #
module SparseMatrix
( SparseMatrix
, matrix
, fromRows
, (!)
, nthRow
, plus
, times
, transpose
, map
, nonZero
, nonZeroRows
, toList
) where
import Flow
import Prelude hiding (map)
import Data.Function (on)
import Data.List (sortBy, groupBy, intercalate)
import Data.Ord (comparing)
import Data.Finite
import Data.Singletons
import Data.Singletons.Decide
import Data.Singletons.Prelude
import Data.Singletons.TypeLits
import Data.Semiring (Semiring(..), DetectableZero(..))
import Data.KleeneAlgebra
import SparseVector (SparseVector)
import qualified SparseVector as Vector
elements of type
newtype SparseMatrix (r :: Nat) (c :: Nat) a =
UnsafeMakeSparseMatrix {
rows :: SparseVector r (SparseVector c a)
}
(!) :: (DetectableZero a, KnownNat r, KnownNat c)
=> SparseMatrix r c a
-> (Finite r, Finite c)
-> a
m ! (r, c) =
(rows m Vector.! r) Vector.! c
nthRow :: (DetectableZero a, KnownNat r, KnownNat c)
=> Finite r
-> SparseMatrix r c a
-> SparseVector c a
nthRow r m =
rows m Vector.! r
that do n't appear in the list are all set to zero . Duplicate indexes
We need detectable zeros so we can filter them out .
matrix :: (DetectableZero a, KnownNat r, KnownNat c)
=> [((Finite r, Finite c), a)]
-> SparseMatrix r c a
matrix l =
UnsafeMakeSparseMatrix {
rows =
sortBy (comparing (fst . fst)) l
|> groupBy ((==) `on` (fst . fst))
|> fmap (\l -> (fst $ fst $ head l, fmap dropRow l))
|> fmap (\(r, elements) -> (r, Vector.vector elements))
|> Vector.vector
}
where
dropRow :: ((r, c), a) -> (c, a)
dropRow ((r, c), x)=
(c, x)
fromRows :: (DetectableZero a, KnownNat r, KnownNat c)
=> [(Finite r, SparseVector c a)]
-> SparseMatrix r c a
fromRows rows =
UnsafeMakeSparseMatrix {
rows =
Vector.vector rows
}
plus :: (DetectableZero a, KnownNat r, KnownNat c)
=> SparseMatrix r c a
-> SparseMatrix r c a
-> SparseMatrix r c a
plus m1 m2 =
UnsafeMakeSparseMatrix {
rows =
rows m1 <+> rows m2
}
times :: (DetectableZero a, KnownNat r, KnownNat m, KnownNat c)
=> SparseMatrix r m a
-> SparseMatrix m c a
-> SparseMatrix r c a
times m1 m2 =
UnsafeMakeSparseMatrix {
rows =
Vector.map (\r -> Vector.map (\c -> r `cross` c) (rows m2Tr)) (rows m1)
}
where
m2Tr =
transpose m2
cross v1 v2 =
Vector.sum (v1 <.> v2)
transpose :: (DetectableZero a, KnownNat r, KnownNat c)
=> SparseMatrix r c a
-> SparseMatrix c r a
transpose m =
UnsafeMakeSparseMatrix {
rows =
Vector.vector [(i, Vector.map (Vector.! i) (rows m)) | i <- finites]
}
| Split a square matrix into four quadrants .
split :: forall s t a. (DetectableZero a, KnownNat s, KnownNat t)
=> SparseMatrix (s + t) (s + t) a
-> ( SparseMatrix s s a
, SparseMatrix s t a
, SparseMatrix t s a
, SparseMatrix t t a
)
split m =
withKnownNat ((sing :: SNat s) %+ (sing :: SNat t)) $
let
(top, bottom) =
Vector.split (rows m)
topSplit =
Vector.map Vector.split top
bottomSplit =
Vector.map Vector.split bottom
a = UnsafeMakeSparseMatrix { rows = Vector.map fst topSplit }
b = UnsafeMakeSparseMatrix { rows = Vector.map snd topSplit }
c = UnsafeMakeSparseMatrix { rows = Vector.map fst bottomSplit }
d = UnsafeMakeSparseMatrix { rows = Vector.map snd bottomSplit }
in
(a, b, c, d)
| Combine four quadrants into a single square matrix .
combine :: forall s t a. (DetectableZero a, KnownNat s, KnownNat t)
=> ( SparseMatrix s s a
, SparseMatrix s t a
, SparseMatrix t s a
, SparseMatrix t t a
)
-> SparseMatrix (s + t) (s + t) a
combine (a, b, c, d) =
withKnownNat ((sing :: SNat s) %+ (sing :: SNat t)) $
let
top =
Vector.zipWith (Vector.++) (rows a) (rows b)
bottom =
Vector.zipWith (Vector.++) (rows c) (rows d)
in
UnsafeMakeSparseMatrix {
rows =
top Vector.++ bottom
}
| We can map from matrices with one type for elements to another given
functions . Specifically , this function must map zeros to zeros .
map :: (DetectableZero a, DetectableZero b, KnownNat r, KnownNat c)
=> (a -> b)
-> SparseMatrix r c a
-> SparseMatrix r c b
map f m =
UnsafeMakeSparseMatrix {
rows =
Vector.map (Vector.map f) (rows m)
}
| Iterate over non - zero elements in a matrix .
nonZero :: (KnownNat r, KnownNat c)
=> SparseMatrix r c a
-> [((Finite r, Finite c), a)]
nonZero m =
concatMap
(\(r, row) -> [((r, c), a) | (c, a) <- Vector.nonZero row])
(Vector.nonZero $ rows m)
| Iterate over non - zero elements in a matrix grouped by rows .
nonZeroRows :: (KnownNat r, KnownNat c)
=> SparseMatrix r c a
-> [(Finite r, [(Finite c, a)])]
nonZeroRows m =
fmap
(\(r, row) -> (r, Vector.nonZero row))
(Vector.nonZero $ rows m)
toList :: (DetectableZero a, KnownNat r, KnownNat c) => SparseMatrix r c a -> [[a]]
toList m =
fmap Vector.toList (Vector.toList $ rows m)
instance (DetectableZero a, KnownNat n) => Semiring (SparseMatrix n n a) where
| Matrix where all entries are zero .
zero =
matrix []
one =
matrix [((i, i), one) | i <- [0..]]
(<+>) =
plus
(<.>) =
times
| We can recognize zero matrices .
instance (DetectableZero a, KnownNat n) => DetectableZero (SparseMatrix n n a) where
isZero m =
isZero (rows m)
| Square matrices over Kleene algebra form a Kleene algebra .
instance (DetectableZero a, KleeneAlgebra a, KnownNat n) => KleeneAlgebra (SparseMatrix n n a) where
star m | Proved Refl <- (sing :: SNat n) %~ (sing :: SNat 0) =
m
star m | Proved Refl <- (sing :: SNat n) %~ (sing :: SNat 1) =
matrix [((0,0), star (m ! (0, 0)))]
star m =
TODO : get rid of ' unsafeCoerce ' or limit it to proving @n = small + large@.
withKnownNat ((sing :: SNat n) `sDiv` (sing :: SNat 2)) $
withKnownNat (((sing :: SNat n) %+ (sing :: SNat 1)) `sDiv` (sing :: SNat 2)) $
withKnownNat (((sing :: SNat n) `sDiv` (sing :: SNat 2))
%+
(((sing :: SNat n) %+ (sing :: SNat 1)) `sDiv` (sing :: SNat 2))
) $
case (sing :: SNat n) %~ (sing :: SNat ((n `Div` 2) + ((n + 1) `Div` 2))) of
Proved Refl ->
combine (a', b', c', d')
where
a :: SparseMatrix (n `Div` 2) (n `Div` 2) a
(a, b, c, d) =
split m
a ' : : SparseMatrix small small a
a' = star (a `plus` (b `times` star d `times` c))
b ' : : SparseMatrix small large a
b' = star (a `plus` (b `times` star d `times` c)) `times` b `times` star d
c ' : : SparseMatrix large small a
c' = star (d `plus` (c `times` star a `times` b)) `times` c `times` star a
d ' : : SparseMatrix large large a
d' = star (d `plus` (c `times` star a `times` b))
Disproved _->
error "impossible"
deriving instance Eq a => Eq (SparseMatrix r c a)
deriving instance Ord a => Ord (SparseMatrix r c a)
instance (DetectableZero a, Show a, KnownNat r, KnownNat c) => Show (SparseMatrix r c a) where
show m =
intercalate "\n"
[ intercalate " " (fmap (padded widest) row) | row <- grid ]
where
grid :: [[a]]
grid =
fmap Vector.toList (Vector.toList $ rows m)
show :: a -> String
show a =
showsPrec 11 a ""
widest :: Int
widest =
foldr max 0 [ length (show a) | a <- concat grid ]
padded :: Int -> a -> String
padded width a =
let
s = show a
in
s ++ take (width - length s) (repeat ' ') |
2822e7410ffd46ea9b17a1adac4db5ab5dd87a9426298bb463965c89dde3968a | logicmoo/wam_common_lisp | init.lsp | (load "../util/system")
(load "defsys")
(load "cmpinit")
( sbt : build - system clos )
;(setq *print-circle* t)
( allocate ' cons 800 t )
( setq si:*gc - verbose * nil )
| null | https://raw.githubusercontent.com/logicmoo/wam_common_lisp/4396d9e26b050f68182d65c9a2d5a939557616dd/prolog/wam_cl/src/clos/init.lsp | lisp | (setq *print-circle* t) | (load "../util/system")
(load "defsys")
(load "cmpinit")
( sbt : build - system clos )
( allocate ' cons 800 t )
( setq si:*gc - verbose * nil )
|
b93227af31c801043da22e3036c6216b89ef8516aa7e0be2d9169bb82e792b9c | didierverna/declt | package.lisp | package.lisp --- Declt setup package definition
Copyright ( C ) 2015 , 2017 , 2019 , 2021
Author : < >
This file is part of Declt .
;; 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.
THIS 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.
;;; Commentary:
;;; Code:
(in-package :cl-user)
(defpackage :net.didierverna.declt.setup
(:documentation "The Declt setup library's package.")
(:use :cl)
# # # # PORTME .
(:import-from #+sbcl :sb-mop
:validate-superclass)
(:import-from :named-readtables
:defreadtable :in-readtable)
(:export
:in-readtable
;; From src/configuration.lisp:
:configuration :configure
;; From src/version.lisp:
:*copyright-years*
:*release-major-level* :*release-minor-level* :*release-status*
:*release-status-level* :*release-name*
:version
;; From src/util.lisp:
:while :endpush :retain :find* :when-let :when-let* :mapcat
:declare-valid-superclass :abstract-class :defabstract
:non-empty-string-p :non-empty-string))
;;; package.lisp ends here
| null | https://raw.githubusercontent.com/didierverna/declt/13bb631eaf282a1fb5ebbb30843df6f21bf3983e/setup/package.lisp | lisp | 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.
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
Commentary:
Code:
From src/configuration.lisp:
From src/version.lisp:
From src/util.lisp:
package.lisp ends here | package.lisp --- Declt setup package definition
Copyright ( C ) 2015 , 2017 , 2019 , 2021
Author : < >
This file is part of Declt .
THIS SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
(in-package :cl-user)
(defpackage :net.didierverna.declt.setup
(:documentation "The Declt setup library's package.")
(:use :cl)
# # # # PORTME .
(:import-from #+sbcl :sb-mop
:validate-superclass)
(:import-from :named-readtables
:defreadtable :in-readtable)
(:export
:in-readtable
:configuration :configure
:*copyright-years*
:*release-major-level* :*release-minor-level* :*release-status*
:*release-status-level* :*release-name*
:version
:while :endpush :retain :find* :when-let :when-let* :mapcat
:declare-valid-superclass :abstract-class :defabstract
:non-empty-string-p :non-empty-string))
|
767cde4593406d2d0666d92d6defb41591a6dd19c20440f7c0acb7550ca3ad92 | AccelerateHS/accelerate-llvm | Module.hs | {-# LANGUAGE CPP #-}
# LANGUAGE RecordWildCards #
# LANGUAGE TemplateHaskell #
-- |
-- Module : Data.Array.Accelerate.LLVM.Native.Compile.Module
Copyright : [ 2014 .. 2017 ] The Accelerate Team
-- License : BSD3
--
Maintainer : < >
-- Stability : experimental
Portability : non - portable ( GHC extensions )
--
module Data.Array.Accelerate.LLVM.Native.Compile.Module (
Module,
compileModule,
execute, executeMain,
nm,
) where
-- accelerate
import Data.Array.Accelerate.Error
import Data.Array.Accelerate.Lifetime
import qualified Data.Array.Accelerate.LLVM.Native.Debug as Debug
-- library
import Control.Exception
import Control.Concurrent
import Data.List
import Foreign.LibFFI
import Foreign.Ptr
import Text.Printf
import Data.ByteString.Short ( ShortByteString )
-- | An encapsulation of the callable functions resulting from compiling
-- a module.
--
data Module = Module {-# UNPACK #-} !(Lifetime FunctionTable)
data FunctionTable = FunctionTable { functionTable :: [Function] }
type Function = (ShortByteString, FunPtr ())
instance Show Module where
showsPrec p (Module m)
= showsPrec p (unsafeGetValue m)
instance Show FunctionTable where
showsPrec _ f
= showString "<<"
. showString (intercalate "," [ show n | (n,_) <- functionTable f ])
. showString ">>"
-- | Execute a named function that was defined in the module. An error is thrown
-- if the requested function is not define in the module.
--
-- The final argument is a continuation to which we pass a function you can call
-- to actually execute the foreign function.
--
# INLINEABLE execute #
execute
:: Module
-> ShortByteString
-> ((ShortByteString, [Arg] -> IO ()) -> IO a)
-> IO a
execute mdl@(Module ft) name k =
withLifetime ft $ \FunctionTable{..} ->
case lookup name functionTable of
Just f -> k (name, \argv -> callFFI f retVoid argv)
Nothing -> $internalError "execute" (printf "function '%s' not found in module: %s\n" (show name) (show mdl))
| Execute the ' main ' function of a module , which is just the first function
-- defined in the module.
--
# INLINEABLE executeMain #
executeMain
:: Module
-> ((ShortByteString, [Arg] -> IO ()) -> IO a)
-> IO a
executeMain (Module ft) k =
withLifetime ft $ \FunctionTable{..} ->
case functionTable of
[] -> $internalError "executeMain" "no functions defined in module"
(name,f):_ -> k (name, \argv -> callFFI f retVoid argv)
-- | Display the global (external) symbol table for this module.
--
nm :: Module -> IO [ShortByteString]
nm (Module ft) =
withLifetime ft $ \FunctionTable{..} ->
return $ map fst functionTable
-- Compile a given module into executable code.
--
-- Note: [Executing JIT-compiled functions]
--
We have the problem that the - general functions dealing with the FFI are
-- exposed as bracketed 'with*' operations, rather than as separate
-- 'create*'/'destroy*' pairs. This is a good design that guarantees that
-- functions clean up their resources on exit, but also means that we can't
-- return a function pointer to the compiled code from within the bracketed
-- expression, because it will no longer be valid once we get around to
-- executing it, as it has already been deallocated!
--
This function provides a wrapper that does the compilation step ( first
-- argument) in a separate thread, returns the compiled functions, then waits
-- until they are no longer needed before allowing the finalisation routines to
-- proceed.
--
compileModule :: (([Function] -> IO ()) -> IO ()) -> IO Module
compileModule compile = mask $ \restore -> do
main <- myThreadId
mfuns <- newEmptyMVar
mdone <- newEmptyMVar
_ <- forkIO . reflectExceptionsTo main . restore . compile $ \funs -> do
putMVar mfuns funs
takeMVar mdone -- thread blocks, keeping 'funs' alive
message "worker thread shutting down" -- we better have a matching message from 'finalise'
--
funs <- takeMVar mfuns
ftab <- newLifetime (FunctionTable funs)
addFinalizer ftab (finalise mdone)
return (Module ftab)
reflectExceptionsTo :: ThreadId -> IO () -> IO ()
reflectExceptionsTo tid action =
catchNonThreadKilled action (throwTo tid)
catchNonThreadKilled :: IO a -> (SomeException -> IO a) -> IO a
catchNonThreadKilled action handler =
action `catch` \e ->
case fromException e of
Just ThreadKilled -> throwIO e
_ -> handler e
finalise :: MVar () -> IO ()
finalise done = do
message "finalising function table"
putMVar done ()
-- Debug
-- -----
# INLINE message #
message :: String -> IO ()
message msg = Debug.traceIO Debug.dump_exec ("exec: " ++ msg)
| null | https://raw.githubusercontent.com/AccelerateHS/accelerate-llvm/cf081587fecec23a19f68bfbd31334166868405e/accelerate-llvm-native/icebox/Data/Array/Accelerate/LLVM/Native/Compile/Module.hs | haskell | # LANGUAGE CPP #
|
Module : Data.Array.Accelerate.LLVM.Native.Compile.Module
License : BSD3
Stability : experimental
accelerate
library
| An encapsulation of the callable functions resulting from compiling
a module.
# UNPACK #
| Execute a named function that was defined in the module. An error is thrown
if the requested function is not define in the module.
The final argument is a continuation to which we pass a function you can call
to actually execute the foreign function.
defined in the module.
| Display the global (external) symbol table for this module.
Compile a given module into executable code.
Note: [Executing JIT-compiled functions]
exposed as bracketed 'with*' operations, rather than as separate
'create*'/'destroy*' pairs. This is a good design that guarantees that
functions clean up their resources on exit, but also means that we can't
return a function pointer to the compiled code from within the bracketed
expression, because it will no longer be valid once we get around to
executing it, as it has already been deallocated!
argument) in a separate thread, returns the compiled functions, then waits
until they are no longer needed before allowing the finalisation routines to
proceed.
thread blocks, keeping 'funs' alive
we better have a matching message from 'finalise'
Debug
----- | # LANGUAGE RecordWildCards #
# LANGUAGE TemplateHaskell #
Copyright : [ 2014 .. 2017 ] The Accelerate Team
Maintainer : < >
Portability : non - portable ( GHC extensions )
module Data.Array.Accelerate.LLVM.Native.Compile.Module (
Module,
compileModule,
execute, executeMain,
nm,
) where
import Data.Array.Accelerate.Error
import Data.Array.Accelerate.Lifetime
import qualified Data.Array.Accelerate.LLVM.Native.Debug as Debug
import Control.Exception
import Control.Concurrent
import Data.List
import Foreign.LibFFI
import Foreign.Ptr
import Text.Printf
import Data.ByteString.Short ( ShortByteString )
data FunctionTable = FunctionTable { functionTable :: [Function] }
type Function = (ShortByteString, FunPtr ())
instance Show Module where
showsPrec p (Module m)
= showsPrec p (unsafeGetValue m)
instance Show FunctionTable where
showsPrec _ f
= showString "<<"
. showString (intercalate "," [ show n | (n,_) <- functionTable f ])
. showString ">>"
# INLINEABLE execute #
execute
:: Module
-> ShortByteString
-> ((ShortByteString, [Arg] -> IO ()) -> IO a)
-> IO a
execute mdl@(Module ft) name k =
withLifetime ft $ \FunctionTable{..} ->
case lookup name functionTable of
Just f -> k (name, \argv -> callFFI f retVoid argv)
Nothing -> $internalError "execute" (printf "function '%s' not found in module: %s\n" (show name) (show mdl))
| Execute the ' main ' function of a module , which is just the first function
# INLINEABLE executeMain #
executeMain
:: Module
-> ((ShortByteString, [Arg] -> IO ()) -> IO a)
-> IO a
executeMain (Module ft) k =
withLifetime ft $ \FunctionTable{..} ->
case functionTable of
[] -> $internalError "executeMain" "no functions defined in module"
(name,f):_ -> k (name, \argv -> callFFI f retVoid argv)
nm :: Module -> IO [ShortByteString]
nm (Module ft) =
withLifetime ft $ \FunctionTable{..} ->
return $ map fst functionTable
We have the problem that the - general functions dealing with the FFI are
This function provides a wrapper that does the compilation step ( first
compileModule :: (([Function] -> IO ()) -> IO ()) -> IO Module
compileModule compile = mask $ \restore -> do
main <- myThreadId
mfuns <- newEmptyMVar
mdone <- newEmptyMVar
_ <- forkIO . reflectExceptionsTo main . restore . compile $ \funs -> do
putMVar mfuns funs
funs <- takeMVar mfuns
ftab <- newLifetime (FunctionTable funs)
addFinalizer ftab (finalise mdone)
return (Module ftab)
reflectExceptionsTo :: ThreadId -> IO () -> IO ()
reflectExceptionsTo tid action =
catchNonThreadKilled action (throwTo tid)
catchNonThreadKilled :: IO a -> (SomeException -> IO a) -> IO a
catchNonThreadKilled action handler =
action `catch` \e ->
case fromException e of
Just ThreadKilled -> throwIO e
_ -> handler e
finalise :: MVar () -> IO ()
finalise done = do
message "finalising function table"
putMVar done ()
# INLINE message #
message :: String -> IO ()
message msg = Debug.traceIO Debug.dump_exec ("exec: " ++ msg)
|
a848c18d785838853866533ce5408c850f8a8a0454a854e2598979528f420d96 | Zulu-Inuoe/clution | encode.lisp | This file is part of yason , a Common Lisp JSON parser / encoder
;;
Copyright ( c ) 2008 - 2014 and contributors
;; All rights reserved.
;;
;; Please see the file LICENSE in the distribution.
(in-package :yason)
(defvar *json-output*)
(defparameter *default-indent* nil
"Set to T or an numeric indentation width in order to have YASON
indent its output by default.")
(defparameter *default-indent-width* 2
"Default indentation width for output if indentation is selected
with no indentation width specified.")
(defgeneric encode (object &optional stream)
(:documentation "Encode OBJECT to STREAM in JSON format. May be
specialized by applications to perform specific rendering. STREAM
defaults to *STANDARD-OUTPUT*."))
(defparameter *char-replacements*
(alexandria:plist-hash-table
'(#\\ "\\\\"
#\" "\\\""
#\Backspace "\\b"
#\Page "\\f"
#\Newline "\\n"
#\Return "\\r"
#\Tab "\\t")))
(defmethod encode ((string string) &optional (stream *standard-output*))
(write-char #\" stream)
(dotimes (i (length string))
(let* ((char (aref string i))
(replacement (gethash char *char-replacements*)))
(if replacement
(write-string replacement stream)
(write-char char stream))))
(write-char #\" stream)
string)
(defmethod encode ((object ratio) &optional (stream *standard-output*))
(encode (coerce object 'double-float) stream)
object)
(defmethod encode ((object float) &optional (stream *standard-output*))
(let ((*read-default-float-format* 'double-float))
(format stream "~F" (coerce object 'double-float)))
object)
(defmethod encode ((object integer) &optional (stream *standard-output*))
(princ object stream))
(defmacro with-aggregate/object ((stream opening-char closing-char) &body body)
"Set up serialization context for aggregate serialization with the
object encoder."
(alexandria:with-gensyms (printed)
`(progn
(write-delimiter ,opening-char ,stream)
(change-indentation ,stream #'+)
(prog1
(let (,printed)
(macrolet ((with-element-output (() &body body)
`(progn
(cond
(,',printed
(write-delimiter #\, ,',stream))
(t
(setf ,',printed t)))
(write-indentation ,',stream)
,@body)))
,@body))
(change-indentation ,stream #'-)
(write-indentation ,stream)
(write-delimiter ,closing-char ,stream)))))
(defun encode-key/value (key value stream)
(encode key stream)
(write-char #\: stream)
(encode value stream))
(defmethod encode ((object hash-table) &optional (stream *standard-output*))
(with-aggregate/object (stream #\{ #\})
(maphash (lambda (key value)
(with-element-output ()
(encode-key/value key value stream)))
object)
object))
(defmethod encode ((object vector) &optional (stream *standard-output*))
(with-aggregate/object (stream #\[ #\])
(loop for value across object
do (with-element-output ()
(encode value stream)))
object))
(defmethod encode ((object list) &optional (stream *standard-output*))
(with-aggregate/object (stream #\[ #\])
(dolist (value object)
(with-element-output ()
(encode value stream)))
object))
(defun encode-assoc-key/value (key value stream)
(let ((string (string key)))
(encode-key/value string value stream)))
(defun encode-alist (object &optional (stream *standard-output*))
(with-aggregate/object (stream #\{ #\})
(loop for (key . value) in object
do (with-element-output ()
(encode-assoc-key/value key value stream)))
object))
(defun encode-plist (object &optional (stream *standard-output*))
(with-aggregate/object (stream #\{ #\})
(loop for (key value) on object by #'cddr
do (with-element-output ()
(encode-assoc-key/value key value stream)))
object))
(defmethod encode ((object (eql 'true)) &optional (stream *standard-output*))
(write-string "true" stream)
object)
(defmethod encode ((object (eql 'false)) &optional (stream *standard-output*))
(write-string "false" stream)
object)
(defmethod encode ((object (eql 'null)) &optional (stream *standard-output*))
(write-string "null" stream)
object)
(defmethod encode ((object (eql t)) &optional (stream *standard-output*))
(write-string "true" stream)
object)
(defmethod encode ((object (eql nil)) &optional (stream *standard-output*))
(write-string "null" stream)
object)
(defclass json-output-stream (trivial-gray-streams:fundamental-character-output-stream)
((output-stream :reader output-stream
:initarg :output-stream)
(stack :accessor stack
:initform nil)
(indent :initarg :indent
:reader indent
:accessor indent%)
(indent-string :initform ""
:accessor indent-string))
(:default-initargs :indent *default-indent*)
(:documentation "Objects of this class capture the state of a JSON stream encoder."))
(defmethod initialize-instance :after ((stream json-output-stream) &key indent)
(when (eq indent t)
(setf (indent% stream) *default-indent-width*)))
(defgeneric make-json-output-stream (stream &key indent))
(defmethod make-json-output-stream (stream &key (indent t))
"Create a JSON output stream with indentation enabled."
(if indent
(make-instance 'json-output-stream :output-stream stream :indent indent)
stream))
(defmethod trivial-gray-streams:stream-write-char ((stream json-output-stream) char)
(write-char char (output-stream stream)))
(defgeneric write-indentation (stream)
(:method ((stream t))
nil)
(:method ((stream json-output-stream))
(when (indent stream)
(fresh-line (output-stream stream))
(write-string (indent-string stream) (output-stream stream)))))
(defgeneric write-delimiter (char stream)
(:method (char stream)
(write-char char stream))
(:method (char (stream json-output-stream))
(write-char char (output-stream stream))))
(defgeneric change-indentation (stream operator)
(:method ((stream t) (operator t))
nil)
(:method ((stream json-output-stream) operator)
(when (indent stream)
(setf (indent-string stream) (make-string (funcall operator (length (indent-string stream))
(indent stream))
:initial-element #\Space)))))
(defun next-aggregate-element ()
(if (car (stack *json-output*))
(write-char (car (stack *json-output*)) (output-stream *json-output*))
(setf (car (stack *json-output*)) #\,)))
(defmacro with-output ((stream &rest args &key indent) &body body)
(declare (ignore indent))
"Set up a JSON streaming encoder context on STREAM, then evaluate BODY."
`(let ((*json-output* (make-instance 'json-output-stream :output-stream ,stream ,@args)))
,@body))
(defmacro with-output-to-string* ((&rest args &key indent) &body body)
"Set up a JSON streaming encoder context, then evaluate BODY.
Return a string with the generated JSON output."
(declare (ignore indent))
`(with-output-to-string (s)
(with-output (s ,@args)
,@body)))
(define-condition no-json-output-context (error)
()
(:report "No JSON output context is active")
(:documentation "This condition is signalled when one of the stream
encoding function is used outside the dynamic context of a
WITH-OUTPUT or WITH-OUTPUT-TO-STRING* body."))
(defmacro with-aggregate/stream ((begin-char end-char) &body body)
"Set up context for aggregate serialization for the stream encoder."
`(progn
(unless (boundp '*json-output*)
(error 'no-json-output-context))
(when (stack *json-output*)
(next-aggregate-element))
(write-indentation *json-output*)
(write-delimiter ,begin-char *json-output*)
(change-indentation *json-output* #'+)
(push nil (stack *json-output*))
(prog1
(progn ,@body)
(pop (stack *json-output*))
(change-indentation *json-output* #'-)
(write-indentation *json-output*)
(write-delimiter ,end-char *json-output*))))
(defmacro with-array (() &body body)
"Open a JSON array, then run BODY. Inside the body,
ENCODE-ARRAY-ELEMENT must be called to encode elements to the opened
array. Must be called within an existing JSON encoder context, see
WITH-OUTPUT and WITH-OUTPUT-TO-STRING*."
`(with-aggregate/stream (#\[ #\]) ,@body))
(defmacro with-object (() &body body)
"Open a JSON object, then run BODY. Inside the body,
ENCODE-OBJECT-ELEMENT or WITH-OBJECT-ELEMENT must be called to encode
elements to the object. Must be called within an existing JSON
encoder context, see WITH-OUTPUT and WITH-OUTPUT-TO-STRING*."
`(with-aggregate/stream (#\{ #\}) ,@body))
(defun encode-array-element (object)
"Encode OBJECT as next array element to the last JSON array opened
with WITH-ARRAY in the dynamic context. OBJECT is encoded using the
ENCODE generic function, so it must be of a type for which an ENCODE
method is defined."
(next-aggregate-element)
(write-indentation *json-output*)
(encode object (output-stream *json-output*)))
(defun encode-array-elements (&rest objects)
"Encode OBJECTS, a list of JSON encodable objects, as array elements."
(dolist (object objects)
(encode-array-element object)))
(defun encode-object-element (key value)
"Encode KEY and VALUE as object element to the last JSON object
opened with WITH-OBJECT in the dynamic context. KEY and VALUE are
encoded using the ENCODE generic function, so they both must be of a
type for which an ENCODE method is defined."
(next-aggregate-element)
(write-indentation *json-output*)
(encode-key/value key value (output-stream *json-output*))
value)
(defun encode-object-elements (&rest elements)
"Encode plist ELEMENTS as object elements."
(loop for (key value) on elements by #'cddr
do (encode-object-element key value)))
(defun encode-object-slots (object slots)
"For each slot in SLOTS, encode that slot on OBJECT as an object element.
Equivalent to calling ENCODE-OBJECT-ELEMENT for each slot where the
key is the slot name, and the value is the (SLOT-VALUE OBJECT slot)"
(loop for slot in slots
do (encode-object-element (string slot)
(slot-value object slot))))
(define-compiler-macro encode-object-slots (&whole form &environment env object raw-slots)
"Compiler macro to allow open-coding with encode-object-slots when slots are literal list."
(let ((slots (macroexpand raw-slots env)))
(cond
((null slots) nil)
((eq (car slots) 'quote)
(setf slots (cadr slots)) ; Get the quoted list
`(with-slots ,slots ,object
,@(loop for slot in slots
collect `(encode-object-element ,(string slot) ,slot))))
(t form))))
(defmacro with-object-element ((key) &body body)
"Open a new encoding context to encode a JSON object element. KEY
is the key of the element. The value will be whatever BODY
serializes to the current JSON output context using one of the
stream encoding functions. This can be used to stream out nested
object structures."
`(progn
(next-aggregate-element)
(write-indentation *json-output*)
(encode ,key (output-stream *json-output*))
(setf (car (stack *json-output*)) #\:)
(unwind-protect
(progn ,@body)
(setf (car (stack *json-output*)) #\,))))
(defgeneric encode-slots (object)
(:documentation
"Generic function to encode object slots. It should be called in an
object encoding context. It uses PROGN combinatation with
MOST-SPECIFIC-LAST order, so that base class slots are encoded
before derived class slots.")
(:method-combination progn :most-specific-last))
(defgeneric encode-object (object)
(:documentation
"Generic function to encode an object. The default implementation
opens a new object encoding context and calls ENCODE-SLOTS on
the argument.")
(:method (object)
(with-object ()
(yason:encode-slots object))))
| null | https://raw.githubusercontent.com/Zulu-Inuoe/clution/b72f7afe5f770ff68a066184a389c23551863f7f/cl-clution/qlfile-libs/yason-v0.7.6/encode.lisp | lisp |
All rights reserved.
Please see the file LICENSE in the distribution.
Get the quoted list | This file is part of yason , a Common Lisp JSON parser / encoder
Copyright ( c ) 2008 - 2014 and contributors
(in-package :yason)
(defvar *json-output*)
(defparameter *default-indent* nil
"Set to T or an numeric indentation width in order to have YASON
indent its output by default.")
(defparameter *default-indent-width* 2
"Default indentation width for output if indentation is selected
with no indentation width specified.")
(defgeneric encode (object &optional stream)
(:documentation "Encode OBJECT to STREAM in JSON format. May be
specialized by applications to perform specific rendering. STREAM
defaults to *STANDARD-OUTPUT*."))
(defparameter *char-replacements*
(alexandria:plist-hash-table
'(#\\ "\\\\"
#\" "\\\""
#\Backspace "\\b"
#\Page "\\f"
#\Newline "\\n"
#\Return "\\r"
#\Tab "\\t")))
(defmethod encode ((string string) &optional (stream *standard-output*))
(write-char #\" stream)
(dotimes (i (length string))
(let* ((char (aref string i))
(replacement (gethash char *char-replacements*)))
(if replacement
(write-string replacement stream)
(write-char char stream))))
(write-char #\" stream)
string)
(defmethod encode ((object ratio) &optional (stream *standard-output*))
(encode (coerce object 'double-float) stream)
object)
(defmethod encode ((object float) &optional (stream *standard-output*))
(let ((*read-default-float-format* 'double-float))
(format stream "~F" (coerce object 'double-float)))
object)
(defmethod encode ((object integer) &optional (stream *standard-output*))
(princ object stream))
(defmacro with-aggregate/object ((stream opening-char closing-char) &body body)
"Set up serialization context for aggregate serialization with the
object encoder."
(alexandria:with-gensyms (printed)
`(progn
(write-delimiter ,opening-char ,stream)
(change-indentation ,stream #'+)
(prog1
(let (,printed)
(macrolet ((with-element-output (() &body body)
`(progn
(cond
(,',printed
(write-delimiter #\, ,',stream))
(t
(setf ,',printed t)))
(write-indentation ,',stream)
,@body)))
,@body))
(change-indentation ,stream #'-)
(write-indentation ,stream)
(write-delimiter ,closing-char ,stream)))))
(defun encode-key/value (key value stream)
(encode key stream)
(write-char #\: stream)
(encode value stream))
(defmethod encode ((object hash-table) &optional (stream *standard-output*))
(with-aggregate/object (stream #\{ #\})
(maphash (lambda (key value)
(with-element-output ()
(encode-key/value key value stream)))
object)
object))
(defmethod encode ((object vector) &optional (stream *standard-output*))
(with-aggregate/object (stream #\[ #\])
(loop for value across object
do (with-element-output ()
(encode value stream)))
object))
(defmethod encode ((object list) &optional (stream *standard-output*))
(with-aggregate/object (stream #\[ #\])
(dolist (value object)
(with-element-output ()
(encode value stream)))
object))
(defun encode-assoc-key/value (key value stream)
(let ((string (string key)))
(encode-key/value string value stream)))
(defun encode-alist (object &optional (stream *standard-output*))
(with-aggregate/object (stream #\{ #\})
(loop for (key . value) in object
do (with-element-output ()
(encode-assoc-key/value key value stream)))
object))
(defun encode-plist (object &optional (stream *standard-output*))
(with-aggregate/object (stream #\{ #\})
(loop for (key value) on object by #'cddr
do (with-element-output ()
(encode-assoc-key/value key value stream)))
object))
(defmethod encode ((object (eql 'true)) &optional (stream *standard-output*))
(write-string "true" stream)
object)
(defmethod encode ((object (eql 'false)) &optional (stream *standard-output*))
(write-string "false" stream)
object)
(defmethod encode ((object (eql 'null)) &optional (stream *standard-output*))
(write-string "null" stream)
object)
(defmethod encode ((object (eql t)) &optional (stream *standard-output*))
(write-string "true" stream)
object)
(defmethod encode ((object (eql nil)) &optional (stream *standard-output*))
(write-string "null" stream)
object)
(defclass json-output-stream (trivial-gray-streams:fundamental-character-output-stream)
((output-stream :reader output-stream
:initarg :output-stream)
(stack :accessor stack
:initform nil)
(indent :initarg :indent
:reader indent
:accessor indent%)
(indent-string :initform ""
:accessor indent-string))
(:default-initargs :indent *default-indent*)
(:documentation "Objects of this class capture the state of a JSON stream encoder."))
(defmethod initialize-instance :after ((stream json-output-stream) &key indent)
(when (eq indent t)
(setf (indent% stream) *default-indent-width*)))
(defgeneric make-json-output-stream (stream &key indent))
(defmethod make-json-output-stream (stream &key (indent t))
"Create a JSON output stream with indentation enabled."
(if indent
(make-instance 'json-output-stream :output-stream stream :indent indent)
stream))
(defmethod trivial-gray-streams:stream-write-char ((stream json-output-stream) char)
(write-char char (output-stream stream)))
(defgeneric write-indentation (stream)
(:method ((stream t))
nil)
(:method ((stream json-output-stream))
(when (indent stream)
(fresh-line (output-stream stream))
(write-string (indent-string stream) (output-stream stream)))))
(defgeneric write-delimiter (char stream)
(:method (char stream)
(write-char char stream))
(:method (char (stream json-output-stream))
(write-char char (output-stream stream))))
(defgeneric change-indentation (stream operator)
(:method ((stream t) (operator t))
nil)
(:method ((stream json-output-stream) operator)
(when (indent stream)
(setf (indent-string stream) (make-string (funcall operator (length (indent-string stream))
(indent stream))
:initial-element #\Space)))))
(defun next-aggregate-element ()
(if (car (stack *json-output*))
(write-char (car (stack *json-output*)) (output-stream *json-output*))
(setf (car (stack *json-output*)) #\,)))
(defmacro with-output ((stream &rest args &key indent) &body body)
(declare (ignore indent))
"Set up a JSON streaming encoder context on STREAM, then evaluate BODY."
`(let ((*json-output* (make-instance 'json-output-stream :output-stream ,stream ,@args)))
,@body))
(defmacro with-output-to-string* ((&rest args &key indent) &body body)
"Set up a JSON streaming encoder context, then evaluate BODY.
Return a string with the generated JSON output."
(declare (ignore indent))
`(with-output-to-string (s)
(with-output (s ,@args)
,@body)))
(define-condition no-json-output-context (error)
()
(:report "No JSON output context is active")
(:documentation "This condition is signalled when one of the stream
encoding function is used outside the dynamic context of a
WITH-OUTPUT or WITH-OUTPUT-TO-STRING* body."))
(defmacro with-aggregate/stream ((begin-char end-char) &body body)
"Set up context for aggregate serialization for the stream encoder."
`(progn
(unless (boundp '*json-output*)
(error 'no-json-output-context))
(when (stack *json-output*)
(next-aggregate-element))
(write-indentation *json-output*)
(write-delimiter ,begin-char *json-output*)
(change-indentation *json-output* #'+)
(push nil (stack *json-output*))
(prog1
(progn ,@body)
(pop (stack *json-output*))
(change-indentation *json-output* #'-)
(write-indentation *json-output*)
(write-delimiter ,end-char *json-output*))))
(defmacro with-array (() &body body)
"Open a JSON array, then run BODY. Inside the body,
ENCODE-ARRAY-ELEMENT must be called to encode elements to the opened
array. Must be called within an existing JSON encoder context, see
WITH-OUTPUT and WITH-OUTPUT-TO-STRING*."
`(with-aggregate/stream (#\[ #\]) ,@body))
(defmacro with-object (() &body body)
"Open a JSON object, then run BODY. Inside the body,
ENCODE-OBJECT-ELEMENT or WITH-OBJECT-ELEMENT must be called to encode
elements to the object. Must be called within an existing JSON
encoder context, see WITH-OUTPUT and WITH-OUTPUT-TO-STRING*."
`(with-aggregate/stream (#\{ #\}) ,@body))
(defun encode-array-element (object)
"Encode OBJECT as next array element to the last JSON array opened
with WITH-ARRAY in the dynamic context. OBJECT is encoded using the
ENCODE generic function, so it must be of a type for which an ENCODE
method is defined."
(next-aggregate-element)
(write-indentation *json-output*)
(encode object (output-stream *json-output*)))
(defun encode-array-elements (&rest objects)
"Encode OBJECTS, a list of JSON encodable objects, as array elements."
(dolist (object objects)
(encode-array-element object)))
(defun encode-object-element (key value)
"Encode KEY and VALUE as object element to the last JSON object
opened with WITH-OBJECT in the dynamic context. KEY and VALUE are
encoded using the ENCODE generic function, so they both must be of a
type for which an ENCODE method is defined."
(next-aggregate-element)
(write-indentation *json-output*)
(encode-key/value key value (output-stream *json-output*))
value)
(defun encode-object-elements (&rest elements)
"Encode plist ELEMENTS as object elements."
(loop for (key value) on elements by #'cddr
do (encode-object-element key value)))
(defun encode-object-slots (object slots)
"For each slot in SLOTS, encode that slot on OBJECT as an object element.
Equivalent to calling ENCODE-OBJECT-ELEMENT for each slot where the
key is the slot name, and the value is the (SLOT-VALUE OBJECT slot)"
(loop for slot in slots
do (encode-object-element (string slot)
(slot-value object slot))))
(define-compiler-macro encode-object-slots (&whole form &environment env object raw-slots)
"Compiler macro to allow open-coding with encode-object-slots when slots are literal list."
(let ((slots (macroexpand raw-slots env)))
(cond
((null slots) nil)
((eq (car slots) 'quote)
`(with-slots ,slots ,object
,@(loop for slot in slots
collect `(encode-object-element ,(string slot) ,slot))))
(t form))))
(defmacro with-object-element ((key) &body body)
"Open a new encoding context to encode a JSON object element. KEY
is the key of the element. The value will be whatever BODY
serializes to the current JSON output context using one of the
stream encoding functions. This can be used to stream out nested
object structures."
`(progn
(next-aggregate-element)
(write-indentation *json-output*)
(encode ,key (output-stream *json-output*))
(setf (car (stack *json-output*)) #\:)
(unwind-protect
(progn ,@body)
(setf (car (stack *json-output*)) #\,))))
(defgeneric encode-slots (object)
(:documentation
"Generic function to encode object slots. It should be called in an
object encoding context. It uses PROGN combinatation with
MOST-SPECIFIC-LAST order, so that base class slots are encoded
before derived class slots.")
(:method-combination progn :most-specific-last))
(defgeneric encode-object (object)
(:documentation
"Generic function to encode an object. The default implementation
opens a new object encoding context and calls ENCODE-SLOTS on
the argument.")
(:method (object)
(with-object ()
(yason:encode-slots object))))
|
6f7581b88c10ec88e02ad32f011d58da2ed0e25e75d827e6c2a438823ad1aae2 | kansetsu7/awesome_name | combinations.cljs | (ns awesome-name.views.combinations
(:require
[awesome-name.component.core :as cpt]
[awesome-name.events :as evt]
[awesome-name.subs :as sub]
[awesome-name.views.shared :as shared]
[clojure.string :as cs]
[re-frame.core :as rf]
[reagent-mui.components :as mui]
[reagent-mui.icons.download :as icon-download]
[reagent-mui.icons.expand-more :as icon-expand-more]
[reagent-mui.icons.upload :as icon-upload]
[reagent-mui.icons.visibility :as icon-visibility]
[reagent-mui.icons.visibility-off :as icon-visibility-off]
[reagent.core :as r]))
(defn form
[]
(let [surname-err-msg @(rf/subscribe [::sub/name-errors :surname])
enable-four-pillars @(rf/subscribe [::sub/advanced-option :enable-four-pillars])
birthday @(rf/subscribe [::sub/combinations-page :birthday])]
[mui/grid {:container true :spacing 2 :sx {:margin-top "10px"}}
[mui/grid {:item true :xs 12}
[mui/text-field {:label "姓氏"
:value (or @(rf/subscribe [::sub/combinations-page :surname]) "")
:variant "outlined"
:error (boolean (seq surname-err-msg))
:on-change #(rf/dispatch-sync (conj [::evt/set-form-field [:surname]] (.. % -target -value)))
:helper-text surname-err-msg}]]
(when enable-four-pillars
[:<>
[mui/grid {:item true :xs 12}
[cpt/date-picker-field {:value-sub birthday
:on-change-evt #(rf/dispatch-sync [::evt/set-form-field [:birthday] %])
:label "生日"}]
[mui/typography {:sx {:color "red"}} "目前選其他年度的功能有問題,如有需求請先用輸入的"]]
[mui/grid {:item true :xs 4}
[mui/text-field {:value (or @(rf/subscribe [::sub/combinations-page :birth-hour]) "")
:label "出生時辰"
:select true
:full-width true
:disabled (nil? birthday)
:on-change #(rf/dispatch-sync (conj [::evt/set-form-field [:birth-hour]] (.. % -target -value)))}
(doall
(for [[option-idx [value label]] (map-indexed vector @(rf/subscribe [::sub/birth-hour-options]))]
[mui/menu-item {:key option-idx :value value} label]))]]])
[mui/grid {:item true :xs 12 :sm 3}
[mui/text-field {:value (or @(rf/subscribe [::sub/combinations-page :zodiac]) "")
:label "生肖"
:select true
:full-width true
:disabled enable-four-pillars
:on-change #(rf/dispatch-sync (conj [::evt/set-form-field [:zodiac]] (.. % -target -value)))}
(doall
(for [[option-idx [value label]] (map-indexed vector @(rf/subscribe [::sub/zodiac :select-options]))]
[mui/menu-item {:key option-idx :value value} label]))]]
[mui/grid {:item true :xs 12 :lg 3}
[mui/text-field {:value (or @(rf/subscribe [::sub/combinations-page :combination-idx]) "")
:label "分數"
:select true
:full-width true
:on-change #(rf/dispatch-sync (conj [::evt/set-form-field [:combination-idx]] (.. % -target -value)))}
(doall
(for [[option-idx comb] (map-indexed vector @(rf/subscribe [::sub/valid-combinations]))]
[mui/menu-item {:key option-idx :value option-idx} (:label comb)]))]]]))
(defn points-tab
[]
[cpt/tab-panel {:value "points"}
[mui/grid {:container true :spacing 2}
[mui/grid {:item true :xs 2}
[mui/text-field {:value (or @(rf/subscribe [::sub/advanced-option :min-81-pts]) 0)
:label "81數理分數低標"
:full-width true
:variant "outlined"
:on-change #(rf/dispatch-sync (conj [::evt/set-advanced-option :min-81-pts] (.. % -target -value)))}]]
[mui/grid {:item true :xs 3}
[mui/text-field {:value @(rf/subscribe [::sub/advanced-option :min-sancai-pts])
:label "三才分數低標"
:select true
:full-width true
:on-change #(rf/dispatch-sync (conj [::evt/set-advanced-option :min-sancai-pts] (.. % -target -value)))}
(doall
(for [[option-idx [value label]] (map-indexed vector @(rf/subscribe [::sub/sancai-luck-options]))]
[mui/menu-item {:key option-idx :value value} label]))]]]])
(defn given-name-tab
[{:keys [single-given-name]}]
[mui/grid {:container true :spacing 2}
[mui/grid {:item true :xs 12}
[mui/form-control-label
{:label "使用單名"
:control (r/as-element
[mui/switch {:checked single-given-name
:on-change #(rf/dispatch-sync (conj [::evt/set-advanced-option :single-given-name] (.. % -target -checked)))}])}]]])
(defn strokes-tab
[{:keys [strokes-to-remove]}]
[mui/grid {:container true :spacing 2}
(doall
(for [[idx strokes] (map-indexed vector @(rf/subscribe [::sub/dictionary-strokes]))]
[mui/grid {:item true :xs 1 :key idx}
[mui/form-control-label
{:label (str strokes)
:control (r/as-element
[mui/checkbox {:checked (boolean (strokes-to-remove strokes))
:on-change #(rf/dispatch-sync [::evt/update-strokes-to-remove strokes (.. % -target -checked)])}])}]]))])
(defn chars-tab
[{:keys [remove-chars click-to-remove use-default-taboo-characters chars-to-remove]}]
[mui/grid {:container true :spacing 2}
[mui/grid {:item true :xs 12}
[mui/form-control-label
{:label "刪除特定字"
:control (r/as-element
[mui/switch {:checked remove-chars
:on-change #(rf/dispatch-sync (conj [::evt/set-advanced-option :remove-chars] (.. % -target -checked)))}])}]]
(when remove-chars
[:<>
[mui/grid {:item true :xs 12 :sx {:margin-left "10px"}}
[mui/form-control-label
{:label "啟用點擊隱藏字"
:control (r/as-element
[mui/switch {:checked click-to-remove
:on-change #(rf/dispatch-sync (conj [::evt/set-advanced-option :click-to-remove (.. % -target -checked)]))}])}]]
[mui/grid {:item true :xs 12 :sx {:margin-left "10px"}}
[mui/form-control-label
{:label "載入預設禁字"
:control (r/as-element
[mui/switch {:checked use-default-taboo-characters
:on-change #(rf/dispatch-sync (conj [::evt/set-use-default-taboo-characters] (.. % -target -checked)))}])}]]
[mui/grid {:item true :xs 12 :sx {:margin-left "10px"}}
[mui/text-field {:value chars-to-remove
:variant "outlined"
:full-width true
:multiline true
:disabled (not remove-chars)
:on-change #(rf/dispatch-sync (conj [::evt/set-advanced-option :chars-to-remove] (.. % -target -value)))}]]])])
(defn four-pillars-tab
[{:keys [enable-four-pillars]}]
[mui/grid {:container true :spacing 2}
[mui/grid {:item true :xs 12}
[mui/form-control-label
{:label "計算八字五行"
:control (r/as-element
[mui/switch {:checked enable-four-pillars
:on-change #(rf/dispatch-sync (conj [::evt/set-advanced-option :enable-four-pillars] (.. % -target -checked)))}])}]]])
(defn import-export-tab
[]
[mui/grid {:container true :spacing 2}
(when-let [err-msg @(rf/subscribe [::sub/error :import])]
[mui/grid {:item true :xs 12}
[mui/form-helper-text {:error true :sx {:font-size "2rem"}} err-msg]])
[mui/grid {:item true}
[mui/button {:variant "outlined" :on-click #(rf/dispatch-sync [::evt/export])}
[icon-download/download]
"匯出"]]
[mui/grid {:item true}
[mui/button {:component "label"
:variant "outlined"
:start-icon (r/as-element [icon-upload/upload])}
"匯入"
[mui/input {:on-change #(evt/import-setting (first (.. % -target -files)))
:type "file"
:style {:display "none"}}]]]])
(defn advanced-option
[]
(let [advanced-option @(rf/subscribe [::sub/advanced-option])]
[mui/accordion {:sx {:margin-top "10px"}}
[mui/accordion-summary {:expand-icon (r/as-element [icon-expand-more/expand-more])
:aria-controls :adv-opt-content
:id :adv-opt-header
:sx {:background-color "darkblue"
:color "white"}}
[mui/typography "進階選項"]]
[mui/accordion-details
[cpt/tab-context {:value (:tab advanced-option)}
[cpt/tab-list {:on-change #(rf/dispatch-sync [::evt/set-advanced-option :tab %2])}
[mui/tab {:label "設定分數" :value "points"}]
[mui/tab {:label "單名" :value "given-name"}]
[mui/tab {:label "排除筆劃" :value "strokes"}]
[mui/tab {:label "設定禁字" :value "chars"}]
[mui/tab {:label "八字五行" :value "four-pillars"}]
[mui/tab {:label "匯出/匯入設定" :value "import-export"}]]
[cpt/tab-panel {:value "points"}
[points-tab]]
[cpt/tab-panel {:value "given-name"}
[given-name-tab advanced-option]]
[cpt/tab-panel {:value "strokes"}
[strokes-tab advanced-option]]
[cpt/tab-panel {:value "chars"}
[chars-tab advanced-option]]
[cpt/tab-panel {:value "four-pillars"}
[four-pillars-tab advanced-option]]
[cpt/tab-panel {:value "import-export"}
[import-export-tab]]]]]))
(defn zodiac-table
[{:keys [strokes]} enable-four-pillars]
(let [surname @(rf/subscribe [::sub/combinations-page :surname])
hide-zodiac-chars @(rf/subscribe [::sub/combinations-page :hide-zodiac-chars])
given-name-chars-count (if (:single-given-name @(rf/subscribe [::sub/advanced-option])) 1 2)]
[mui/grid {:item true :xs 11}
[:table {:width "100%" :style {:border-collapse "collapse"}}
[:tbody
[:tr
[:th {:width "15%" :style {:border-style "solid" :border-width "1px"}} "欄位"]
[:th {:width "70%" :style {:border-style "solid" :border-width "1px"} :col-span 2} "選字"]]
[:tr
[:td {:style {:border-style "solid" :border-width "1px"}}
"姓" [:br]
(str "筆劃:" (cs/join ", " (:surname strokes)))]
[:td {:col-span 2 :style {:border-style "solid" :border-width "1px"}}
surname]]
(doall
(for [idx (range given-name-chars-count)]
(let [{:keys [better normal worse]} @(rf/subscribe [::sub/preferred-characters idx])
hide-normal-chars (get-in hide-zodiac-chars [:normal idx])
hide-worse-chars (get-in hide-zodiac-chars [:worse idx])]
[:<> {:key idx}
[:tr
[:td {:row-span 3 :style {:border-style "solid" :border-width "1px"}}
(str "名(第" (inc idx) "字)") [:br]
(str "筆劃:" (get-in strokes [:given-name idx]))]
[:td {:width "15%" :style {:border-style "solid" :border-width "1px"}}
"生肖喜用"]
[:td {:style {:border-style "solid" :border-width "1px" :padding-top "15px" :padding-bottom "15px"}}
(doall
(for [[c-idx c] (map-indexed vector better)]
[:<> {:key c-idx}
[mui/typography {:variant :span :font-size "1.2rem" :on-click #(rf/dispatch-sync [::evt/add-chars-to-remove (.. % -target -textContent)])}
c]
(when enable-four-pillars
[shared/render-element @(rf/subscribe [::sub/character-element c])])
(when-not (= c-idx (-> better count dec))
[mui/typography {:variant :span :font-size "1.2rem"}
", "])]))]]
[:tr
[:td {:style {:border-style "solid" :border-width "1px"}}
"不喜不忌"
[mui/icon-button {:aria-label "vis-normal" :size "small" :on-click #(rf/dispatch-sync [::evt/set-form-field [:hide-zodiac-chars :normal idx] (not hide-normal-chars)])}
(if hide-normal-chars
[icon-visibility-off/visibility-off]
[icon-visibility/visibility])]]
[:td {:style {:border-style "solid" :border-width "1px" :padding-top "15px" :padding-bottom "15px"}}
(when-not hide-normal-chars
(doall
(for [[c-idx c] (map-indexed vector normal)]
[:<> {:key c-idx}
[mui/typography {:variant :span :font-size "1.2rem" :on-click #(rf/dispatch-sync [::evt/add-chars-to-remove (.. % -target -textContent)])}
c]
(when enable-four-pillars
[shared/render-element @(rf/subscribe [::sub/character-element c])])
(when-not (= c-idx (-> normal count dec))
[mui/typography {:variant :span :font-size "1.2rem"}
", "])])))]]
[:tr
[:td {:style {:border-style "solid" :border-width "1px"}}
"生肖忌用"
[mui/icon-button {:aria-label "vis-worse" :size "small" :on-click #(rf/dispatch-sync [::evt/set-form-field [:hide-zodiac-chars :worse idx] (not hide-worse-chars)])}
(if hide-worse-chars
[icon-visibility-off/visibility-off]
[icon-visibility/visibility])]]
[:td {:style {:border-style "solid" :border-width "1px" :padding-top "15px" :padding-bottom "15px"}}
(when-not hide-worse-chars
(doall
(for [[c-idx c] (map-indexed vector worse)]
[:<> {:key c-idx}
[mui/typography {:variant :span :font-size "1.2rem" :on-click #(rf/dispatch-sync [::evt/add-chars-to-remove (.. % -target -textContent)])}
c]
(when enable-four-pillars
[shared/render-element @(rf/subscribe [::sub/character-element c])])
(when-not (= c-idx (-> worse count dec))
[mui/typography {:variant :span :font-size "1.2rem"}
", "])])))]]])))]]]))
(defn main
[]
[:<>
[form]
(when-let [selected-combination @(rf/subscribe [::sub/selected-combination])]
(let [surname @(rf/subscribe [::sub/combinations-page :surname])
sancai-attrs-of-selected-combination @(rf/subscribe [::sub/sancai-attrs-of-selected-combination selected-combination])
eighty-one @(rf/subscribe [::sub/eighty-one])
enable-four-pillars @(rf/subscribe [::sub/advanced-option :enable-four-pillars])
four-pillars @(rf/subscribe [::sub/combinations-page :four-pillars])
elements @(rf/subscribe [::sub/combinations-page :elements])
element-ratio @(rf/subscribe [::sub/four-pillars-element-ratio])]
[mui/grid {:container true :spacing 2 :sx {:margin-top "10px"}}
[shared/sancai-calc selected-combination surname]
(when enable-four-pillars
[shared/four-pillars-elements four-pillars elements element-ratio])
[zodiac-table selected-combination enable-four-pillars]
[shared/sancai-table selected-combination sancai-attrs-of-selected-combination]
[shared/eighty-one-table selected-combination eighty-one]]))
[advanced-option]])
| null | https://raw.githubusercontent.com/kansetsu7/awesome_name/32d6d0f4c9a957d4739bb79d584d6298b4f6364e/src/awesome_name/views/combinations.cljs | clojure | (ns awesome-name.views.combinations
(:require
[awesome-name.component.core :as cpt]
[awesome-name.events :as evt]
[awesome-name.subs :as sub]
[awesome-name.views.shared :as shared]
[clojure.string :as cs]
[re-frame.core :as rf]
[reagent-mui.components :as mui]
[reagent-mui.icons.download :as icon-download]
[reagent-mui.icons.expand-more :as icon-expand-more]
[reagent-mui.icons.upload :as icon-upload]
[reagent-mui.icons.visibility :as icon-visibility]
[reagent-mui.icons.visibility-off :as icon-visibility-off]
[reagent.core :as r]))
(defn form
[]
(let [surname-err-msg @(rf/subscribe [::sub/name-errors :surname])
enable-four-pillars @(rf/subscribe [::sub/advanced-option :enable-four-pillars])
birthday @(rf/subscribe [::sub/combinations-page :birthday])]
[mui/grid {:container true :spacing 2 :sx {:margin-top "10px"}}
[mui/grid {:item true :xs 12}
[mui/text-field {:label "姓氏"
:value (or @(rf/subscribe [::sub/combinations-page :surname]) "")
:variant "outlined"
:error (boolean (seq surname-err-msg))
:on-change #(rf/dispatch-sync (conj [::evt/set-form-field [:surname]] (.. % -target -value)))
:helper-text surname-err-msg}]]
(when enable-four-pillars
[:<>
[mui/grid {:item true :xs 12}
[cpt/date-picker-field {:value-sub birthday
:on-change-evt #(rf/dispatch-sync [::evt/set-form-field [:birthday] %])
:label "生日"}]
[mui/typography {:sx {:color "red"}} "目前選其他年度的功能有問題,如有需求請先用輸入的"]]
[mui/grid {:item true :xs 4}
[mui/text-field {:value (or @(rf/subscribe [::sub/combinations-page :birth-hour]) "")
:label "出生時辰"
:select true
:full-width true
:disabled (nil? birthday)
:on-change #(rf/dispatch-sync (conj [::evt/set-form-field [:birth-hour]] (.. % -target -value)))}
(doall
(for [[option-idx [value label]] (map-indexed vector @(rf/subscribe [::sub/birth-hour-options]))]
[mui/menu-item {:key option-idx :value value} label]))]]])
[mui/grid {:item true :xs 12 :sm 3}
[mui/text-field {:value (or @(rf/subscribe [::sub/combinations-page :zodiac]) "")
:label "生肖"
:select true
:full-width true
:disabled enable-four-pillars
:on-change #(rf/dispatch-sync (conj [::evt/set-form-field [:zodiac]] (.. % -target -value)))}
(doall
(for [[option-idx [value label]] (map-indexed vector @(rf/subscribe [::sub/zodiac :select-options]))]
[mui/menu-item {:key option-idx :value value} label]))]]
[mui/grid {:item true :xs 12 :lg 3}
[mui/text-field {:value (or @(rf/subscribe [::sub/combinations-page :combination-idx]) "")
:label "分數"
:select true
:full-width true
:on-change #(rf/dispatch-sync (conj [::evt/set-form-field [:combination-idx]] (.. % -target -value)))}
(doall
(for [[option-idx comb] (map-indexed vector @(rf/subscribe [::sub/valid-combinations]))]
[mui/menu-item {:key option-idx :value option-idx} (:label comb)]))]]]))
(defn points-tab
[]
[cpt/tab-panel {:value "points"}
[mui/grid {:container true :spacing 2}
[mui/grid {:item true :xs 2}
[mui/text-field {:value (or @(rf/subscribe [::sub/advanced-option :min-81-pts]) 0)
:label "81數理分數低標"
:full-width true
:variant "outlined"
:on-change #(rf/dispatch-sync (conj [::evt/set-advanced-option :min-81-pts] (.. % -target -value)))}]]
[mui/grid {:item true :xs 3}
[mui/text-field {:value @(rf/subscribe [::sub/advanced-option :min-sancai-pts])
:label "三才分數低標"
:select true
:full-width true
:on-change #(rf/dispatch-sync (conj [::evt/set-advanced-option :min-sancai-pts] (.. % -target -value)))}
(doall
(for [[option-idx [value label]] (map-indexed vector @(rf/subscribe [::sub/sancai-luck-options]))]
[mui/menu-item {:key option-idx :value value} label]))]]]])
(defn given-name-tab
[{:keys [single-given-name]}]
[mui/grid {:container true :spacing 2}
[mui/grid {:item true :xs 12}
[mui/form-control-label
{:label "使用單名"
:control (r/as-element
[mui/switch {:checked single-given-name
:on-change #(rf/dispatch-sync (conj [::evt/set-advanced-option :single-given-name] (.. % -target -checked)))}])}]]])
(defn strokes-tab
[{:keys [strokes-to-remove]}]
[mui/grid {:container true :spacing 2}
(doall
(for [[idx strokes] (map-indexed vector @(rf/subscribe [::sub/dictionary-strokes]))]
[mui/grid {:item true :xs 1 :key idx}
[mui/form-control-label
{:label (str strokes)
:control (r/as-element
[mui/checkbox {:checked (boolean (strokes-to-remove strokes))
:on-change #(rf/dispatch-sync [::evt/update-strokes-to-remove strokes (.. % -target -checked)])}])}]]))])
(defn chars-tab
[{:keys [remove-chars click-to-remove use-default-taboo-characters chars-to-remove]}]
[mui/grid {:container true :spacing 2}
[mui/grid {:item true :xs 12}
[mui/form-control-label
{:label "刪除特定字"
:control (r/as-element
[mui/switch {:checked remove-chars
:on-change #(rf/dispatch-sync (conj [::evt/set-advanced-option :remove-chars] (.. % -target -checked)))}])}]]
(when remove-chars
[:<>
[mui/grid {:item true :xs 12 :sx {:margin-left "10px"}}
[mui/form-control-label
{:label "啟用點擊隱藏字"
:control (r/as-element
[mui/switch {:checked click-to-remove
:on-change #(rf/dispatch-sync (conj [::evt/set-advanced-option :click-to-remove (.. % -target -checked)]))}])}]]
[mui/grid {:item true :xs 12 :sx {:margin-left "10px"}}
[mui/form-control-label
{:label "載入預設禁字"
:control (r/as-element
[mui/switch {:checked use-default-taboo-characters
:on-change #(rf/dispatch-sync (conj [::evt/set-use-default-taboo-characters] (.. % -target -checked)))}])}]]
[mui/grid {:item true :xs 12 :sx {:margin-left "10px"}}
[mui/text-field {:value chars-to-remove
:variant "outlined"
:full-width true
:multiline true
:disabled (not remove-chars)
:on-change #(rf/dispatch-sync (conj [::evt/set-advanced-option :chars-to-remove] (.. % -target -value)))}]]])])
(defn four-pillars-tab
[{:keys [enable-four-pillars]}]
[mui/grid {:container true :spacing 2}
[mui/grid {:item true :xs 12}
[mui/form-control-label
{:label "計算八字五行"
:control (r/as-element
[mui/switch {:checked enable-four-pillars
:on-change #(rf/dispatch-sync (conj [::evt/set-advanced-option :enable-four-pillars] (.. % -target -checked)))}])}]]])
(defn import-export-tab
[]
[mui/grid {:container true :spacing 2}
(when-let [err-msg @(rf/subscribe [::sub/error :import])]
[mui/grid {:item true :xs 12}
[mui/form-helper-text {:error true :sx {:font-size "2rem"}} err-msg]])
[mui/grid {:item true}
[mui/button {:variant "outlined" :on-click #(rf/dispatch-sync [::evt/export])}
[icon-download/download]
"匯出"]]
[mui/grid {:item true}
[mui/button {:component "label"
:variant "outlined"
:start-icon (r/as-element [icon-upload/upload])}
"匯入"
[mui/input {:on-change #(evt/import-setting (first (.. % -target -files)))
:type "file"
:style {:display "none"}}]]]])
(defn advanced-option
[]
(let [advanced-option @(rf/subscribe [::sub/advanced-option])]
[mui/accordion {:sx {:margin-top "10px"}}
[mui/accordion-summary {:expand-icon (r/as-element [icon-expand-more/expand-more])
:aria-controls :adv-opt-content
:id :adv-opt-header
:sx {:background-color "darkblue"
:color "white"}}
[mui/typography "進階選項"]]
[mui/accordion-details
[cpt/tab-context {:value (:tab advanced-option)}
[cpt/tab-list {:on-change #(rf/dispatch-sync [::evt/set-advanced-option :tab %2])}
[mui/tab {:label "設定分數" :value "points"}]
[mui/tab {:label "單名" :value "given-name"}]
[mui/tab {:label "排除筆劃" :value "strokes"}]
[mui/tab {:label "設定禁字" :value "chars"}]
[mui/tab {:label "八字五行" :value "four-pillars"}]
[mui/tab {:label "匯出/匯入設定" :value "import-export"}]]
[cpt/tab-panel {:value "points"}
[points-tab]]
[cpt/tab-panel {:value "given-name"}
[given-name-tab advanced-option]]
[cpt/tab-panel {:value "strokes"}
[strokes-tab advanced-option]]
[cpt/tab-panel {:value "chars"}
[chars-tab advanced-option]]
[cpt/tab-panel {:value "four-pillars"}
[four-pillars-tab advanced-option]]
[cpt/tab-panel {:value "import-export"}
[import-export-tab]]]]]))
(defn zodiac-table
[{:keys [strokes]} enable-four-pillars]
(let [surname @(rf/subscribe [::sub/combinations-page :surname])
hide-zodiac-chars @(rf/subscribe [::sub/combinations-page :hide-zodiac-chars])
given-name-chars-count (if (:single-given-name @(rf/subscribe [::sub/advanced-option])) 1 2)]
[mui/grid {:item true :xs 11}
[:table {:width "100%" :style {:border-collapse "collapse"}}
[:tbody
[:tr
[:th {:width "15%" :style {:border-style "solid" :border-width "1px"}} "欄位"]
[:th {:width "70%" :style {:border-style "solid" :border-width "1px"} :col-span 2} "選字"]]
[:tr
[:td {:style {:border-style "solid" :border-width "1px"}}
"姓" [:br]
(str "筆劃:" (cs/join ", " (:surname strokes)))]
[:td {:col-span 2 :style {:border-style "solid" :border-width "1px"}}
surname]]
(doall
(for [idx (range given-name-chars-count)]
(let [{:keys [better normal worse]} @(rf/subscribe [::sub/preferred-characters idx])
hide-normal-chars (get-in hide-zodiac-chars [:normal idx])
hide-worse-chars (get-in hide-zodiac-chars [:worse idx])]
[:<> {:key idx}
[:tr
[:td {:row-span 3 :style {:border-style "solid" :border-width "1px"}}
(str "名(第" (inc idx) "字)") [:br]
(str "筆劃:" (get-in strokes [:given-name idx]))]
[:td {:width "15%" :style {:border-style "solid" :border-width "1px"}}
"生肖喜用"]
[:td {:style {:border-style "solid" :border-width "1px" :padding-top "15px" :padding-bottom "15px"}}
(doall
(for [[c-idx c] (map-indexed vector better)]
[:<> {:key c-idx}
[mui/typography {:variant :span :font-size "1.2rem" :on-click #(rf/dispatch-sync [::evt/add-chars-to-remove (.. % -target -textContent)])}
c]
(when enable-four-pillars
[shared/render-element @(rf/subscribe [::sub/character-element c])])
(when-not (= c-idx (-> better count dec))
[mui/typography {:variant :span :font-size "1.2rem"}
", "])]))]]
[:tr
[:td {:style {:border-style "solid" :border-width "1px"}}
"不喜不忌"
[mui/icon-button {:aria-label "vis-normal" :size "small" :on-click #(rf/dispatch-sync [::evt/set-form-field [:hide-zodiac-chars :normal idx] (not hide-normal-chars)])}
(if hide-normal-chars
[icon-visibility-off/visibility-off]
[icon-visibility/visibility])]]
[:td {:style {:border-style "solid" :border-width "1px" :padding-top "15px" :padding-bottom "15px"}}
(when-not hide-normal-chars
(doall
(for [[c-idx c] (map-indexed vector normal)]
[:<> {:key c-idx}
[mui/typography {:variant :span :font-size "1.2rem" :on-click #(rf/dispatch-sync [::evt/add-chars-to-remove (.. % -target -textContent)])}
c]
(when enable-four-pillars
[shared/render-element @(rf/subscribe [::sub/character-element c])])
(when-not (= c-idx (-> normal count dec))
[mui/typography {:variant :span :font-size "1.2rem"}
", "])])))]]
[:tr
[:td {:style {:border-style "solid" :border-width "1px"}}
"生肖忌用"
[mui/icon-button {:aria-label "vis-worse" :size "small" :on-click #(rf/dispatch-sync [::evt/set-form-field [:hide-zodiac-chars :worse idx] (not hide-worse-chars)])}
(if hide-worse-chars
[icon-visibility-off/visibility-off]
[icon-visibility/visibility])]]
[:td {:style {:border-style "solid" :border-width "1px" :padding-top "15px" :padding-bottom "15px"}}
(when-not hide-worse-chars
(doall
(for [[c-idx c] (map-indexed vector worse)]
[:<> {:key c-idx}
[mui/typography {:variant :span :font-size "1.2rem" :on-click #(rf/dispatch-sync [::evt/add-chars-to-remove (.. % -target -textContent)])}
c]
(when enable-four-pillars
[shared/render-element @(rf/subscribe [::sub/character-element c])])
(when-not (= c-idx (-> worse count dec))
[mui/typography {:variant :span :font-size "1.2rem"}
", "])])))]]])))]]]))
(defn main
[]
[:<>
[form]
(when-let [selected-combination @(rf/subscribe [::sub/selected-combination])]
(let [surname @(rf/subscribe [::sub/combinations-page :surname])
sancai-attrs-of-selected-combination @(rf/subscribe [::sub/sancai-attrs-of-selected-combination selected-combination])
eighty-one @(rf/subscribe [::sub/eighty-one])
enable-four-pillars @(rf/subscribe [::sub/advanced-option :enable-four-pillars])
four-pillars @(rf/subscribe [::sub/combinations-page :four-pillars])
elements @(rf/subscribe [::sub/combinations-page :elements])
element-ratio @(rf/subscribe [::sub/four-pillars-element-ratio])]
[mui/grid {:container true :spacing 2 :sx {:margin-top "10px"}}
[shared/sancai-calc selected-combination surname]
(when enable-four-pillars
[shared/four-pillars-elements four-pillars elements element-ratio])
[zodiac-table selected-combination enable-four-pillars]
[shared/sancai-table selected-combination sancai-attrs-of-selected-combination]
[shared/eighty-one-table selected-combination eighty-one]]))
[advanced-option]])
|
|
485e4b9a3d80b63d05a8ef1e0d380dc5b67aa0461f960c9100596b2762cd4e22 | apache/couchdb-rebar | dummy_sup.erl | -module(dummy_sup).
-behaviour(supervisor).
-export([start_link/0]).
-export([init/1]).
start_link() ->
supervisor:start_link({local, ?MODULE}, ?MODULE, []).
init([]) ->
Dummy = {dummy_server,
{dummy_server, start_link, []},
permanent, 5000, worker, [dummy_server]},
{ok, {{one_for_one, 10, 10}, [Dummy]}}.
| null | https://raw.githubusercontent.com/apache/couchdb-rebar/8578221c20d0caa3deb724e5622a924045ffa8bf/test/upgrade_project/apps/dummy/src/dummy_sup.erl | erlang | -module(dummy_sup).
-behaviour(supervisor).
-export([start_link/0]).
-export([init/1]).
start_link() ->
supervisor:start_link({local, ?MODULE}, ?MODULE, []).
init([]) ->
Dummy = {dummy_server,
{dummy_server, start_link, []},
permanent, 5000, worker, [dummy_server]},
{ok, {{one_for_one, 10, 10}, [Dummy]}}.
|
|
11fd2643f91504a21091c9d8144e765b19de2a185082f44035a5bf0b729a8ab2 | Drup/dowsing | Timer.ml | type t = Float.t ref
let make () = ref 0.
let get t = !t
let start t =
t := Unix.gettimeofday ()
let stop t =
t := Unix.gettimeofday () -. !t
| null | https://raw.githubusercontent.com/Drup/dowsing/6a7b6a9d1206689da45f7030c700c58a0b3c3d8a/lib/utils/Timer.ml | ocaml | type t = Float.t ref
let make () = ref 0.
let get t = !t
let start t =
t := Unix.gettimeofday ()
let stop t =
t := Unix.gettimeofday () -. !t
|
|
05c9c690e464d43176167a06d34a3bd2002637aeac9312461f0a38d68a2176d7 | sjl/advent | 2015.lisp |
(ql:quickload "beef")
(ql:quickload "alexandria")
(ql:quickload "split-sequence")
(ql:quickload "cl-arrows")
(ql:quickload "fset")
(ql:quickload "cl-ppcre")
(ql:quickload "ironclad")
(ql:quickload "smug")
(ql:quickload "bit-smasher")
(ql:quickload "optima")
(defpackage #:advent
(:use #:cl)
(:use #:cl-arrows)
(:use #:split-sequence)
(:use #:smug))
(in-package #:advent)
(declaim (optimize (debug 3)))
;;;; Day 1
(defun instruction-to-num (ch)
(cond
((eql ch #\() 1)
((eql ch #\)) -1)
(t 0)))
(defun advent-1-1 ()
(loop :for c :across (beef:slurp "data/1")
:sum (instruction-to-num c)))
(defun advent-1-2 ()
(loop :for c :across (beef:slurp "data/1")
:sum (instruction-to-num c) :into floor
:sum 1
:until (= floor -1)))
;;;; Day 2
(defun advent-2-data ()
(->> (beef:slurp "data/2")
beef:trim-whitespace-right
beef:split-lines
(mapcar (lambda (s)
(->> s
(split-sequence #\x)
(mapcar #'parse-integer))))))
(defun advent-2-1 ()
(loop :for dims :in (advent-2-data)
:for (w h l) = dims
:for sides = (list (* w h)
(* w l)
(* h l))
:for paper = (* 2 (apply #'+ sides))
:for slack = (apply #'min sides)
:sum (+ paper slack)))
(defun advent-2-2 ()
(loop :for dims :in (advent-2-data)
:for (w h l) = dims
:for sides = (list (* 2 (+ w h))
(* 2 (+ w l))
(* 2 (+ h l)))
:for ribbon = (apply #'min sides)
:for bow = (apply #'* dims)
:sum (+ ribbon bow)))
;;;; Day 3
(defun advent-3-data ()
(beef:trim-whitespace (beef:slurp "data/3")))
(defun instruction-to-offsets (instruction)
(case instruction
(#\> '(1 0))
(#\< '(-1 0))
(#\^ '(0 1))
(#\v '(0 -1))))
(defun step-santa (loc dir)
(destructuring-bind (x y) loc
(destructuring-bind (dx dy) (instruction-to-offsets dir)
(list (+ x dx) (+ y dy)))))
(defun houses (data)
(loop
:with loc = '(0 0)
:with visited = (fset:set '(0 0))
:for dir :across data
:do (setq loc (step-santa loc dir))
:do (fset:includef visited loc)
:finally (return visited)))
(defun advent-3-1 (data)
(fset:size (houses data)))
(defun advent-3-2 (data)
(fset:size
(fset:union
; come directly at me
(houses (ppcre:regex-replace-all "(.)." data "\\1"))
(houses (ppcre:regex-replace-all ".(.)" data "\\1")))))
;;;; Day 4
(defun advent-4-data ()
"ckczppom")
(defun md5 (str)
(ironclad:byte-array-to-hex-string
(ironclad:digest-sequence :md5
(ironclad:ascii-string-to-byte-array str))))
(defun mine (data zeroes)
(let ((target (apply #'concatenate 'string
(loop :repeat zeroes :collect "0"))))
(loop :for i :upfrom 1
:for hash = (->> i
prin1-to-string
(concatenate 'string data)
md5)
:until (equal target (subseq hash 0 zeroes))
:finally (return i))))
(defun advent-4-1 (data)
(mine data 5))
(defun advent-4-2 (data)
(mine data 6))
;;;; Day 5
(defun advent-5-data ()
(-> "data/5"
beef:slurp
beef:trim-whitespace-right
beef:split-lines))
(defun join-strings (strings delim)
"Join strings into a single string with the given delimiter string interleaved.
Delim must not contain a ~.
"
(format nil (concatenate 'string "~{~A~^" delim "~}") strings))
(defparameter *bad-pairs* '("ab" "cd" "pq" "xy"))
(defun count-vowels (s)
(length (ppcre:regex-replace-all "[^aeiou]" s "")))
(defun has-run (s)
(when (ppcre:scan "(.)\\1" s) t))
(defun has-bad (s)
(when (ppcre:scan (join-strings *bad-pairs* "|") s) t))
(defun is-nice (s)
(and (>= (count-vowels s) 3)
(has-run s)
(not (has-bad s))))
(defun advent-5-1 (data)
(count-if #'is-nice data))
(defun has-run-2 (s)
(when (ppcre:scan "(..).*\\1" s) t))
(defun has-repeat (s)
(when (ppcre:scan "(.).\\1" s) t))
(defun is-nice-2 (s)
(and (has-run-2 s)
(has-repeat s)))
(defun advent-5-2 (data)
(count-if #'is-nice-2 data))
;;;; Day 6
(defun advent-6-data ()
(beef:slurp-lines "data/6" :ignore-trailing-newline t))
(defmacro loop-array (arr name &rest body)
(let ((i (gensym "index")))
`(loop :for ,i :below (array-total-size ,arr)
:for ,name = (row-major-aref ,arr ,i)
,@body)))
(defun parse-indexes (s)
(->> s
(split-sequence #\,)
(mapcar #'parse-integer)))
(defun flip (b)
(if (zerop b) 1 0))
(defun parse-line (line)
(let ((parts (split-sequence #\space line)))
(list (parse-indexes (beef:index parts -3))
(parse-indexes (beef:index parts -1))
(cond
((equal (car parts) "toggle") :toggle)
((equal (cadr parts) "on") :on)
((equal (cadr parts) "off") :off)
(t (error "Unknown operation!"))))))
(defmacro loop-square (r c from-row from-col to-row to-col &rest body)
`(loop :for ,r :from ,from-row :to ,to-row
:do (loop :for ,c :from ,from-col :to ,to-col
,@body)))
(defun advent-6-1 (data)
(let ((lights (make-array '(1000 1000) :element-type 'bit)))
(loop
:for line :in data
:for ((from-row from-col) (to-row to-col) operation) = (parse-line line)
:do (loop-square
r c from-row from-col to-row to-col
:do (setf (bit lights r c)
(case operation
(:toggle (flip (bit lights r c)))
(:on 1)
(:off 0)
(t 0)))))
(loop-array lights b
:sum b)))
(defun advent-6-2 (data)
(let ((lights (make-array '(1000 1000) :element-type 'integer)))
(loop
:for line :in data
:for ((from-row from-col) (to-row to-col) operation) = (parse-line line)
:do (loop-square
r c from-row from-col to-row to-col
:do (case operation
(:toggle (incf (aref lights r c) 2))
(:on (incf (aref lights r c)))
(:off (when (not (zerop (aref lights r c)))
(decf (aref lights r c)))))))
(loop-array lights b
:sum b)))
;;;; Day 7
(defun advent-7-data ()
(beef:slurp-lines "data/7" :ignore-trailing-newline t))
(defun advent-7-2-data ()
(beef:slurp-lines "data/7-2" :ignore-trailing-newline t))
(defun int->bits (i)
(bitsmash:bits<- (format nil "~4,'0X" i)))
(defun bit-lshift (bit-array distance)
(replace (make-array (length bit-array) :element-type 'bit)
bit-array
:start1 0
:start2 (bitsmash:int<- distance)))
(defun bit-rshift (bit-array distance)
(let ((width (length bit-array))
(distance (bitsmash:int<- distance)))
(replace (make-array width :element-type 'bit)
bit-array
:start1 distance
:end2 (- width distance))))
(defun .zero-or-more (parser)
(.plus (.let* ((x parser)
(xs (.zero-or-more parser)))
(.identity (cons x xs)))
(.identity ())))
(defun .one-or-more (parser)
(.let* ((x parser)
(y (.zero-or-more parser)))
(.identity (cons x y))))
(defun parse-7 (line)
(labels ((.whitespace ()
(.first (.one-or-more (.is 'member '(#\space #\tab)))))
(.arrow ()
(.first (.string= "->")))
(.number ()
(.let* ((digits (.first (.one-or-more (.is 'digit-char-p)))))
(.identity (parse-integer (concatenate 'string digits)))))
(.wire ()
(.let* ((chars (.first (.one-or-more (.is 'lower-case-p)))))
(.identity (concatenate 'string chars))))
(.source ()
(.or (.wire) (.number)))
(.string-choice (strs)
(if (not strs)
(.fail)
(.or (.string= (car strs))
(.string-choice (cdr strs)))))
(.dest ()
(.progn (.whitespace) (.arrow) (.whitespace)
(.wire)))
(.constant-source ()
(.let* ((val (.source)))
(.identity (list #'identity (list val)))))
(.binary-op ()
(let ((ops '(("AND" . bit-and)
("OR" . bit-ior)
("LSHIFT" . bit-lshift)
("RSHIFT" . bit-rshift))))
(.let* ((name (.string-choice (mapcar #'car ops))))
(.identity (cdr (assoc name ops :test #'equal))))))
(.binary-source ()
(.let* ((left (.source))
(_ (.whitespace))
(op (.binary-op))
(_ (.whitespace))
(right (.source)))
(.identity (list op (list left right)))))
(.unary-op ()
(.let* ((_ (.string= "NOT")))
(.identity #'bit-not)))
(.unary-source ()
(.let* ((op (.unary-op))
(_ (.whitespace))
(source (.source)))
(.identity (list op (list source)))))
(.instruction ()
(.let* ((source (.or (.binary-source)
(.unary-source)
(.constant-source)))
(dest (.dest)))
(.identity (concatenate 'list source (list dest))))))
(parse (.instruction) line)))
(defun advent-7-1 (data)
(let ((circuit (make-hash-table :test #'equal))
(commands (mapcar #'parse-7 data)))
(labels ((retrieve (source)
(cond
((stringp source) (gethash source circuit))
((integerp source) (int->bits source))
(t (error "what?"))))
(ready (args)
(every #'identity args))
(perform (fn args dest)
(setf (gethash dest circuit)
(apply fn args)))
(try-command (command)
"If the command is ready to go, run it and return nil. Otherwise,
return the command itself."
(destructuring-bind (fn args dest) command
(let ((vals (mapcar #'retrieve args)))
(if (ready vals)
(progn
(perform fn vals dest)
nil)
command)))))
(loop :while commands
:do (setf commands
(loop :for command :in commands
:when (try-command command)
:collect :it)))
(bitsmash:bits->int (gethash "a" circuit)))))
;;;; Day 8
(defun advent-8-data ()
(beef:slurp-lines "data/8" :ignore-trailing-newline t))
(defconstant +backslash+ #\\ )
(defconstant +quote+ #\" )
(defun parse-8 (line)
(labels ((.hex-digit ()
(.or
(.is #'digit-char-p)
(.is #'member '(#\a #\b #\c #\d #\e #\f))))
(.hex-escape ()
(.let* ((_ (.char= #\x))
(a (.hex-digit))
(b (.hex-digit)))
(.identity
(->> (format nil "~A~A" a b)
bitsmash:hex->int
code-char))))
(.escaped-char ()
(.progn
(.char= +backslash+)
(.or (.char= +backslash+)
(.char= +quote+)
(.hex-escape))))
(.normal-char ()
(.is-not 'member (list +backslash+ +quote+)))
(.string-char ()
(.or (.normal-char)
(.escaped-char)))
(.full-string ()
(.prog2
(.char= +quote+)
(.first (.zero-or-more (.string-char)))
(.char= +quote+))))
(parse (.full-string) line)))
(defun .wrap (fn parser)
(.let* ((v parser))
(.identity (funcall fn v))))
(defun parse-8-2 (line)
(labels ((.special-char ()
(.let* ((ch (.or (.char= +backslash+)
(.char= +quote+))))
(.identity (list +backslash+ ch))))
(.normal-char ()
(.wrap #'list
(.is-not 'member (list +backslash+ +quote+))))
(.string-char ()
(.or (.normal-char)
(.special-char)))
(.full-string ()
(.let* ((chars (.zero-or-more (.string-char))))
(.identity (apply #'concatenate 'list chars)))))
(append (list +quote+)
(parse (.full-string) line)
(list +quote+))))
(defun advent-8-1 (data)
(loop :for line :in data
:for chars = (parse-8 line)
:sum (- (length line)
(length chars))))
(defun advent-8-2 (data)
(loop :for line :in data
:for chars = (parse-8-2 line)
:sum (- (length chars)
(length line))))
;;;; Day 9
(defun advent-9-data ()
(beef:slurp-lines "data/9" :ignore-trailing-newline t))
Thanks
;
(defun permutations (bag)
"Return a list of all the permutations of the input."
If the input is nil , there is only one permutation :
;; nil itself
(if (null bag)
'(())
;; Otherwise, take an element, e, out of the bag.
;; Generate all permutations of the remaining elements,
;; And add e to the front of each of these.
;; Do this for all possible e to generate all permutations.
(mapcan #'(lambda (e)
(mapcar #'(lambda (p) (cons e p))
(permutations
(remove e bag :count 1 :test #'eq))))
bag)))
(defun advent-9 (data)
(let ((distances (make-hash-table :test #'equal)))
(loop :for line :in data
:for (a to b _ dist) = (split-sequence #\space line)
:for distance = (parse-integer dist)
:do (progn
(setf (gethash (cons a b) distances) distance)
(setf (gethash (cons b a) distances) distance)))
(labels ((score-route (route)
(optima:match route
((list _) 0)
((list* a b _) (+ (gethash (cons a b) distances)
(score-route (cdr route))))))
(dedupe (l)
(remove-duplicates l :test #'equal)))
(loop :for route :in (->> distances
beef:hash-keys
(mapcar #'car)
dedupe
permutations)
:for score = (score-route route)
:minimizing score :into min-dist
:maximizing score :into max-dist
:finally (return (cons min-dist max-dist))))))
(defmethod print-object ((object hash-table) stream)
(format stream "#HASH{~%~{~{ (~s : ~s)~}~%~}}"
(loop for key being the hash-keys of object
using (hash-value value)
collect (list key value))))
;;;; Day 10
(defun advent-10-data ()
"1321131112")
(defun look-and-say (seq)
(let ((runs (list))
(len 1)
(current -1))
(flet ((mark-run ()
(setf runs (cons current (cons len runs)))))
(loop :for n :in seq
:do (if (= current n)
(incf len)
(progn
(when (not (= -1 current))
(mark-run))
(setf len 1)
(setf current n)))
:finally (mark-run))
(reverse runs))))
(defun iterate (n f data)
(declare (optimize speed (debug 0)))
(dotimes (_ n)
(setf data (funcall f data)))
data)
(defun las-to-list (s)
(loop :for digit :across s
:collect (-> digit string parse-integer)))
(defun advent-10-1 (data)
(length (iterate 40 #'look-and-say (las-to-list data))))
(defun advent-10-2 (data)
(length (iterate 50 #'look-and-say (las-to-list data))))
;;;; Day 11
(defun advent-11-data ()
"vzbxkghb")
(defparameter base 26)
(defparameter ascii-alpha-start (char-code #\a))
(defun num-to-char (n)
(code-char (+ n ascii-alpha-start)))
(defun char-to-num (ch)
(- (char-code ch) ascii-alpha-start))
(defmacro loop-window (seq width binding-form &rest body)
(let ((i (gensym "IGNORE"))
(s (gensym "SEQ"))
(n (gensym "WIDTH"))
(tail (gensym "TAIL")))
`(let ((,s ,seq)
(,n ,width))
(loop :for ,i :upto (- (length ,s) ,n)
:for ,tail :on ,s
:for ,binding-form = (subseq ,tail 0 ,n)
,@body))))
(defun is-straight-3 (l)
(destructuring-bind (a b c) l
(and (= 1 (- b a))
(= 1 (- c b)))))
(defun has-straight-3 (nums)
(loop-window nums 3 triplet
:thereis (is-straight-3 triplet)))
(defparameter bad-chars
(mapcar #'char-to-num '(#\i #\l #\o)))
(defun no-bad (nums)
(loop :for bad :in bad-chars
:never (find bad nums)))
(defun two-pairs (nums)
(-> nums
(loop-window 2 (a b)
:when (= a b)
:collect a)
remove-duplicates
length
(>= 2)))
(defun valid (nums)
(and (has-straight-3 nums)
(no-bad nums)
(two-pairs nums)
nums))
(defun incr-nums (nums)
(labels ((inc-mod (x)
(mod (1+ x) base))
(inc (nums)
(if (not nums)
'(1)
(let ((head (inc-mod (car nums))))
(if (zerop head)
(cons head (inc (cdr nums)))
(cons head (cdr nums)))))))
(reverse (inc (reverse nums)))))
(defun advent-11-1 (data)
(flet ((chars-to-string (chs)
(apply #'concatenate 'string (mapcar #'string chs)))
(nums-to-chars (nums)
(mapcar #'num-to-char nums))
(string-to-nums (str)
(loop :for ch :across str
:collect (char-to-num ch))))
(-> (loop :for pw = (incr-nums (string-to-nums data))
:then (incr-nums pw)
:thereis (valid pw))
nums-to-chars
chars-to-string)))
;;;; Day 12
(defun advent-12-data ()
(beef:trim-whitespace (beef:slurp "data/12")))
(defun parse-json (s)
(labels ((.number ()
(.let* ((negation (.optional (.char= #\-)))
(digits (.first (.one-or-more (.is 'digit-char-p)))))
(.identity (let ((i (parse-integer (concatenate 'string digits)))
(c (if negation -1 1)))
(* i c)))))
(.string-char ()
(.wrap #'list (.is-not 'member (list +quote+))))
(.string-guts ()
(.let* ((chars (.zero-or-more (.string-char))))
(.identity (apply #'concatenate 'string chars))))
(.string ()
(.prog2
(.char= +quote+)
(.string-guts)
(.char= +quote+)))
(.map-pair ()
(.let* ((key (.string))
(_ (.char= #\:))
(value (.expression)))
(.identity (cons key value))))
(.map-guts ()
(.or
(.let* ((p (.map-pair))
(_ (.char= #\,))
(remaining (.map-guts)))
(.identity (cons p remaining)))
(.wrap #'list (.map-pair))
(.identity '())))
(.map ()
(.prog2
(.char= #\{)
(.wrap (lambda (v) (cons :map v))
(.map-guts))
(.char= #\})))
(.array-guts ()
(.or
(.let* ((item (.expression))
(_ (.char= #\,))
(remaining (.array-guts)))
(.identity (cons item remaining)))
(.wrap #'list (.expression))
(.identity '())))
(.array ()
(.prog2
(.char= #\[)
(.wrap (lambda (v) (cons :array v))
(.array-guts))
(.char= #\])))
(.expression ()
(.or (.array)
(.map)
(.string)
(.number))))
(parse (.expression) s)))
(defun walk-sum (v)
(cond
((not v) 0)
((typep v 'integer) v)
((typep v 'string) 0)
((eql (car v) :array) (loop :for value in (cdr v)
:sum (walk-sum value)))
((eql (car v) :map) (loop :for (key . value) :in (cdr v)
:sum (walk-sum value)))
(:else (error (format nil "wat? ~a" v)))))
(defun walk-sum-2 (v)
(cond
((not v) 0)
((typep v 'integer) v)
((typep v 'string) 0)
((eql (car v) :array) (loop :for value in (cdr v)
:sum (walk-sum-2 value)))
((eql (car v) :map)
(if (member "red" (mapcar #'cdr (cdr v))
:test #'equal)
0
(loop :for (key . value) :in (cdr v)
:sum (walk-sum-2 value))))
(:else (error (format nil "wat? ~a" v)))))
(defun advent-12-1 (data)
(walk-sum (parse-json data)))
(defun advent-12-2 (data)
(walk-sum-2 (parse-json data)))
;;;; Day 13
(defun advent-13-data ()
(beef:slurp-lines "data/13" :ignore-trailing-newline t))
(defvar *wat* nil)
(defmacro map-when (test fn val &rest args)
(let ((v (gensym "VALUE")))
`(let ((,v ,val))
(if ,test
(apply ,fn ,v ,args)
,v))))
(defun split-lines-13 (lines)
(loop :for line :in lines
:collect (ppcre:register-groups-bind
(a dir amount b)
("(\\w+) would (gain|lose) (\\d+) .*? next to (\\w+)."
line)
(list a b (map-when (equal "lose" dir)
#'-
(parse-integer amount))))))
(defun rate-seating (vals arrangement)
(labels ((find-val (a b)
(or (gethash (cons a b) vals) 0))
(rate-one-direction (arr)
(+ (loop-window arr 2 (a b) :sum (find-val a b))
(find-val (car (last arr)) (car arr)))))
(+ (rate-one-direction arrangement)
(rate-one-direction (reverse arrangement)))))
(defun advent-13-1 (data)
(let* ((tups (split-lines-13 data))
(attendees (remove-duplicates (mapcar #'car tups) :test #'equal))
(vals (make-hash-table :test #'equal)))
(loop :for (a b val) :in tups
:do (setf (gethash (cons a b) vals) val))
(loop :for arrangement :in (permutations attendees)
:maximize (rate-seating vals arrangement))))
(defun advent-13-2 (data)
(let* ((tups (split-lines-13 data))
(attendees (cons "Self" (remove-duplicates (mapcar #'car tups) :test #'equal)))
(vals (make-hash-table :test #'equal)))
(loop :for (a b val) :in tups
:do (setf (gethash (cons a b) vals) val))
(loop :for arrangement :in (permutations attendees)
:maximize (rate-seating vals arrangement))))
Day 14
(defun advent-14-data ()
(beef:slurp-lines "data/14" :ignore-trailing-newline t))
(defun tick (deer)
(destructuring-bind
(name speed sprint-period rest-period traveled currently remaining)
deer
(let ((remaining (1- remaining)))
(if (equal currently :resting)
(list name speed sprint-period rest-period
traveled
(if (zerop remaining) :sprinting :resting)
(if (zerop remaining) sprint-period remaining))
(list name speed sprint-period rest-period
(+ traveled speed)
(if (zerop remaining) :resting :sprinting)
(if (zerop remaining) rest-period remaining))))))
(defun parse-deers (lines)
(loop :for line :in lines
:collect (ppcre:register-groups-bind
(name speed sprint-period rest-period)
("(\\w+) can fly (\\d+) km/s for (\\d+) .* (\\d+) seconds."
line)
(list name
(parse-integer speed)
(parse-integer sprint-period)
(parse-integer rest-period)
0
:sprinting
(parse-integer sprint-period)))))
(defun find-leaders (deers)
(let ((dist (reduce #'max deers :key (beef:partial #'nth 4))))
(remove-if-not (lambda (deer)
(= dist (nth 4 deer)))
deers)))
(defun advent-14-1 (data n)
(apply #'max
(loop :for i :upto n
:for deers := (parse-deers data) :then (mapcar #'tick deers)
:finally (return (mapcar (beef:partial #'nth 4) deers)))))
(defun advent-14-2 (data n)
(let ((scores (make-hash-table :test #'equal))
(deers (parse-deers data)))
(loop :for (name) :in deers
:do (setf (gethash name scores) 0))
(loop :for i :upto n
:do (setf deers (mapcar #'tick deers))
:do (loop :for (name) :in (find-leaders deers)
:do (incf (gethash name scores))))
(apply #'max (beef:hash-values scores))))
;;;; Day 15
(defun advent-15-data ()
(beef:slurp-lines "data/15" :ignore-trailing-newline t))
(defun split-ingredients (line)
(ppcre:register-groups-bind
(name (#'parse-integer capacity durability flavor texture calories))
("(\\w+): capacity (-?\\d+), durability (-?\\d+), flavor (-?\\d+), texture (-?\\d+), calories (-?\\d+)"
line)
(list name capacity durability flavor texture calories)))
(defun calc-contribution (ingr amount)
(cons (car ingr)
(mapcar (beef:partial #'* amount)
(cdr ingr))))
(defun calc-contributions (ingrs alist)
(mapcar #'calc-contribution ingrs alist))
(defun sum-totals (ingrs)
(->> ingrs
(mapcar #'cdr)
(apply #'mapcar #'+)
(mapcar (lambda (x) (if (< x 0) 0 x)))))
(defun advent-15-1 (data)
(let ((ingredients (mapcar #'split-ingredients data))
(limit 100)
(amounts (list)))
; fuckin lol
(loop :for a :upto limit :do
(loop :for b :upto (- limit a) :do
(loop :for c :upto (- limit a b) :do
(setf amounts
(cons (list a b c (- limit a b c))
amounts)))))
(loop :for alist :in amounts
:maximize (->> alist
(calc-contributions ingredients)
sum-totals
butlast
(apply #'*)))))
(defun advent-15-2 (data)
(let ((ingredients (mapcar #'split-ingredients data))
(limit 100)
(amounts (list)))
; fuckin lol
(loop :for a :upto limit :do
(loop :for b :upto (- limit a) :do
(loop :for c :upto (- limit a b) :do
(setf amounts
(cons (list a b c (- limit a b c))
amounts)))))
(loop :for alist :in amounts
:for val = (->> alist
(calc-contributions ingredients)
sum-totals)
:when (= (car (last val)) 500)
:maximize (apply #'* (butlast val)))))
;;;; Scratch
#+comment
(advent-15-2 (advent-15-data))
| null | https://raw.githubusercontent.com/sjl/advent/9c8c7f5a874678280244a8f7b865db49b907c64c/src/old/2015/2015.lisp | lisp | Day 1
Day 2
Day 3
come directly at me
Day 4
Day 5
Day 6
Day 7
Day 8
Day 9
nil itself
Otherwise, take an element, e, out of the bag.
Generate all permutations of the remaining elements,
And add e to the front of each of these.
Do this for all possible e to generate all permutations.
Day 10
Day 11
Day 12
Day 13
Day 15
fuckin lol
fuckin lol
Scratch |
(ql:quickload "beef")
(ql:quickload "alexandria")
(ql:quickload "split-sequence")
(ql:quickload "cl-arrows")
(ql:quickload "fset")
(ql:quickload "cl-ppcre")
(ql:quickload "ironclad")
(ql:quickload "smug")
(ql:quickload "bit-smasher")
(ql:quickload "optima")
(defpackage #:advent
(:use #:cl)
(:use #:cl-arrows)
(:use #:split-sequence)
(:use #:smug))
(in-package #:advent)
(declaim (optimize (debug 3)))
(defun instruction-to-num (ch)
(cond
((eql ch #\() 1)
((eql ch #\)) -1)
(t 0)))
(defun advent-1-1 ()
(loop :for c :across (beef:slurp "data/1")
:sum (instruction-to-num c)))
(defun advent-1-2 ()
(loop :for c :across (beef:slurp "data/1")
:sum (instruction-to-num c) :into floor
:sum 1
:until (= floor -1)))
(defun advent-2-data ()
(->> (beef:slurp "data/2")
beef:trim-whitespace-right
beef:split-lines
(mapcar (lambda (s)
(->> s
(split-sequence #\x)
(mapcar #'parse-integer))))))
(defun advent-2-1 ()
(loop :for dims :in (advent-2-data)
:for (w h l) = dims
:for sides = (list (* w h)
(* w l)
(* h l))
:for paper = (* 2 (apply #'+ sides))
:for slack = (apply #'min sides)
:sum (+ paper slack)))
(defun advent-2-2 ()
(loop :for dims :in (advent-2-data)
:for (w h l) = dims
:for sides = (list (* 2 (+ w h))
(* 2 (+ w l))
(* 2 (+ h l)))
:for ribbon = (apply #'min sides)
:for bow = (apply #'* dims)
:sum (+ ribbon bow)))
(defun advent-3-data ()
(beef:trim-whitespace (beef:slurp "data/3")))
(defun instruction-to-offsets (instruction)
(case instruction
(#\> '(1 0))
(#\< '(-1 0))
(#\^ '(0 1))
(#\v '(0 -1))))
(defun step-santa (loc dir)
(destructuring-bind (x y) loc
(destructuring-bind (dx dy) (instruction-to-offsets dir)
(list (+ x dx) (+ y dy)))))
(defun houses (data)
(loop
:with loc = '(0 0)
:with visited = (fset:set '(0 0))
:for dir :across data
:do (setq loc (step-santa loc dir))
:do (fset:includef visited loc)
:finally (return visited)))
(defun advent-3-1 (data)
(fset:size (houses data)))
(defun advent-3-2 (data)
(fset:size
(fset:union
(houses (ppcre:regex-replace-all "(.)." data "\\1"))
(houses (ppcre:regex-replace-all ".(.)" data "\\1")))))
(defun advent-4-data ()
"ckczppom")
(defun md5 (str)
(ironclad:byte-array-to-hex-string
(ironclad:digest-sequence :md5
(ironclad:ascii-string-to-byte-array str))))
(defun mine (data zeroes)
(let ((target (apply #'concatenate 'string
(loop :repeat zeroes :collect "0"))))
(loop :for i :upfrom 1
:for hash = (->> i
prin1-to-string
(concatenate 'string data)
md5)
:until (equal target (subseq hash 0 zeroes))
:finally (return i))))
(defun advent-4-1 (data)
(mine data 5))
(defun advent-4-2 (data)
(mine data 6))
(defun advent-5-data ()
(-> "data/5"
beef:slurp
beef:trim-whitespace-right
beef:split-lines))
(defun join-strings (strings delim)
"Join strings into a single string with the given delimiter string interleaved.
Delim must not contain a ~.
"
(format nil (concatenate 'string "~{~A~^" delim "~}") strings))
(defparameter *bad-pairs* '("ab" "cd" "pq" "xy"))
(defun count-vowels (s)
(length (ppcre:regex-replace-all "[^aeiou]" s "")))
(defun has-run (s)
(when (ppcre:scan "(.)\\1" s) t))
(defun has-bad (s)
(when (ppcre:scan (join-strings *bad-pairs* "|") s) t))
(defun is-nice (s)
(and (>= (count-vowels s) 3)
(has-run s)
(not (has-bad s))))
(defun advent-5-1 (data)
(count-if #'is-nice data))
(defun has-run-2 (s)
(when (ppcre:scan "(..).*\\1" s) t))
(defun has-repeat (s)
(when (ppcre:scan "(.).\\1" s) t))
(defun is-nice-2 (s)
(and (has-run-2 s)
(has-repeat s)))
(defun advent-5-2 (data)
(count-if #'is-nice-2 data))
(defun advent-6-data ()
(beef:slurp-lines "data/6" :ignore-trailing-newline t))
(defmacro loop-array (arr name &rest body)
(let ((i (gensym "index")))
`(loop :for ,i :below (array-total-size ,arr)
:for ,name = (row-major-aref ,arr ,i)
,@body)))
(defun parse-indexes (s)
(->> s
(split-sequence #\,)
(mapcar #'parse-integer)))
(defun flip (b)
(if (zerop b) 1 0))
(defun parse-line (line)
(let ((parts (split-sequence #\space line)))
(list (parse-indexes (beef:index parts -3))
(parse-indexes (beef:index parts -1))
(cond
((equal (car parts) "toggle") :toggle)
((equal (cadr parts) "on") :on)
((equal (cadr parts) "off") :off)
(t (error "Unknown operation!"))))))
(defmacro loop-square (r c from-row from-col to-row to-col &rest body)
`(loop :for ,r :from ,from-row :to ,to-row
:do (loop :for ,c :from ,from-col :to ,to-col
,@body)))
(defun advent-6-1 (data)
(let ((lights (make-array '(1000 1000) :element-type 'bit)))
(loop
:for line :in data
:for ((from-row from-col) (to-row to-col) operation) = (parse-line line)
:do (loop-square
r c from-row from-col to-row to-col
:do (setf (bit lights r c)
(case operation
(:toggle (flip (bit lights r c)))
(:on 1)
(:off 0)
(t 0)))))
(loop-array lights b
:sum b)))
(defun advent-6-2 (data)
(let ((lights (make-array '(1000 1000) :element-type 'integer)))
(loop
:for line :in data
:for ((from-row from-col) (to-row to-col) operation) = (parse-line line)
:do (loop-square
r c from-row from-col to-row to-col
:do (case operation
(:toggle (incf (aref lights r c) 2))
(:on (incf (aref lights r c)))
(:off (when (not (zerop (aref lights r c)))
(decf (aref lights r c)))))))
(loop-array lights b
:sum b)))
(defun advent-7-data ()
(beef:slurp-lines "data/7" :ignore-trailing-newline t))
(defun advent-7-2-data ()
(beef:slurp-lines "data/7-2" :ignore-trailing-newline t))
(defun int->bits (i)
(bitsmash:bits<- (format nil "~4,'0X" i)))
(defun bit-lshift (bit-array distance)
(replace (make-array (length bit-array) :element-type 'bit)
bit-array
:start1 0
:start2 (bitsmash:int<- distance)))
(defun bit-rshift (bit-array distance)
(let ((width (length bit-array))
(distance (bitsmash:int<- distance)))
(replace (make-array width :element-type 'bit)
bit-array
:start1 distance
:end2 (- width distance))))
(defun .zero-or-more (parser)
(.plus (.let* ((x parser)
(xs (.zero-or-more parser)))
(.identity (cons x xs)))
(.identity ())))
(defun .one-or-more (parser)
(.let* ((x parser)
(y (.zero-or-more parser)))
(.identity (cons x y))))
(defun parse-7 (line)
(labels ((.whitespace ()
(.first (.one-or-more (.is 'member '(#\space #\tab)))))
(.arrow ()
(.first (.string= "->")))
(.number ()
(.let* ((digits (.first (.one-or-more (.is 'digit-char-p)))))
(.identity (parse-integer (concatenate 'string digits)))))
(.wire ()
(.let* ((chars (.first (.one-or-more (.is 'lower-case-p)))))
(.identity (concatenate 'string chars))))
(.source ()
(.or (.wire) (.number)))
(.string-choice (strs)
(if (not strs)
(.fail)
(.or (.string= (car strs))
(.string-choice (cdr strs)))))
(.dest ()
(.progn (.whitespace) (.arrow) (.whitespace)
(.wire)))
(.constant-source ()
(.let* ((val (.source)))
(.identity (list #'identity (list val)))))
(.binary-op ()
(let ((ops '(("AND" . bit-and)
("OR" . bit-ior)
("LSHIFT" . bit-lshift)
("RSHIFT" . bit-rshift))))
(.let* ((name (.string-choice (mapcar #'car ops))))
(.identity (cdr (assoc name ops :test #'equal))))))
(.binary-source ()
(.let* ((left (.source))
(_ (.whitespace))
(op (.binary-op))
(_ (.whitespace))
(right (.source)))
(.identity (list op (list left right)))))
(.unary-op ()
(.let* ((_ (.string= "NOT")))
(.identity #'bit-not)))
(.unary-source ()
(.let* ((op (.unary-op))
(_ (.whitespace))
(source (.source)))
(.identity (list op (list source)))))
(.instruction ()
(.let* ((source (.or (.binary-source)
(.unary-source)
(.constant-source)))
(dest (.dest)))
(.identity (concatenate 'list source (list dest))))))
(parse (.instruction) line)))
(defun advent-7-1 (data)
(let ((circuit (make-hash-table :test #'equal))
(commands (mapcar #'parse-7 data)))
(labels ((retrieve (source)
(cond
((stringp source) (gethash source circuit))
((integerp source) (int->bits source))
(t (error "what?"))))
(ready (args)
(every #'identity args))
(perform (fn args dest)
(setf (gethash dest circuit)
(apply fn args)))
(try-command (command)
"If the command is ready to go, run it and return nil. Otherwise,
return the command itself."
(destructuring-bind (fn args dest) command
(let ((vals (mapcar #'retrieve args)))
(if (ready vals)
(progn
(perform fn vals dest)
nil)
command)))))
(loop :while commands
:do (setf commands
(loop :for command :in commands
:when (try-command command)
:collect :it)))
(bitsmash:bits->int (gethash "a" circuit)))))
(defun advent-8-data ()
(beef:slurp-lines "data/8" :ignore-trailing-newline t))
(defconstant +backslash+ #\\ )
(defconstant +quote+ #\" )
(defun parse-8 (line)
(labels ((.hex-digit ()
(.or
(.is #'digit-char-p)
(.is #'member '(#\a #\b #\c #\d #\e #\f))))
(.hex-escape ()
(.let* ((_ (.char= #\x))
(a (.hex-digit))
(b (.hex-digit)))
(.identity
(->> (format nil "~A~A" a b)
bitsmash:hex->int
code-char))))
(.escaped-char ()
(.progn
(.char= +backslash+)
(.or (.char= +backslash+)
(.char= +quote+)
(.hex-escape))))
(.normal-char ()
(.is-not 'member (list +backslash+ +quote+)))
(.string-char ()
(.or (.normal-char)
(.escaped-char)))
(.full-string ()
(.prog2
(.char= +quote+)
(.first (.zero-or-more (.string-char)))
(.char= +quote+))))
(parse (.full-string) line)))
(defun .wrap (fn parser)
(.let* ((v parser))
(.identity (funcall fn v))))
(defun parse-8-2 (line)
(labels ((.special-char ()
(.let* ((ch (.or (.char= +backslash+)
(.char= +quote+))))
(.identity (list +backslash+ ch))))
(.normal-char ()
(.wrap #'list
(.is-not 'member (list +backslash+ +quote+))))
(.string-char ()
(.or (.normal-char)
(.special-char)))
(.full-string ()
(.let* ((chars (.zero-or-more (.string-char))))
(.identity (apply #'concatenate 'list chars)))))
(append (list +quote+)
(parse (.full-string) line)
(list +quote+))))
(defun advent-8-1 (data)
(loop :for line :in data
:for chars = (parse-8 line)
:sum (- (length line)
(length chars))))
(defun advent-8-2 (data)
(loop :for line :in data
:for chars = (parse-8-2 line)
:sum (- (length chars)
(length line))))
(defun advent-9-data ()
(beef:slurp-lines "data/9" :ignore-trailing-newline t))
Thanks
(defun permutations (bag)
"Return a list of all the permutations of the input."
If the input is nil , there is only one permutation :
(if (null bag)
'(())
(mapcan #'(lambda (e)
(mapcar #'(lambda (p) (cons e p))
(permutations
(remove e bag :count 1 :test #'eq))))
bag)))
(defun advent-9 (data)
(let ((distances (make-hash-table :test #'equal)))
(loop :for line :in data
:for (a to b _ dist) = (split-sequence #\space line)
:for distance = (parse-integer dist)
:do (progn
(setf (gethash (cons a b) distances) distance)
(setf (gethash (cons b a) distances) distance)))
(labels ((score-route (route)
(optima:match route
((list _) 0)
((list* a b _) (+ (gethash (cons a b) distances)
(score-route (cdr route))))))
(dedupe (l)
(remove-duplicates l :test #'equal)))
(loop :for route :in (->> distances
beef:hash-keys
(mapcar #'car)
dedupe
permutations)
:for score = (score-route route)
:minimizing score :into min-dist
:maximizing score :into max-dist
:finally (return (cons min-dist max-dist))))))
(defmethod print-object ((object hash-table) stream)
(format stream "#HASH{~%~{~{ (~s : ~s)~}~%~}}"
(loop for key being the hash-keys of object
using (hash-value value)
collect (list key value))))
(defun advent-10-data ()
"1321131112")
(defun look-and-say (seq)
(let ((runs (list))
(len 1)
(current -1))
(flet ((mark-run ()
(setf runs (cons current (cons len runs)))))
(loop :for n :in seq
:do (if (= current n)
(incf len)
(progn
(when (not (= -1 current))
(mark-run))
(setf len 1)
(setf current n)))
:finally (mark-run))
(reverse runs))))
(defun iterate (n f data)
(declare (optimize speed (debug 0)))
(dotimes (_ n)
(setf data (funcall f data)))
data)
(defun las-to-list (s)
(loop :for digit :across s
:collect (-> digit string parse-integer)))
(defun advent-10-1 (data)
(length (iterate 40 #'look-and-say (las-to-list data))))
(defun advent-10-2 (data)
(length (iterate 50 #'look-and-say (las-to-list data))))
(defun advent-11-data ()
"vzbxkghb")
(defparameter base 26)
(defparameter ascii-alpha-start (char-code #\a))
(defun num-to-char (n)
(code-char (+ n ascii-alpha-start)))
(defun char-to-num (ch)
(- (char-code ch) ascii-alpha-start))
(defmacro loop-window (seq width binding-form &rest body)
(let ((i (gensym "IGNORE"))
(s (gensym "SEQ"))
(n (gensym "WIDTH"))
(tail (gensym "TAIL")))
`(let ((,s ,seq)
(,n ,width))
(loop :for ,i :upto (- (length ,s) ,n)
:for ,tail :on ,s
:for ,binding-form = (subseq ,tail 0 ,n)
,@body))))
(defun is-straight-3 (l)
(destructuring-bind (a b c) l
(and (= 1 (- b a))
(= 1 (- c b)))))
(defun has-straight-3 (nums)
(loop-window nums 3 triplet
:thereis (is-straight-3 triplet)))
(defparameter bad-chars
(mapcar #'char-to-num '(#\i #\l #\o)))
(defun no-bad (nums)
(loop :for bad :in bad-chars
:never (find bad nums)))
(defun two-pairs (nums)
(-> nums
(loop-window 2 (a b)
:when (= a b)
:collect a)
remove-duplicates
length
(>= 2)))
(defun valid (nums)
(and (has-straight-3 nums)
(no-bad nums)
(two-pairs nums)
nums))
(defun incr-nums (nums)
(labels ((inc-mod (x)
(mod (1+ x) base))
(inc (nums)
(if (not nums)
'(1)
(let ((head (inc-mod (car nums))))
(if (zerop head)
(cons head (inc (cdr nums)))
(cons head (cdr nums)))))))
(reverse (inc (reverse nums)))))
(defun advent-11-1 (data)
(flet ((chars-to-string (chs)
(apply #'concatenate 'string (mapcar #'string chs)))
(nums-to-chars (nums)
(mapcar #'num-to-char nums))
(string-to-nums (str)
(loop :for ch :across str
:collect (char-to-num ch))))
(-> (loop :for pw = (incr-nums (string-to-nums data))
:then (incr-nums pw)
:thereis (valid pw))
nums-to-chars
chars-to-string)))
(defun advent-12-data ()
(beef:trim-whitespace (beef:slurp "data/12")))
(defun parse-json (s)
(labels ((.number ()
(.let* ((negation (.optional (.char= #\-)))
(digits (.first (.one-or-more (.is 'digit-char-p)))))
(.identity (let ((i (parse-integer (concatenate 'string digits)))
(c (if negation -1 1)))
(* i c)))))
(.string-char ()
(.wrap #'list (.is-not 'member (list +quote+))))
(.string-guts ()
(.let* ((chars (.zero-or-more (.string-char))))
(.identity (apply #'concatenate 'string chars))))
(.string ()
(.prog2
(.char= +quote+)
(.string-guts)
(.char= +quote+)))
(.map-pair ()
(.let* ((key (.string))
(_ (.char= #\:))
(value (.expression)))
(.identity (cons key value))))
(.map-guts ()
(.or
(.let* ((p (.map-pair))
(_ (.char= #\,))
(remaining (.map-guts)))
(.identity (cons p remaining)))
(.wrap #'list (.map-pair))
(.identity '())))
(.map ()
(.prog2
(.char= #\{)
(.wrap (lambda (v) (cons :map v))
(.map-guts))
(.char= #\})))
(.array-guts ()
(.or
(.let* ((item (.expression))
(_ (.char= #\,))
(remaining (.array-guts)))
(.identity (cons item remaining)))
(.wrap #'list (.expression))
(.identity '())))
(.array ()
(.prog2
(.char= #\[)
(.wrap (lambda (v) (cons :array v))
(.array-guts))
(.char= #\])))
(.expression ()
(.or (.array)
(.map)
(.string)
(.number))))
(parse (.expression) s)))
(defun walk-sum (v)
(cond
((not v) 0)
((typep v 'integer) v)
((typep v 'string) 0)
((eql (car v) :array) (loop :for value in (cdr v)
:sum (walk-sum value)))
((eql (car v) :map) (loop :for (key . value) :in (cdr v)
:sum (walk-sum value)))
(:else (error (format nil "wat? ~a" v)))))
(defun walk-sum-2 (v)
(cond
((not v) 0)
((typep v 'integer) v)
((typep v 'string) 0)
((eql (car v) :array) (loop :for value in (cdr v)
:sum (walk-sum-2 value)))
((eql (car v) :map)
(if (member "red" (mapcar #'cdr (cdr v))
:test #'equal)
0
(loop :for (key . value) :in (cdr v)
:sum (walk-sum-2 value))))
(:else (error (format nil "wat? ~a" v)))))
(defun advent-12-1 (data)
(walk-sum (parse-json data)))
(defun advent-12-2 (data)
(walk-sum-2 (parse-json data)))
(defun advent-13-data ()
(beef:slurp-lines "data/13" :ignore-trailing-newline t))
(defvar *wat* nil)
(defmacro map-when (test fn val &rest args)
(let ((v (gensym "VALUE")))
`(let ((,v ,val))
(if ,test
(apply ,fn ,v ,args)
,v))))
(defun split-lines-13 (lines)
(loop :for line :in lines
:collect (ppcre:register-groups-bind
(a dir amount b)
("(\\w+) would (gain|lose) (\\d+) .*? next to (\\w+)."
line)
(list a b (map-when (equal "lose" dir)
#'-
(parse-integer amount))))))
(defun rate-seating (vals arrangement)
(labels ((find-val (a b)
(or (gethash (cons a b) vals) 0))
(rate-one-direction (arr)
(+ (loop-window arr 2 (a b) :sum (find-val a b))
(find-val (car (last arr)) (car arr)))))
(+ (rate-one-direction arrangement)
(rate-one-direction (reverse arrangement)))))
(defun advent-13-1 (data)
(let* ((tups (split-lines-13 data))
(attendees (remove-duplicates (mapcar #'car tups) :test #'equal))
(vals (make-hash-table :test #'equal)))
(loop :for (a b val) :in tups
:do (setf (gethash (cons a b) vals) val))
(loop :for arrangement :in (permutations attendees)
:maximize (rate-seating vals arrangement))))
(defun advent-13-2 (data)
(let* ((tups (split-lines-13 data))
(attendees (cons "Self" (remove-duplicates (mapcar #'car tups) :test #'equal)))
(vals (make-hash-table :test #'equal)))
(loop :for (a b val) :in tups
:do (setf (gethash (cons a b) vals) val))
(loop :for arrangement :in (permutations attendees)
:maximize (rate-seating vals arrangement))))
Day 14
(defun advent-14-data ()
(beef:slurp-lines "data/14" :ignore-trailing-newline t))
(defun tick (deer)
(destructuring-bind
(name speed sprint-period rest-period traveled currently remaining)
deer
(let ((remaining (1- remaining)))
(if (equal currently :resting)
(list name speed sprint-period rest-period
traveled
(if (zerop remaining) :sprinting :resting)
(if (zerop remaining) sprint-period remaining))
(list name speed sprint-period rest-period
(+ traveled speed)
(if (zerop remaining) :resting :sprinting)
(if (zerop remaining) rest-period remaining))))))
(defun parse-deers (lines)
(loop :for line :in lines
:collect (ppcre:register-groups-bind
(name speed sprint-period rest-period)
("(\\w+) can fly (\\d+) km/s for (\\d+) .* (\\d+) seconds."
line)
(list name
(parse-integer speed)
(parse-integer sprint-period)
(parse-integer rest-period)
0
:sprinting
(parse-integer sprint-period)))))
(defun find-leaders (deers)
(let ((dist (reduce #'max deers :key (beef:partial #'nth 4))))
(remove-if-not (lambda (deer)
(= dist (nth 4 deer)))
deers)))
(defun advent-14-1 (data n)
(apply #'max
(loop :for i :upto n
:for deers := (parse-deers data) :then (mapcar #'tick deers)
:finally (return (mapcar (beef:partial #'nth 4) deers)))))
(defun advent-14-2 (data n)
(let ((scores (make-hash-table :test #'equal))
(deers (parse-deers data)))
(loop :for (name) :in deers
:do (setf (gethash name scores) 0))
(loop :for i :upto n
:do (setf deers (mapcar #'tick deers))
:do (loop :for (name) :in (find-leaders deers)
:do (incf (gethash name scores))))
(apply #'max (beef:hash-values scores))))
(defun advent-15-data ()
(beef:slurp-lines "data/15" :ignore-trailing-newline t))
(defun split-ingredients (line)
(ppcre:register-groups-bind
(name (#'parse-integer capacity durability flavor texture calories))
("(\\w+): capacity (-?\\d+), durability (-?\\d+), flavor (-?\\d+), texture (-?\\d+), calories (-?\\d+)"
line)
(list name capacity durability flavor texture calories)))
(defun calc-contribution (ingr amount)
(cons (car ingr)
(mapcar (beef:partial #'* amount)
(cdr ingr))))
(defun calc-contributions (ingrs alist)
(mapcar #'calc-contribution ingrs alist))
(defun sum-totals (ingrs)
(->> ingrs
(mapcar #'cdr)
(apply #'mapcar #'+)
(mapcar (lambda (x) (if (< x 0) 0 x)))))
(defun advent-15-1 (data)
(let ((ingredients (mapcar #'split-ingredients data))
(limit 100)
(amounts (list)))
(loop :for a :upto limit :do
(loop :for b :upto (- limit a) :do
(loop :for c :upto (- limit a b) :do
(setf amounts
(cons (list a b c (- limit a b c))
amounts)))))
(loop :for alist :in amounts
:maximize (->> alist
(calc-contributions ingredients)
sum-totals
butlast
(apply #'*)))))
(defun advent-15-2 (data)
(let ((ingredients (mapcar #'split-ingredients data))
(limit 100)
(amounts (list)))
(loop :for a :upto limit :do
(loop :for b :upto (- limit a) :do
(loop :for c :upto (- limit a b) :do
(setf amounts
(cons (list a b c (- limit a b c))
amounts)))))
(loop :for alist :in amounts
:for val = (->> alist
(calc-contributions ingredients)
sum-totals)
:when (= (car (last val)) 500)
:maximize (apply #'* (butlast val)))))
#+comment
(advent-15-2 (advent-15-data))
|
9dbb0f275f8e46dd5a52b4ebe66c295edd9eab53b4bee1e87bedd3ab5054864c | dwincort/UISF | UISF.hs | module FRP.UISF
( -- UI functions
UISF
: : ( ) ( ) - > IO ( )
: : UIParams - > UISF ( ) ( ) - > IO ( )
, UIParams, defaultUIParams
, uiInitialize, uiClose, uiTitle, uiSize, uiInitFlow, uiTickDelay, uiCloseOnEsc, uiBackground
, Dimension -- type Dimension = (Int, Int)
-- Widgets
: : String - > UISF a a
: : ( )
: : Show a = > UISF a ( )
: : Show b = > UISF a b - > UISF a b
data WrapSetting = NoWrap | CharWrap | WordWrap
: : WrapSetting - > UISF String ( )
, textbox -- :: String -> UISF (Event String) String
, textField -- :: WrapSetting -> String -> UISF (Event String) String
, textboxE -- :: String -> UISF (Event String) String
: : String - > UISF a b - > UISF a b
: : UISF a a
, button -- :: String -> UISF () Bool
, stickyButton -- :: String -> UISF () Bool
: : String - > Bool - > UISF ( ) Bool
, checkGroup -- :: [(String, a)] -> UISF () [a]
: : [ String ] - > Int - > UISF ( ) Int
: : RealFrac a = > ( a , a ) - > a - > UISF ( ) a
: : Integral a = > a - > ( a , a ) - > a - > UISF ( ) a
: : RealFrac a = > Layout - > Time - > Color - > UISF [ ( a , Time ) ] ( )
data Color = Black | Blue | Green | Cyan | Red | Magenta | Yellow | White ...
, histogram -- :: RealFrac a => Layout -> UISF (Event [a]) ()
: : RealFrac a = > Layout - > UISF ( SEvent [ ( a , String ) ] ) ( )
: : Layout - > Dimension - > UISF a b - > UISF a b
: : ( Eq a , Show a ) = > [ a ] - > Int - > UISF ( SEvent [ a ] , SEvent Int ) Int
: : ( Eq a , Show a ) = > UISF ( [ a ] , Int ) Int
, canvas -- :: Dimension -> UISF (Event Graphic) ()
: : Layout - > ( a - > Dimension - > Graphic ) - > UISF ( Event a ) ( )
-- Widget Utilities
: : UISF a b - > UISF a b
: : ( Int , Int , Int , Int ) - > UISF a b - > UISF a b
: : Dimension - > UISF a b - > UISF a b
: : Layout - > UISF a b - > UISF a b
, makeLayout -- :: LayoutType -> LayoutType -> Layout
, LayoutType (..) -- data LayoutType = Stretchy { minSize :: Int } | Fixed { fixedSize :: Int }
, Layout -- data Layout = Layout {..}
Time , effects , and asynchrony
: : ( ) Time
: : ( ) DeltaT
, ArrowIO(..)
, asyncVT
, asyncE
, asyncC
, module FRP.UISF.AuxFunctions
, module Control.Arrow
) where
import FRP.UISF.UITypes
import FRP.UISF.UISF
import FRP.UISF.Widget
import FRP.UISF.Graphics (Color (..), WrapSetting(..),Dimension)
import FRP.UISF.AuxFunctions
import FRP.UISF.Asynchrony
import Control.Arrow
# DEPRECATED " As of UISF-0.4.0.0 , use accumTime instead , which is a little different but should work fine " #
getTime :: UISF () Time
getTime = accumTime
| null | https://raw.githubusercontent.com/dwincort/UISF/291a6155e41f351d938daed3d2be6f8baf832a19/FRP/UISF.hs | haskell | UI functions
type Dimension = (Int, Int)
Widgets
:: String -> UISF (Event String) String
:: WrapSetting -> String -> UISF (Event String) String
:: String -> UISF (Event String) String
:: String -> UISF () Bool
:: String -> UISF () Bool
:: [(String, a)] -> UISF () [a]
:: RealFrac a => Layout -> UISF (Event [a]) ()
:: Dimension -> UISF (Event Graphic) ()
Widget Utilities
:: LayoutType -> LayoutType -> Layout
data LayoutType = Stretchy { minSize :: Int } | Fixed { fixedSize :: Int }
data Layout = Layout {..} | module FRP.UISF
UISF
: : ( ) ( ) - > IO ( )
: : UIParams - > UISF ( ) ( ) - > IO ( )
, UIParams, defaultUIParams
, uiInitialize, uiClose, uiTitle, uiSize, uiInitFlow, uiTickDelay, uiCloseOnEsc, uiBackground
: : String - > UISF a a
: : ( )
: : Show a = > UISF a ( )
: : Show b = > UISF a b - > UISF a b
data WrapSetting = NoWrap | CharWrap | WordWrap
: : WrapSetting - > UISF String ( )
: : String - > UISF a b - > UISF a b
: : UISF a a
: : String - > Bool - > UISF ( ) Bool
: : [ String ] - > Int - > UISF ( ) Int
: : RealFrac a = > ( a , a ) - > a - > UISF ( ) a
: : Integral a = > a - > ( a , a ) - > a - > UISF ( ) a
: : RealFrac a = > Layout - > Time - > Color - > UISF [ ( a , Time ) ] ( )
data Color = Black | Blue | Green | Cyan | Red | Magenta | Yellow | White ...
: : RealFrac a = > Layout - > UISF ( SEvent [ ( a , String ) ] ) ( )
: : Layout - > Dimension - > UISF a b - > UISF a b
: : ( Eq a , Show a ) = > [ a ] - > Int - > UISF ( SEvent [ a ] , SEvent Int ) Int
: : ( Eq a , Show a ) = > UISF ( [ a ] , Int ) Int
: : Layout - > ( a - > Dimension - > Graphic ) - > UISF ( Event a ) ( )
: : UISF a b - > UISF a b
: : ( Int , Int , Int , Int ) - > UISF a b - > UISF a b
: : Dimension - > UISF a b - > UISF a b
: : Layout - > UISF a b - > UISF a b
Time , effects , and asynchrony
: : ( ) Time
: : ( ) DeltaT
, ArrowIO(..)
, asyncVT
, asyncE
, asyncC
, module FRP.UISF.AuxFunctions
, module Control.Arrow
) where
import FRP.UISF.UITypes
import FRP.UISF.UISF
import FRP.UISF.Widget
import FRP.UISF.Graphics (Color (..), WrapSetting(..),Dimension)
import FRP.UISF.AuxFunctions
import FRP.UISF.Asynchrony
import Control.Arrow
# DEPRECATED " As of UISF-0.4.0.0 , use accumTime instead , which is a little different but should work fine " #
getTime :: UISF () Time
getTime = accumTime
|
c452ca73cbce251932c500dc63f8c57fbf19b7d6ef098c70e40f30239a06ef45 | pveber/biotk | bam_traversal.ml | open Core
open Biotk
open Rresult
let time f =
let start = Core_unix.gettimeofday () in
let y = f () in
let stop = Core_unix.gettimeofday () in
(y, stop -. start)
let ok_exn = function
| Ok x -> x
| Error (`Msg msg) -> failwith msg
| Error `Parse_error -> failwith "Incorrect format for location"
let ok_exn' = function
| Ok x -> x
| Error e -> failwith (Error.to_string_hum e)
let loc_of_al = function
| { Sam.rname = Some chr ; pos = Some pos ; seq = Some seq ; _ } ->
let lo = pos - 1 in
let len = String.length seq in
let hi = lo + len in
Some GLoc.{ chr ; lo ; hi }
| _ -> None
let loc_of_al0 header al =
let open Result in
Bam.Alignment0.decode al header >>| loc_of_al
let indexed_traversal ~bam ~bai ~loc =
let visited = ref 0 in
let count =
Bam_iterator.fold0 ~loc ~bam ~bai ~init:0 ~f:(fun header n al ->
incr visited ;
match loc_of_al0 header al with
| Ok (Some loc') ->
if GLoc.intersects loc loc' then n + 1 else n
| Ok None -> n
| Error _ -> assert false
)
|> ok_exn
in
count, !visited
let full_traversal ~bam ~loc =
let visited = ref 0 in
let count =
ok_exn' @@ Bam.with_file bam ~f:(fun _ als ->
Fun.flip Caml.Seq.filter als Result.(fun al ->
incr visited ;
match map al ~f:loc_of_al with
| Ok (Some loc') ->
GLoc.intersects loc loc'
| Ok None -> false
| Error _ -> assert false
)
|> Caml.List.of_seq
|> List.length
|> R.ok
)
in
count, !visited
let main ~bam ~bai ~loc () =
let loc = ok_exn GLoc.(of_string loc) in
let (intersecting, visited), t = time (fun () -> indexed_traversal ~bam ~bai ~loc) in
let (intersecting', visited'), t' = time (fun () -> full_traversal ~bam ~loc) in
printf "(/\\ %d, visited = %d, %f) VS (/\\ %d, visited = %d, %f)\n" intersecting visited t intersecting' visited' t'
let command =
let open Command.Let_syntax in
Command.basic
~summary:"BAM traversal demo/test"
[%map_open
let bam = flag "--bam" (required Filename_unix.arg_type) ~doc:"PATH BAM file"
and bai = flag "--bai" (required Filename_unix.arg_type) ~doc:"PATH BAI file"
and loc = flag "--loc" (required string) ~doc:"LOC Location CHR:START-END" in
main ~bam ~bai ~loc ]
let () = Command_unix.run command
| null | https://raw.githubusercontent.com/pveber/biotk/422640d9303c90c43ecb4b679a8bf5867998119c/examples/bam_traversal.ml | ocaml | open Core
open Biotk
open Rresult
let time f =
let start = Core_unix.gettimeofday () in
let y = f () in
let stop = Core_unix.gettimeofday () in
(y, stop -. start)
let ok_exn = function
| Ok x -> x
| Error (`Msg msg) -> failwith msg
| Error `Parse_error -> failwith "Incorrect format for location"
let ok_exn' = function
| Ok x -> x
| Error e -> failwith (Error.to_string_hum e)
let loc_of_al = function
| { Sam.rname = Some chr ; pos = Some pos ; seq = Some seq ; _ } ->
let lo = pos - 1 in
let len = String.length seq in
let hi = lo + len in
Some GLoc.{ chr ; lo ; hi }
| _ -> None
let loc_of_al0 header al =
let open Result in
Bam.Alignment0.decode al header >>| loc_of_al
let indexed_traversal ~bam ~bai ~loc =
let visited = ref 0 in
let count =
Bam_iterator.fold0 ~loc ~bam ~bai ~init:0 ~f:(fun header n al ->
incr visited ;
match loc_of_al0 header al with
| Ok (Some loc') ->
if GLoc.intersects loc loc' then n + 1 else n
| Ok None -> n
| Error _ -> assert false
)
|> ok_exn
in
count, !visited
let full_traversal ~bam ~loc =
let visited = ref 0 in
let count =
ok_exn' @@ Bam.with_file bam ~f:(fun _ als ->
Fun.flip Caml.Seq.filter als Result.(fun al ->
incr visited ;
match map al ~f:loc_of_al with
| Ok (Some loc') ->
GLoc.intersects loc loc'
| Ok None -> false
| Error _ -> assert false
)
|> Caml.List.of_seq
|> List.length
|> R.ok
)
in
count, !visited
let main ~bam ~bai ~loc () =
let loc = ok_exn GLoc.(of_string loc) in
let (intersecting, visited), t = time (fun () -> indexed_traversal ~bam ~bai ~loc) in
let (intersecting', visited'), t' = time (fun () -> full_traversal ~bam ~loc) in
printf "(/\\ %d, visited = %d, %f) VS (/\\ %d, visited = %d, %f)\n" intersecting visited t intersecting' visited' t'
let command =
let open Command.Let_syntax in
Command.basic
~summary:"BAM traversal demo/test"
[%map_open
let bam = flag "--bam" (required Filename_unix.arg_type) ~doc:"PATH BAM file"
and bai = flag "--bai" (required Filename_unix.arg_type) ~doc:"PATH BAI file"
and loc = flag "--loc" (required string) ~doc:"LOC Location CHR:START-END" in
main ~bam ~bai ~loc ]
let () = Command_unix.run command
|
|
33b00ff823b60a03033b6462bc3d4cd01a7653864f6b804fec0836293ece387e | DavidAlphaFox/RabbitMQ | rabbit_amqp1_0_framing.erl | The contents of this file are subject to the Mozilla Public License
%% Version 1.1 (the "License"); you may not use this file except in
%% compliance with the License. You may obtain a copy of the License
%% at /
%%
Software distributed under the License is distributed on an " AS IS "
%% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
%% the License for the specific language governing rights and
%% limitations under the License.
%%
The Original Code is RabbitMQ .
%%
The Initial Developer of the Original Code is GoPivotal , Inc.
Copyright ( c ) 2007 - 2014 GoPivotal , Inc. All rights reserved .
%%
-module(rabbit_amqp1_0_framing).
-export([encode/1, encode_described/3, decode/1, version/0,
symbol_for/1, number_for/1, encode_bin/1, decode_bin/1, pprint/1]).
%% debug
-export([fill_from_list/2, fill_from_map/2]).
-include("rabbit_amqp1_0.hrl").
version() ->
{1, 0, 0}.
%% These are essentially in lieu of code generation ..
fill_from_list(Record, Fields) ->
{Res, _} = lists:foldl(
fun (Field, {Record1, Num}) ->
DecodedField = decode(Field),
{setelement(Num, Record1, DecodedField),
Num + 1}
end,
{Record, 2}, Fields),
Res.
fill_from_map(Record, Fields) ->
{Res, _} = lists:foldl(
fun (Key, {Record1, Num}) ->
case proplists:get_value(Key, Fields) of
undefined ->
{Record1, Num+1};
Value ->
{setelement(Num, Record1, decode(Value)), Num+1}
end
end,
{Record, 2}, keys(Record)),
Res.
TODO should this be part of a more general handler for AMQP values etc ?
fill_from_binary(F = #'v1_0.data'{}, Field) ->
F#'v1_0.data'{content = Field}.
TODO so should this ?
fill_from_amqp(F = #'v1_0.amqp_value'{}, Field) ->
F#'v1_0.amqp_value'{content = Field}.
keys(Record) ->
[{symbol, symbolify(K)} || K <- rabbit_amqp1_0_framing0:fields(Record)].
symbolify(FieldName) when is_atom(FieldName) ->
re:replace(atom_to_list(FieldName), "_", "-", [{return,list}, global]).
%% TODO: in fields of composite types with multiple=true, "a null
value and a zero - length array ( with a correct type for its
%% elements) both describe an absence of a value and should be treated
as semantically identical . " ( see section 1.3 )
%% A sequence comes as an arbitrary list of values; it's not a
%% composite type.
decode({described, Descriptor, {list, Fields}}) ->
case rabbit_amqp1_0_framing0:record_for(Descriptor) of
#'v1_0.amqp_sequence'{} ->
#'v1_0.amqp_sequence'{content = [decode(F) || F <- Fields]};
Else ->
fill_from_list(Else, Fields)
end;
decode({described, Descriptor, {map, Fields}}) ->
case rabbit_amqp1_0_framing0:record_for(Descriptor) of
#'v1_0.application_properties'{} ->
#'v1_0.application_properties'{content = decode_map(Fields)};
#'v1_0.delivery_annotations'{} ->
#'v1_0.delivery_annotations'{content = decode_map(Fields)};
#'v1_0.message_annotations'{} ->
#'v1_0.message_annotations'{content = decode_map(Fields)};
#'v1_0.footer'{} ->
#'v1_0.footer'{content = decode_map(Fields)};
Else ->
fill_from_map(Else, Fields)
end;
decode({described, Descriptor, {binary, Field}}) ->
fill_from_binary(rabbit_amqp1_0_framing0:record_for(Descriptor), Field);
decode({described, Descriptor, Field}) ->
fill_from_amqp(rabbit_amqp1_0_framing0:record_for(Descriptor), Field);
decode(null) ->
undefined;
decode(Other) ->
Other.
decode_map(Fields) ->
[{decode(K), decode(V)} || {K, V} <- Fields].
encode_described(list, ListOrNumber, Frame) ->
Desc = descriptor(ListOrNumber),
{described, Desc,
{list, lists:map(fun encode/1, tl(tuple_to_list(Frame)))}};
encode_described(map, ListOrNumber, Frame) ->
Desc = descriptor(ListOrNumber),
{described, Desc,
{map, lists:zip(keys(Frame),
lists:map(fun encode/1, tl(tuple_to_list(Frame))))}};
encode_described(binary, ListOrNumber, #'v1_0.data'{content = Content}) ->
Desc = descriptor(ListOrNumber),
{described, Desc, {binary, Content}};
encode_described('*', ListOrNumber, #'v1_0.amqp_value'{content = Content}) ->
Desc = descriptor(ListOrNumber),
{described, Desc, Content};
encode_described(annotations, ListOrNumber, Frame) ->
encode_described(map, ListOrNumber, Frame).
encode(X) ->
rabbit_amqp1_0_framing0:encode(X).
encode_bin(X) ->
rabbit_amqp1_0_binary_generator:generate(encode(X)).
decode_bin(X) -> [decode(PerfDesc) || PerfDesc <- decode_bin0(X)].
decode_bin0(<<>>) -> [];
decode_bin0(X) -> {PerfDesc, Rest} = rabbit_amqp1_0_binary_parser:parse(X),
[PerfDesc | decode_bin0(Rest)].
symbol_for(X) ->
rabbit_amqp1_0_framing0:symbol_for(X).
number_for(X) ->
rabbit_amqp1_0_framing0:number_for(X).
descriptor(Symbol) when is_list(Symbol) ->
{symbol, Symbol};
descriptor(Number) when is_number(Number) ->
{ulong, Number}.
pprint(Thing) when is_tuple(Thing) ->
case rabbit_amqp1_0_framing0:fields(Thing) of
unknown -> Thing;
Names -> [T|L] = tuple_to_list(Thing),
{T, lists:zip(Names, [pprint(I) || I <- L])}
end;
pprint(Other) -> Other.
| null | https://raw.githubusercontent.com/DavidAlphaFox/RabbitMQ/0a64e6f0464a9a4ce85c6baa52fb1c584689f49a/plugins-src/rabbitmq-amqp1.0/src/rabbit_amqp1_0_framing.erl | erlang | Version 1.1 (the "License"); you may not use this file except in
compliance with the License. You may obtain a copy of the License
at /
basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
the License for the specific language governing rights and
limitations under the License.
debug
These are essentially in lieu of code generation ..
TODO: in fields of composite types with multiple=true, "a null
elements) both describe an absence of a value and should be treated
A sequence comes as an arbitrary list of values; it's not a
composite type. | The contents of this file are subject to the Mozilla Public License
Software distributed under the License is distributed on an " AS IS "
The Original Code is RabbitMQ .
The Initial Developer of the Original Code is GoPivotal , Inc.
Copyright ( c ) 2007 - 2014 GoPivotal , Inc. All rights reserved .
-module(rabbit_amqp1_0_framing).
-export([encode/1, encode_described/3, decode/1, version/0,
symbol_for/1, number_for/1, encode_bin/1, decode_bin/1, pprint/1]).
-export([fill_from_list/2, fill_from_map/2]).
-include("rabbit_amqp1_0.hrl").
version() ->
{1, 0, 0}.
fill_from_list(Record, Fields) ->
{Res, _} = lists:foldl(
fun (Field, {Record1, Num}) ->
DecodedField = decode(Field),
{setelement(Num, Record1, DecodedField),
Num + 1}
end,
{Record, 2}, Fields),
Res.
fill_from_map(Record, Fields) ->
{Res, _} = lists:foldl(
fun (Key, {Record1, Num}) ->
case proplists:get_value(Key, Fields) of
undefined ->
{Record1, Num+1};
Value ->
{setelement(Num, Record1, decode(Value)), Num+1}
end
end,
{Record, 2}, keys(Record)),
Res.
TODO should this be part of a more general handler for AMQP values etc ?
fill_from_binary(F = #'v1_0.data'{}, Field) ->
F#'v1_0.data'{content = Field}.
TODO so should this ?
fill_from_amqp(F = #'v1_0.amqp_value'{}, Field) ->
F#'v1_0.amqp_value'{content = Field}.
keys(Record) ->
[{symbol, symbolify(K)} || K <- rabbit_amqp1_0_framing0:fields(Record)].
symbolify(FieldName) when is_atom(FieldName) ->
re:replace(atom_to_list(FieldName), "_", "-", [{return,list}, global]).
value and a zero - length array ( with a correct type for its
as semantically identical . " ( see section 1.3 )
decode({described, Descriptor, {list, Fields}}) ->
case rabbit_amqp1_0_framing0:record_for(Descriptor) of
#'v1_0.amqp_sequence'{} ->
#'v1_0.amqp_sequence'{content = [decode(F) || F <- Fields]};
Else ->
fill_from_list(Else, Fields)
end;
decode({described, Descriptor, {map, Fields}}) ->
case rabbit_amqp1_0_framing0:record_for(Descriptor) of
#'v1_0.application_properties'{} ->
#'v1_0.application_properties'{content = decode_map(Fields)};
#'v1_0.delivery_annotations'{} ->
#'v1_0.delivery_annotations'{content = decode_map(Fields)};
#'v1_0.message_annotations'{} ->
#'v1_0.message_annotations'{content = decode_map(Fields)};
#'v1_0.footer'{} ->
#'v1_0.footer'{content = decode_map(Fields)};
Else ->
fill_from_map(Else, Fields)
end;
decode({described, Descriptor, {binary, Field}}) ->
fill_from_binary(rabbit_amqp1_0_framing0:record_for(Descriptor), Field);
decode({described, Descriptor, Field}) ->
fill_from_amqp(rabbit_amqp1_0_framing0:record_for(Descriptor), Field);
decode(null) ->
undefined;
decode(Other) ->
Other.
decode_map(Fields) ->
[{decode(K), decode(V)} || {K, V} <- Fields].
encode_described(list, ListOrNumber, Frame) ->
Desc = descriptor(ListOrNumber),
{described, Desc,
{list, lists:map(fun encode/1, tl(tuple_to_list(Frame)))}};
encode_described(map, ListOrNumber, Frame) ->
Desc = descriptor(ListOrNumber),
{described, Desc,
{map, lists:zip(keys(Frame),
lists:map(fun encode/1, tl(tuple_to_list(Frame))))}};
encode_described(binary, ListOrNumber, #'v1_0.data'{content = Content}) ->
Desc = descriptor(ListOrNumber),
{described, Desc, {binary, Content}};
encode_described('*', ListOrNumber, #'v1_0.amqp_value'{content = Content}) ->
Desc = descriptor(ListOrNumber),
{described, Desc, Content};
encode_described(annotations, ListOrNumber, Frame) ->
encode_described(map, ListOrNumber, Frame).
encode(X) ->
rabbit_amqp1_0_framing0:encode(X).
encode_bin(X) ->
rabbit_amqp1_0_binary_generator:generate(encode(X)).
decode_bin(X) -> [decode(PerfDesc) || PerfDesc <- decode_bin0(X)].
decode_bin0(<<>>) -> [];
decode_bin0(X) -> {PerfDesc, Rest} = rabbit_amqp1_0_binary_parser:parse(X),
[PerfDesc | decode_bin0(Rest)].
symbol_for(X) ->
rabbit_amqp1_0_framing0:symbol_for(X).
number_for(X) ->
rabbit_amqp1_0_framing0:number_for(X).
descriptor(Symbol) when is_list(Symbol) ->
{symbol, Symbol};
descriptor(Number) when is_number(Number) ->
{ulong, Number}.
pprint(Thing) when is_tuple(Thing) ->
case rabbit_amqp1_0_framing0:fields(Thing) of
unknown -> Thing;
Names -> [T|L] = tuple_to_list(Thing),
{T, lists:zip(Names, [pprint(I) || I <- L])}
end;
pprint(Other) -> Other.
|
144fb44f89905117bce47e3e94c24f27e7a94030d696f57ee646481f4033d75f | 2600hz/kazoo | ecallmgr_fs_channels.erl | %%%-----------------------------------------------------------------------------
( C ) 2013 - 2020 , 2600Hz
%%% @doc Track the FreeSWITCH channel information, and provide accessors
@author
@author
%%%
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 /.
%%%
%%% @end
%%%-----------------------------------------------------------------------------
-module(ecallmgr_fs_channels).
-behaviour(gen_listener).
-export([start_link/0]).
-export([sync/2]).
-export([summary/0
,summary/1
]).
-export([details/0
,details/1
]).
-export([show_all/0]).
-export([per_minute_accounts/0]).
-export([per_minute_channels/1]).
-export([flush_node/1]).
-export([new/1]).
-export([destroy/2]).
-export([update/2, update/3, updates/2]).
-export([cleanup_old_channels/0, cleanup_old_channels/1
,max_channel_uptime/0
,set_max_channel_uptime/1, set_max_channel_uptime/2
]).
-export([match_presence/1]).
-export([count/0]).
-export([handle_query_auth_id/2]).
-export([handle_query_user_channels/2]).
-export([handle_query_account_channels/2]).
-export([handle_query_channels/2]).
-export([handle_channel_status/2]).
-export([has_channels_for_owner/1]).
-export([init/1
,handle_call/3
,handle_cast/2
,handle_info/2
,handle_event/2
,terminate/2
,code_change/3
]).
-include("ecallmgr.hrl").
-define(SERVER, ?MODULE).
-define(RESPONDERS, [{{?MODULE, 'handle_query_auth_id'}
,[{<<"call_event">>, <<"query_auth_id_req">>}]
}
,{{?MODULE, 'handle_query_user_channels'}
,[{<<"call_event">>, <<"query_user_channels_req">>}]
}
,{{?MODULE, 'handle_query_account_channels'}
,[{<<"call_event">>, <<"query_account_channels_req">>}]
}
,{{?MODULE, 'handle_query_channels'}
,[{<<"call_event">>, <<"query_channels_req">>}]
}
,{{?MODULE, 'handle_channel_status'}
,[{<<"call_event">>, <<"channel_status_req">>}]
}
]).
-define(BINDINGS, [{'call', [{'restrict_to', ['status_req']}
,'federate'
]}
]).
-define(QUEUE_NAME, <<>>).
-define(QUEUE_OPTIONS, []).
-define(CONSUME_OPTIONS, []).
-define(CALL_PARK_FEATURE, "*3").
-record(state, {max_channel_cleanup_ref :: reference()}).
-type state() :: #state{}.
-define(DESTROY_DEFER_MAX_TRIES, 5).
-define(DESTROY_DEFER_TIME, 5 * ?MILLISECONDS_IN_SECOND).
%%%=============================================================================
%%% API
%%%=============================================================================
%%------------------------------------------------------------------------------
%% @doc Starts the server.
%% @end
%%------------------------------------------------------------------------------
-spec start_link() -> kz_types:startlink_ret().
start_link() ->
gen_listener:start_link({'local', ?SERVER}, ?MODULE, [{'responders', ?RESPONDERS}
,{'bindings', ?BINDINGS}
,{'queue_name', ?QUEUE_NAME}
,{'queue_options', ?QUEUE_OPTIONS}
,{'consume_options', ?CONSUME_OPTIONS}
], []).
-spec sync(atom(), kz_term:ne_binaries()) -> 'ok'.
sync(Node, Channels) ->
gen_server:cast(?SERVER, {'sync_channels', Node, Channels}).
-spec summary() -> 'ok'.
summary() ->
MatchSpec = [{#channel{_ = '_'}
,[]
,['$_']
}],
print_summary(ets:select(?CHANNELS_TBL, MatchSpec, 1)).
-spec summary(kz_term:text()) -> 'ok'.
summary(Node) when not is_atom(Node) ->
summary(kz_term:to_atom(Node, 'true'));
summary(Node) ->
MatchSpec = [{#channel{node='$1', _ = '_'}
,[{'=:=', '$1', {'const', Node}}]
,['$_']
}],
print_summary(ets:select(?CHANNELS_TBL, MatchSpec, 1)).
-spec details() -> 'ok'.
details() ->
MatchSpec = [{#channel{_ = '_'}
,[]
,['$_']
}],
print_details(ets:select(?CHANNELS_TBL, MatchSpec, 1)).
-spec details(kz_term:text()) -> 'ok'.
details(UUID) when not is_binary(UUID) ->
details(kz_term:to_binary(UUID));
details(UUID) ->
MatchSpec = [{#channel{uuid='$1', _ = '_'}
,[{'=:=', '$1', {'const', UUID}}]
,['$_']
}],
print_details(ets:select(?CHANNELS_TBL, MatchSpec, 1)).
-spec show_all() -> kz_json:objects().
show_all() ->
ets:foldl(fun(Channel, Acc) ->
[ecallmgr_fs_channel:to_json(Channel) | Acc]
end, [], ?CHANNELS_TBL).
-spec per_minute_accounts() -> kz_term:ne_binaries().
per_minute_accounts() ->
MatchSpec = [{#channel{account_id = '$1'
,account_billing = <<"per_minute">>
,reseller_id = '$2'
,reseller_billing = <<"per_minute">>
,_ = '_'}
,[{'andalso', {'=/=', '$1', 'undefined'}, {'=/=', '$2', 'undefined'}}]
,['$$']
}
,{#channel{reseller_id = '$1', reseller_billing = <<"per_minute">>, _ = '_'}
,[{'=/=', '$1', 'undefined'}]
,['$$']
}
,{#channel{account_id = '$1', account_billing = <<"per_minute">>, _ = '_'}
,[{'=/=', '$1', 'undefined'}]
,['$$']
}
],
lists:usort(lists:flatten(ets:select(?CHANNELS_TBL, MatchSpec))).
-spec per_minute_channels(kz_term:ne_binary()) -> [{atom(), kz_term:ne_binary()}].
per_minute_channels(AccountId) ->
MatchSpec = [{#channel{node = '$1'
,uuid = '$2'
,reseller_id = AccountId
,reseller_billing = <<"per_minute">>
,_ = '_'
}
,[]
,[{{'$1', '$2'}}]
}
,{#channel{node = '$1'
,uuid = '$2'
,account_id = AccountId
,account_billing = <<"per_minute">>
,_ = '_'
}
,[]
,[{{'$1', '$2'}}]
}
],
ets:select(?CHANNELS_TBL, MatchSpec).
-spec flush_node(string() | binary() | atom()) -> 'ok'.
flush_node(Node) ->
gen_server:cast(?SERVER, {'flush_node', kz_term:to_atom(Node, 'true')}).
-spec new(channel()) -> 'ok'.
new(#channel{}=Channel) ->
gen_server:call(?SERVER, {'new_channel', Channel}).
-spec destroy(kz_term:ne_binary(), atom()) -> 'ok'.
destroy(UUID, Node) ->
gen_server:cast(?SERVER, {'destroy_channel', UUID, Node}).
-spec update(kz_term:ne_binary(), channel()) -> 'ok'.
update(UUID, Channel) ->
gen_server:call(?SERVER, {'update_channel', UUID, Channel}).
-spec update(kz_term:ne_binary(), pos_integer(), any()) -> 'ok'.
update(UUID, Key, Value) ->
updates(UUID, [{Key, Value}]).
-spec updates(kz_term:ne_binary(), channel_updates()) -> 'ok'.
updates(UUID, Updates) ->
gen_server:cast(?SERVER, {'channel_updates', UUID, Updates}).
-spec format_updates(kz_term:proplist()) -> kz_term:ne_binary().
format_updates(Updates) ->
Fields = record_info('fields', 'channel'),
Out = [io_lib:format("~s=~p", [lists:nth(Field - 1, Fields), V]) || {Field, V} <- Updates],
kz_binary:join(Out, <<",">>).
-spec count() -> non_neg_integer().
count() -> ets:info(?CHANNELS_TBL, 'size').
-spec match_presence(kz_term:ne_binary()) -> kz_term:proplist_kv(kz_term:ne_binary(), atom()).
match_presence(PresenceId) ->
MatchSpec = [{#channel{uuid = '$1'
,presence_id = '$2'
,node = '$3'
, _ = '_'
}
,[{'=:=', '$2', {'const', PresenceId}}]
,[{{'$1', '$3'}}]}
],
ets:select(?CHANNELS_TBL, MatchSpec).
-spec handle_query_auth_id(kz_json:object(), kz_term:proplist()) -> 'ok'.
handle_query_auth_id(JObj, _Props) ->
'true' = kapi_call:query_auth_id_req_v(JObj),
AuthId = kz_json:get_ne_binary_value(<<"Auth-ID">>, JObj),
Channels = case find_by_auth_id(AuthId) of
{'error', 'not_found'} -> [];
{'ok', C} -> C
end,
Resp = [{<<"Channels">>, Channels}
,{<<"Msg-ID">>, kz_api:msg_id(JObj)}
| kz_api:default_headers(?APP_NAME, ?APP_VERSION)
],
ServerId = kz_json:get_value(<<"Server-ID">>, JObj),
kapi_call:publish_query_auth_id_resp(ServerId, Resp).
-spec handle_query_user_channels(kz_json:object(), kz_term:proplist()) -> 'ok'.
handle_query_user_channels(JObj, _Props) ->
'true' = kapi_call:query_user_channels_req_v(JObj),
UserChannels0 = case kz_json:get_value(<<"Realm">>, JObj) of
'undefined' -> [];
Realm ->
Usernames = kz_json:get_first_defined([<<"Username">>
,<<"Usernames">>
], JObj),
find_by_user_realm(Usernames, Realm)
end,
UserChannels1 = case kz_json:get_value(<<"Authorizing-IDs">>, JObj) of
'undefined' -> [];
AuthIds -> find_by_authorizing_id(AuthIds)
end,
UserChannels2 = lists:keymerge(1, UserChannels0, UserChannels1),
handle_query_users_channels(JObj, UserChannels2).
-spec handle_query_users_channels(kz_json:object(), kz_term:proplist()) -> 'ok'.
handle_query_users_channels(JObj, Cs) ->
Channels = [Channel || {_, Channel} <- Cs],
send_user_query_resp(JObj, Channels).
-spec send_user_query_resp(kz_json:object(), kz_json:objects()) -> 'ok'.
send_user_query_resp(JObj, []) ->
case kz_json:is_true(<<"Active-Only">>, JObj, 'true') of
'true' -> lager:debug("no channels, not sending response");
'false' ->
lager:debug("no channels, sending empty response"),
Resp = [{<<"Channels">>, []}
,{<<"Msg-ID">>, kz_api:msg_id(JObj)}
| kz_api:default_headers(?APP_NAME, ?APP_VERSION)
],
ServerId = kz_json:get_value(<<"Server-ID">>, JObj),
lager:debug("sending back channel data to ~s", [ServerId]),
kapi_call:publish_query_user_channels_resp(ServerId, Resp)
end;
send_user_query_resp(JObj, Cs) ->
Resp = [{<<"Channels">>, Cs}
,{<<"Msg-ID">>, kz_api:msg_id(JObj)}
| kz_api:default_headers(?APP_NAME, ?APP_VERSION)
],
ServerId = kz_json:get_value(<<"Server-ID">>, JObj),
lager:debug("sending back channel data to ~s", [ServerId]),
kapi_call:publish_query_user_channels_resp(ServerId, Resp).
-spec handle_query_account_channels(kz_json:object(), kz_term:ne_binary()) -> 'ok'.
handle_query_account_channels(JObj, _) ->
AccountId = kz_json:get_value(<<"Account-ID">>, JObj),
case find_account_channels(AccountId) of
{'error', 'not_found'} -> send_account_query_resp(JObj, []);
{'ok', Cs} -> send_account_query_resp(JObj, Cs)
end.
-spec send_account_query_resp(kz_json:object(), kz_json:objects()) -> 'ok'.
send_account_query_resp(JObj, Cs) ->
Resp = [{<<"Channels">>, Cs}
,{<<"Msg-ID">>, kz_api:msg_id(JObj)}
| kz_api:default_headers(?APP_NAME, ?APP_VERSION)
],
ServerId = kz_json:get_value(<<"Server-ID">>, JObj),
lager:debug("sending back channel data to ~s", [ServerId]),
kapi_call:publish_query_account_channels_resp(ServerId, Resp).
-spec handle_query_channels(kz_json:object(), kz_term:proplist()) -> 'ok'.
handle_query_channels(JObj, _Props) ->
'true' = kapi_call:query_channels_req_v(JObj),
Fields = kz_json:get_value(<<"Fields">>, JObj, []),
CallId = kz_json:get_value(<<"Call-ID">>, JObj),
Channels = query_channels(Fields, CallId),
case kz_term:is_empty(Channels) and
kz_json:is_true(<<"Active-Only">>, JObj, 'false')
of
'true' ->
lager:debug("not sending query_channels resp due to active-only=true");
'false' ->
Resp = [{<<"Channels">>, Channels}
,{<<"Msg-ID">>, kz_api:msg_id(JObj)}
| kz_api:default_headers(?APP_NAME, ?APP_VERSION)
],
kapi_call:publish_query_channels_resp(kz_json:get_value(<<"Server-ID">>, JObj), Resp)
end.
-spec handle_channel_status(kz_json:object(), kz_term:proplist()) -> 'ok'.
handle_channel_status(JObj, _Props) ->
'true' = kapi_call:channel_status_req_v(JObj),
_ = kz_log:put_callid(JObj),
CallId = kz_api:call_id(JObj),
lager:debug("channel status request received"),
case ecallmgr_fs_channel:fetch(CallId) of
{'error', 'not_found'} ->
maybe_send_empty_channel_resp(CallId, JObj);
{'ok', Channel} ->
Node = kz_json:get_binary_value(<<"node">>, Channel),
Hostname = case binary:split(Node, <<"@">>) of
[_, Host] -> Host;
Other -> Other
end,
lager:debug("channel is on ~s", [Hostname]),
Resp =
props:filter_undefined(
[{<<"Call-ID">>, CallId}
,{<<"Status">>, <<"active">>}
,{<<"Switch-Hostname">>, Hostname}
,{<<"Switch-Nodename">>, kz_term:to_binary(Node)}
,{<<"Switch-URL">>, ecallmgr_fs_nodes:sip_url(Node)}
,{<<"Other-Leg-Call-ID">>, kz_json:get_value(<<"other_leg">>, Channel)}
,{<<"Realm">>, kz_json:get_value(<<"realm">>, Channel)}
,{<<"Username">>, kz_json:get_value(<<"username">>, Channel)}
,{<<"Custom-Channel-Vars">>, kz_json:from_list(ecallmgr_fs_channel:channel_ccvs(Channel))}
,{<<"Custom-Application-Vars">>, kz_json:from_list(ecallmgr_fs_channel:channel_cavs(Channel))}
,{<<"Msg-ID">>, kz_api:msg_id(JObj)}
| kz_api:default_headers(?APP_NAME, ?APP_VERSION)
]
),
kapi_call:publish_channel_status_resp(kz_api:server_id(JObj), Resp)
end.
-spec maybe_send_empty_channel_resp(kz_term:ne_binary(), kz_json:object()) -> 'ok'.
maybe_send_empty_channel_resp(CallId, JObj) ->
case kz_json:is_true(<<"Active-Only">>, JObj) of
'true' -> 'ok';
'false' -> send_empty_channel_resp(CallId, JObj)
end.
-spec send_empty_channel_resp(kz_term:ne_binary(), kz_json:object()) -> 'ok'.
send_empty_channel_resp(CallId, JObj) ->
Resp = [{<<"Call-ID">>, CallId}
,{<<"Status">>, <<"terminated">>}
,{<<"Error-Msg">>, <<"no node found with channel">>}
,{<<"Msg-ID">>, kz_api:msg_id(JObj)}
| kz_api:default_headers(?APP_NAME, ?APP_VERSION)
],
kapi_call:publish_channel_status_resp(kz_api:server_id(JObj), Resp).
%%%=============================================================================
%%% gen_server callbacks
%%%=============================================================================
%%------------------------------------------------------------------------------
%% @doc Initializes the server.
%% @end
%%------------------------------------------------------------------------------
-spec init([]) -> {'ok', state()}.
init([]) ->
kz_log:put_callid(?DEFAULT_LOG_SYSTEM_ID),
process_flag('trap_exit', 'true'),
lager:debug("starting new fs channels"),
_ = ets:new(?CHANNELS_TBL, ['set'
,'protected'
,'named_table'
,{'keypos', #channel.uuid}
,{read_concurrency, true}
]),
{'ok', #state{max_channel_cleanup_ref=start_cleanup_ref()}}.
-define(CLEANUP_TIMEOUT
,kapps_config:get_integer(?APP_NAME, <<"max_channel_cleanup_timeout_ms">>, ?MILLISECONDS_IN_MINUTE)
).
-spec start_cleanup_ref() -> reference().
start_cleanup_ref() ->
erlang:start_timer(?CLEANUP_TIMEOUT, self(), 'ok').
%%------------------------------------------------------------------------------
%% @doc Handling call messages.
%% @end
%%------------------------------------------------------------------------------
-spec handle_call(any(), kz_term:pid_ref(), state()) -> kz_types:handle_call_ret_state(state()).
handle_call({'new_channel', #channel{uuid=UUID}=Channel}, _, State) ->
case ets:insert_new(?CHANNELS_TBL, Channel) of
'true'->
lager:debug("channel ~s added", [UUID]),
{'reply', 'ok', State};
'false' ->
lager:debug("channel ~s already exists", [UUID]),
{'reply', {'error', 'channel_exists'}, State}
end;
handle_call({'update_channel', UUID, Channel}, _, State) ->
lager:debug("updating channel ~s", [UUID]),
ets:insert(?CHANNELS_TBL, Channel),
{'reply', 'ok', State};
handle_call({'channel_updates', _UUID, []}, _, State) ->
{'reply', 'ok', State};
handle_call({'channel_updates', UUID, Update}, _, State) ->
ets:update_element(?CHANNELS_TBL, UUID, Update),
{'reply', 'ok', State};
handle_call(_, _, State) ->
{'reply', {'error', 'not_implemented'}, State}.
%%------------------------------------------------------------------------------
%% @doc Handling cast messages.
%% @end
%%------------------------------------------------------------------------------
-spec handle_cast(any(), state()) -> {'noreply', state()}.
handle_cast({'channel_updates', UUID, Updates}, State) ->
kz_log:put_callid(UUID),
lager:debug("updating channel properties: ~s", [format_updates(Updates)]),
ets:update_element(?CHANNELS_TBL, UUID, Updates),
{'noreply', State};
handle_cast({'destroy_channel', UUID, Node}, State) ->
kz_log:put_callid(UUID),
MatchSpec = [{#channel{uuid='$1', node='$2', _ = '_'}
,[{'andalso', {'=:=', '$2', {'const', Node}}
,{'=:=', '$1', UUID}}
],
['true']
}],
N = ets:select_delete(?CHANNELS_TBL, MatchSpec),
lager:debug("removed ~p channel(s) with id ~s on ~s", [N, UUID, Node]),
{'noreply', State, 'hibernate'};
handle_cast({'sync_channels', Node, Channels}, State) ->
lager:debug("ensuring channel cache is in sync with ~s", [Node]),
MatchSpec = [{#channel{uuid = '$1', node = '$2', _ = '_'}
,[{'=:=', '$2', {'const', Node}}]
,['$1']}
],
CachedChannels = sets:from_list(ets:select(?CHANNELS_TBL, MatchSpec)),
SyncChannels = sets:from_list(Channels),
Remove = sets:subtract(CachedChannels, SyncChannels),
Add = sets:subtract(SyncChannels, CachedChannels),
_ = [delete_and_maybe_disconnect(Node, UUID, ets:lookup(?CHANNELS_TBL, UUID))
|| UUID <- sets:to_list(Remove)
],
_ = [begin
lager:debug("trying to add channel ~s to cache during sync with ~s", [UUID, Node]),
case ecallmgr_fs_channel:renew(Node, UUID) of
{'error', _R} -> lager:warning("failed to sync channel ~s: ~p", [UUID, _R]);
{'ok', C} ->
lager:debug("added channel ~s to cache during sync with ~s", [UUID, Node]),
ets:insert(?CHANNELS_TBL, C),
PublishReconect = kapps_config:get_boolean(?APP_NAME, <<"publish_channel_reconnect">>, 'false'),
handle_channel_reconnected(C, PublishReconect)
end
end
|| UUID <- sets:to_list(Add)
],
{'noreply', State, 'hibernate'};
handle_cast({'flush_node', Node}, State) ->
lager:debug("flushing all channels in cache associated to node ~s", [Node]),
LocalChannelsMS = [{#channel{node = '$1'
,handling_locally='true'
,_ = '_'
}
,[{'=:=', '$1', {'const', Node}}]
,['$_']}
],
case ets:select(?CHANNELS_TBL, LocalChannelsMS) of
[] ->
lager:debug("no locally handled channels");
LocalChannels ->
_P = kz_process:spawn(fun handle_channels_disconnected/1, [LocalChannels]),
lager:debug("sending channel disconnects for local channels: ~p", [LocalChannels])
end,
MatchSpec = [{#channel{node = '$1', _ = '_'}
,[{'=:=', '$1', {'const', Node}}]
,['true']}
],
ets:select_delete(?CHANNELS_TBL, MatchSpec),
{'noreply', State};
handle_cast({'gen_listener',{'created_queue', _QueueName}}, State) ->
{'noreply', State};
handle_cast({'gen_listener',{'is_consuming',_IsConsuming}}, State) ->
{'noreply', State};
handle_cast(_Req, State) ->
lager:debug("unhandled cast: ~p", [_Req]),
{'noreply', State}.
%%------------------------------------------------------------------------------
%% @doc Handling all non call/cast messages.
%% @end
%%------------------------------------------------------------------------------
-spec handle_info(any(), state()) -> kz_types:handle_info_ret_state(state()).
handle_info({'timeout', Ref, _Msg}, #state{max_channel_cleanup_ref=Ref}=State) ->
maybe_cleanup_old_channels(),
{'noreply', State#state{max_channel_cleanup_ref=start_cleanup_ref()}};
handle_info(_Msg, State) ->
lager:debug("unhandled message: ~p", [_Msg]),
{'noreply', State}.
%%------------------------------------------------------------------------------
%% @doc Allows listener to pass options to handlers.
%% @end
%%------------------------------------------------------------------------------
-spec handle_event(kz_json:object(), state()) -> gen_listener:handle_event_return().
handle_event(_JObj, #state{}) ->
{'reply', []}.
%%------------------------------------------------------------------------------
%% @doc This function is called by a `gen_server' when it is about to
%% terminate. It should be the opposite of `Module:init/1' and do any
%% necessary cleaning up. When it returns, the `gen_server' terminates
with . The return value is ignored .
%%
%% @end
%%------------------------------------------------------------------------------
-spec terminate(any(), state()) -> 'ok'.
terminate(_Reason, #state{}) ->
ets:delete(?CHANNELS_TBL),
lager:info("fs channels terminating: ~p", [_Reason]).
%%------------------------------------------------------------------------------
%% @doc Convert process state when code is changed.
%% @end
%%------------------------------------------------------------------------------
-spec code_change(any(), state(), any()) -> {'ok', state()}.
code_change(_OldVsn, State, _Extra) ->
{'ok', State}.
%%%=============================================================================
Internal functions
%%%=============================================================================
%%------------------------------------------------------------------------------
%% @doc
%% @end
%%------------------------------------------------------------------------------
-spec find_by_auth_id(kz_term:ne_binary()) ->
{'ok', kz_json:objects()} |
{'error', 'not_found'}.
find_by_auth_id(AuthorizingId) ->
MatchSpec = [{#channel{authorizing_id = '$1', _ = '_'}
,[{'=:=', '$1', {'const', AuthorizingId}}]
,['$_']}
],
case ets:select(?CHANNELS_TBL, MatchSpec) of
[] -> {'error', 'not_found'};
Channels -> {'ok', [ecallmgr_fs_channel:to_json(Channel)
|| Channel <- Channels
]}
end.
-spec has_channels_for_owner(kz_term:ne_binary()) -> boolean().
has_channels_for_owner(OwnerId) ->
MatchSpec = [{#channel{owner_id = '$1'
,_ = '_'
}
,[]
,[{'=:=', '$1', {const, OwnerId}}]
}
],
Count = ets:select_count(?CHANNELS_TBL, MatchSpec),
lager:info("found ~p channels", [Count]),
Count > 0.
-spec find_by_authorizing_id(kz_term:ne_binaries()) -> [] | kz_term:proplist().
find_by_authorizing_id(AuthIds) ->
find_by_authorizing_id(AuthIds, []).
-spec find_by_authorizing_id(kz_term:ne_binaries(), kz_term:proplist()) -> [] | kz_term:proplist().
find_by_authorizing_id([], Acc) -> Acc;
find_by_authorizing_id([AuthId|AuthIds], Acc) ->
Pattern = #channel{authorizing_id=AuthId
,_='_'},
case ets:match_object(?CHANNELS_TBL, Pattern) of
[] -> find_by_authorizing_id(AuthIds, Acc);
Channels ->
Cs = [{Channel#channel.uuid, ecallmgr_fs_channel:to_json(Channel)}
|| Channel <- Channels
],
find_by_authorizing_id(AuthIds, lists:keymerge(1, Acc, Cs))
end.
-spec find_by_user_realm(kz_term:api_binary() | kz_term:ne_binaries(), kz_term:ne_binary()) -> [] | kz_term:proplist().
find_by_user_realm('undefined', Realm) ->
Pattern = #channel{realm=kz_term:to_lower_binary(Realm)
,_='_'},
case ets:match_object(?CHANNELS_TBL, Pattern) of
[] -> [];
Channels ->
[{Channel#channel.uuid, ecallmgr_fs_channel:to_json(Channel)}
|| Channel <- Channels
]
end;
find_by_user_realm(<<?CALL_PARK_FEATURE, _/binary>>=Username, Realm) ->
Pattern = #channel{destination=kz_term:to_lower_binary(Username)
,realm=kz_term:to_lower_binary(Realm)
,other_leg='undefined'
,_='_'},
case ets:match_object(?CHANNELS_TBL, Pattern) of
[] -> [];
Channels ->
[{Channel#channel.uuid, ecallmgr_fs_channel:to_json(Channel)}
|| Channel <- Channels
]
end;
find_by_user_realm(Usernames, Realm) when is_list(Usernames) ->
ETSUsernames = build_matchspec_ors(Usernames),
MatchSpec = [{#channel{username='$1'
,realm=kz_term:to_lower_binary(Realm)
,_ = '_'}
,[ETSUsernames]
,['$_']
}],
case ets:select(?CHANNELS_TBL, MatchSpec) of
[] -> [];
Channels ->
[{Channel#channel.uuid, ecallmgr_fs_channel:to_json(Channel)}
|| Channel <- Channels
]
end;
find_by_user_realm(Username, Realm) ->
Pattern = #channel{username=kz_term:to_lower_binary(Username)
,realm=kz_term:to_lower_binary(Realm)
,_='_'},
case ets:match_object(?CHANNELS_TBL, Pattern) of
[] -> [];
Channels ->
[{Channel#channel.uuid, ecallmgr_fs_channel:to_json(Channel)}
|| Channel <- Channels
]
end.
-spec find_account_channels(kz_term:ne_binary()) ->
{'ok', kz_json:objects()} |
{'error', 'not_found'}.
find_account_channels(<<"all">>) ->
case ets:match_object(?CHANNELS_TBL, #channel{_='_'}) of
[] -> {'error', 'not_found'};
Channels ->
{'ok', [ecallmgr_fs_channel:to_json(Channel)
|| Channel <- Channels
]}
end;
find_account_channels(AccountId) ->
case ets:match_object(?CHANNELS_TBL, #channel{account_id=AccountId, _='_'}) of
[] -> {'error', 'not_found'};
Channels ->
{'ok', [ecallmgr_fs_channel:to_json(Channel)
|| Channel <- Channels
]}
end.
-spec build_matchspec_ors(kz_term:ne_binaries()) -> tuple() | 'false'.
build_matchspec_ors(Usernames) ->
lists:foldl(fun build_matchspec_ors_fold/2
,'false'
,Usernames
).
-spec build_matchspec_ors_fold(kz_term:ne_binary(), tuple() | 'false') -> tuple().
build_matchspec_ors_fold(Username, Acc) ->
{'or', {'=:=', '$1', kz_term:to_lower_binary(Username)}, Acc}.
-spec query_channels(kz_term:ne_binaries(), kz_term:api_binary()) -> kz_json:object().
query_channels(Fields, 'undefined') ->
query_channels(ets:match_object(?CHANNELS_TBL, #channel{_='_'}, 1)
,Fields
,kz_json:new()
);
query_channels(Fields, CallId) ->
query_channels(ets:match_object(?CHANNELS_TBL, #channel{uuid=CallId, _='_'}, 1)
,Fields
,kz_json:new()
).
-spec query_channels({[channel()], ets:continuation()} | '$end_of_table', kz_term:ne_binary() | kz_term:ne_binaries(), kz_json:object()) ->
kz_json:object().
query_channels('$end_of_table', _, Channels) -> Channels;
query_channels({[#channel{uuid=CallId}=Channel], Continuation}
,<<"all">>, Channels) ->
JObj = ecallmgr_fs_channel:to_api_json(Channel),
query_channels(ets:match_object(Continuation)
,<<"all">>
,kz_json:set_value(CallId, JObj, Channels)
);
query_channels({[#channel{uuid=CallId}=Channel], Continuation}
,Fields, Channels) ->
ChannelProps = ecallmgr_fs_channel:to_api_props(Channel),
JObj = kz_json:from_list(
[{Field, props:get_value(Field, ChannelProps)}
|| Field <- Fields
]),
query_channels(ets:match_object(Continuation)
,Fields
,kz_json:set_value(CallId, JObj, Channels)
).
-define(SUMMARY_HEADER, "| ~-50s | ~-40s | ~-9s | ~-15s | ~-32s |~n").
print_summary('$end_of_table') ->
io:format("No channels found!~n", []);
print_summary(Match) ->
io:format("+----------------------------------------------------+------------------------------------------+-----------+-----------------+----------------------------------+~n"),
io:format(?SUMMARY_HEADER
,[ <<"UUID">>, <<"Node">>, <<"Direction">>, <<"Destination">>, <<"Account-ID">>]
),
io:format("+====================================================+==========================================+===========+=================+==================================+~n"),
print_summary(Match, 0).
print_summary('$end_of_table', Count) ->
io:format("+----------------------------------------------------+------------------------------------------+-----------+-----------------+----------------------------------+~n"),
io:format("Found ~p channels~n", [Count]);
print_summary({[#channel{uuid=UUID
,node=Node
,direction=Direction
,destination=Destination
,account_id=AccountId
}]
,Continuation}
,Count) ->
io:format(?SUMMARY_HEADER
,[UUID, Node, Direction, Destination, AccountId]
),
print_summary(ets:select(Continuation), Count + 1).
print_details('$end_of_table') ->
io:format("No channels found!~n", []);
print_details(Match) ->
print_details(Match, 0).
print_details('$end_of_table', Count) ->
io:format("~nFound ~p channels~n", [Count]);
print_details({[#channel{}=Channel]
,Continuation}
,Count) ->
io:format("~n"),
_ = [io:format("~-19s: ~s~n", [K, kz_term:to_binary(V)])
|| {K, V} <- ecallmgr_fs_channel:to_props(Channel),
not kz_json:is_json_object(V)
],
print_details(ets:select(Continuation), Count + 1).
-spec handle_channel_reconnected(channel(), boolean()) -> 'ok'.
handle_channel_reconnected(#channel{handling_locally='true'
,uuid=_UUID
}=Channel
,'true') ->
lager:debug("channel ~s connected, publishing update", [_UUID]),
publish_channel_connection_event(Channel, [{<<"Event-Name">>, <<"CHANNEL_CONNECTED">>}]);
handle_channel_reconnected(_Channel, _ShouldPublish) ->
'ok'.
-spec handle_channels_disconnected(channels()) -> 'ok'.
handle_channels_disconnected(LocalChannels) ->
_ = [catch handle_channel_disconnected(LocalChannel) || LocalChannel <- LocalChannels],
'ok'.
-spec handle_channel_disconnected(channel()) -> 'ok'.
handle_channel_disconnected(Channel) ->
publish_channel_connection_event(Channel, [{<<"Event-Name">>, <<"CHANNEL_DISCONNECTED">>}]).
-spec publish_channel_connection_event(channel(), kz_term:proplist()) -> 'ok'.
publish_channel_connection_event(#channel{uuid=UUID
,direction=Direction
,node=Node
,presence_id=PresenceId
,answered=IsAnswered
,from=From
,to=To
}=Channel
,ChannelSpecific) ->
Event = [{<<"Timestamp">>, kz_time:now_s()}
,{<<"Call-ID">>, UUID}
,{<<"Call-Direction">>, Direction}
,{<<"Media-Server">>, Node}
,{<<"Custom-Channel-Vars">>, connection_ccvs(Channel)}
,{<<"Custom-Application-Vars">>, connection_cavs(Channel)}
,{<<"To">>, To}
,{<<"From">>, From}
,{<<"Presence-ID">>, PresenceId}
,{<<"Channel-Call-State">>, channel_call_state(IsAnswered)}
| kz_api:default_headers(?APP_NAME, ?APP_VERSION) ++ ChannelSpecific
],
_ = kz_amqp_worker:cast(Event, fun kapi_call:publish_event/1),
lager:debug("published channel connection event (~s) for ~s", [kz_api:event_name(Event), UUID]).
-spec channel_call_state(boolean()) -> kz_term:api_binary().
channel_call_state('true') ->
<<"ANSWERED">>;
channel_call_state('false') ->
'undefined'.
-spec connection_ccvs(channel()) -> kz_term:api_object().
connection_ccvs(#channel{ccvs=CCVs}) -> CCVs.
-spec connection_cavs(channel()) -> kz_term:api_object().
connection_cavs(#channel{cavs=CAVs}) -> CAVs.
-define(MAX_CHANNEL_UPTIME_KEY, <<"max_channel_uptime_s">>).
-spec max_channel_uptime() -> non_neg_integer().
max_channel_uptime() ->
kapps_config:get_integer(?APP_NAME, ?MAX_CHANNEL_UPTIME_KEY, 0).
-spec set_max_channel_uptime(non_neg_integer()) ->
{'ok', kz_json:object()} |
kz_datamgr:data_error().
set_max_channel_uptime(MaxAge) ->
set_max_channel_uptime(MaxAge, 'true').
-spec set_max_channel_uptime(non_neg_integer(), boolean()) ->
{'ok', kz_json:object()} |
kz_datamgr:data_error().
set_max_channel_uptime(MaxAge, 'true') ->
kapps_config:set_default(?APP_NAME, ?MAX_CHANNEL_UPTIME_KEY, kz_term:to_integer(MaxAge));
set_max_channel_uptime(MaxAge, 'false') ->
kapps_config:set(?APP_NAME, ?MAX_CHANNEL_UPTIME_KEY, kz_term:to_integer(MaxAge)).
-spec maybe_cleanup_old_channels() -> 'ok'.
maybe_cleanup_old_channels() ->
case max_channel_uptime() of
N when N =< 0 -> 'ok';
MaxAge ->
_P = kz_process:spawn(fun cleanup_old_channels/1, [MaxAge]),
'ok'
end.
-spec cleanup_old_channels() -> non_neg_integer().
cleanup_old_channels() ->
cleanup_old_channels(max_channel_uptime()).
-spec cleanup_old_channels(non_neg_integer()) -> non_neg_integer().
cleanup_old_channels(MaxAge) ->
NoOlderThan = kz_time:now_s() - MaxAge,
MatchSpec = [{#channel{uuid='$1'
,node='$2'
,timestamp='$3'
,handling_locally='true'
,_ = '_'
}
,[{'<', '$3', NoOlderThan}]
,[['$1', '$2', '$3']]
}],
case ets:select(?CHANNELS_TBL, MatchSpec) of
[] -> 0;
OldChannels ->
N = length(OldChannels),
lager:debug("~p channels over ~p seconds old", [N, MaxAge]),
hangup_old_channels(OldChannels),
N
end.
-type old_channel() :: [kz_term:ne_binary() | atom() | kz_time:gregorian_seconds()].
-type old_channels() :: [old_channel(),...].
-spec hangup_old_channels(old_channels()) -> 'ok'.
hangup_old_channels(OldChannels) ->
lists:foreach(fun hangup_old_channel/1, OldChannels).
-spec hangup_old_channel(old_channel()) -> 'ok'.
hangup_old_channel([UUID, Node, Started]) ->
lager:debug("killing channel ~s on ~s, started ~s"
,[UUID, Node, kz_time:pretty_print_datetime(Started)]),
freeswitch:api(Node, 'uuid_kill', UUID).
-spec delete_and_maybe_disconnect(atom(), kz_term:ne_binary(), [channel()]) -> 'ok' | 'true'.
delete_and_maybe_disconnect(Node, UUID, [#channel{handling_locally='true'}=Channel]) ->
lager:debug("emitting channel disconnect ~s during sync with ~s", [UUID, Node]),
handle_channel_disconnected(Channel),
ets:delete(?CHANNELS_TBL, UUID);
delete_and_maybe_disconnect(Node, UUID, [_Channel]) ->
lager:debug("removed channel ~s from cache during sync with ~s", [UUID, Node]),
ets:delete(?CHANNELS_TBL, UUID);
delete_and_maybe_disconnect(Node, UUID, []) ->
lager:debug("channel ~s not found during sync delete with ~s", [UUID, Node]).
| null | https://raw.githubusercontent.com/2600hz/kazoo/24519b9af9792caa67f7c09bbb9d27e2418f7ad6/applications/ecallmgr/src/ecallmgr_fs_channels.erl | erlang | -----------------------------------------------------------------------------
@doc Track the FreeSWITCH channel information, and provide accessors
@end
-----------------------------------------------------------------------------
=============================================================================
API
=============================================================================
------------------------------------------------------------------------------
@doc Starts the server.
@end
------------------------------------------------------------------------------
=============================================================================
gen_server callbacks
=============================================================================
------------------------------------------------------------------------------
@doc Initializes the server.
@end
------------------------------------------------------------------------------
------------------------------------------------------------------------------
@doc Handling call messages.
@end
------------------------------------------------------------------------------
------------------------------------------------------------------------------
@doc Handling cast messages.
@end
------------------------------------------------------------------------------
------------------------------------------------------------------------------
@doc Handling all non call/cast messages.
@end
------------------------------------------------------------------------------
------------------------------------------------------------------------------
@doc Allows listener to pass options to handlers.
@end
------------------------------------------------------------------------------
------------------------------------------------------------------------------
@doc This function is called by a `gen_server' when it is about to
terminate. It should be the opposite of `Module:init/1' and do any
necessary cleaning up. When it returns, the `gen_server' terminates
@end
------------------------------------------------------------------------------
------------------------------------------------------------------------------
@doc Convert process state when code is changed.
@end
------------------------------------------------------------------------------
=============================================================================
=============================================================================
------------------------------------------------------------------------------
@doc
@end
------------------------------------------------------------------------------ | ( C ) 2013 - 2020 , 2600Hz
@author
@author
This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
-module(ecallmgr_fs_channels).
-behaviour(gen_listener).
-export([start_link/0]).
-export([sync/2]).
-export([summary/0
,summary/1
]).
-export([details/0
,details/1
]).
-export([show_all/0]).
-export([per_minute_accounts/0]).
-export([per_minute_channels/1]).
-export([flush_node/1]).
-export([new/1]).
-export([destroy/2]).
-export([update/2, update/3, updates/2]).
-export([cleanup_old_channels/0, cleanup_old_channels/1
,max_channel_uptime/0
,set_max_channel_uptime/1, set_max_channel_uptime/2
]).
-export([match_presence/1]).
-export([count/0]).
-export([handle_query_auth_id/2]).
-export([handle_query_user_channels/2]).
-export([handle_query_account_channels/2]).
-export([handle_query_channels/2]).
-export([handle_channel_status/2]).
-export([has_channels_for_owner/1]).
-export([init/1
,handle_call/3
,handle_cast/2
,handle_info/2
,handle_event/2
,terminate/2
,code_change/3
]).
-include("ecallmgr.hrl").
-define(SERVER, ?MODULE).
-define(RESPONDERS, [{{?MODULE, 'handle_query_auth_id'}
,[{<<"call_event">>, <<"query_auth_id_req">>}]
}
,{{?MODULE, 'handle_query_user_channels'}
,[{<<"call_event">>, <<"query_user_channels_req">>}]
}
,{{?MODULE, 'handle_query_account_channels'}
,[{<<"call_event">>, <<"query_account_channels_req">>}]
}
,{{?MODULE, 'handle_query_channels'}
,[{<<"call_event">>, <<"query_channels_req">>}]
}
,{{?MODULE, 'handle_channel_status'}
,[{<<"call_event">>, <<"channel_status_req">>}]
}
]).
-define(BINDINGS, [{'call', [{'restrict_to', ['status_req']}
,'federate'
]}
]).
-define(QUEUE_NAME, <<>>).
-define(QUEUE_OPTIONS, []).
-define(CONSUME_OPTIONS, []).
-define(CALL_PARK_FEATURE, "*3").
-record(state, {max_channel_cleanup_ref :: reference()}).
-type state() :: #state{}.
-define(DESTROY_DEFER_MAX_TRIES, 5).
-define(DESTROY_DEFER_TIME, 5 * ?MILLISECONDS_IN_SECOND).
-spec start_link() -> kz_types:startlink_ret().
start_link() ->
gen_listener:start_link({'local', ?SERVER}, ?MODULE, [{'responders', ?RESPONDERS}
,{'bindings', ?BINDINGS}
,{'queue_name', ?QUEUE_NAME}
,{'queue_options', ?QUEUE_OPTIONS}
,{'consume_options', ?CONSUME_OPTIONS}
], []).
-spec sync(atom(), kz_term:ne_binaries()) -> 'ok'.
sync(Node, Channels) ->
gen_server:cast(?SERVER, {'sync_channels', Node, Channels}).
-spec summary() -> 'ok'.
summary() ->
MatchSpec = [{#channel{_ = '_'}
,[]
,['$_']
}],
print_summary(ets:select(?CHANNELS_TBL, MatchSpec, 1)).
-spec summary(kz_term:text()) -> 'ok'.
summary(Node) when not is_atom(Node) ->
summary(kz_term:to_atom(Node, 'true'));
summary(Node) ->
MatchSpec = [{#channel{node='$1', _ = '_'}
,[{'=:=', '$1', {'const', Node}}]
,['$_']
}],
print_summary(ets:select(?CHANNELS_TBL, MatchSpec, 1)).
-spec details() -> 'ok'.
details() ->
MatchSpec = [{#channel{_ = '_'}
,[]
,['$_']
}],
print_details(ets:select(?CHANNELS_TBL, MatchSpec, 1)).
-spec details(kz_term:text()) -> 'ok'.
details(UUID) when not is_binary(UUID) ->
details(kz_term:to_binary(UUID));
details(UUID) ->
MatchSpec = [{#channel{uuid='$1', _ = '_'}
,[{'=:=', '$1', {'const', UUID}}]
,['$_']
}],
print_details(ets:select(?CHANNELS_TBL, MatchSpec, 1)).
-spec show_all() -> kz_json:objects().
show_all() ->
ets:foldl(fun(Channel, Acc) ->
[ecallmgr_fs_channel:to_json(Channel) | Acc]
end, [], ?CHANNELS_TBL).
-spec per_minute_accounts() -> kz_term:ne_binaries().
per_minute_accounts() ->
MatchSpec = [{#channel{account_id = '$1'
,account_billing = <<"per_minute">>
,reseller_id = '$2'
,reseller_billing = <<"per_minute">>
,_ = '_'}
,[{'andalso', {'=/=', '$1', 'undefined'}, {'=/=', '$2', 'undefined'}}]
,['$$']
}
,{#channel{reseller_id = '$1', reseller_billing = <<"per_minute">>, _ = '_'}
,[{'=/=', '$1', 'undefined'}]
,['$$']
}
,{#channel{account_id = '$1', account_billing = <<"per_minute">>, _ = '_'}
,[{'=/=', '$1', 'undefined'}]
,['$$']
}
],
lists:usort(lists:flatten(ets:select(?CHANNELS_TBL, MatchSpec))).
-spec per_minute_channels(kz_term:ne_binary()) -> [{atom(), kz_term:ne_binary()}].
per_minute_channels(AccountId) ->
MatchSpec = [{#channel{node = '$1'
,uuid = '$2'
,reseller_id = AccountId
,reseller_billing = <<"per_minute">>
,_ = '_'
}
,[]
,[{{'$1', '$2'}}]
}
,{#channel{node = '$1'
,uuid = '$2'
,account_id = AccountId
,account_billing = <<"per_minute">>
,_ = '_'
}
,[]
,[{{'$1', '$2'}}]
}
],
ets:select(?CHANNELS_TBL, MatchSpec).
-spec flush_node(string() | binary() | atom()) -> 'ok'.
flush_node(Node) ->
gen_server:cast(?SERVER, {'flush_node', kz_term:to_atom(Node, 'true')}).
-spec new(channel()) -> 'ok'.
new(#channel{}=Channel) ->
gen_server:call(?SERVER, {'new_channel', Channel}).
-spec destroy(kz_term:ne_binary(), atom()) -> 'ok'.
destroy(UUID, Node) ->
gen_server:cast(?SERVER, {'destroy_channel', UUID, Node}).
-spec update(kz_term:ne_binary(), channel()) -> 'ok'.
update(UUID, Channel) ->
gen_server:call(?SERVER, {'update_channel', UUID, Channel}).
-spec update(kz_term:ne_binary(), pos_integer(), any()) -> 'ok'.
update(UUID, Key, Value) ->
updates(UUID, [{Key, Value}]).
-spec updates(kz_term:ne_binary(), channel_updates()) -> 'ok'.
updates(UUID, Updates) ->
gen_server:cast(?SERVER, {'channel_updates', UUID, Updates}).
-spec format_updates(kz_term:proplist()) -> kz_term:ne_binary().
format_updates(Updates) ->
Fields = record_info('fields', 'channel'),
Out = [io_lib:format("~s=~p", [lists:nth(Field - 1, Fields), V]) || {Field, V} <- Updates],
kz_binary:join(Out, <<",">>).
-spec count() -> non_neg_integer().
count() -> ets:info(?CHANNELS_TBL, 'size').
-spec match_presence(kz_term:ne_binary()) -> kz_term:proplist_kv(kz_term:ne_binary(), atom()).
match_presence(PresenceId) ->
MatchSpec = [{#channel{uuid = '$1'
,presence_id = '$2'
,node = '$3'
, _ = '_'
}
,[{'=:=', '$2', {'const', PresenceId}}]
,[{{'$1', '$3'}}]}
],
ets:select(?CHANNELS_TBL, MatchSpec).
-spec handle_query_auth_id(kz_json:object(), kz_term:proplist()) -> 'ok'.
handle_query_auth_id(JObj, _Props) ->
'true' = kapi_call:query_auth_id_req_v(JObj),
AuthId = kz_json:get_ne_binary_value(<<"Auth-ID">>, JObj),
Channels = case find_by_auth_id(AuthId) of
{'error', 'not_found'} -> [];
{'ok', C} -> C
end,
Resp = [{<<"Channels">>, Channels}
,{<<"Msg-ID">>, kz_api:msg_id(JObj)}
| kz_api:default_headers(?APP_NAME, ?APP_VERSION)
],
ServerId = kz_json:get_value(<<"Server-ID">>, JObj),
kapi_call:publish_query_auth_id_resp(ServerId, Resp).
-spec handle_query_user_channels(kz_json:object(), kz_term:proplist()) -> 'ok'.
handle_query_user_channels(JObj, _Props) ->
'true' = kapi_call:query_user_channels_req_v(JObj),
UserChannels0 = case kz_json:get_value(<<"Realm">>, JObj) of
'undefined' -> [];
Realm ->
Usernames = kz_json:get_first_defined([<<"Username">>
,<<"Usernames">>
], JObj),
find_by_user_realm(Usernames, Realm)
end,
UserChannels1 = case kz_json:get_value(<<"Authorizing-IDs">>, JObj) of
'undefined' -> [];
AuthIds -> find_by_authorizing_id(AuthIds)
end,
UserChannels2 = lists:keymerge(1, UserChannels0, UserChannels1),
handle_query_users_channels(JObj, UserChannels2).
-spec handle_query_users_channels(kz_json:object(), kz_term:proplist()) -> 'ok'.
handle_query_users_channels(JObj, Cs) ->
Channels = [Channel || {_, Channel} <- Cs],
send_user_query_resp(JObj, Channels).
-spec send_user_query_resp(kz_json:object(), kz_json:objects()) -> 'ok'.
send_user_query_resp(JObj, []) ->
case kz_json:is_true(<<"Active-Only">>, JObj, 'true') of
'true' -> lager:debug("no channels, not sending response");
'false' ->
lager:debug("no channels, sending empty response"),
Resp = [{<<"Channels">>, []}
,{<<"Msg-ID">>, kz_api:msg_id(JObj)}
| kz_api:default_headers(?APP_NAME, ?APP_VERSION)
],
ServerId = kz_json:get_value(<<"Server-ID">>, JObj),
lager:debug("sending back channel data to ~s", [ServerId]),
kapi_call:publish_query_user_channels_resp(ServerId, Resp)
end;
send_user_query_resp(JObj, Cs) ->
Resp = [{<<"Channels">>, Cs}
,{<<"Msg-ID">>, kz_api:msg_id(JObj)}
| kz_api:default_headers(?APP_NAME, ?APP_VERSION)
],
ServerId = kz_json:get_value(<<"Server-ID">>, JObj),
lager:debug("sending back channel data to ~s", [ServerId]),
kapi_call:publish_query_user_channels_resp(ServerId, Resp).
-spec handle_query_account_channels(kz_json:object(), kz_term:ne_binary()) -> 'ok'.
handle_query_account_channels(JObj, _) ->
AccountId = kz_json:get_value(<<"Account-ID">>, JObj),
case find_account_channels(AccountId) of
{'error', 'not_found'} -> send_account_query_resp(JObj, []);
{'ok', Cs} -> send_account_query_resp(JObj, Cs)
end.
-spec send_account_query_resp(kz_json:object(), kz_json:objects()) -> 'ok'.
send_account_query_resp(JObj, Cs) ->
Resp = [{<<"Channels">>, Cs}
,{<<"Msg-ID">>, kz_api:msg_id(JObj)}
| kz_api:default_headers(?APP_NAME, ?APP_VERSION)
],
ServerId = kz_json:get_value(<<"Server-ID">>, JObj),
lager:debug("sending back channel data to ~s", [ServerId]),
kapi_call:publish_query_account_channels_resp(ServerId, Resp).
-spec handle_query_channels(kz_json:object(), kz_term:proplist()) -> 'ok'.
handle_query_channels(JObj, _Props) ->
'true' = kapi_call:query_channels_req_v(JObj),
Fields = kz_json:get_value(<<"Fields">>, JObj, []),
CallId = kz_json:get_value(<<"Call-ID">>, JObj),
Channels = query_channels(Fields, CallId),
case kz_term:is_empty(Channels) and
kz_json:is_true(<<"Active-Only">>, JObj, 'false')
of
'true' ->
lager:debug("not sending query_channels resp due to active-only=true");
'false' ->
Resp = [{<<"Channels">>, Channels}
,{<<"Msg-ID">>, kz_api:msg_id(JObj)}
| kz_api:default_headers(?APP_NAME, ?APP_VERSION)
],
kapi_call:publish_query_channels_resp(kz_json:get_value(<<"Server-ID">>, JObj), Resp)
end.
-spec handle_channel_status(kz_json:object(), kz_term:proplist()) -> 'ok'.
handle_channel_status(JObj, _Props) ->
'true' = kapi_call:channel_status_req_v(JObj),
_ = kz_log:put_callid(JObj),
CallId = kz_api:call_id(JObj),
lager:debug("channel status request received"),
case ecallmgr_fs_channel:fetch(CallId) of
{'error', 'not_found'} ->
maybe_send_empty_channel_resp(CallId, JObj);
{'ok', Channel} ->
Node = kz_json:get_binary_value(<<"node">>, Channel),
Hostname = case binary:split(Node, <<"@">>) of
[_, Host] -> Host;
Other -> Other
end,
lager:debug("channel is on ~s", [Hostname]),
Resp =
props:filter_undefined(
[{<<"Call-ID">>, CallId}
,{<<"Status">>, <<"active">>}
,{<<"Switch-Hostname">>, Hostname}
,{<<"Switch-Nodename">>, kz_term:to_binary(Node)}
,{<<"Switch-URL">>, ecallmgr_fs_nodes:sip_url(Node)}
,{<<"Other-Leg-Call-ID">>, kz_json:get_value(<<"other_leg">>, Channel)}
,{<<"Realm">>, kz_json:get_value(<<"realm">>, Channel)}
,{<<"Username">>, kz_json:get_value(<<"username">>, Channel)}
,{<<"Custom-Channel-Vars">>, kz_json:from_list(ecallmgr_fs_channel:channel_ccvs(Channel))}
,{<<"Custom-Application-Vars">>, kz_json:from_list(ecallmgr_fs_channel:channel_cavs(Channel))}
,{<<"Msg-ID">>, kz_api:msg_id(JObj)}
| kz_api:default_headers(?APP_NAME, ?APP_VERSION)
]
),
kapi_call:publish_channel_status_resp(kz_api:server_id(JObj), Resp)
end.
-spec maybe_send_empty_channel_resp(kz_term:ne_binary(), kz_json:object()) -> 'ok'.
maybe_send_empty_channel_resp(CallId, JObj) ->
case kz_json:is_true(<<"Active-Only">>, JObj) of
'true' -> 'ok';
'false' -> send_empty_channel_resp(CallId, JObj)
end.
-spec send_empty_channel_resp(kz_term:ne_binary(), kz_json:object()) -> 'ok'.
send_empty_channel_resp(CallId, JObj) ->
Resp = [{<<"Call-ID">>, CallId}
,{<<"Status">>, <<"terminated">>}
,{<<"Error-Msg">>, <<"no node found with channel">>}
,{<<"Msg-ID">>, kz_api:msg_id(JObj)}
| kz_api:default_headers(?APP_NAME, ?APP_VERSION)
],
kapi_call:publish_channel_status_resp(kz_api:server_id(JObj), Resp).
-spec init([]) -> {'ok', state()}.
init([]) ->
kz_log:put_callid(?DEFAULT_LOG_SYSTEM_ID),
process_flag('trap_exit', 'true'),
lager:debug("starting new fs channels"),
_ = ets:new(?CHANNELS_TBL, ['set'
,'protected'
,'named_table'
,{'keypos', #channel.uuid}
,{read_concurrency, true}
]),
{'ok', #state{max_channel_cleanup_ref=start_cleanup_ref()}}.
-define(CLEANUP_TIMEOUT
,kapps_config:get_integer(?APP_NAME, <<"max_channel_cleanup_timeout_ms">>, ?MILLISECONDS_IN_MINUTE)
).
-spec start_cleanup_ref() -> reference().
start_cleanup_ref() ->
erlang:start_timer(?CLEANUP_TIMEOUT, self(), 'ok').
-spec handle_call(any(), kz_term:pid_ref(), state()) -> kz_types:handle_call_ret_state(state()).
handle_call({'new_channel', #channel{uuid=UUID}=Channel}, _, State) ->
case ets:insert_new(?CHANNELS_TBL, Channel) of
'true'->
lager:debug("channel ~s added", [UUID]),
{'reply', 'ok', State};
'false' ->
lager:debug("channel ~s already exists", [UUID]),
{'reply', {'error', 'channel_exists'}, State}
end;
handle_call({'update_channel', UUID, Channel}, _, State) ->
lager:debug("updating channel ~s", [UUID]),
ets:insert(?CHANNELS_TBL, Channel),
{'reply', 'ok', State};
handle_call({'channel_updates', _UUID, []}, _, State) ->
{'reply', 'ok', State};
handle_call({'channel_updates', UUID, Update}, _, State) ->
ets:update_element(?CHANNELS_TBL, UUID, Update),
{'reply', 'ok', State};
handle_call(_, _, State) ->
{'reply', {'error', 'not_implemented'}, State}.
-spec handle_cast(any(), state()) -> {'noreply', state()}.
handle_cast({'channel_updates', UUID, Updates}, State) ->
kz_log:put_callid(UUID),
lager:debug("updating channel properties: ~s", [format_updates(Updates)]),
ets:update_element(?CHANNELS_TBL, UUID, Updates),
{'noreply', State};
handle_cast({'destroy_channel', UUID, Node}, State) ->
kz_log:put_callid(UUID),
MatchSpec = [{#channel{uuid='$1', node='$2', _ = '_'}
,[{'andalso', {'=:=', '$2', {'const', Node}}
,{'=:=', '$1', UUID}}
],
['true']
}],
N = ets:select_delete(?CHANNELS_TBL, MatchSpec),
lager:debug("removed ~p channel(s) with id ~s on ~s", [N, UUID, Node]),
{'noreply', State, 'hibernate'};
handle_cast({'sync_channels', Node, Channels}, State) ->
lager:debug("ensuring channel cache is in sync with ~s", [Node]),
MatchSpec = [{#channel{uuid = '$1', node = '$2', _ = '_'}
,[{'=:=', '$2', {'const', Node}}]
,['$1']}
],
CachedChannels = sets:from_list(ets:select(?CHANNELS_TBL, MatchSpec)),
SyncChannels = sets:from_list(Channels),
Remove = sets:subtract(CachedChannels, SyncChannels),
Add = sets:subtract(SyncChannels, CachedChannels),
_ = [delete_and_maybe_disconnect(Node, UUID, ets:lookup(?CHANNELS_TBL, UUID))
|| UUID <- sets:to_list(Remove)
],
_ = [begin
lager:debug("trying to add channel ~s to cache during sync with ~s", [UUID, Node]),
case ecallmgr_fs_channel:renew(Node, UUID) of
{'error', _R} -> lager:warning("failed to sync channel ~s: ~p", [UUID, _R]);
{'ok', C} ->
lager:debug("added channel ~s to cache during sync with ~s", [UUID, Node]),
ets:insert(?CHANNELS_TBL, C),
PublishReconect = kapps_config:get_boolean(?APP_NAME, <<"publish_channel_reconnect">>, 'false'),
handle_channel_reconnected(C, PublishReconect)
end
end
|| UUID <- sets:to_list(Add)
],
{'noreply', State, 'hibernate'};
handle_cast({'flush_node', Node}, State) ->
lager:debug("flushing all channels in cache associated to node ~s", [Node]),
LocalChannelsMS = [{#channel{node = '$1'
,handling_locally='true'
,_ = '_'
}
,[{'=:=', '$1', {'const', Node}}]
,['$_']}
],
case ets:select(?CHANNELS_TBL, LocalChannelsMS) of
[] ->
lager:debug("no locally handled channels");
LocalChannels ->
_P = kz_process:spawn(fun handle_channels_disconnected/1, [LocalChannels]),
lager:debug("sending channel disconnects for local channels: ~p", [LocalChannels])
end,
MatchSpec = [{#channel{node = '$1', _ = '_'}
,[{'=:=', '$1', {'const', Node}}]
,['true']}
],
ets:select_delete(?CHANNELS_TBL, MatchSpec),
{'noreply', State};
handle_cast({'gen_listener',{'created_queue', _QueueName}}, State) ->
{'noreply', State};
handle_cast({'gen_listener',{'is_consuming',_IsConsuming}}, State) ->
{'noreply', State};
handle_cast(_Req, State) ->
lager:debug("unhandled cast: ~p", [_Req]),
{'noreply', State}.
-spec handle_info(any(), state()) -> kz_types:handle_info_ret_state(state()).
handle_info({'timeout', Ref, _Msg}, #state{max_channel_cleanup_ref=Ref}=State) ->
maybe_cleanup_old_channels(),
{'noreply', State#state{max_channel_cleanup_ref=start_cleanup_ref()}};
handle_info(_Msg, State) ->
lager:debug("unhandled message: ~p", [_Msg]),
{'noreply', State}.
-spec handle_event(kz_json:object(), state()) -> gen_listener:handle_event_return().
handle_event(_JObj, #state{}) ->
{'reply', []}.
with . The return value is ignored .
-spec terminate(any(), state()) -> 'ok'.
terminate(_Reason, #state{}) ->
ets:delete(?CHANNELS_TBL),
lager:info("fs channels terminating: ~p", [_Reason]).
-spec code_change(any(), state(), any()) -> {'ok', state()}.
code_change(_OldVsn, State, _Extra) ->
{'ok', State}.
Internal functions
-spec find_by_auth_id(kz_term:ne_binary()) ->
{'ok', kz_json:objects()} |
{'error', 'not_found'}.
find_by_auth_id(AuthorizingId) ->
MatchSpec = [{#channel{authorizing_id = '$1', _ = '_'}
,[{'=:=', '$1', {'const', AuthorizingId}}]
,['$_']}
],
case ets:select(?CHANNELS_TBL, MatchSpec) of
[] -> {'error', 'not_found'};
Channels -> {'ok', [ecallmgr_fs_channel:to_json(Channel)
|| Channel <- Channels
]}
end.
-spec has_channels_for_owner(kz_term:ne_binary()) -> boolean().
has_channels_for_owner(OwnerId) ->
MatchSpec = [{#channel{owner_id = '$1'
,_ = '_'
}
,[]
,[{'=:=', '$1', {const, OwnerId}}]
}
],
Count = ets:select_count(?CHANNELS_TBL, MatchSpec),
lager:info("found ~p channels", [Count]),
Count > 0.
-spec find_by_authorizing_id(kz_term:ne_binaries()) -> [] | kz_term:proplist().
find_by_authorizing_id(AuthIds) ->
find_by_authorizing_id(AuthIds, []).
-spec find_by_authorizing_id(kz_term:ne_binaries(), kz_term:proplist()) -> [] | kz_term:proplist().
find_by_authorizing_id([], Acc) -> Acc;
find_by_authorizing_id([AuthId|AuthIds], Acc) ->
Pattern = #channel{authorizing_id=AuthId
,_='_'},
case ets:match_object(?CHANNELS_TBL, Pattern) of
[] -> find_by_authorizing_id(AuthIds, Acc);
Channels ->
Cs = [{Channel#channel.uuid, ecallmgr_fs_channel:to_json(Channel)}
|| Channel <- Channels
],
find_by_authorizing_id(AuthIds, lists:keymerge(1, Acc, Cs))
end.
-spec find_by_user_realm(kz_term:api_binary() | kz_term:ne_binaries(), kz_term:ne_binary()) -> [] | kz_term:proplist().
find_by_user_realm('undefined', Realm) ->
Pattern = #channel{realm=kz_term:to_lower_binary(Realm)
,_='_'},
case ets:match_object(?CHANNELS_TBL, Pattern) of
[] -> [];
Channels ->
[{Channel#channel.uuid, ecallmgr_fs_channel:to_json(Channel)}
|| Channel <- Channels
]
end;
find_by_user_realm(<<?CALL_PARK_FEATURE, _/binary>>=Username, Realm) ->
Pattern = #channel{destination=kz_term:to_lower_binary(Username)
,realm=kz_term:to_lower_binary(Realm)
,other_leg='undefined'
,_='_'},
case ets:match_object(?CHANNELS_TBL, Pattern) of
[] -> [];
Channels ->
[{Channel#channel.uuid, ecallmgr_fs_channel:to_json(Channel)}
|| Channel <- Channels
]
end;
find_by_user_realm(Usernames, Realm) when is_list(Usernames) ->
ETSUsernames = build_matchspec_ors(Usernames),
MatchSpec = [{#channel{username='$1'
,realm=kz_term:to_lower_binary(Realm)
,_ = '_'}
,[ETSUsernames]
,['$_']
}],
case ets:select(?CHANNELS_TBL, MatchSpec) of
[] -> [];
Channels ->
[{Channel#channel.uuid, ecallmgr_fs_channel:to_json(Channel)}
|| Channel <- Channels
]
end;
find_by_user_realm(Username, Realm) ->
Pattern = #channel{username=kz_term:to_lower_binary(Username)
,realm=kz_term:to_lower_binary(Realm)
,_='_'},
case ets:match_object(?CHANNELS_TBL, Pattern) of
[] -> [];
Channels ->
[{Channel#channel.uuid, ecallmgr_fs_channel:to_json(Channel)}
|| Channel <- Channels
]
end.
-spec find_account_channels(kz_term:ne_binary()) ->
{'ok', kz_json:objects()} |
{'error', 'not_found'}.
find_account_channels(<<"all">>) ->
case ets:match_object(?CHANNELS_TBL, #channel{_='_'}) of
[] -> {'error', 'not_found'};
Channels ->
{'ok', [ecallmgr_fs_channel:to_json(Channel)
|| Channel <- Channels
]}
end;
find_account_channels(AccountId) ->
case ets:match_object(?CHANNELS_TBL, #channel{account_id=AccountId, _='_'}) of
[] -> {'error', 'not_found'};
Channels ->
{'ok', [ecallmgr_fs_channel:to_json(Channel)
|| Channel <- Channels
]}
end.
-spec build_matchspec_ors(kz_term:ne_binaries()) -> tuple() | 'false'.
build_matchspec_ors(Usernames) ->
lists:foldl(fun build_matchspec_ors_fold/2
,'false'
,Usernames
).
-spec build_matchspec_ors_fold(kz_term:ne_binary(), tuple() | 'false') -> tuple().
build_matchspec_ors_fold(Username, Acc) ->
{'or', {'=:=', '$1', kz_term:to_lower_binary(Username)}, Acc}.
-spec query_channels(kz_term:ne_binaries(), kz_term:api_binary()) -> kz_json:object().
query_channels(Fields, 'undefined') ->
query_channels(ets:match_object(?CHANNELS_TBL, #channel{_='_'}, 1)
,Fields
,kz_json:new()
);
query_channels(Fields, CallId) ->
query_channels(ets:match_object(?CHANNELS_TBL, #channel{uuid=CallId, _='_'}, 1)
,Fields
,kz_json:new()
).
-spec query_channels({[channel()], ets:continuation()} | '$end_of_table', kz_term:ne_binary() | kz_term:ne_binaries(), kz_json:object()) ->
kz_json:object().
query_channels('$end_of_table', _, Channels) -> Channels;
query_channels({[#channel{uuid=CallId}=Channel], Continuation}
,<<"all">>, Channels) ->
JObj = ecallmgr_fs_channel:to_api_json(Channel),
query_channels(ets:match_object(Continuation)
,<<"all">>
,kz_json:set_value(CallId, JObj, Channels)
);
query_channels({[#channel{uuid=CallId}=Channel], Continuation}
,Fields, Channels) ->
ChannelProps = ecallmgr_fs_channel:to_api_props(Channel),
JObj = kz_json:from_list(
[{Field, props:get_value(Field, ChannelProps)}
|| Field <- Fields
]),
query_channels(ets:match_object(Continuation)
,Fields
,kz_json:set_value(CallId, JObj, Channels)
).
-define(SUMMARY_HEADER, "| ~-50s | ~-40s | ~-9s | ~-15s | ~-32s |~n").
print_summary('$end_of_table') ->
io:format("No channels found!~n", []);
print_summary(Match) ->
io:format("+----------------------------------------------------+------------------------------------------+-----------+-----------------+----------------------------------+~n"),
io:format(?SUMMARY_HEADER
,[ <<"UUID">>, <<"Node">>, <<"Direction">>, <<"Destination">>, <<"Account-ID">>]
),
io:format("+====================================================+==========================================+===========+=================+==================================+~n"),
print_summary(Match, 0).
print_summary('$end_of_table', Count) ->
io:format("+----------------------------------------------------+------------------------------------------+-----------+-----------------+----------------------------------+~n"),
io:format("Found ~p channels~n", [Count]);
print_summary({[#channel{uuid=UUID
,node=Node
,direction=Direction
,destination=Destination
,account_id=AccountId
}]
,Continuation}
,Count) ->
io:format(?SUMMARY_HEADER
,[UUID, Node, Direction, Destination, AccountId]
),
print_summary(ets:select(Continuation), Count + 1).
print_details('$end_of_table') ->
io:format("No channels found!~n", []);
print_details(Match) ->
print_details(Match, 0).
print_details('$end_of_table', Count) ->
io:format("~nFound ~p channels~n", [Count]);
print_details({[#channel{}=Channel]
,Continuation}
,Count) ->
io:format("~n"),
_ = [io:format("~-19s: ~s~n", [K, kz_term:to_binary(V)])
|| {K, V} <- ecallmgr_fs_channel:to_props(Channel),
not kz_json:is_json_object(V)
],
print_details(ets:select(Continuation), Count + 1).
-spec handle_channel_reconnected(channel(), boolean()) -> 'ok'.
handle_channel_reconnected(#channel{handling_locally='true'
,uuid=_UUID
}=Channel
,'true') ->
lager:debug("channel ~s connected, publishing update", [_UUID]),
publish_channel_connection_event(Channel, [{<<"Event-Name">>, <<"CHANNEL_CONNECTED">>}]);
handle_channel_reconnected(_Channel, _ShouldPublish) ->
'ok'.
-spec handle_channels_disconnected(channels()) -> 'ok'.
handle_channels_disconnected(LocalChannels) ->
_ = [catch handle_channel_disconnected(LocalChannel) || LocalChannel <- LocalChannels],
'ok'.
-spec handle_channel_disconnected(channel()) -> 'ok'.
handle_channel_disconnected(Channel) ->
publish_channel_connection_event(Channel, [{<<"Event-Name">>, <<"CHANNEL_DISCONNECTED">>}]).
-spec publish_channel_connection_event(channel(), kz_term:proplist()) -> 'ok'.
publish_channel_connection_event(#channel{uuid=UUID
,direction=Direction
,node=Node
,presence_id=PresenceId
,answered=IsAnswered
,from=From
,to=To
}=Channel
,ChannelSpecific) ->
Event = [{<<"Timestamp">>, kz_time:now_s()}
,{<<"Call-ID">>, UUID}
,{<<"Call-Direction">>, Direction}
,{<<"Media-Server">>, Node}
,{<<"Custom-Channel-Vars">>, connection_ccvs(Channel)}
,{<<"Custom-Application-Vars">>, connection_cavs(Channel)}
,{<<"To">>, To}
,{<<"From">>, From}
,{<<"Presence-ID">>, PresenceId}
,{<<"Channel-Call-State">>, channel_call_state(IsAnswered)}
| kz_api:default_headers(?APP_NAME, ?APP_VERSION) ++ ChannelSpecific
],
_ = kz_amqp_worker:cast(Event, fun kapi_call:publish_event/1),
lager:debug("published channel connection event (~s) for ~s", [kz_api:event_name(Event), UUID]).
-spec channel_call_state(boolean()) -> kz_term:api_binary().
channel_call_state('true') ->
<<"ANSWERED">>;
channel_call_state('false') ->
'undefined'.
-spec connection_ccvs(channel()) -> kz_term:api_object().
connection_ccvs(#channel{ccvs=CCVs}) -> CCVs.
-spec connection_cavs(channel()) -> kz_term:api_object().
connection_cavs(#channel{cavs=CAVs}) -> CAVs.
-define(MAX_CHANNEL_UPTIME_KEY, <<"max_channel_uptime_s">>).
-spec max_channel_uptime() -> non_neg_integer().
max_channel_uptime() ->
kapps_config:get_integer(?APP_NAME, ?MAX_CHANNEL_UPTIME_KEY, 0).
-spec set_max_channel_uptime(non_neg_integer()) ->
{'ok', kz_json:object()} |
kz_datamgr:data_error().
set_max_channel_uptime(MaxAge) ->
set_max_channel_uptime(MaxAge, 'true').
-spec set_max_channel_uptime(non_neg_integer(), boolean()) ->
{'ok', kz_json:object()} |
kz_datamgr:data_error().
set_max_channel_uptime(MaxAge, 'true') ->
kapps_config:set_default(?APP_NAME, ?MAX_CHANNEL_UPTIME_KEY, kz_term:to_integer(MaxAge));
set_max_channel_uptime(MaxAge, 'false') ->
kapps_config:set(?APP_NAME, ?MAX_CHANNEL_UPTIME_KEY, kz_term:to_integer(MaxAge)).
-spec maybe_cleanup_old_channels() -> 'ok'.
maybe_cleanup_old_channels() ->
case max_channel_uptime() of
N when N =< 0 -> 'ok';
MaxAge ->
_P = kz_process:spawn(fun cleanup_old_channels/1, [MaxAge]),
'ok'
end.
-spec cleanup_old_channels() -> non_neg_integer().
cleanup_old_channels() ->
cleanup_old_channels(max_channel_uptime()).
-spec cleanup_old_channels(non_neg_integer()) -> non_neg_integer().
cleanup_old_channels(MaxAge) ->
NoOlderThan = kz_time:now_s() - MaxAge,
MatchSpec = [{#channel{uuid='$1'
,node='$2'
,timestamp='$3'
,handling_locally='true'
,_ = '_'
}
,[{'<', '$3', NoOlderThan}]
,[['$1', '$2', '$3']]
}],
case ets:select(?CHANNELS_TBL, MatchSpec) of
[] -> 0;
OldChannels ->
N = length(OldChannels),
lager:debug("~p channels over ~p seconds old", [N, MaxAge]),
hangup_old_channels(OldChannels),
N
end.
-type old_channel() :: [kz_term:ne_binary() | atom() | kz_time:gregorian_seconds()].
-type old_channels() :: [old_channel(),...].
-spec hangup_old_channels(old_channels()) -> 'ok'.
hangup_old_channels(OldChannels) ->
lists:foreach(fun hangup_old_channel/1, OldChannels).
-spec hangup_old_channel(old_channel()) -> 'ok'.
hangup_old_channel([UUID, Node, Started]) ->
lager:debug("killing channel ~s on ~s, started ~s"
,[UUID, Node, kz_time:pretty_print_datetime(Started)]),
freeswitch:api(Node, 'uuid_kill', UUID).
-spec delete_and_maybe_disconnect(atom(), kz_term:ne_binary(), [channel()]) -> 'ok' | 'true'.
delete_and_maybe_disconnect(Node, UUID, [#channel{handling_locally='true'}=Channel]) ->
lager:debug("emitting channel disconnect ~s during sync with ~s", [UUID, Node]),
handle_channel_disconnected(Channel),
ets:delete(?CHANNELS_TBL, UUID);
delete_and_maybe_disconnect(Node, UUID, [_Channel]) ->
lager:debug("removed channel ~s from cache during sync with ~s", [UUID, Node]),
ets:delete(?CHANNELS_TBL, UUID);
delete_and_maybe_disconnect(Node, UUID, []) ->
lager:debug("channel ~s not found during sync delete with ~s", [UUID, Node]).
|
803b8701785d7db78c1212747c2150bc56ef4787c281ced7e86fa01fe2b88840 | mtravers/wuwei | t-session.lisp | (in-package :wu)
(5am:def-suite :session :in :wuwei)
(5am:in-suite :session)
;;; Tests of session and login machinery
;;; Test dropping a cookie to establish session
(5am:test session-basics
(publish :path (test-path "session1")
:function #'(lambda (req ent)
(with-session (req ent)
(with-http-response-and-body (req ent)
(html (:html (:body "foo")))))))
(let ((cookie-jar (make-instance 'net.aserve.client:cookie-jar)))
(multiple-value-bind (response response-code response-headers)
(net.aserve.client::do-http-request (test-url "session1")
:cookies cookie-jar)
(declare (ignore response response-headers))
(5am:is (equal 200 response-code))
(5am:is (net.aserve.client::cookie-jar-items cookie-jar)))))
(def-session-variable *test-2* 0)
;;; Test session variable machinery without a web trip
(5am:test session-variables
(let ((*session* (make-new-session nil nil)))
(with-session-variables
(5am:is (equal 0 *test-2*))
(incf *test-2*))
(let ((*test-2* nil))
(with-session-variables
(5am:is (equal 1 *test-2*))))))
(def-session-variable *test-session-var* 0)
Test that session state is working ( combines the above two )
(5am:test session-state
(publish :path (test-path "session2")
:function #'(lambda (req ent)
(with-session (req ent)
(with-http-response-and-body (req ent)
(html (:html (:body (:princ "v") (:princ *test-session-var*))))
(incf *test-session-var*)
))))
(let ((cookie-jar (make-instance 'net.aserve.client:cookie-jar)))
(multiple-value-bind (response response-code response-headers)
(net.aserve.client::do-http-request (test-url "session2")
:cookies cookie-jar)
(declare (ignore response-headers))
(5am:is (equal 200 response-code))
(5am:is (net.aserve.client::cookie-jar-items cookie-jar))
(5am:is (search "v0" response)))
(multiple-value-bind (response response-code response-headers)
(net.aserve.client::do-http-request (test-url "session2")
:cookies cookie-jar)
(declare (ignore response-code response-headers))
(5am:is (search "v1" response)))
))
(defun test-login (req ent)
(with-http-response-and-body (req ent)
(render-update
(:redirect "/login"))))
;;; This is how you do a login. Note that the make-new-session has to be OUTSIDE the with-http-response-and-body, to allow the cookies to be set early.
(publish :path (test-path "login")
:function #'(lambda (req ent)
(setq *session* (make-new-session req ent))
(with-http-response-and-body (req ent)
(html "logged in"))
))
;;; Tests protection of an ajax method against unlogged-in users, and logging in.
(5am:test login-required
(let* ((test nil)
(url (format nil ":~A~A"
*test-port*
(ajax-continuation (:login-handler 'test-login :keep t)
(setq test t)
(render-update (:alert "snockity"))))))
(let ((res (net.aserve.client:do-http-request url :method :post :query '((:bogus . "value")))))
(5am:is (not test)) ;should NOT run the continuation
;; Should be getting a redirect command back
(5am:is (search "window.location.href" res)))
;; simulate a login and try again
(let ((cookie-jar (make-instance 'net.aserve.client:cookie-jar)))
(multiple-value-bind (response response-code response-headers)
(net.aserve.client::do-http-request (test-url "login")
:cookies cookie-jar)
(declare (ignore response response-headers))
(5am:is (equal 200 response-code))
(5am:is (net.aserve.client::cookie-jar-items cookie-jar))
(let ((res (net.aserve.client:do-http-request url :method :post :query '((:bogus . "value"))
:cookies cookie-jar)))
(5am:is-true test)
(5am:is (search "alert(" res)))
))))
| null | https://raw.githubusercontent.com/mtravers/wuwei/c0968cca10554fa12567d48be6f932bf4418dbe1/t/t-session.lisp | lisp | Tests of session and login machinery
Test dropping a cookie to establish session
Test session variable machinery without a web trip
This is how you do a login. Note that the make-new-session has to be OUTSIDE the with-http-response-and-body, to allow the cookies to be set early.
Tests protection of an ajax method against unlogged-in users, and logging in.
should NOT run the continuation
Should be getting a redirect command back
simulate a login and try again | (in-package :wu)
(5am:def-suite :session :in :wuwei)
(5am:in-suite :session)
(5am:test session-basics
(publish :path (test-path "session1")
:function #'(lambda (req ent)
(with-session (req ent)
(with-http-response-and-body (req ent)
(html (:html (:body "foo")))))))
(let ((cookie-jar (make-instance 'net.aserve.client:cookie-jar)))
(multiple-value-bind (response response-code response-headers)
(net.aserve.client::do-http-request (test-url "session1")
:cookies cookie-jar)
(declare (ignore response response-headers))
(5am:is (equal 200 response-code))
(5am:is (net.aserve.client::cookie-jar-items cookie-jar)))))
(def-session-variable *test-2* 0)
(5am:test session-variables
(let ((*session* (make-new-session nil nil)))
(with-session-variables
(5am:is (equal 0 *test-2*))
(incf *test-2*))
(let ((*test-2* nil))
(with-session-variables
(5am:is (equal 1 *test-2*))))))
(def-session-variable *test-session-var* 0)
Test that session state is working ( combines the above two )
(5am:test session-state
(publish :path (test-path "session2")
:function #'(lambda (req ent)
(with-session (req ent)
(with-http-response-and-body (req ent)
(html (:html (:body (:princ "v") (:princ *test-session-var*))))
(incf *test-session-var*)
))))
(let ((cookie-jar (make-instance 'net.aserve.client:cookie-jar)))
(multiple-value-bind (response response-code response-headers)
(net.aserve.client::do-http-request (test-url "session2")
:cookies cookie-jar)
(declare (ignore response-headers))
(5am:is (equal 200 response-code))
(5am:is (net.aserve.client::cookie-jar-items cookie-jar))
(5am:is (search "v0" response)))
(multiple-value-bind (response response-code response-headers)
(net.aserve.client::do-http-request (test-url "session2")
:cookies cookie-jar)
(declare (ignore response-code response-headers))
(5am:is (search "v1" response)))
))
(defun test-login (req ent)
(with-http-response-and-body (req ent)
(render-update
(:redirect "/login"))))
(publish :path (test-path "login")
:function #'(lambda (req ent)
(setq *session* (make-new-session req ent))
(with-http-response-and-body (req ent)
(html "logged in"))
))
(5am:test login-required
(let* ((test nil)
(url (format nil ":~A~A"
*test-port*
(ajax-continuation (:login-handler 'test-login :keep t)
(setq test t)
(render-update (:alert "snockity"))))))
(let ((res (net.aserve.client:do-http-request url :method :post :query '((:bogus . "value")))))
(5am:is (search "window.location.href" res)))
(let ((cookie-jar (make-instance 'net.aserve.client:cookie-jar)))
(multiple-value-bind (response response-code response-headers)
(net.aserve.client::do-http-request (test-url "login")
:cookies cookie-jar)
(declare (ignore response response-headers))
(5am:is (equal 200 response-code))
(5am:is (net.aserve.client::cookie-jar-items cookie-jar))
(let ((res (net.aserve.client:do-http-request url :method :post :query '((:bogus . "value"))
:cookies cookie-jar)))
(5am:is-true test)
(5am:is (search "alert(" res)))
))))
|
6929a6c0f92145823e7b5e2a701c9e7d614559dd2942299a2b69f7e47275c517 | itchyny/miv | Cmdline.hs | # , LambdaCase , OverloadedStrings #
module Cmdline where
import Data.Text (Text, unpack)
import Data.YAML
import Prelude hiding (show)
import ShowText
data Cmdline = CmdlineExCommand
| CmdlineForwardSearch
| CmdlineBackwardSearch
| CmdlineInput
deriving (Eq, Ord)
instance ShowText Cmdline where
show CmdlineExCommand = ":"
show CmdlineForwardSearch = "/"
show CmdlineBackwardSearch = "?"
show CmdlineInput = "@"
instance FromYAML Cmdline where
parseYAML = withStr "!!str" \case
":" -> return CmdlineExCommand
"/" -> return CmdlineForwardSearch
"?" -> return CmdlineBackwardSearch
"@" -> return CmdlineInput
x -> fail $ unpack $ "failed to parse cmdline: " <> x
cmdlinePattern :: Cmdline -> Text
cmdlinePattern CmdlineExCommand = ":"
cmdlinePattern CmdlineForwardSearch = "/"
cmdlinePattern CmdlineBackwardSearch = "\\?"
cmdlinePattern CmdlineInput = "@"
| null | https://raw.githubusercontent.com/itchyny/miv/36aba3a52e3169654af482cee6181172194a347e/src/Cmdline.hs | haskell | # , LambdaCase , OverloadedStrings #
module Cmdline where
import Data.Text (Text, unpack)
import Data.YAML
import Prelude hiding (show)
import ShowText
data Cmdline = CmdlineExCommand
| CmdlineForwardSearch
| CmdlineBackwardSearch
| CmdlineInput
deriving (Eq, Ord)
instance ShowText Cmdline where
show CmdlineExCommand = ":"
show CmdlineForwardSearch = "/"
show CmdlineBackwardSearch = "?"
show CmdlineInput = "@"
instance FromYAML Cmdline where
parseYAML = withStr "!!str" \case
":" -> return CmdlineExCommand
"/" -> return CmdlineForwardSearch
"?" -> return CmdlineBackwardSearch
"@" -> return CmdlineInput
x -> fail $ unpack $ "failed to parse cmdline: " <> x
cmdlinePattern :: Cmdline -> Text
cmdlinePattern CmdlineExCommand = ":"
cmdlinePattern CmdlineForwardSearch = "/"
cmdlinePattern CmdlineBackwardSearch = "\\?"
cmdlinePattern CmdlineInput = "@"
|
|
f54983da5f39ec41dcfe50ca8dfd0eafe11b882645f0a3197262d533fbce4fca | rabbitmq/rabbitmq-status | status_render.erl | The contents of this file are subject to the Mozilla Public License
Version 1.1 ( the " License " ) ; you may not use this file except in
%% compliance with the License. You may obtain a copy of the License at
%% /
%%
Software distributed under the License is distributed on an " AS IS "
%% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
%% License for the specific language governing rights and limitations
%% under the License.
%%
The Original Code is RabbitMQ Status Plugin .
%%
The Initial Developers of the Original Code are LShift Ltd.
%%
Copyright ( C ) 2009 LShift Ltd.
%%
%% All Rights Reserved.
%%
%% Contributor(s): ______________________________________.
%%
-module(status_render).
-export([render_conns/0, render_queues/0, widget_to_binary/1]).
-export([escape/1, format_info_item/2, format_info/2, print/2]).
-include_lib("rabbit_common/include/rabbit.hrl").
%%--------------------------------------------------------------------
render_conns() ->
ConnKeys = [pid, address, port, peer_address, peer_port, recv_oct, recv_cnt,
send_oct, send_cnt, send_pend, state,
channels, user, vhost, timeout, frame_max],
Conns = rabbit_networking:connection_info_all(),
[[{Key, format_info_item(Key, Conn)} || Key <- ConnKeys] || Conn <- Conns].
render_queues() ->
QueueKeys = [name, durable, auto_delete, arguments, pid, messages_ready,
messages_unacknowledged, messages, consumers, memory],
Queues = lists:flatten([
[{Vhost, Queue} || Queue <- rabbit_amqqueue:info_all(Vhost)]
|| Vhost <- rabbit_access_control:list_vhosts()]),
[[{vhost, format_info(vhost, Vhost)}] ++
[{Key, format_info_item(Key, Queue)} || Key <- QueueKeys]
|| {Vhost, Queue} <- Queues].
widget_to_binary(A) ->
case A of
B when is_binary(B) -> B;
F when is_float(F) -> print("~.3f", [F]);
N when is_number(N) -> print("~p", [N]);
L when is_list(L) ->
case io_lib:printable_list(L) of
true -> L;
false -> lists:map(fun (C) -> widget_to_binary(C) end, L)
end;
{escape, Body} when is_binary(Body) orelse is_list(Body) ->
print("~s", [Body]);
{escape, Body} ->
print("~w", Body);
{memory, Mem} when is_number(Mem) ->
print("~pMB", [trunc(Mem/1048576)]);
{memory, Mem} ->
print("~p", [Mem]);
{Form, Body} when is_list(Body) ->
print(Form, Body);
{Form, Body} ->
print(Form, [Body]);
P -> print("~p", [P]) %% shouldn't be used, better to escape.
end.
print(Fmt, Val) when is_list(Val) ->
escape(lists:flatten(io_lib:format(Fmt, Val)));
print(Fmt, Val) ->
print(Fmt, [Val]).
print_no_escape(Fmt, Val) when is_list(Val) ->
list_to_binary(lists:flatten(io_lib:format(Fmt, Val))).
escape(A) ->
mochiweb_html:escape(A).
format_info_item(Key, Items) ->
format_info(Key, proplists:get_value(Key, Items)).
format_info(Key, Value) ->
case Value of
#resource{name = Name} -> %% queue name
Name;
Value when (Key =:= address orelse Key =:= peer_address) andalso
is_tuple(Value) ->
list_to_binary(inet_parse:ntoa(Value));
Value when is_number(Value) -> %% memory stats, counters
Value;
Value when is_binary(Value) -> %% vhost, username
Value;
Value -> %% queue arguments
print_no_escape("~w", [Value])
end.
| null | https://raw.githubusercontent.com/rabbitmq/rabbitmq-status/121829bb890ee6465d7c92b034f571a85df29f8f/src/status_render.erl | erlang | compliance with the License. You may obtain a copy of the License at
/
basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
License for the specific language governing rights and limitations
under the License.
All Rights Reserved.
Contributor(s): ______________________________________.
--------------------------------------------------------------------
shouldn't be used, better to escape.
queue name
memory stats, counters
vhost, username
queue arguments | The contents of this file are subject to the Mozilla Public License
Version 1.1 ( the " License " ) ; you may not use this file except in
Software distributed under the License is distributed on an " AS IS "
The Original Code is RabbitMQ Status Plugin .
The Initial Developers of the Original Code are LShift Ltd.
Copyright ( C ) 2009 LShift Ltd.
-module(status_render).
-export([render_conns/0, render_queues/0, widget_to_binary/1]).
-export([escape/1, format_info_item/2, format_info/2, print/2]).
-include_lib("rabbit_common/include/rabbit.hrl").
render_conns() ->
ConnKeys = [pid, address, port, peer_address, peer_port, recv_oct, recv_cnt,
send_oct, send_cnt, send_pend, state,
channels, user, vhost, timeout, frame_max],
Conns = rabbit_networking:connection_info_all(),
[[{Key, format_info_item(Key, Conn)} || Key <- ConnKeys] || Conn <- Conns].
render_queues() ->
QueueKeys = [name, durable, auto_delete, arguments, pid, messages_ready,
messages_unacknowledged, messages, consumers, memory],
Queues = lists:flatten([
[{Vhost, Queue} || Queue <- rabbit_amqqueue:info_all(Vhost)]
|| Vhost <- rabbit_access_control:list_vhosts()]),
[[{vhost, format_info(vhost, Vhost)}] ++
[{Key, format_info_item(Key, Queue)} || Key <- QueueKeys]
|| {Vhost, Queue} <- Queues].
widget_to_binary(A) ->
case A of
B when is_binary(B) -> B;
F when is_float(F) -> print("~.3f", [F]);
N when is_number(N) -> print("~p", [N]);
L when is_list(L) ->
case io_lib:printable_list(L) of
true -> L;
false -> lists:map(fun (C) -> widget_to_binary(C) end, L)
end;
{escape, Body} when is_binary(Body) orelse is_list(Body) ->
print("~s", [Body]);
{escape, Body} ->
print("~w", Body);
{memory, Mem} when is_number(Mem) ->
print("~pMB", [trunc(Mem/1048576)]);
{memory, Mem} ->
print("~p", [Mem]);
{Form, Body} when is_list(Body) ->
print(Form, Body);
{Form, Body} ->
print(Form, [Body]);
end.
print(Fmt, Val) when is_list(Val) ->
escape(lists:flatten(io_lib:format(Fmt, Val)));
print(Fmt, Val) ->
print(Fmt, [Val]).
print_no_escape(Fmt, Val) when is_list(Val) ->
list_to_binary(lists:flatten(io_lib:format(Fmt, Val))).
escape(A) ->
mochiweb_html:escape(A).
format_info_item(Key, Items) ->
format_info(Key, proplists:get_value(Key, Items)).
format_info(Key, Value) ->
case Value of
Name;
Value when (Key =:= address orelse Key =:= peer_address) andalso
is_tuple(Value) ->
list_to_binary(inet_parse:ntoa(Value));
Value;
Value;
print_no_escape("~w", [Value])
end.
|
8c7215f07b8e79a1ebc54584b351584d5bf2e52521cefa97f71250c0a36ff267 | redplanetlabs/proxy-plus | project.clj | (defproject com.rpl/proxy-plus "0.0.9-SNAPSHOT"
:description "A faster and more usable replacement for Clojure's proxy."
:java-source-paths ["test/java"]
:test-paths ["test/clj"]
:dependencies [[org.clojure/clojure "1.10.0"]
[com.rpl/specter "1.1.3"]
[org.ow2.asm/asm "4.2"]
[org.ow2.asm/asm-commons "4.2"]
[org.ow2.asm/asm-util "4.2"]
[org.ow2.asm/asm-analysis "4.2"]]
:profiles {:bench {:dependencies [[criterium "0.4.5"]]}
}
)
| null | https://raw.githubusercontent.com/redplanetlabs/proxy-plus/32190425408625eb3721af456ed15586983b9351/project.clj | clojure | (defproject com.rpl/proxy-plus "0.0.9-SNAPSHOT"
:description "A faster and more usable replacement for Clojure's proxy."
:java-source-paths ["test/java"]
:test-paths ["test/clj"]
:dependencies [[org.clojure/clojure "1.10.0"]
[com.rpl/specter "1.1.3"]
[org.ow2.asm/asm "4.2"]
[org.ow2.asm/asm-commons "4.2"]
[org.ow2.asm/asm-util "4.2"]
[org.ow2.asm/asm-analysis "4.2"]]
:profiles {:bench {:dependencies [[criterium "0.4.5"]]}
}
)
|
|
6aa201c83ee85e8d8ed29de267157b97ae91b107a517bc4e8afb0fe8ae0fb3b7 | cark/cark.behavior-tree | guard.cljc | (ns cark.behavior-tree.node-defs.guard
"The :guard node is a special kind of branch node that can only have two children.
The first child is called the predicate node, the second child is the payload node.
It is usefull for possibly interrupting a running subtree based on the predicate result.
Each time the :guard node is executed, that is when it is :fresh or :running, the
predicate node will be re-run (refreshing it if it was in a :success or :failure state)
- If the predicate succeeds, the payload node is then executed, and its result state assigned to the :guard node.
- If the predicate fails, the payload node is not executed, or is interrupted when running, and the :guard node is set as :failure.
The predicate node must succeed or fail in a single tick."
(:require [cark.behavior-tree.context :as ctx]
[cark.behavior-tree.db :as db]
[cark.behavior-tree.tree :as tree]
[cark.behavior-tree.type :as type]
[cark.behavior-tree.base-nodes :as bn]
[cark.behavior-tree.hiccup.spec :as hs]
[clojure.spec.alpha :as s]))
(defn compile-node [tree id tag params [predicate-id payload-id]]
[(fn guard-tick [ctx arg]
(case (db/get-node-status ctx id)
:fresh (recur (db/set-node-status ctx id :running) arg)
:running (let [ctx (ctx/tick ctx predicate-id)]
(case (db/get-node-status ctx predicate-id)
:running (throw (ex-info "Guard predicate must succeed or fail in a single tick" {}))
:failure (-> (ctx/set-node-status ctx predicate-id :fresh)
(ctx/set-node-status payload-id :fresh)
(db/set-node-status id :failure))
:success (let [ctx (-> (ctx/set-node-status ctx predicate-id :fresh)
(ctx/tick payload-id))
payload-status (db/get-node-status ctx payload-id)]
(case payload-status
(:success :failure) (-> (ctx/set-node-status ctx payload-id :fresh)
(db/set-node-status id payload-status))
:running ctx))))))
tree])
(defn register []
(type/register
(bn/branch
{::type/tag :guard
::type/children-spec (s/& (s/* ::hs/child)
#(= (count %) 2))
::type/compile-func compile-node})))
| null | https://raw.githubusercontent.com/cark/cark.behavior-tree/4e229fcc2ed3af3c66e74d2c51dda6684927d254/src/main/cark/behavior_tree/node_defs/guard.cljc | clojure | (ns cark.behavior-tree.node-defs.guard
"The :guard node is a special kind of branch node that can only have two children.
The first child is called the predicate node, the second child is the payload node.
It is usefull for possibly interrupting a running subtree based on the predicate result.
Each time the :guard node is executed, that is when it is :fresh or :running, the
predicate node will be re-run (refreshing it if it was in a :success or :failure state)
- If the predicate succeeds, the payload node is then executed, and its result state assigned to the :guard node.
- If the predicate fails, the payload node is not executed, or is interrupted when running, and the :guard node is set as :failure.
The predicate node must succeed or fail in a single tick."
(:require [cark.behavior-tree.context :as ctx]
[cark.behavior-tree.db :as db]
[cark.behavior-tree.tree :as tree]
[cark.behavior-tree.type :as type]
[cark.behavior-tree.base-nodes :as bn]
[cark.behavior-tree.hiccup.spec :as hs]
[clojure.spec.alpha :as s]))
(defn compile-node [tree id tag params [predicate-id payload-id]]
[(fn guard-tick [ctx arg]
(case (db/get-node-status ctx id)
:fresh (recur (db/set-node-status ctx id :running) arg)
:running (let [ctx (ctx/tick ctx predicate-id)]
(case (db/get-node-status ctx predicate-id)
:running (throw (ex-info "Guard predicate must succeed or fail in a single tick" {}))
:failure (-> (ctx/set-node-status ctx predicate-id :fresh)
(ctx/set-node-status payload-id :fresh)
(db/set-node-status id :failure))
:success (let [ctx (-> (ctx/set-node-status ctx predicate-id :fresh)
(ctx/tick payload-id))
payload-status (db/get-node-status ctx payload-id)]
(case payload-status
(:success :failure) (-> (ctx/set-node-status ctx payload-id :fresh)
(db/set-node-status id payload-status))
:running ctx))))))
tree])
(defn register []
(type/register
(bn/branch
{::type/tag :guard
::type/children-spec (s/& (s/* ::hs/child)
#(= (count %) 2))
::type/compile-func compile-node})))
|
|
ecec483b2619dacb6a21ee3e2e2fe01ccda6fbb57ba855b1efc2f94bf27cae03 | cedlemo/OCaml-GI-ctypes-bindings-generator | Numerable_icon.mli | open Ctypes
type t
val t_typ : t typ
(*Not implemented gtk_numerable_icon_new type interface not implemented*)
(*Not implemented gtk_numerable_icon_new_with_style_context type interface not implemented*)
Not implemented gtk_numerable_icon_get_background_gicon return type interface not handled
val get_background_icon_name :
t -> string option
val get_count :
t -> int32
val get_label :
t -> string option
val get_style_context :
t -> Style_context.t ptr option
(*Not implemented gtk_numerable_icon_set_background_gicon type interface not implemented*)
val set_background_icon_name :
t -> string option -> unit
val set_count :
t -> int32 -> unit
val set_label :
t -> string option -> unit
val set_style_context :
t -> Style_context.t ptr -> unit
| null | https://raw.githubusercontent.com/cedlemo/OCaml-GI-ctypes-bindings-generator/21a4d449f9dbd6785131979b91aa76877bad2615/tools/Gtk3/Numerable_icon.mli | ocaml | Not implemented gtk_numerable_icon_new type interface not implemented
Not implemented gtk_numerable_icon_new_with_style_context type interface not implemented
Not implemented gtk_numerable_icon_set_background_gicon type interface not implemented | open Ctypes
type t
val t_typ : t typ
Not implemented gtk_numerable_icon_get_background_gicon return type interface not handled
val get_background_icon_name :
t -> string option
val get_count :
t -> int32
val get_label :
t -> string option
val get_style_context :
t -> Style_context.t ptr option
val set_background_icon_name :
t -> string option -> unit
val set_count :
t -> int32 -> unit
val set_label :
t -> string option -> unit
val set_style_context :
t -> Style_context.t ptr -> unit
|
0e637c9cf0c499de8ab2b50a419d0f9a65f6135cc79b0809b9a7c89ab6e2c4e4 | coq/opam-coq-archive | archive2web.ml | module StrSet = Set.Make(String)
module StrMap = Map.Make(String)
[@@@ocaml.warning "-3"]
type package_name = string
[@@deriving yojson]
type package_version = {
homepage : string option;
keywords : string list;
categories : string list;
authors : string list;
description : string option;
date : string option;
version : string;
suite : string;
src: string option;
checksum: string option;
} [@@deriving yojson]
type package_info = {
versions : package_version list;
most_recent : string;
} [@@deriving yojson]
type packages = (string * package_info) list [@@deriving yojson]
[@@@ocaml.warning "+3"]
module PkgVersionSet = Set.Make(struct
type t = package_version
let compare p1 p2 = String.compare p1.version p2.version
end)
let warning s = Printf.eprintf "W: %s\n%!" s
let (/) = Filename.concat
let parse_args v =
match Array.to_list v with
| [] | [_] -> Printf.eprintf "archive2web root1 root2..."; exit 1
| _ :: roots -> roots
let read_file fname =
let ic = open_in fname in
let b = Buffer.create 1024 in
Buffer.add_channel b ic (in_channel_length ic);
Buffer.contents b
let strip_prefix prefix fullname =
let len_prefix = String.length prefix in
String.sub fullname len_prefix (String.length fullname - len_prefix)
let fold_subdirs base acc f = Array.fold_left f acc (Sys.readdir base)
open OpamParserTypes.FullPos
let has_tilde s =
let len = String.length s in
if s.[len - 1] = '~' then String.sub s 0 (len-1), true
else s, false
let digits v =
let v, tilde = has_tilde v in
try
match String.split_on_char '.' v with
| [] -> int_of_string v, 0, tilde
| [x] -> int_of_string x, 0, tilde
| x :: y :: _ -> int_of_string x, int_of_string y, tilde
with Failure _ -> warning "incomplete version parsing"; 0,0,false
let rec find_section name = function
| [] -> None
| Section s :: _ when name = s.section_kind.pelem -> Some s
| _ :: xs -> find_section name xs
let rec find_var_str name = function
| [] -> None
| Variable({ pelem = n; _ },{ pelem = String v; _ }) :: _ when name = n -> Some v
| _ :: xs -> find_var_str name xs
let rec find_var_str_list name = function
| [] -> []
| Variable({ pelem = n; _ },{ pelem = List( { pelem = vl; _}); _ }) :: _ when name = n ->
List.map (function { pelem = String s; _ } -> s | _ -> assert false) vl
| _ :: xs -> find_var_str_list name xs
let rec find_var name = function
| [] -> None
| Variable({ pelem = n; _ },v) :: _ when name = n -> Some v
| _ :: xs -> find_var name xs
let has_prefix prefix s =
let len_prefix = String.length prefix in
let len = String.length s in
if len > len_prefix && String.sub s 0 len_prefix = prefix then
Some (String.trim (String.sub s len_prefix (len - len_prefix)))
else None
let rec filtermap f = function
| [] -> []
| x :: xs ->
match f x with Some x -> x :: filtermap f xs | _ -> filtermap f xs
let parse_author_name s =
let r = Str.regexp "[^<]*" in
if Str.string_match r s 0 then
String.trim (Str.matched_string s)
else raise (Invalid_argument "author_name")
let obind o f =
match o with
| Some x -> f x
| None -> None
let omap o f =
match o with
| Some x -> Some (f x)
| None -> None
let extract_package_version_data ~suite ~version ~package_file opam_file =
let tags = find_var_str_list "tags" opam_file in
let date =
match filtermap (has_prefix "date:") tags with
| [] -> None
| [x] -> Some x
| x :: _ -> warning (Printf.sprintf "multiple date tag in %s" package_file); Some x in
let homepage = find_var_str "homepage" opam_file in
let description = find_var_str "description" opam_file in
let description = match description with
| None -> find_var_str "synopsis" opam_file
| Some _ -> description
in
let description = omap description String.trim in
let tags = find_var_str_list "tags" opam_file in
let keywords = filtermap (has_prefix "keyword:") tags in
let categories = filtermap (has_prefix "category:") tags in
let authors = find_var_str_list "authors" opam_file in
let authors = List.map parse_author_name authors in
let url = find_section "url" opam_file in
let src = obind url (fun sec -> find_var_str "src" @@ List.map (fun x -> x.pelem) sec.section_items.pelem) in
let src = match src with
| None -> obind url (fun sec -> find_var_str "archive" @@ List.map (fun x -> x.pelem) sec.section_items.pelem)
| Some _ -> src
in
let checksum = obind url (fun sec -> find_var_str "checksum" @@ List.map (fun x -> x.pelem) sec.section_items.pelem) in
{ version;
homepage;
keywords;
categories;
authors;
description;
date;
suite;
src;
checksum;
}
let do_one_package_version root pname version =
let pdir = pname ^ "." ^ version in
let package_file = root / "packages" / pname / pdir / "opam" in
let { OpamParserTypes.FullPos.file_contents; _ } = OpamParser.FullPos.file package_file in
extract_package_version_data ~suite:root ~version ~package_file (List.map (fun x -> x.pelem) file_contents)
let merge_package_versions p1 p2 =
{ versions = p1.versions @ p2.versions;
most_recent =
if OpamVersionCompare.compare p1.most_recent p2.most_recent < 0 then
p2.most_recent else p1.most_recent }
let do_one_package pkgs ~versions root name =
let versions = List.rev (List.sort OpamVersionCompare.compare versions) in
let most_recent = List.hd versions in
let versions = List.map (do_one_package_version root name) versions in
let pkg = { versions; most_recent } in
StrMap.update name (function None -> Some pkg | Some pkg' -> Some (merge_package_versions pkg' pkg)) pkgs
let get_version pname pdir = strip_prefix (pname ^ ".") (Filename.basename pdir)
let do_one_suite pkgs root =
fold_subdirs (root / "packages") pkgs (fun pkgs pname ->
let versions =
fold_subdirs (root / "packages" / pname) [] (fun versions pdir ->
get_version pname pdir :: versions)
in
do_one_package pkgs ~versions root pname)
let () =
let roots = parse_args Sys.argv in
let packages = List.fold_left do_one_suite StrMap.empty roots in
print_endline @@ Yojson.Safe.to_string @@ packages_to_yojson @@ StrMap.bindings packages
| null | https://raw.githubusercontent.com/coq/opam-coq-archive/02a50c59307880c2abd7a67df03859c06a4863bc/scripts/archive2web.ml | ocaml | module StrSet = Set.Make(String)
module StrMap = Map.Make(String)
[@@@ocaml.warning "-3"]
type package_name = string
[@@deriving yojson]
type package_version = {
homepage : string option;
keywords : string list;
categories : string list;
authors : string list;
description : string option;
date : string option;
version : string;
suite : string;
src: string option;
checksum: string option;
} [@@deriving yojson]
type package_info = {
versions : package_version list;
most_recent : string;
} [@@deriving yojson]
type packages = (string * package_info) list [@@deriving yojson]
[@@@ocaml.warning "+3"]
module PkgVersionSet = Set.Make(struct
type t = package_version
let compare p1 p2 = String.compare p1.version p2.version
end)
let warning s = Printf.eprintf "W: %s\n%!" s
let (/) = Filename.concat
let parse_args v =
match Array.to_list v with
| [] | [_] -> Printf.eprintf "archive2web root1 root2..."; exit 1
| _ :: roots -> roots
let read_file fname =
let ic = open_in fname in
let b = Buffer.create 1024 in
Buffer.add_channel b ic (in_channel_length ic);
Buffer.contents b
let strip_prefix prefix fullname =
let len_prefix = String.length prefix in
String.sub fullname len_prefix (String.length fullname - len_prefix)
let fold_subdirs base acc f = Array.fold_left f acc (Sys.readdir base)
open OpamParserTypes.FullPos
let has_tilde s =
let len = String.length s in
if s.[len - 1] = '~' then String.sub s 0 (len-1), true
else s, false
let digits v =
let v, tilde = has_tilde v in
try
match String.split_on_char '.' v with
| [] -> int_of_string v, 0, tilde
| [x] -> int_of_string x, 0, tilde
| x :: y :: _ -> int_of_string x, int_of_string y, tilde
with Failure _ -> warning "incomplete version parsing"; 0,0,false
let rec find_section name = function
| [] -> None
| Section s :: _ when name = s.section_kind.pelem -> Some s
| _ :: xs -> find_section name xs
let rec find_var_str name = function
| [] -> None
| Variable({ pelem = n; _ },{ pelem = String v; _ }) :: _ when name = n -> Some v
| _ :: xs -> find_var_str name xs
let rec find_var_str_list name = function
| [] -> []
| Variable({ pelem = n; _ },{ pelem = List( { pelem = vl; _}); _ }) :: _ when name = n ->
List.map (function { pelem = String s; _ } -> s | _ -> assert false) vl
| _ :: xs -> find_var_str_list name xs
let rec find_var name = function
| [] -> None
| Variable({ pelem = n; _ },v) :: _ when name = n -> Some v
| _ :: xs -> find_var name xs
let has_prefix prefix s =
let len_prefix = String.length prefix in
let len = String.length s in
if len > len_prefix && String.sub s 0 len_prefix = prefix then
Some (String.trim (String.sub s len_prefix (len - len_prefix)))
else None
let rec filtermap f = function
| [] -> []
| x :: xs ->
match f x with Some x -> x :: filtermap f xs | _ -> filtermap f xs
let parse_author_name s =
let r = Str.regexp "[^<]*" in
if Str.string_match r s 0 then
String.trim (Str.matched_string s)
else raise (Invalid_argument "author_name")
let obind o f =
match o with
| Some x -> f x
| None -> None
let omap o f =
match o with
| Some x -> Some (f x)
| None -> None
let extract_package_version_data ~suite ~version ~package_file opam_file =
let tags = find_var_str_list "tags" opam_file in
let date =
match filtermap (has_prefix "date:") tags with
| [] -> None
| [x] -> Some x
| x :: _ -> warning (Printf.sprintf "multiple date tag in %s" package_file); Some x in
let homepage = find_var_str "homepage" opam_file in
let description = find_var_str "description" opam_file in
let description = match description with
| None -> find_var_str "synopsis" opam_file
| Some _ -> description
in
let description = omap description String.trim in
let tags = find_var_str_list "tags" opam_file in
let keywords = filtermap (has_prefix "keyword:") tags in
let categories = filtermap (has_prefix "category:") tags in
let authors = find_var_str_list "authors" opam_file in
let authors = List.map parse_author_name authors in
let url = find_section "url" opam_file in
let src = obind url (fun sec -> find_var_str "src" @@ List.map (fun x -> x.pelem) sec.section_items.pelem) in
let src = match src with
| None -> obind url (fun sec -> find_var_str "archive" @@ List.map (fun x -> x.pelem) sec.section_items.pelem)
| Some _ -> src
in
let checksum = obind url (fun sec -> find_var_str "checksum" @@ List.map (fun x -> x.pelem) sec.section_items.pelem) in
{ version;
homepage;
keywords;
categories;
authors;
description;
date;
suite;
src;
checksum;
}
let do_one_package_version root pname version =
let pdir = pname ^ "." ^ version in
let package_file = root / "packages" / pname / pdir / "opam" in
let { OpamParserTypes.FullPos.file_contents; _ } = OpamParser.FullPos.file package_file in
extract_package_version_data ~suite:root ~version ~package_file (List.map (fun x -> x.pelem) file_contents)
let merge_package_versions p1 p2 =
{ versions = p1.versions @ p2.versions;
most_recent =
if OpamVersionCompare.compare p1.most_recent p2.most_recent < 0 then
p2.most_recent else p1.most_recent }
let do_one_package pkgs ~versions root name =
let versions = List.rev (List.sort OpamVersionCompare.compare versions) in
let most_recent = List.hd versions in
let versions = List.map (do_one_package_version root name) versions in
let pkg = { versions; most_recent } in
StrMap.update name (function None -> Some pkg | Some pkg' -> Some (merge_package_versions pkg' pkg)) pkgs
let get_version pname pdir = strip_prefix (pname ^ ".") (Filename.basename pdir)
let do_one_suite pkgs root =
fold_subdirs (root / "packages") pkgs (fun pkgs pname ->
let versions =
fold_subdirs (root / "packages" / pname) [] (fun versions pdir ->
get_version pname pdir :: versions)
in
do_one_package pkgs ~versions root pname)
let () =
let roots = parse_args Sys.argv in
let packages = List.fold_left do_one_suite StrMap.empty roots in
print_endline @@ Yojson.Safe.to_string @@ packages_to_yojson @@ StrMap.bindings packages
|
|
c75f7acabb8ea03f2ccf7b7b114b8cd05156e566480d48d56023fd7b85eb4cfa | thelema/ocaml-community | text_tag_bind.ml | ##ifdef CAMLTK
let tag_bind widget tag eventsequence action =
check_class widget widget_text_table;
tkCommand [|
cCAMLtoTKwidget widget_text_table widget;
TkToken "tag";
TkToken "bind";
cCAMLtoTKtextTag tag;
cCAMLtoTKeventSequence eventsequence;
begin match action with
| BindRemove -> TkToken ""
| BindSet (what, f) ->
let cbId = register_callback widget (wrapeventInfo f what) in
TkToken ("camlcb " ^ cbId ^ (writeeventField what))
| BindSetBreakable (what, f) ->
let cbId = register_callback widget (wrapeventInfo f what) in
TkToken ("camlcb " ^ cbId ^ (writeeventField what) ^
" ; if { $BreakBindingsSequence == 1 } then { break ;} ; \
set BreakBindingsSequence 0")
| BindExtend (what, f) ->
let cbId = register_callback widget (wrapeventInfo f what) in
TkToken ("+camlcb " ^ cbId ^ (writeeventField what))
end
|]
;;
##else
let tag_bind ~tag ~events ?(extend = false) ?(breakable = false)
?(fields = []) ?action widget =
tkCommand [|
cCAMLtoTKwidget widget;
TkToken "tag";
TkToken "bind";
cCAMLtoTKtextTag tag;
cCAMLtoTKeventSequence events;
begin match action with
| None -> TkToken ""
| Some f ->
let cbId =
register_callback widget ~callback: (wrapeventInfo f fields) in
let cb = if extend then "+camlcb " else "camlcb " in
let cb = cb ^ cbId ^ writeeventField fields in
let cb =
if breakable then
cb ^ " ; if { $BreakBindingsSequence == 1 } then { break ;}"
^ " ; set BreakBindingsSequence 0"
else cb in
TkToken cb
end
|]
;;
##endif
| null | https://raw.githubusercontent.com/thelema/ocaml-community/ed0a2424bbf13d1b33292725e089f0d7ba94b540/otherlibs/labltk/builtin/text_tag_bind.ml | ocaml | ##ifdef CAMLTK
let tag_bind widget tag eventsequence action =
check_class widget widget_text_table;
tkCommand [|
cCAMLtoTKwidget widget_text_table widget;
TkToken "tag";
TkToken "bind";
cCAMLtoTKtextTag tag;
cCAMLtoTKeventSequence eventsequence;
begin match action with
| BindRemove -> TkToken ""
| BindSet (what, f) ->
let cbId = register_callback widget (wrapeventInfo f what) in
TkToken ("camlcb " ^ cbId ^ (writeeventField what))
| BindSetBreakable (what, f) ->
let cbId = register_callback widget (wrapeventInfo f what) in
TkToken ("camlcb " ^ cbId ^ (writeeventField what) ^
" ; if { $BreakBindingsSequence == 1 } then { break ;} ; \
set BreakBindingsSequence 0")
| BindExtend (what, f) ->
let cbId = register_callback widget (wrapeventInfo f what) in
TkToken ("+camlcb " ^ cbId ^ (writeeventField what))
end
|]
;;
##else
let tag_bind ~tag ~events ?(extend = false) ?(breakable = false)
?(fields = []) ?action widget =
tkCommand [|
cCAMLtoTKwidget widget;
TkToken "tag";
TkToken "bind";
cCAMLtoTKtextTag tag;
cCAMLtoTKeventSequence events;
begin match action with
| None -> TkToken ""
| Some f ->
let cbId =
register_callback widget ~callback: (wrapeventInfo f fields) in
let cb = if extend then "+camlcb " else "camlcb " in
let cb = cb ^ cbId ^ writeeventField fields in
let cb =
if breakable then
cb ^ " ; if { $BreakBindingsSequence == 1 } then { break ;}"
^ " ; set BreakBindingsSequence 0"
else cb in
TkToken cb
end
|]
;;
##endif
|
|
015bbf4a6c3b66f72a8530f6aba4961de22dfa96cb30a4726156eb79e8a32d5d | icicle-lang/icicle-ambiata | Analysis.hs | # LANGUAGE NoImplicitPrelude #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE PatternGuards #
module Icicle.Sea.FromAvalanche.Analysis (
factVarsOfProgram
, resumablesOfProgram
, accumsOfProgram
, outputsOfProgram
, readsOfProgram
, typesOfProgram
) where
import Icicle.Avalanche.Prim.Flat
import Icicle.Avalanche.Program
import Icicle.Avalanche.Statement.Statement
import Icicle.Common.Annot
import Icicle.Common.Base
import Icicle.Common.Exp
import Icicle.Common.Type
import Icicle.Data.Name
import Icicle.Sea.Data
import P
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Set (Set)
import qualified Data.Set as Set
------------------------------------------------------------------------
-- Analysis
factVarsOfProgram :: Eq n
=> Program (Annot a) n Prim
-> Maybe (ValType, [(Name n, ValType)])
factVarsOfProgram = factVarsOfStatement . statements
factVarsOfStatement :: Eq n
=> Statement (Annot a) n Prim
-> Maybe (ValType, [(Name n, ValType)])
factVarsOfStatement stmt
= case stmt of
Block [] -> Nothing
Block (s:ss) -> factVarsOfStatement s <|>
factVarsOfStatement (Block ss)
Let _ _ ss -> factVarsOfStatement ss
If _ tt ee -> factVarsOfStatement tt <|>
factVarsOfStatement ee
InitAccumulator _ ss -> factVarsOfStatement ss
Read _ _ _ ss -> factVarsOfStatement ss
Write _ _ -> Nothing
Output _ _ _ -> Nothing
While _ _ _ _ ss -> factVarsOfStatement ss
ForeachInts _ _ _ _ ss-> factVarsOfStatement ss
ForeachFacts binds vt _
-> Just (vt, factBindValue binds)
------------------------------------------------------------------------
resumablesOfProgram :: Eq n => Program (Annot a) n Prim -> Map (Name n) ValType
resumablesOfProgram = resumablesOfStatement . statements
resumablesOfStatement :: Eq n => Statement (Annot a) n Prim -> Map (Name n) ValType
resumablesOfStatement stmt
= case stmt of
Block [] -> Map.empty
Block (s:ss) -> resumablesOfStatement s `Map.union`
resumablesOfStatement (Block ss)
Let _ _ ss -> resumablesOfStatement ss
If _ tt ee -> resumablesOfStatement tt `Map.union`
resumablesOfStatement ee
ForeachInts _ _ _ _ ss -> resumablesOfStatement ss
While _ _ _ _ ss -> resumablesOfStatement ss
ForeachFacts _ _ ss -> resumablesOfStatement ss
InitAccumulator _ ss -> resumablesOfStatement ss
Read _ _ _ ss -> resumablesOfStatement ss
Write _ _ -> Map.empty
Output _ _ _ -> Map.empty
------------------------------------------------------------------------
accumsOfProgram :: Eq n => Program (Annot a) n Prim -> Map (Name n) (ValType)
accumsOfProgram = accumsOfStatement . statements
accumsOfStatement :: Eq n => Statement (Annot a) n Prim -> Map (Name n) (ValType)
accumsOfStatement stmt
= case stmt of
Block [] -> Map.empty
Block (s:ss) -> accumsOfStatement s `Map.union`
accumsOfStatement (Block ss)
Let _ _ ss -> accumsOfStatement ss
If _ tt ee -> accumsOfStatement tt `Map.union`
accumsOfStatement ee
While _ _ _ _ ss -> accumsOfStatement ss
ForeachInts _ _ _ _ ss -> accumsOfStatement ss
ForeachFacts _ _ ss -> accumsOfStatement ss
Read _ _ _ ss -> accumsOfStatement ss
Write _ _ -> Map.empty
Output _ _ _ -> Map.empty
InitAccumulator (Accumulator n avt _) ss
-> Map.singleton n avt `Map.union`
accumsOfStatement ss
------------------------------------------------------------------------
readsOfProgram :: Eq n => Program (Annot a) n Prim -> Map (Name n) (ValType)
readsOfProgram = readsOfStatement . statements
readsOfStatement :: Eq n => Statement (Annot a) n Prim -> Map (Name n) (ValType)
readsOfStatement stmt
= case stmt of
Block [] -> Map.empty
Block (s:ss) -> readsOfStatement s `Map.union`
readsOfStatement (Block ss)
Let _ _ ss -> readsOfStatement ss
If _ tt ee -> readsOfStatement tt `Map.union`
readsOfStatement ee
While _ n t _ ss -> Map.singleton n t `Map.union` readsOfStatement ss
ForeachInts _ _ _ _ ss -> readsOfStatement ss
ForeachFacts _ _ ss -> readsOfStatement ss
InitAccumulator _ ss -> readsOfStatement ss
Write _ _ -> Map.empty
Output _ _ _ -> Map.empty
Read n _ vt ss
-> Map.singleton n vt `Map.union`
readsOfStatement ss
------------------------------------------------------------------------
outputsOfProgram :: Program (Annot a) n Prim -> [(OutputId, MeltedType)]
outputsOfProgram = Map.toList . outputsOfStatement . statements
outputsOfStatement :: Statement (Annot a) n Prim -> Map OutputId MeltedType
outputsOfStatement stmt
= case stmt of
Block [] -> Map.empty
Block (s:ss) -> outputsOfStatement s `Map.union`
outputsOfStatement (Block ss)
Let _ _ ss -> outputsOfStatement ss
If _ tt ee -> outputsOfStatement tt `Map.union`
outputsOfStatement ee
While _ _ _ _ ss -> outputsOfStatement ss
ForeachInts _ _ _ _ ss -> outputsOfStatement ss
ForeachFacts _ _ ss -> outputsOfStatement ss
InitAccumulator _ ss -> outputsOfStatement ss
Read _ _ _ ss -> outputsOfStatement ss
Write _ _ -> Map.empty
Output n t xts
-> Map.singleton n $ MeltedType t (fmap snd xts)
------------------------------------------------------------------------
typesOfProgram :: Program (Annot a) n Prim -> Set ValType
typesOfProgram = typesOfStatement . statements
typesOfStatement :: Statement (Annot a) n Prim -> Set ValType
typesOfStatement stmt
= case stmt of
Block [] -> Set.empty
Block (s:ss) -> typesOfStatement s `Set.union`
typesOfStatement (Block ss)
Let _ x ss -> typesOfExp x `Set.union`
typesOfStatement ss
If x tt ee -> typesOfExp x `Set.union`
typesOfStatement tt `Set.union`
typesOfStatement ee
While _ _ nt t s -> Set.singleton nt `Set.union`
typesOfExp t `Set.union`
typesOfStatement s
ForeachInts _ _ f t s-> typesOfExp f `Set.union`
typesOfExp t `Set.union`
typesOfStatement s
Write _ x -> typesOfExp x
ForeachFacts binds _ ss
-> Set.fromList (fmap snd $ factBindsAll binds) `Set.union`
typesOfStatement ss
InitAccumulator (Accumulator _ at x) ss
-> Set.singleton at `Set.union`
typesOfExp x `Set.union`
typesOfStatement ss
Read _ _ vt ss
-> Set.singleton vt `Set.union`
typesOfStatement ss
-- vt is the unmelted type, which is not actually part of the program
Output _ _vt xs
-> Set.unions (fmap goOut xs)
where
goOut (x,t)
= typesOfExp x `Set.union` Set.singleton t
typesOfExp :: Exp (Annot a) n Prim -> Set ValType
typesOfExp xx
= case xx of
XVar a _
-> ann a
XPrim a _
-> ann a
XValue _ vt _
-> Set.singleton vt
XApp a b c
-> ann a `Set.union` typesOfExp b `Set.union` typesOfExp c
XLam a _ vt b
-> ann a `Set.union` Set.singleton vt `Set.union` typesOfExp b
XLet a _ b c
-> ann a `Set.union` typesOfExp b `Set.union` typesOfExp c
where
ann a = Set.singleton $ functionReturns $ annType a
| null | https://raw.githubusercontent.com/icicle-lang/icicle-ambiata/9b9cc45a75f66603007e4db7e5f3ba908cae2df2/icicle-compiler/src/Icicle/Sea/FromAvalanche/Analysis.hs | haskell | # LANGUAGE OverloadedStrings #
----------------------------------------------------------------------
Analysis
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
vt is the unmelted type, which is not actually part of the program | # LANGUAGE NoImplicitPrelude #
# LANGUAGE PatternGuards #
module Icicle.Sea.FromAvalanche.Analysis (
factVarsOfProgram
, resumablesOfProgram
, accumsOfProgram
, outputsOfProgram
, readsOfProgram
, typesOfProgram
) where
import Icicle.Avalanche.Prim.Flat
import Icicle.Avalanche.Program
import Icicle.Avalanche.Statement.Statement
import Icicle.Common.Annot
import Icicle.Common.Base
import Icicle.Common.Exp
import Icicle.Common.Type
import Icicle.Data.Name
import Icicle.Sea.Data
import P
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Set (Set)
import qualified Data.Set as Set
factVarsOfProgram :: Eq n
=> Program (Annot a) n Prim
-> Maybe (ValType, [(Name n, ValType)])
factVarsOfProgram = factVarsOfStatement . statements
factVarsOfStatement :: Eq n
=> Statement (Annot a) n Prim
-> Maybe (ValType, [(Name n, ValType)])
factVarsOfStatement stmt
= case stmt of
Block [] -> Nothing
Block (s:ss) -> factVarsOfStatement s <|>
factVarsOfStatement (Block ss)
Let _ _ ss -> factVarsOfStatement ss
If _ tt ee -> factVarsOfStatement tt <|>
factVarsOfStatement ee
InitAccumulator _ ss -> factVarsOfStatement ss
Read _ _ _ ss -> factVarsOfStatement ss
Write _ _ -> Nothing
Output _ _ _ -> Nothing
While _ _ _ _ ss -> factVarsOfStatement ss
ForeachInts _ _ _ _ ss-> factVarsOfStatement ss
ForeachFacts binds vt _
-> Just (vt, factBindValue binds)
resumablesOfProgram :: Eq n => Program (Annot a) n Prim -> Map (Name n) ValType
resumablesOfProgram = resumablesOfStatement . statements
resumablesOfStatement :: Eq n => Statement (Annot a) n Prim -> Map (Name n) ValType
resumablesOfStatement stmt
= case stmt of
Block [] -> Map.empty
Block (s:ss) -> resumablesOfStatement s `Map.union`
resumablesOfStatement (Block ss)
Let _ _ ss -> resumablesOfStatement ss
If _ tt ee -> resumablesOfStatement tt `Map.union`
resumablesOfStatement ee
ForeachInts _ _ _ _ ss -> resumablesOfStatement ss
While _ _ _ _ ss -> resumablesOfStatement ss
ForeachFacts _ _ ss -> resumablesOfStatement ss
InitAccumulator _ ss -> resumablesOfStatement ss
Read _ _ _ ss -> resumablesOfStatement ss
Write _ _ -> Map.empty
Output _ _ _ -> Map.empty
accumsOfProgram :: Eq n => Program (Annot a) n Prim -> Map (Name n) (ValType)
accumsOfProgram = accumsOfStatement . statements
accumsOfStatement :: Eq n => Statement (Annot a) n Prim -> Map (Name n) (ValType)
accumsOfStatement stmt
= case stmt of
Block [] -> Map.empty
Block (s:ss) -> accumsOfStatement s `Map.union`
accumsOfStatement (Block ss)
Let _ _ ss -> accumsOfStatement ss
If _ tt ee -> accumsOfStatement tt `Map.union`
accumsOfStatement ee
While _ _ _ _ ss -> accumsOfStatement ss
ForeachInts _ _ _ _ ss -> accumsOfStatement ss
ForeachFacts _ _ ss -> accumsOfStatement ss
Read _ _ _ ss -> accumsOfStatement ss
Write _ _ -> Map.empty
Output _ _ _ -> Map.empty
InitAccumulator (Accumulator n avt _) ss
-> Map.singleton n avt `Map.union`
accumsOfStatement ss
readsOfProgram :: Eq n => Program (Annot a) n Prim -> Map (Name n) (ValType)
readsOfProgram = readsOfStatement . statements
readsOfStatement :: Eq n => Statement (Annot a) n Prim -> Map (Name n) (ValType)
readsOfStatement stmt
= case stmt of
Block [] -> Map.empty
Block (s:ss) -> readsOfStatement s `Map.union`
readsOfStatement (Block ss)
Let _ _ ss -> readsOfStatement ss
If _ tt ee -> readsOfStatement tt `Map.union`
readsOfStatement ee
While _ n t _ ss -> Map.singleton n t `Map.union` readsOfStatement ss
ForeachInts _ _ _ _ ss -> readsOfStatement ss
ForeachFacts _ _ ss -> readsOfStatement ss
InitAccumulator _ ss -> readsOfStatement ss
Write _ _ -> Map.empty
Output _ _ _ -> Map.empty
Read n _ vt ss
-> Map.singleton n vt `Map.union`
readsOfStatement ss
outputsOfProgram :: Program (Annot a) n Prim -> [(OutputId, MeltedType)]
outputsOfProgram = Map.toList . outputsOfStatement . statements
outputsOfStatement :: Statement (Annot a) n Prim -> Map OutputId MeltedType
outputsOfStatement stmt
= case stmt of
Block [] -> Map.empty
Block (s:ss) -> outputsOfStatement s `Map.union`
outputsOfStatement (Block ss)
Let _ _ ss -> outputsOfStatement ss
If _ tt ee -> outputsOfStatement tt `Map.union`
outputsOfStatement ee
While _ _ _ _ ss -> outputsOfStatement ss
ForeachInts _ _ _ _ ss -> outputsOfStatement ss
ForeachFacts _ _ ss -> outputsOfStatement ss
InitAccumulator _ ss -> outputsOfStatement ss
Read _ _ _ ss -> outputsOfStatement ss
Write _ _ -> Map.empty
Output n t xts
-> Map.singleton n $ MeltedType t (fmap snd xts)
typesOfProgram :: Program (Annot a) n Prim -> Set ValType
typesOfProgram = typesOfStatement . statements
typesOfStatement :: Statement (Annot a) n Prim -> Set ValType
typesOfStatement stmt
= case stmt of
Block [] -> Set.empty
Block (s:ss) -> typesOfStatement s `Set.union`
typesOfStatement (Block ss)
Let _ x ss -> typesOfExp x `Set.union`
typesOfStatement ss
If x tt ee -> typesOfExp x `Set.union`
typesOfStatement tt `Set.union`
typesOfStatement ee
While _ _ nt t s -> Set.singleton nt `Set.union`
typesOfExp t `Set.union`
typesOfStatement s
ForeachInts _ _ f t s-> typesOfExp f `Set.union`
typesOfExp t `Set.union`
typesOfStatement s
Write _ x -> typesOfExp x
ForeachFacts binds _ ss
-> Set.fromList (fmap snd $ factBindsAll binds) `Set.union`
typesOfStatement ss
InitAccumulator (Accumulator _ at x) ss
-> Set.singleton at `Set.union`
typesOfExp x `Set.union`
typesOfStatement ss
Read _ _ vt ss
-> Set.singleton vt `Set.union`
typesOfStatement ss
Output _ _vt xs
-> Set.unions (fmap goOut xs)
where
goOut (x,t)
= typesOfExp x `Set.union` Set.singleton t
typesOfExp :: Exp (Annot a) n Prim -> Set ValType
typesOfExp xx
= case xx of
XVar a _
-> ann a
XPrim a _
-> ann a
XValue _ vt _
-> Set.singleton vt
XApp a b c
-> ann a `Set.union` typesOfExp b `Set.union` typesOfExp c
XLam a _ vt b
-> ann a `Set.union` Set.singleton vt `Set.union` typesOfExp b
XLet a _ b c
-> ann a `Set.union` typesOfExp b `Set.union` typesOfExp c
where
ann a = Set.singleton $ functionReturns $ annType a
|
8bcead2ddf4a23a2c637e2868444e35814ea4695a7000d934b5043ff4c812261 | philnguyen/soft-contract | reverse-dep.rkt | #lang racket
(require soft-contract/fake-contract)
(define (append xs ys)
(if (empty? xs) ys
(cons (car xs) (append (cdr xs) ys))))
(define (reverse xs)
(if (empty? xs) empty
(append (cdr xs) (cons (car xs) empty))))
(provide/contract
[reverse (->i ([xs (listof any/c)])
(res (xs)
(and/c (listof any/c)
(λ (ys) (equal? (empty? xs) (empty? ys))))))]
[append ((listof any/c) (listof any/c) . -> . (listof any/c))])
| null | https://raw.githubusercontent.com/philnguyen/soft-contract/5e07dc2d622ee80b961f4e8aebd04ce950720239/soft-contract/test/programs/safe/sym-exe/reverse-dep.rkt | racket | #lang racket
(require soft-contract/fake-contract)
(define (append xs ys)
(if (empty? xs) ys
(cons (car xs) (append (cdr xs) ys))))
(define (reverse xs)
(if (empty? xs) empty
(append (cdr xs) (cons (car xs) empty))))
(provide/contract
[reverse (->i ([xs (listof any/c)])
(res (xs)
(and/c (listof any/c)
(λ (ys) (equal? (empty? xs) (empty? ys))))))]
[append ((listof any/c) (listof any/c) . -> . (listof any/c))])
|
|
13a9e55d50ce161150fdfb1f9d133ec0e70b185f15f2d0f39d8fc3e3e3791fdd | SNePS/SNePS2 | rels.lisp | -*- Mode : Lisp ; Syntax : Common - Lisp ; Package : USER ; Base : 10 -*-
Copyright ( C ) 1984 - -2013
Research Foundation of State University of New York
;;; Version: $Id: rels.lisp,v
;;; This file is part of SNePS.
$ BEGIN LICENSE$
The contents of this file are subject to the University at
Buffalo Public License Version 1.0 ( the " License " ) ; you may
;;; not use this file except in compliance with the License. You
;;; may obtain a copy of the License at
;;; . edu/sneps/Downloads/ubpl.pdf.
;;;
Software distributed under the License is distributed on an
" AS IS " basis , WITHOUT WARRANTY OF ANY KIND , either express
;;; or implied. See the License for the specific language gov
;;; erning rights and limitations under the License.
;;;
The Original Code is SNePS 2.8 .
;;;
The Initial Developer of the Original Code is Research Foun
dation of State University of New York , on behalf of Univer
sity at Buffalo .
;;;
Portions created by the Initial Developer are Copyright ( C )
2011 Research Foundation of State University of New York , on
behalf of University at Buffalo . All Rights Reserved .
$ END LICENSE$
(define a1 a2 a3 a4 after agent antonym associated before cause
class direction equiv etime from in indobj instr into lex location
manner member mode object on onto part place possessor proper-name
property rel skf sp-rel stime subclass superclass synonym time to whole
kn_cat)
| null | https://raw.githubusercontent.com/SNePS/SNePS2/d3862108609b1879f2c546112072ad4caefc050d/demo/sneps/brachet-dist/rels.lisp | lisp | Syntax : Common - Lisp ; Package : USER ; Base : 10 -*-
Version: $Id: rels.lisp,v
This file is part of SNePS.
you may
not use this file except in compliance with the License. You
may obtain a copy of the License at
. edu/sneps/Downloads/ubpl.pdf.
or implied. See the License for the specific language gov
erning rights and limitations under the License.
|
Copyright ( C ) 1984 - -2013
Research Foundation of State University of New York
$ BEGIN LICENSE$
The contents of this file are subject to the University at
Software distributed under the License is distributed on an
" AS IS " basis , WITHOUT WARRANTY OF ANY KIND , either express
The Original Code is SNePS 2.8 .
The Initial Developer of the Original Code is Research Foun
dation of State University of New York , on behalf of Univer
sity at Buffalo .
Portions created by the Initial Developer are Copyright ( C )
2011 Research Foundation of State University of New York , on
behalf of University at Buffalo . All Rights Reserved .
$ END LICENSE$
(define a1 a2 a3 a4 after agent antonym associated before cause
class direction equiv etime from in indobj instr into lex location
manner member mode object on onto part place possessor proper-name
property rel skf sp-rel stime subclass superclass synonym time to whole
kn_cat)
|
90f11a909729117365aa78e0fffb95f276be04a4cab80d75f9818d6a80d9f930 | xsc/version-clj | qualifiers.cljc | (ns version-clj.qualifiers)
(def default-qualifiers
"Order Map for well-known Qualifiers."
{ "alpha" 0 "a" 0
"beta" 1 "b" 1
"milestone" 2 "m" 2
"rc" 3 "cr" 3
"snapshot" 5
"" 6 "final" 6 "stable" 6 })
| null | https://raw.githubusercontent.com/xsc/version-clj/f5ccd13cef363e9933bc453a6c7048fa800968d9/src/version_clj/qualifiers.cljc | clojure | (ns version-clj.qualifiers)
(def default-qualifiers
"Order Map for well-known Qualifiers."
{ "alpha" 0 "a" 0
"beta" 1 "b" 1
"milestone" 2 "m" 2
"rc" 3 "cr" 3
"snapshot" 5
"" 6 "final" 6 "stable" 6 })
|
|
c5eb205202448dad37175379e317b85a12c9471ccb75ef7855253de72fe69fb4 | mejgun/haskell-tdlib | SetFileGenerationProgress.hs | {-# LANGUAGE OverloadedStrings #-}
-- |
module TD.Query.SetFileGenerationProgress where
import qualified Data.Aeson as A
import qualified Data.Aeson.Types as T
import qualified Utils as U
-- |
Informs TDLib on a file generation progress
data SetFileGenerationProgress = SetFileGenerationProgress
{ -- | The number of bytes already generated
local_prefix_size :: Maybe Int,
-- | Expected size of the generated file, in bytes; 0 if unknown
expected_size :: Maybe Int,
-- | The identifier of the generation process
generation_id :: Maybe Int
}
deriving (Eq)
instance Show SetFileGenerationProgress where
show
SetFileGenerationProgress
{ local_prefix_size = local_prefix_size_,
expected_size = expected_size_,
generation_id = generation_id_
} =
"SetFileGenerationProgress"
++ U.cc
[ U.p "local_prefix_size" local_prefix_size_,
U.p "expected_size" expected_size_,
U.p "generation_id" generation_id_
]
instance T.ToJSON SetFileGenerationProgress where
toJSON
SetFileGenerationProgress
{ local_prefix_size = local_prefix_size_,
expected_size = expected_size_,
generation_id = generation_id_
} =
A.object
[ "@type" A..= T.String "setFileGenerationProgress",
"local_prefix_size" A..= local_prefix_size_,
"expected_size" A..= expected_size_,
"generation_id" A..= U.toS generation_id_
]
| null | https://raw.githubusercontent.com/mejgun/haskell-tdlib/9bd82101be6e6218daf816228f6141fe89d97e8b/src/TD/Query/SetFileGenerationProgress.hs | haskell | # LANGUAGE OverloadedStrings #
|
|
| The number of bytes already generated
| Expected size of the generated file, in bytes; 0 if unknown
| The identifier of the generation process |
module TD.Query.SetFileGenerationProgress where
import qualified Data.Aeson as A
import qualified Data.Aeson.Types as T
import qualified Utils as U
Informs TDLib on a file generation progress
data SetFileGenerationProgress = SetFileGenerationProgress
local_prefix_size :: Maybe Int,
expected_size :: Maybe Int,
generation_id :: Maybe Int
}
deriving (Eq)
instance Show SetFileGenerationProgress where
show
SetFileGenerationProgress
{ local_prefix_size = local_prefix_size_,
expected_size = expected_size_,
generation_id = generation_id_
} =
"SetFileGenerationProgress"
++ U.cc
[ U.p "local_prefix_size" local_prefix_size_,
U.p "expected_size" expected_size_,
U.p "generation_id" generation_id_
]
instance T.ToJSON SetFileGenerationProgress where
toJSON
SetFileGenerationProgress
{ local_prefix_size = local_prefix_size_,
expected_size = expected_size_,
generation_id = generation_id_
} =
A.object
[ "@type" A..= T.String "setFileGenerationProgress",
"local_prefix_size" A..= local_prefix_size_,
"expected_size" A..= expected_size_,
"generation_id" A..= U.toS generation_id_
]
|
e27cce8080d7d5d88c8c1fe76a1874f95f095d192e476b26227f4668b524e872 | scheme/edwin48 | test-groups.scm | (define-structure test-groups
(export run-test)
(open scheme
formats
srfi-13
edwin:group
edwin:region
edwin:mark
edwin:buffer
edwin:motion)
(begin
(define (print . stuff)
(for-each
(lambda (s) (display s) (newline))
stuff))
(define (print-group group)
(print
(group-extract-string group
(group-start-index group)
(group-end-index group))))
(define (run-test)
(newline)
(display "Should print \"Hello\": ")
(test-group-insert-char)
(newline)
(display "Should print \"Hello World.\": ")
(test-group-region-transform)
(newline)
(display "Should print \"Hello!(x3)\": ")
(test-region-insert)
(newline)
(display "Testing line-start+end:\n")
(test-line-start+end)
(newline))
(define (test-group-insert-char)
(let* ((buffer (make-buffer))
(group (make-group buffer)))
(set-buffer-group! buffer group)
(group-insert-char! (buffer-group buffer) 0 #\H)
(group-insert-char! (buffer-group buffer) 1 #\e)
(group-insert-char! (buffer-group buffer) 2 #\l)
(group-insert-char! (buffer-group buffer) 3 #\l)
(group-insert-char! (buffer-group buffer) 4 #\o)
(print-group group)))
(define (test-group-region-transform)
(let* ((buffer (make-buffer))
(group (make-group buffer))
(_ (set-buffer-group! buffer group))
(_ (group-insert-string! group 0 "Hello dlroW."))
(left-mark (make-mark group 6))
(right-mark (make-mark group 11))
(region (make-region left-mark right-mark))
(_ (region-transform! region string-reverse)))
(print-group group)))
(define (test-region-insert)
(let* ((buffer (make-buffer))
(group (make-group buffer))
(_ (set-buffer-group! buffer group))
(_ (group-insert-string! group 0 "Hello!"))
(left-mark (make-mark group 0))
(right-mark (make-mark group 6))
(region (make-region left-mark right-mark)))
(region-insert! right-mark region)
(region-insert! right-mark region)
(region-insert! right-mark region)
(print-group group)))
(define (test-line-start+end)
(let* ((buffer (make-buffer))
(group (make-group buffer))
(_ (set-buffer-group! buffer group))
(_ (group-insert-string! group 0 "aaaaa\nbbbbb\nccccc\nddddd"))
(left-mark (make-mark group 3))
(right-mark (make-mark group 14)))
(cond ((not (equal? (mark-index (line-start right-mark 0)) 12))
(display "Error, should have been 12\n"))
((not (equal? (mark-index (line-end right-mark -1)) 11))
(display "Error, should have been 11\n"))
((not (equal? (mark-index (line-start left-mark 2)) 12))
(display "Error, should have been 12\n"))
((not (equal? (mark-index (line-end left-mark 3)) 23))
(display "Error, should have been 23\n"))
(else
(display "All line-start+end tests passed")))))
)
) | null | https://raw.githubusercontent.com/scheme/edwin48/fbe3c7ca14f1418eafddebd35f78ad12e42ea851/scratch/test-groups.scm | scheme | (define-structure test-groups
(export run-test)
(open scheme
formats
srfi-13
edwin:group
edwin:region
edwin:mark
edwin:buffer
edwin:motion)
(begin
(define (print . stuff)
(for-each
(lambda (s) (display s) (newline))
stuff))
(define (print-group group)
(print
(group-extract-string group
(group-start-index group)
(group-end-index group))))
(define (run-test)
(newline)
(display "Should print \"Hello\": ")
(test-group-insert-char)
(newline)
(display "Should print \"Hello World.\": ")
(test-group-region-transform)
(newline)
(display "Should print \"Hello!(x3)\": ")
(test-region-insert)
(newline)
(display "Testing line-start+end:\n")
(test-line-start+end)
(newline))
(define (test-group-insert-char)
(let* ((buffer (make-buffer))
(group (make-group buffer)))
(set-buffer-group! buffer group)
(group-insert-char! (buffer-group buffer) 0 #\H)
(group-insert-char! (buffer-group buffer) 1 #\e)
(group-insert-char! (buffer-group buffer) 2 #\l)
(group-insert-char! (buffer-group buffer) 3 #\l)
(group-insert-char! (buffer-group buffer) 4 #\o)
(print-group group)))
(define (test-group-region-transform)
(let* ((buffer (make-buffer))
(group (make-group buffer))
(_ (set-buffer-group! buffer group))
(_ (group-insert-string! group 0 "Hello dlroW."))
(left-mark (make-mark group 6))
(right-mark (make-mark group 11))
(region (make-region left-mark right-mark))
(_ (region-transform! region string-reverse)))
(print-group group)))
(define (test-region-insert)
(let* ((buffer (make-buffer))
(group (make-group buffer))
(_ (set-buffer-group! buffer group))
(_ (group-insert-string! group 0 "Hello!"))
(left-mark (make-mark group 0))
(right-mark (make-mark group 6))
(region (make-region left-mark right-mark)))
(region-insert! right-mark region)
(region-insert! right-mark region)
(region-insert! right-mark region)
(print-group group)))
(define (test-line-start+end)
(let* ((buffer (make-buffer))
(group (make-group buffer))
(_ (set-buffer-group! buffer group))
(_ (group-insert-string! group 0 "aaaaa\nbbbbb\nccccc\nddddd"))
(left-mark (make-mark group 3))
(right-mark (make-mark group 14)))
(cond ((not (equal? (mark-index (line-start right-mark 0)) 12))
(display "Error, should have been 12\n"))
((not (equal? (mark-index (line-end right-mark -1)) 11))
(display "Error, should have been 11\n"))
((not (equal? (mark-index (line-start left-mark 2)) 12))
(display "Error, should have been 12\n"))
((not (equal? (mark-index (line-end left-mark 3)) 23))
(display "Error, should have been 23\n"))
(else
(display "All line-start+end tests passed")))))
)
) |
|
7a4f55c9adbd5449b86cc45e387ba3a41b770010f648c41e51ba1c7ea7bc101f | pookleblinky/lifescripts | coinfast.rkt | #lang racket
I 've been doing a stochastic intermittent fast , based on coinflips .
;; Each morning, flip a coin. Heads, eat. Tails, fast.
The EV of heads over 7 days is 3.5 , same as scheduled ADF .
(require "../machinery/rng.rkt")
(provide feast?)
;; I want to be able to easily change the meaning, so that say at maintenance
heads becomes tdee+15 % , etc .
(define rules "Heads feast, tails fast.")
(define (feast?)
(printf "~a You got: ~a ~n" rules (coinflip)))
TODO : save to a ring buffer of last 7 days
| null | https://raw.githubusercontent.com/pookleblinky/lifescripts/eab3fe5aaf2c9f5ee9baaa441cb5d556cd7a3a78/fitness/coinfast.rkt | racket | Each morning, flip a coin. Heads, eat. Tails, fast.
I want to be able to easily change the meaning, so that say at maintenance | #lang racket
I 've been doing a stochastic intermittent fast , based on coinflips .
The EV of heads over 7 days is 3.5 , same as scheduled ADF .
(require "../machinery/rng.rkt")
(provide feast?)
heads becomes tdee+15 % , etc .
(define rules "Heads feast, tails fast.")
(define (feast?)
(printf "~a You got: ~a ~n" rules (coinflip)))
TODO : save to a ring buffer of last 7 days
|
7c8980c24eb4f10ee22b31abae8782c383fcbb4ccfaa3254625f5cb1f792b50e | monadbobo/ocaml-core | reader.mli | * A reader lets one do buffered input from a file descriptor .
Each of the read functions returns a deferred that will become determined when the
read completes . It is an error to have two simultaneous reads . That is , if one calls
a read function , one should not call another read function until the first one
completes .
If the file descriptor underlying a reader is closed , the reader will return EOF
( after all the buffered bytes have been read ) .
Each of the read functions returns a deferred that will become determined when the
read completes. It is an error to have two simultaneous reads. That is, if one calls
a read function, one should not call another read function until the first one
completes.
If the file descriptor underlying a reader is closed, the reader will return EOF
(after all the buffered bytes have been read). *)
open Core.Std
open Import
module Read_result : sig
type 'a t = [ `Ok of 'a | `Eof ] with bin_io, sexp
include Monad.S with type 'a t := 'a t
end
module Id : Unique_id
type t with sexp_of
* [ io_stats ] Overall IO statistics for all readers
val io_stats : Io_stats.t
(** [last_read_time t] returns time of the most recent [read] system call that
returned data. *)
val last_read_time : t -> Time.t
* [ stdin ] is a reader for file descriptor 0 . It is lazy because we do n't want
to create it in all programs that happen to link with async .
to create it in all programs that happen to link with async. *)
val stdin : t Lazy.t
(** [open_file file] opens [file] for reading and returns a reader reading from
it.
*)
val open_file : ?buf_len:int -> string -> t Deferred.t
* [ transfer t pipe_w ] transfers data from [ t ] into [ pipe_w ] one chunk at a time
( whatever is read from the underlying file descriptor without post - processing ) . The
result becomes determined after reaching EOF on [ t ] and the final bytes have been
transferred .
This function will normally not be needed ( see [ pipe ] ) .
(whatever is read from the underlying file descriptor without post-processing). The
result becomes determined after reaching EOF on [t] and the final bytes have been
transferred.
This function will normally not be needed (see [pipe]). *)
val transfer : t -> string Pipe.Writer.t -> unit Deferred.t
* [ pipe t ] returns the reader end of a pipe that will continually be filled with chunks
of data from the underlying Reader.t . The pipe will be closed when the reader
reaches EOF .
of data from the underlying Reader.t. The pipe will be closed when the reader
reaches EOF. *)
val pipe : t -> string Pipe.Reader.t
* [ create ~buf_len fd ] creates a new reader that is reading from [ fd ] .
@param access_raw_data default = None if specified this function will
be given access to the raw bits as they are read by the reader . No
guarantee of granularity is made .
@param access_raw_data default = None if specified this function will
be given access to the raw bits as they are read by the reader. No
guarantee of granularity is made. *)
val create : ?buf_len:int -> Fd.t -> t
val of_in_channel : in_channel -> Fd.Kind.t -> t
* [ with_file file f ] opens [ files ] , creates a reader with it , and passes the reader to
[ f ] . It closes the reader when the result of [ f ] becomes determined , and returns
[ f ] 's result .
NOTE , you need to be careful that all your IO is done when the deferred you return
becomes determined . If for example , you use [ with_file ] , and call [ lines ] , make sure
you return a deferred that becomes determined when the EOF is reached on the pipe ,
not when you get the pipe ( because you get it straight away ) .
[f]. It closes the reader when the result of [f] becomes determined, and returns
[f]'s result.
NOTE, you need to be careful that all your IO is done when the deferred you return
becomes determined. If for example, you use [with_file], and call [lines], make sure
you return a deferred that becomes determined when the EOF is reached on the pipe,
not when you get the pipe (because you get it straight away).
*)
val with_file :
?buf_len:int -> ?exclusive:bool -> string -> f:(t -> 'a Deferred.t) -> 'a Deferred.t
(** [close t] closes the underlying file descriptor of the reader. *)
val close : t -> unit Deferred.t
(** [closed t] returns a deferred that is filled in when the reader is
* closed by a call to close. The deferred becomes determined after the
* underlying close() system call completes.
*)
val closed : t -> unit Deferred.t
(** [close_was_started t] returns [true] if the closing process for the [Reader] has
been started (it may not yet be closed, however). *)
val close_was_started : t -> bool
(** [id t] @return a name for this reader that is unique across all
instances of the reader module. *)
val id : t -> Id.t
(** [fd t] @return the Fd.t used to create this reader *)
val fd : t -> Fd.t
* [ read t ? pos ? len buf ] reads up to [ len ] bytes into buf , blocking
until some data is available or end - of - input is reached . The resulting
[ i ] satisfies [ 0 < i < = len ] .
until some data is available or end-of-input is reached. The resulting
[i] satisfies [0 < i <= len]. *)
val read : t -> ?pos:int -> ?len:int -> string -> int Read_result.t Deferred.t
(** [read_one_chunk_at_a_time_until_eof t ~handle_chunk] reads into [t]'s internal
buffer, and whenever bytes are available, applies [handle_chunk] to them. It waits to
read again until the deferred returned by [handle_chunk] becomes determined. *)
val read_one_chunk_at_a_time_until_eof
: t
-> handle_chunk:(Bigstring.t
-> pos:int
-> len:int
-> [ `Stop of 'a | `Continue ] Deferred.t)
-> [ `Eof
| `Stopped of 'a
] Deferred.t
* [ read_substring t ss ] reads up to [ Substring.length ss ] bytes into [ ss ] ,
blocking until some data is available or Eof is reched . The resulting [ i ]
satisfies [ 0 < i < = Substring.length ss ] .
blocking until some data is available or Eof is reched. The resulting [i]
satisfies [0 < i <= Substring.length ss]. *)
val read_substring : t -> Substring.t -> int Read_result.t Deferred.t
val read_bigsubstring : t -> Bigsubstring.t -> int Read_result.t Deferred.t
val read_char : t -> char Read_result.t Deferred.t
* [ really_read t buf ? pos ? len ] reads until it fills [ len ] bytes of [ buf ]
starting at [ pos ] or runs out of input . In the former case it returns ` Ok .
In the latter , it returns [ ` Eof n ] where [ n ] is the number of bytes that
were read before end of input , and [ 0 < = n < String.length ss ] .
starting at [pos] or runs out of input. In the former case it returns `Ok.
In the latter, it returns [`Eof n] where [n] is the number of bytes that
were read before end of input, and [0 <= n < String.length ss]. *)
val really_read :
t -> ?pos:int -> ?len:int -> string
-> [ `Ok
| `Eof of int ] Deferred.t
val really_read_substring :
t -> Substring.t
-> [ `Ok
0 < = i < Substring.length ss
val really_read_bigsubstring :
t -> Bigsubstring.t
-> [ `Ok
0 < = i < Substring.length ss
(** [read_until t pred ~keep_delim] reads until it hits a delimiter [c] such that:
- in case [pred = `Char c'], [c = c']
- in case [pred = `Pred p], [p c = true]
[`Char c'] is equivalent to [`Pred (fun c -> c = c')] but the underlying
implementation is more efficient, in particular it will not call a function on every
input character.
[read_until] returns a freshly-allocated string consisting of all
the characters read and optionally including the delimiter as per
[keep_delim]. *)
val read_until :
t -> [`Pred of (char -> bool) | `Char of char] -> keep_delim:bool
-> [ `Ok of string
| `Eof_without_delim of string
| `Eof ] Deferred.t
(** just like read_until, except you have the option of specifiying a
maximum number of chars to read. *)
val read_until_max :
t
-> [`Pred of (char -> bool) | `Char of char]
-> keep_delim:bool
-> max:int
-> [ `Ok of string
| `Eof_without_delim of string
| `Eof
| `Max_exceeded of string] Deferred.t
* [ read_line t ] reads up to , and including the next newline ( \n )
character and returns a freshly - allocated string containing
everything up to but not including the newline character . If
read_line encounters EOF before the newline char then everything
read up to but not including EOF will be returned as a line .
character and returns a freshly-allocated string containing
everything up to but not including the newline character. If
read_line encounters EOF before the newline char then everything
read up to but not including EOF will be returned as a line. *)
val read_line : t -> string Read_result.t Deferred.t
type 'a read = ?parse_pos : Sexp.Parse_pos.t -> 'a
(** [read_sexp t] reads the next sexp. *)
val read_sexp : (t -> Sexp.t Read_result.t Deferred.t) read
* [ read_sexps t ] reads all the sexps and returns them as a pipe .
val read_sexps : (t -> Sexp.t Pipe.Reader.t) read
* [ read_bin_prot ? max_len t bp_reader ] reads the next binary protocol
message using binary protocol reader [ bp_reader ] . The format is the
" size - prefixed binary protocol " , in which the length of the data is
prefixed as a 64 - bit integer to the data . This is the format that
Writer.write_bin_prot writes .
message using binary protocol reader [bp_reader]. The format is the
"size-prefixed binary protocol", in which the length of the data is
prefixed as a 64-bit integer to the data. This is the format that
Writer.write_bin_prot writes. *)
val read_bin_prot :
?max_len:int
-> t
-> 'a Bin_prot.Type_class.reader
-> 'a Read_result.t Deferred.t
* Read and return a buffer containing one marshaled value , but do n't
unmarshal it . You can just call Marshal.from_string on the string ,
and cast it to the desired type ( preferrably the actual
type ) . similar to Marshal.from_channel , but suffers from the
String - length limitation ( 16 MB ) on 32bit platforms .
unmarshal it. You can just call Marshal.from_string on the string,
and cast it to the desired type (preferrably the actual
type). similar to Marshal.from_channel, but suffers from the
String-length limitation (16MB) on 32bit platforms. *)
val read_marshal_raw : t -> string Read_result.t Deferred.t
(** Like read_marshal_raw, but unmarshal the value after reading it *)
val read_marshal : t -> 'a Read_result.t Deferred.t
(** [recv t] returns a string that was written with Writer.send *)
val recv : t -> string Read_result.t Deferred.t
* [ read_all t read_one ] returns a pipe that receives all values read from [ t ] by
repeatedly using [ read_one t ] . When [ read_all ] reaches EOF , it closes the resulting
pipe , but not [ t ] .
repeatedly using [read_one t]. When [read_all] reaches EOF, it closes the resulting
pipe, but not [t]. *)
val read_all : t -> (t -> 'a Read_result.t Deferred.t) -> 'a Pipe.Reader.t
* [ lines t ] reads all the lines from [ t ] and puts them in the pipe , one line per
pipe element .
pipe element. *)
val lines : t -> string Pipe.Reader.t
* [ contents t ] returns the string corresponding to the full contents
( up to EOF ) of the reader .
(up to EOF) of the reader. *)
val contents : t -> string Deferred.t
(** [file_contents file] returns the string with the full contents of the file *)
val file_contents : string -> string Deferred.t
(** [load_sexp ?exclusive file ~f] loads and convert the S-expression in a given [file]
using [f], and returns the deferred conversion result as a variant of either [Ok res]
or [Error exn] otherwise. This function provides accurate error locations for failed
conversions. *)
val load_sexp
: ?exclusive:bool -> string -> (Sexp.t -> 'a) -> 'a Or_error.t Deferred.t
val load_sexp_exn
: ?exclusive:bool -> string -> (Sexp.t -> 'a) -> 'a Deferred.t
(** [load_sexps file ~f] load and convert the S-expressions in a given [file] using [f],
and return the deferred list of conversion results as variants of either [Ok res] or
[Error exn] otherwise. This function is as efficient as [load_sexps] followed by
conversion if there are no errors, but provides accurate error locations for failed
conversions. *)
val load_sexps
: ?exclusive:bool -> string -> (Sexp.t -> 'a) -> 'a list Or_error.t Deferred.t
val load_sexps_exn
: ?exclusive:bool -> string -> (Sexp.t -> 'a) -> 'a list Deferred.t
| null | https://raw.githubusercontent.com/monadbobo/ocaml-core/9c1c06e7a1af7e15b6019a325d7dbdbd4cdb4020/base/async/unix/lib/reader.mli | ocaml | * [last_read_time t] returns time of the most recent [read] system call that
returned data.
* [open_file file] opens [file] for reading and returns a reader reading from
it.
* [close t] closes the underlying file descriptor of the reader.
* [closed t] returns a deferred that is filled in when the reader is
* closed by a call to close. The deferred becomes determined after the
* underlying close() system call completes.
* [close_was_started t] returns [true] if the closing process for the [Reader] has
been started (it may not yet be closed, however).
* [id t] @return a name for this reader that is unique across all
instances of the reader module.
* [fd t] @return the Fd.t used to create this reader
* [read_one_chunk_at_a_time_until_eof t ~handle_chunk] reads into [t]'s internal
buffer, and whenever bytes are available, applies [handle_chunk] to them. It waits to
read again until the deferred returned by [handle_chunk] becomes determined.
* [read_until t pred ~keep_delim] reads until it hits a delimiter [c] such that:
- in case [pred = `Char c'], [c = c']
- in case [pred = `Pred p], [p c = true]
[`Char c'] is equivalent to [`Pred (fun c -> c = c')] but the underlying
implementation is more efficient, in particular it will not call a function on every
input character.
[read_until] returns a freshly-allocated string consisting of all
the characters read and optionally including the delimiter as per
[keep_delim].
* just like read_until, except you have the option of specifiying a
maximum number of chars to read.
* [read_sexp t] reads the next sexp.
* Like read_marshal_raw, but unmarshal the value after reading it
* [recv t] returns a string that was written with Writer.send
* [file_contents file] returns the string with the full contents of the file
* [load_sexp ?exclusive file ~f] loads and convert the S-expression in a given [file]
using [f], and returns the deferred conversion result as a variant of either [Ok res]
or [Error exn] otherwise. This function provides accurate error locations for failed
conversions.
* [load_sexps file ~f] load and convert the S-expressions in a given [file] using [f],
and return the deferred list of conversion results as variants of either [Ok res] or
[Error exn] otherwise. This function is as efficient as [load_sexps] followed by
conversion if there are no errors, but provides accurate error locations for failed
conversions. | * A reader lets one do buffered input from a file descriptor .
Each of the read functions returns a deferred that will become determined when the
read completes . It is an error to have two simultaneous reads . That is , if one calls
a read function , one should not call another read function until the first one
completes .
If the file descriptor underlying a reader is closed , the reader will return EOF
( after all the buffered bytes have been read ) .
Each of the read functions returns a deferred that will become determined when the
read completes. It is an error to have two simultaneous reads. That is, if one calls
a read function, one should not call another read function until the first one
completes.
If the file descriptor underlying a reader is closed, the reader will return EOF
(after all the buffered bytes have been read). *)
open Core.Std
open Import
module Read_result : sig
type 'a t = [ `Ok of 'a | `Eof ] with bin_io, sexp
include Monad.S with type 'a t := 'a t
end
module Id : Unique_id
type t with sexp_of
* [ io_stats ] Overall IO statistics for all readers
val io_stats : Io_stats.t
val last_read_time : t -> Time.t
* [ stdin ] is a reader for file descriptor 0 . It is lazy because we do n't want
to create it in all programs that happen to link with async .
to create it in all programs that happen to link with async. *)
val stdin : t Lazy.t
val open_file : ?buf_len:int -> string -> t Deferred.t
* [ transfer t pipe_w ] transfers data from [ t ] into [ pipe_w ] one chunk at a time
( whatever is read from the underlying file descriptor without post - processing ) . The
result becomes determined after reaching EOF on [ t ] and the final bytes have been
transferred .
This function will normally not be needed ( see [ pipe ] ) .
(whatever is read from the underlying file descriptor without post-processing). The
result becomes determined after reaching EOF on [t] and the final bytes have been
transferred.
This function will normally not be needed (see [pipe]). *)
val transfer : t -> string Pipe.Writer.t -> unit Deferred.t
* [ pipe t ] returns the reader end of a pipe that will continually be filled with chunks
of data from the underlying Reader.t . The pipe will be closed when the reader
reaches EOF .
of data from the underlying Reader.t. The pipe will be closed when the reader
reaches EOF. *)
val pipe : t -> string Pipe.Reader.t
* [ create ~buf_len fd ] creates a new reader that is reading from [ fd ] .
@param access_raw_data default = None if specified this function will
be given access to the raw bits as they are read by the reader . No
guarantee of granularity is made .
@param access_raw_data default = None if specified this function will
be given access to the raw bits as they are read by the reader. No
guarantee of granularity is made. *)
val create : ?buf_len:int -> Fd.t -> t
val of_in_channel : in_channel -> Fd.Kind.t -> t
* [ with_file file f ] opens [ files ] , creates a reader with it , and passes the reader to
[ f ] . It closes the reader when the result of [ f ] becomes determined , and returns
[ f ] 's result .
NOTE , you need to be careful that all your IO is done when the deferred you return
becomes determined . If for example , you use [ with_file ] , and call [ lines ] , make sure
you return a deferred that becomes determined when the EOF is reached on the pipe ,
not when you get the pipe ( because you get it straight away ) .
[f]. It closes the reader when the result of [f] becomes determined, and returns
[f]'s result.
NOTE, you need to be careful that all your IO is done when the deferred you return
becomes determined. If for example, you use [with_file], and call [lines], make sure
you return a deferred that becomes determined when the EOF is reached on the pipe,
not when you get the pipe (because you get it straight away).
*)
val with_file :
?buf_len:int -> ?exclusive:bool -> string -> f:(t -> 'a Deferred.t) -> 'a Deferred.t
val close : t -> unit Deferred.t
val closed : t -> unit Deferred.t
val close_was_started : t -> bool
val id : t -> Id.t
val fd : t -> Fd.t
* [ read t ? pos ? len buf ] reads up to [ len ] bytes into buf , blocking
until some data is available or end - of - input is reached . The resulting
[ i ] satisfies [ 0 < i < = len ] .
until some data is available or end-of-input is reached. The resulting
[i] satisfies [0 < i <= len]. *)
val read : t -> ?pos:int -> ?len:int -> string -> int Read_result.t Deferred.t
val read_one_chunk_at_a_time_until_eof
: t
-> handle_chunk:(Bigstring.t
-> pos:int
-> len:int
-> [ `Stop of 'a | `Continue ] Deferred.t)
-> [ `Eof
| `Stopped of 'a
] Deferred.t
* [ read_substring t ss ] reads up to [ Substring.length ss ] bytes into [ ss ] ,
blocking until some data is available or Eof is reched . The resulting [ i ]
satisfies [ 0 < i < = Substring.length ss ] .
blocking until some data is available or Eof is reched. The resulting [i]
satisfies [0 < i <= Substring.length ss]. *)
val read_substring : t -> Substring.t -> int Read_result.t Deferred.t
val read_bigsubstring : t -> Bigsubstring.t -> int Read_result.t Deferred.t
val read_char : t -> char Read_result.t Deferred.t
* [ really_read t buf ? pos ? len ] reads until it fills [ len ] bytes of [ buf ]
starting at [ pos ] or runs out of input . In the former case it returns ` Ok .
In the latter , it returns [ ` Eof n ] where [ n ] is the number of bytes that
were read before end of input , and [ 0 < = n < String.length ss ] .
starting at [pos] or runs out of input. In the former case it returns `Ok.
In the latter, it returns [`Eof n] where [n] is the number of bytes that
were read before end of input, and [0 <= n < String.length ss]. *)
val really_read :
t -> ?pos:int -> ?len:int -> string
-> [ `Ok
| `Eof of int ] Deferred.t
val really_read_substring :
t -> Substring.t
-> [ `Ok
0 < = i < Substring.length ss
val really_read_bigsubstring :
t -> Bigsubstring.t
-> [ `Ok
0 < = i < Substring.length ss
val read_until :
t -> [`Pred of (char -> bool) | `Char of char] -> keep_delim:bool
-> [ `Ok of string
| `Eof_without_delim of string
| `Eof ] Deferred.t
val read_until_max :
t
-> [`Pred of (char -> bool) | `Char of char]
-> keep_delim:bool
-> max:int
-> [ `Ok of string
| `Eof_without_delim of string
| `Eof
| `Max_exceeded of string] Deferred.t
* [ read_line t ] reads up to , and including the next newline ( \n )
character and returns a freshly - allocated string containing
everything up to but not including the newline character . If
read_line encounters EOF before the newline char then everything
read up to but not including EOF will be returned as a line .
character and returns a freshly-allocated string containing
everything up to but not including the newline character. If
read_line encounters EOF before the newline char then everything
read up to but not including EOF will be returned as a line. *)
val read_line : t -> string Read_result.t Deferred.t
type 'a read = ?parse_pos : Sexp.Parse_pos.t -> 'a
val read_sexp : (t -> Sexp.t Read_result.t Deferred.t) read
* [ read_sexps t ] reads all the sexps and returns them as a pipe .
val read_sexps : (t -> Sexp.t Pipe.Reader.t) read
* [ read_bin_prot ? max_len t bp_reader ] reads the next binary protocol
message using binary protocol reader [ bp_reader ] . The format is the
" size - prefixed binary protocol " , in which the length of the data is
prefixed as a 64 - bit integer to the data . This is the format that
Writer.write_bin_prot writes .
message using binary protocol reader [bp_reader]. The format is the
"size-prefixed binary protocol", in which the length of the data is
prefixed as a 64-bit integer to the data. This is the format that
Writer.write_bin_prot writes. *)
val read_bin_prot :
?max_len:int
-> t
-> 'a Bin_prot.Type_class.reader
-> 'a Read_result.t Deferred.t
* Read and return a buffer containing one marshaled value , but do n't
unmarshal it . You can just call Marshal.from_string on the string ,
and cast it to the desired type ( preferrably the actual
type ) . similar to Marshal.from_channel , but suffers from the
String - length limitation ( 16 MB ) on 32bit platforms .
unmarshal it. You can just call Marshal.from_string on the string,
and cast it to the desired type (preferrably the actual
type). similar to Marshal.from_channel, but suffers from the
String-length limitation (16MB) on 32bit platforms. *)
val read_marshal_raw : t -> string Read_result.t Deferred.t
val read_marshal : t -> 'a Read_result.t Deferred.t
val recv : t -> string Read_result.t Deferred.t
* [ read_all t read_one ] returns a pipe that receives all values read from [ t ] by
repeatedly using [ read_one t ] . When [ read_all ] reaches EOF , it closes the resulting
pipe , but not [ t ] .
repeatedly using [read_one t]. When [read_all] reaches EOF, it closes the resulting
pipe, but not [t]. *)
val read_all : t -> (t -> 'a Read_result.t Deferred.t) -> 'a Pipe.Reader.t
* [ lines t ] reads all the lines from [ t ] and puts them in the pipe , one line per
pipe element .
pipe element. *)
val lines : t -> string Pipe.Reader.t
* [ contents t ] returns the string corresponding to the full contents
( up to EOF ) of the reader .
(up to EOF) of the reader. *)
val contents : t -> string Deferred.t
val file_contents : string -> string Deferred.t
val load_sexp
: ?exclusive:bool -> string -> (Sexp.t -> 'a) -> 'a Or_error.t Deferred.t
val load_sexp_exn
: ?exclusive:bool -> string -> (Sexp.t -> 'a) -> 'a Deferred.t
val load_sexps
: ?exclusive:bool -> string -> (Sexp.t -> 'a) -> 'a list Or_error.t Deferred.t
val load_sexps_exn
: ?exclusive:bool -> string -> (Sexp.t -> 'a) -> 'a list Deferred.t
|
ce83599eaa018b9133ce68f000f7e97663cc3cbeaed8d4248b819b186df89bb1 | janestreet/base | test_nativeint.ml | open! Import
open! Nativeint
let%expect_test "hash coherence" =
check_int_hash_coherence [%here] (module Nativeint);
[%expect {| |}]
;;
type test_case = nativeint * int32 * int64
let test_cases : test_case list =
[ 0x0000_0011n, 0x1100_0000l, 0x1100_0000_0000_0000L
; 0x0000_1122n, 0x2211_0000l, 0x2211_0000_0000_0000L
; 0x0011_2233n, 0x3322_1100l, 0x3322_1100_0000_0000L
; 0x1122_3344n, 0x4433_2211l, 0x4433_2211_0000_0000L
]
;;
let%expect_test "bswap native" =
List.iter test_cases ~f:(fun (arg, bswap_int32, bswap_int64) ->
let result = bswap arg in
match Sys.word_size_in_bits with
| 32 -> assert (Int32.equal bswap_int32 (Nativeint.to_int32_trunc result))
| 64 -> assert (Int64.equal bswap_int64 (Nativeint.to_int64 result))
| _ -> assert false)
;;
| null | https://raw.githubusercontent.com/janestreet/base/221b085f3fcd77597f8245b4d73de3970b238e71/test/test_nativeint.ml | ocaml | open! Import
open! Nativeint
let%expect_test "hash coherence" =
check_int_hash_coherence [%here] (module Nativeint);
[%expect {| |}]
;;
type test_case = nativeint * int32 * int64
let test_cases : test_case list =
[ 0x0000_0011n, 0x1100_0000l, 0x1100_0000_0000_0000L
; 0x0000_1122n, 0x2211_0000l, 0x2211_0000_0000_0000L
; 0x0011_2233n, 0x3322_1100l, 0x3322_1100_0000_0000L
; 0x1122_3344n, 0x4433_2211l, 0x4433_2211_0000_0000L
]
;;
let%expect_test "bswap native" =
List.iter test_cases ~f:(fun (arg, bswap_int32, bswap_int64) ->
let result = bswap arg in
match Sys.word_size_in_bits with
| 32 -> assert (Int32.equal bswap_int32 (Nativeint.to_int32_trunc result))
| 64 -> assert (Int64.equal bswap_int64 (Nativeint.to_int64 result))
| _ -> assert false)
;;
|
|
ff980cd466593482e1cf3dc61699155738d26a13164d3fbf6f71822febc10ccd | paf31/dovetail | FFI.hs | # LANGUAGE ImportQualifiedPost #
{-# LANGUAGE OverloadedStrings #-}
module Dovetail.FFI
(
-- * Foreign function interface
FFI(..)
, ForeignImport(..)
, toEnv
, toExterns
) where
import Data.Map qualified as Map
import Dovetail.Types
import Language.PureScript qualified as P
import Language.PureScript.Externs qualified as Externs
| Describes a module which is implemented in Haskell , and made available
to PureScript code using its foreign function interface .
--
-- Right now, this consists only of foreign value declarations, even though
the FFI supports other forms of interop .
--
-- Values of this type can be constructed directly, but in many cases it is
simpler to use the " Dovetail . FFI.Builder " module
-- instead.
--
-- Values of this type can be consumed by the 'toExterns' and 'toEnv' functions,
and their results passed to the PureScript APIs or the low - level functions in
" Dovetail . Evaluate " and " Dovetail . Build " ,
-- directly, but it is more likely that you will use values of this type with the
higher - level ' Dovetail.ffi ' function .
data FFI ctx = FFI
{ ffi_moduleName :: P.ModuleName
^ The module name for the module being implemented in Haskell .
, ffi_values :: [ForeignImport ctx]
^ A list of values implemented in Haskell in this module .
}
| A single value implemented in a foreign Haskell module .
data ForeignImport ctx = ForeignImport
{ fv_name :: P.Ident
^ The name of this value in PureScript code
, fv_type :: P.SourceType
^ The PureScript type of this value
, fv_value :: Value ctx
-- ^ The value itself
}
| Convert a foreign module into a PureScript externs file , for use during
-- separate compilation.
--
-- For advanced use cases, the result may be used with the functions in the
" Dovetail . Build " module .
toExterns :: FFI ctx -> P.ExternsFile
toExterns (FFI mn vals) =
Externs.ExternsFile
{ Externs.efVersion = "0.14.2"
, Externs.efModuleName = mn
, Externs.efExports = [P.ValueRef P.nullSourceSpan name | ForeignImport name _ _ <- vals]
, Externs.efImports = [ P.ExternsImport (P.ModuleName "Prim") P.Implicit (Just (P.ModuleName "Prim"))
, P.ExternsImport (P.ModuleName "Prim") P.Implicit Nothing
]
, Externs.efFixities = []
, Externs.efTypeFixities = []
, Externs.efDeclarations = [Externs.EDValue name ty | ForeignImport name ty _ <- vals]
, Externs.efSourceSpan = P.nullSourceSpan
}
-- | Convert a foreign module into an evaluation environment.
--
-- For advanced use cases, the result may be used with the functions in the
" Dovetail . Evaluate " module .
toEnv :: FFI ctx -> Env ctx
toEnv (FFI mn vals) =
envFromMap $ Map.fromList [ (P.mkQualified name mn, val) | ForeignImport name _ val <- vals ] | null | https://raw.githubusercontent.com/paf31/dovetail/60e00e247b643ad9c05e4137396ffddedcd8bcb6/dovetail/src/Dovetail/FFI.hs | haskell | # LANGUAGE OverloadedStrings #
* Foreign function interface
Right now, this consists only of foreign value declarations, even though
Values of this type can be constructed directly, but in many cases it is
instead.
Values of this type can be consumed by the 'toExterns' and 'toEnv' functions,
directly, but it is more likely that you will use values of this type with the
^ The value itself
separate compilation.
For advanced use cases, the result may be used with the functions in the
| Convert a foreign module into an evaluation environment.
For advanced use cases, the result may be used with the functions in the | # LANGUAGE ImportQualifiedPost #
module Dovetail.FFI
(
FFI(..)
, ForeignImport(..)
, toEnv
, toExterns
) where
import Data.Map qualified as Map
import Dovetail.Types
import Language.PureScript qualified as P
import Language.PureScript.Externs qualified as Externs
| Describes a module which is implemented in Haskell , and made available
to PureScript code using its foreign function interface .
the FFI supports other forms of interop .
simpler to use the " Dovetail . FFI.Builder " module
and their results passed to the PureScript APIs or the low - level functions in
" Dovetail . Evaluate " and " Dovetail . Build " ,
higher - level ' Dovetail.ffi ' function .
data FFI ctx = FFI
{ ffi_moduleName :: P.ModuleName
^ The module name for the module being implemented in Haskell .
, ffi_values :: [ForeignImport ctx]
^ A list of values implemented in Haskell in this module .
}
| A single value implemented in a foreign Haskell module .
data ForeignImport ctx = ForeignImport
{ fv_name :: P.Ident
^ The name of this value in PureScript code
, fv_type :: P.SourceType
^ The PureScript type of this value
, fv_value :: Value ctx
}
| Convert a foreign module into a PureScript externs file , for use during
" Dovetail . Build " module .
toExterns :: FFI ctx -> P.ExternsFile
toExterns (FFI mn vals) =
Externs.ExternsFile
{ Externs.efVersion = "0.14.2"
, Externs.efModuleName = mn
, Externs.efExports = [P.ValueRef P.nullSourceSpan name | ForeignImport name _ _ <- vals]
, Externs.efImports = [ P.ExternsImport (P.ModuleName "Prim") P.Implicit (Just (P.ModuleName "Prim"))
, P.ExternsImport (P.ModuleName "Prim") P.Implicit Nothing
]
, Externs.efFixities = []
, Externs.efTypeFixities = []
, Externs.efDeclarations = [Externs.EDValue name ty | ForeignImport name ty _ <- vals]
, Externs.efSourceSpan = P.nullSourceSpan
}
" Dovetail . Evaluate " module .
toEnv :: FFI ctx -> Env ctx
toEnv (FFI mn vals) =
envFromMap $ Map.fromList [ (P.mkQualified name mn, val) | ForeignImport name _ val <- vals ] |
a0129cf842b491dc933fa837199203e8d33fb2c372f5a4e45e3be874dd2e6cea | atlas-engineer/nyxt | small-web.lisp | SPDX - FileCopyrightText : Atlas Engineer LLC
SPDX - License - Identifier : BSD-3 - Clause
(nyxt:define-package :nyxt/small-web-mode
(:documentation "Mode for Gopher/Gemini page interaction."))
(in-package :nyxt/small-web-mode)
(define-mode small-web-mode ()
"Gopher/Gemini page interaction mode.
Renders gopher elements (provided by `cl-gopher') to human-readable HTML.
The default style is rendering info messages to <pre> text, inlining
images/sounds and showing everything else as buttons.
The rendering of pages is done via the `render' method, while rendering of
separate lines constituting a page is done in `line->html'. If you're
unsatisfied with how pages are rendered, override either of the two.
For example, if you want to render images as links instead of inline image
loading, you'd need to override `line->html' in the following way:
\(defun image->link (line)
(spinneret:with-html-string
(:a :href (cl-gopher:uri-for-gopher-line line)
(cl-gopher:display-string line))))
\(defmethod line->html ((line cl-gopher:image)) (image->link line))
\(defmethod line->html ((line cl-gopher:gif)) (image->link line))
\(defmethod line->html ((line cl-gopher:png)) (image->link line))
Gemini support is a bit more chaotic, but you can override `line->html' for
`phos/gemtext' elements too."
((visible-in-status-p nil)
(url :documentation "The URL being opened.")
(model :documentation "The contents of the current page.")
(redirections nil :documentation "The list of redirection Gemini URLs.")
(allowed-redirections-count
5
:documentation "The number of redirections that Gemini resources are allowed to make.")
(style (theme:themed-css (nyxt::theme *browser*)
`(body
:background-color ,theme:background)
`(pre
:background-color ,theme:secondary
:padding "2px"
:margin "0"
:border-radius 0)
`(.button
:margin "0 3px 3px 0"
:font-size "15px")
`(.search
:background-color ,theme:accent
:color ,theme:on-accent)
`(.error
:background-color ,theme:accent
:color ,theme:on-accent
:padding "1em 0"))))
(:toggler-command-p nil))
;;; Gopher rendering.
(defmethod cl-gopher:display-string :around ((line cl-gopher:gopher-line))
(cl-ppcre:regex-replace-all "\\e\\[[\\d;]*[A-Za-z]" (slot-value line 'cl-gopher:display-string) ""))
(export-always 'line->html)
(defgeneric line->html (line)
(:documentation "Transform a Gopher or Gemini line to a reasonable HTML representation."))
(export-always 'gopher-render)
(defgeneric gopher-render (line)
(:documentation "Produce a Gopher page content string/array given LINE.
Second return value should be the MIME-type of the content.
Implies that `small-web-mode' is enabled."))
(defmethod line->html ((line cl-gopher:gopher-line))
(spinneret:with-html-string
(:pre "[" (symbol-name (class-name (class-of line))) "] "
(cl-gopher:display-string line)
" (" (cl-gopher:uri-for-gopher-line line) ")")))
(defmethod line->html ((line cl-gopher:error-code))
(spinneret:with-html-string
(:pre :class "error"
"Error: " (cl-gopher:display-string line))))
(defmethod line->html ((line cl-gopher:info-message))
(let ((line (cl-gopher:display-string line)))
(spinneret:with-html-string
(if (str:blankp line)
(:br)
(:pre line)))))
(defmethod line->html ((line cl-gopher:submenu))
(spinneret:with-html-string
(:a :class "button" :href (cl-gopher:uri-for-gopher-line line)
(cl-gopher:display-string line))))
(defun image->html (line)
(let ((uri (cl-gopher:uri-for-gopher-line line)))
(spinneret:with-html-string
(:a :href uri
(:img :src uri
:alt (cl-gopher:display-string line))))))
(defmethod line->html ((line cl-gopher:image)) (image->html line))
(defmethod line->html ((line cl-gopher:gif)) (image->html line))
(defmethod line->html ((line cl-gopher:png)) (image->html line))
(defmethod line->html ((line cl-gopher:sound-file))
(spinneret:with-html-string
(:audio :src (cl-gopher:uri-for-gopher-line line)
:controls t
(cl-gopher:display-string line))))
(defmethod line->html ((line cl-gopher:search-line))
(spinneret:with-html-string
(:a :class "button search"
:href (cl-gopher:uri-for-gopher-line line)
(:b "[SEARCH] ") (cl-gopher:display-string line))))
(defmethod line->html ((line cl-gopher:html-file))
(let ((selector (cl-gopher:selector line)))
(spinneret:with-html-string
(:a :class "button"
:href (if (str:starts-with-p "URL:" selector)
(sera:slice selector 4)
selector)
(cl-gopher:display-string line))
(:br))))
(defmethod line->html ((line cl-gopher:text-file))
(spinneret:with-html-string
(:a :class "button"
:href (cl-gopher:uri-for-gopher-line line)
(cl-gopher:display-string line))
(:br)))
(defun file-link->html (line)
(spinneret:with-html-string
(:a :class "button"
:style (format nil "background-color: ~a" (theme:primary-color (theme *browser*)))
:href (cl-gopher:uri-for-gopher-line line)
(:b "[FILE] ") (cl-gopher:display-string line))
(:br)))
(defmethod line->html ((line cl-gopher:binary-file)) (file-link->html line))
(defmethod line->html ((line cl-gopher:binhex-file)) (file-link->html line))
(defmethod line->html ((line cl-gopher:dos-file)) (file-link->html line))
(defmethod line->html ((line cl-gopher:uuencoded-file)) (file-link->html line))
(defmethod line->html ((line cl-gopher:unknown)) (file-link->html line))
(defmethod gopher-render ((line cl-gopher:gopher-line))
(alex:when-let ((contents (cl-gopher:get-line-contents line))
(spinneret:*html-style* :tree)
(mode (find-submode 'small-web-mode)))
(setf (model mode) contents)
(values (spinneret:with-html-string
(:nstyle (style (current-buffer)))
(:nstyle (style mode))
(loop for line in (cl-gopher:lines contents)
collect (:raw (line->html line))))
"text/html;charset=utf8")))
(defmethod gopher-render ((line cl-gopher:html-file))
(let ((contents (cl-gopher:get-line-contents line)))
(values (cl-gopher:content-string contents) "text/html;charset=utf8")))
(defmethod gopher-render ((line cl-gopher:text-file))
(let ((contents (cl-gopher:get-line-contents line)))
;; TODO: Guess encoding?
(values (str:join +newline+ (cl-gopher:lines contents)) "text/plain;charset=utf8")))
(defun render-binary-content (line &optional mime)
(let* ((url (quri:uri (cl-gopher:uri-for-gopher-line line)))
(file (pathname (quri:uri-path url)))
(mime (or mime (mimes:mime file)))
(contents (cl-gopher:get-line-contents line)))
(values (cl-gopher:content-array contents) mime)))
(defmethod gopher-render ((line cl-gopher:image)) (render-binary-content line))
(defmethod gopher-render ((line cl-gopher:binary-file)) (render-binary-content line))
(defmethod gopher-render ((line cl-gopher:binhex-file)) (render-binary-content line))
(defmethod gopher-render ((line cl-gopher:dos-file)) (render-binary-content line))
(defmethod gopher-render ((line cl-gopher:uuencoded-file)) (render-binary-content line))
(defmethod gopher-render ((line cl-gopher:gif)) (render-binary-content line "image/gif"))
(defmethod gopher-render ((line cl-gopher:png)) (render-binary-content line "image/png"))
TODO : : display - isolated - p ? 's behavior implies inability to embed it
;; into pages of the bigger Web, which is exactly what display-isolated means.
(define-internal-scheme "gopher"
(lambda (url buffer)
(handler-case
(let* ((line (if (uiop:emptyp (quri:uri-path (quri:uri url)))
(buffer-load (str:concat url "/") :buffer buffer)
(cl-gopher:parse-gopher-uri url))))
(if (and (typep line 'cl-gopher:search-line)
(uiop:emptyp (cl-gopher:terms line)))
(progn (setf (cl-gopher:terms line)
(prompt1 :prompt (format nil "Search query for ~a" url)
:sources 'prompter:raw-source))
(buffer-load (cl-gopher:uri-for-gopher-line line) :buffer buffer))
(with-current-buffer buffer
(gopher-render line))))
(cl-gopher:bad-submenu-error ()
(error-help (format nil "Malformed line at ~s" url)
(format nil "One of the lines on this page has an improper format.
Please report this to the server admin.")))
(cl-gopher:bad-uri-error ()
(error-help (format nil "Malformed URL: ~s" url)
(format nil "The URL you inputted most probably has a typo in it.
Please, check URL correctness and try again.")))
(usocket:ns-condition (condition)
(error-help (format nil "Error resolving ~s" url)
(format nil "Original text of ~a:~%~a" (type-of condition) condition)))
(usocket:socket-condition (condition)
(error-help (format nil "Socket malfunction when accessing ~s" url)
(format nil "Original text of ~a:~%~a" (type-of condition) condition)))
(condition (condition)
(error-help "Unknown error"
(format nil "Original text of ~a:~%~a" (type-of condition) condition))))))
Gemini rendering .
(defmethod line->html ((element gemtext:element))
(spinneret:with-html-string
(:pre (gemtext:text element))))
(defmethod line->html ((element gemtext:paragraph))
(spinneret:with-html-string
(:p (gemtext:text element))))
(defmethod line->html ((element gemtext:title))
(spinneret:with-html-string
(case (gemtext:level element)
(1 (:h1 (gemtext:text element)))
(2 (:h2 (gemtext:text element)))
(3 (:h3 (gemtext:text element))))))
;; TODO: We used to build <ul>-lists out of those. Should we?
(defmethod line->html ((element gemtext:item))
(spinneret:with-html-string
(:li (gemtext:text element))))
(defmethod line->html ((element gemtext:link))
(spinneret:with-html-string
(let* ((url (render-url (gemtext:url element)))
(path (quri:uri-path (gemtext:url element)))
(mime (unless (uiop:emptyp path)
(mimes:mime-lookup path)))
(text (cond
((not (uiop:emptyp (gemtext:text element)))
(gemtext:text element))
((not (uiop:emptyp url))
url)
(t "[LINK]"))))
(cond
((str:starts-with-p "image/" mime)
(:a :href url (:img :src url :alt text)))
((str:starts-with-p "audio/" mime)
(:audio :src url :controls t text))
((str:starts-with-p "video/" mime)
(:video :src url :controls t))
(t (:a :class "button" :href url text))))
(:br)))
(export-always 'gemtext-render)
(defun gemtext-render (gemtext buffer)
"Renders the Gemtext (Gemini markup format) to HTML.
Implies that `small-web-mode' is enabled."
(let ((mode (find-submode 'small-web-mode buffer))
(elements (phos/gemtext:parse-string gemtext))
(spinneret::*html-style* :tree))
(setf (model mode) elements)
(values (spinneret:with-html-string
(:nstyle (style buffer))
(when mode
(:nstyle (style mode)))
(loop for element in elements
collect (:raw (nyxt/small-web-mode:line->html element))))
"text/html;charset=utf8")))
TODO : : secure - p t ? Gemini is encrypted , so it can be considered secure .
(define-internal-scheme "gemini"
(lambda (url buffer)
(handler-case
(sera:mvlet* ((status meta body (gemini:request url)))
(unless (member status '(:redirect :permanent-redirect))
(setf (nyxt/small-web-mode:redirections (find-submode 'small-web-mode)) nil))
(case status
((:input :sensitive-input)
(let ((text (quri:url-encode
(handler-case
(prompt1 :prompt meta
:sources 'prompter:raw-source
:invisible-input-p (eq status :sensitive-input))
(nyxt::prompt-buffer-canceled () "")))))
(buffer-load (str:concat url "?" text) :buffer buffer)))
(:success
(if (str:starts-with-p "text/gemini" meta)
(gemtext-render body buffer)
(values body meta)))
((:redirect :permanent-redirect)
(push url (nyxt/small-web-mode:redirections (find-submode 'small-web-mode)))
(if (< (length (nyxt/small-web-mode:redirections (find-submode 'small-web-mode)))
(nyxt/small-web-mode:allowed-redirections-count (find-submode 'small-web-mode)))
(buffer-load (quri:merge-uris (quri:uri meta) (quri:uri url)) :buffer buffer)
(error-help
"Error"
(format nil "The server has caused too many (~a+) redirections.~& ~a~{ -> ~a~}"
(nyxt/small-web-mode:allowed-redirections-count (find-submode 'small-web-mode))
(alex:lastcar (nyxt/small-web-mode:redirections (find-submode 'small-web-mode)))
(butlast (nyxt/small-web-mode:redirections (find-submode 'small-web-mode)))))))
((:temporary-failure :server-unavailable :cgi-error :proxy-error
:permanent-failure :not-found :gone :proxy-request-refused :bad-request)
(error-help "Error" meta))
(:slow-down
(error-help
"Slow down error"
(format nil "Try reloading the page in ~a seconds." meta)))
((:client-certificate-required :certificate-not-authorised :certificate-not-valid)
(error-help "Certificate error" meta))))
(gemini::malformed-response (e)
(error-help
"Malformed response"
(format nil "The response for the URL you're requesting (~s) is malformed:~2%~a" url e)))
(usocket:ns-condition (condition)
(error-help (format nil "Error resolving ~s" url)
(format nil "Original text of ~a:~%~a" (type-of condition) condition)))
(usocket:socket-condition (condition)
(error-help (format nil "Socket malfunction when accessing ~s" url)
(format nil "Original text of ~a:~%~a" (type-of condition) condition)))
(condition (condition)
(error-help "Unknown error"
(format nil "Original text of ~a:~%~a" (type-of condition) condition))))))
(define-auto-rule '(match-scheme "gopher" "gemini")
:included '(small-web-mode))
| null | https://raw.githubusercontent.com/atlas-engineer/nyxt/07063f399afddfe4679b28a351cf16ad04dd019d/source/mode/small-web.lisp | lisp | Gopher rendering.
TODO: Guess encoding?
into pages of the bigger Web, which is exactly what display-isolated means.
TODO: We used to build <ul>-lists out of those. Should we? | SPDX - FileCopyrightText : Atlas Engineer LLC
SPDX - License - Identifier : BSD-3 - Clause
(nyxt:define-package :nyxt/small-web-mode
(:documentation "Mode for Gopher/Gemini page interaction."))
(in-package :nyxt/small-web-mode)
(define-mode small-web-mode ()
"Gopher/Gemini page interaction mode.
Renders gopher elements (provided by `cl-gopher') to human-readable HTML.
The default style is rendering info messages to <pre> text, inlining
images/sounds and showing everything else as buttons.
The rendering of pages is done via the `render' method, while rendering of
separate lines constituting a page is done in `line->html'. If you're
unsatisfied with how pages are rendered, override either of the two.
For example, if you want to render images as links instead of inline image
loading, you'd need to override `line->html' in the following way:
\(defun image->link (line)
(spinneret:with-html-string
(:a :href (cl-gopher:uri-for-gopher-line line)
(cl-gopher:display-string line))))
\(defmethod line->html ((line cl-gopher:image)) (image->link line))
\(defmethod line->html ((line cl-gopher:gif)) (image->link line))
\(defmethod line->html ((line cl-gopher:png)) (image->link line))
Gemini support is a bit more chaotic, but you can override `line->html' for
`phos/gemtext' elements too."
((visible-in-status-p nil)
(url :documentation "The URL being opened.")
(model :documentation "The contents of the current page.")
(redirections nil :documentation "The list of redirection Gemini URLs.")
(allowed-redirections-count
5
:documentation "The number of redirections that Gemini resources are allowed to make.")
(style (theme:themed-css (nyxt::theme *browser*)
`(body
:background-color ,theme:background)
`(pre
:background-color ,theme:secondary
:padding "2px"
:margin "0"
:border-radius 0)
`(.button
:margin "0 3px 3px 0"
:font-size "15px")
`(.search
:background-color ,theme:accent
:color ,theme:on-accent)
`(.error
:background-color ,theme:accent
:color ,theme:on-accent
:padding "1em 0"))))
(:toggler-command-p nil))
(defmethod cl-gopher:display-string :around ((line cl-gopher:gopher-line))
(cl-ppcre:regex-replace-all "\\e\\[[\\d;]*[A-Za-z]" (slot-value line 'cl-gopher:display-string) ""))
(export-always 'line->html)
(defgeneric line->html (line)
(:documentation "Transform a Gopher or Gemini line to a reasonable HTML representation."))
(export-always 'gopher-render)
(defgeneric gopher-render (line)
(:documentation "Produce a Gopher page content string/array given LINE.
Second return value should be the MIME-type of the content.
Implies that `small-web-mode' is enabled."))
(defmethod line->html ((line cl-gopher:gopher-line))
(spinneret:with-html-string
(:pre "[" (symbol-name (class-name (class-of line))) "] "
(cl-gopher:display-string line)
" (" (cl-gopher:uri-for-gopher-line line) ")")))
(defmethod line->html ((line cl-gopher:error-code))
(spinneret:with-html-string
(:pre :class "error"
"Error: " (cl-gopher:display-string line))))
(defmethod line->html ((line cl-gopher:info-message))
(let ((line (cl-gopher:display-string line)))
(spinneret:with-html-string
(if (str:blankp line)
(:br)
(:pre line)))))
(defmethod line->html ((line cl-gopher:submenu))
(spinneret:with-html-string
(:a :class "button" :href (cl-gopher:uri-for-gopher-line line)
(cl-gopher:display-string line))))
(defun image->html (line)
(let ((uri (cl-gopher:uri-for-gopher-line line)))
(spinneret:with-html-string
(:a :href uri
(:img :src uri
:alt (cl-gopher:display-string line))))))
(defmethod line->html ((line cl-gopher:image)) (image->html line))
(defmethod line->html ((line cl-gopher:gif)) (image->html line))
(defmethod line->html ((line cl-gopher:png)) (image->html line))
(defmethod line->html ((line cl-gopher:sound-file))
(spinneret:with-html-string
(:audio :src (cl-gopher:uri-for-gopher-line line)
:controls t
(cl-gopher:display-string line))))
(defmethod line->html ((line cl-gopher:search-line))
(spinneret:with-html-string
(:a :class "button search"
:href (cl-gopher:uri-for-gopher-line line)
(:b "[SEARCH] ") (cl-gopher:display-string line))))
(defmethod line->html ((line cl-gopher:html-file))
(let ((selector (cl-gopher:selector line)))
(spinneret:with-html-string
(:a :class "button"
:href (if (str:starts-with-p "URL:" selector)
(sera:slice selector 4)
selector)
(cl-gopher:display-string line))
(:br))))
(defmethod line->html ((line cl-gopher:text-file))
(spinneret:with-html-string
(:a :class "button"
:href (cl-gopher:uri-for-gopher-line line)
(cl-gopher:display-string line))
(:br)))
(defun file-link->html (line)
(spinneret:with-html-string
(:a :class "button"
:style (format nil "background-color: ~a" (theme:primary-color (theme *browser*)))
:href (cl-gopher:uri-for-gopher-line line)
(:b "[FILE] ") (cl-gopher:display-string line))
(:br)))
(defmethod line->html ((line cl-gopher:binary-file)) (file-link->html line))
(defmethod line->html ((line cl-gopher:binhex-file)) (file-link->html line))
(defmethod line->html ((line cl-gopher:dos-file)) (file-link->html line))
(defmethod line->html ((line cl-gopher:uuencoded-file)) (file-link->html line))
(defmethod line->html ((line cl-gopher:unknown)) (file-link->html line))
(defmethod gopher-render ((line cl-gopher:gopher-line))
(alex:when-let ((contents (cl-gopher:get-line-contents line))
(spinneret:*html-style* :tree)
(mode (find-submode 'small-web-mode)))
(setf (model mode) contents)
(values (spinneret:with-html-string
(:nstyle (style (current-buffer)))
(:nstyle (style mode))
(loop for line in (cl-gopher:lines contents)
collect (:raw (line->html line))))
"text/html;charset=utf8")))
(defmethod gopher-render ((line cl-gopher:html-file))
(let ((contents (cl-gopher:get-line-contents line)))
(values (cl-gopher:content-string contents) "text/html;charset=utf8")))
(defmethod gopher-render ((line cl-gopher:text-file))
(let ((contents (cl-gopher:get-line-contents line)))
(values (str:join +newline+ (cl-gopher:lines contents)) "text/plain;charset=utf8")))
(defun render-binary-content (line &optional mime)
(let* ((url (quri:uri (cl-gopher:uri-for-gopher-line line)))
(file (pathname (quri:uri-path url)))
(mime (or mime (mimes:mime file)))
(contents (cl-gopher:get-line-contents line)))
(values (cl-gopher:content-array contents) mime)))
(defmethod gopher-render ((line cl-gopher:image)) (render-binary-content line))
(defmethod gopher-render ((line cl-gopher:binary-file)) (render-binary-content line))
(defmethod gopher-render ((line cl-gopher:binhex-file)) (render-binary-content line))
(defmethod gopher-render ((line cl-gopher:dos-file)) (render-binary-content line))
(defmethod gopher-render ((line cl-gopher:uuencoded-file)) (render-binary-content line))
(defmethod gopher-render ((line cl-gopher:gif)) (render-binary-content line "image/gif"))
(defmethod gopher-render ((line cl-gopher:png)) (render-binary-content line "image/png"))
TODO : : display - isolated - p ? 's behavior implies inability to embed it
(define-internal-scheme "gopher"
(lambda (url buffer)
(handler-case
(let* ((line (if (uiop:emptyp (quri:uri-path (quri:uri url)))
(buffer-load (str:concat url "/") :buffer buffer)
(cl-gopher:parse-gopher-uri url))))
(if (and (typep line 'cl-gopher:search-line)
(uiop:emptyp (cl-gopher:terms line)))
(progn (setf (cl-gopher:terms line)
(prompt1 :prompt (format nil "Search query for ~a" url)
:sources 'prompter:raw-source))
(buffer-load (cl-gopher:uri-for-gopher-line line) :buffer buffer))
(with-current-buffer buffer
(gopher-render line))))
(cl-gopher:bad-submenu-error ()
(error-help (format nil "Malformed line at ~s" url)
(format nil "One of the lines on this page has an improper format.
Please report this to the server admin.")))
(cl-gopher:bad-uri-error ()
(error-help (format nil "Malformed URL: ~s" url)
(format nil "The URL you inputted most probably has a typo in it.
Please, check URL correctness and try again.")))
(usocket:ns-condition (condition)
(error-help (format nil "Error resolving ~s" url)
(format nil "Original text of ~a:~%~a" (type-of condition) condition)))
(usocket:socket-condition (condition)
(error-help (format nil "Socket malfunction when accessing ~s" url)
(format nil "Original text of ~a:~%~a" (type-of condition) condition)))
(condition (condition)
(error-help "Unknown error"
(format nil "Original text of ~a:~%~a" (type-of condition) condition))))))
Gemini rendering .
(defmethod line->html ((element gemtext:element))
(spinneret:with-html-string
(:pre (gemtext:text element))))
(defmethod line->html ((element gemtext:paragraph))
(spinneret:with-html-string
(:p (gemtext:text element))))
(defmethod line->html ((element gemtext:title))
(spinneret:with-html-string
(case (gemtext:level element)
(1 (:h1 (gemtext:text element)))
(2 (:h2 (gemtext:text element)))
(3 (:h3 (gemtext:text element))))))
(defmethod line->html ((element gemtext:item))
(spinneret:with-html-string
(:li (gemtext:text element))))
(defmethod line->html ((element gemtext:link))
(spinneret:with-html-string
(let* ((url (render-url (gemtext:url element)))
(path (quri:uri-path (gemtext:url element)))
(mime (unless (uiop:emptyp path)
(mimes:mime-lookup path)))
(text (cond
((not (uiop:emptyp (gemtext:text element)))
(gemtext:text element))
((not (uiop:emptyp url))
url)
(t "[LINK]"))))
(cond
((str:starts-with-p "image/" mime)
(:a :href url (:img :src url :alt text)))
((str:starts-with-p "audio/" mime)
(:audio :src url :controls t text))
((str:starts-with-p "video/" mime)
(:video :src url :controls t))
(t (:a :class "button" :href url text))))
(:br)))
(export-always 'gemtext-render)
(defun gemtext-render (gemtext buffer)
"Renders the Gemtext (Gemini markup format) to HTML.
Implies that `small-web-mode' is enabled."
(let ((mode (find-submode 'small-web-mode buffer))
(elements (phos/gemtext:parse-string gemtext))
(spinneret::*html-style* :tree))
(setf (model mode) elements)
(values (spinneret:with-html-string
(:nstyle (style buffer))
(when mode
(:nstyle (style mode)))
(loop for element in elements
collect (:raw (nyxt/small-web-mode:line->html element))))
"text/html;charset=utf8")))
TODO : : secure - p t ? Gemini is encrypted , so it can be considered secure .
(define-internal-scheme "gemini"
(lambda (url buffer)
(handler-case
(sera:mvlet* ((status meta body (gemini:request url)))
(unless (member status '(:redirect :permanent-redirect))
(setf (nyxt/small-web-mode:redirections (find-submode 'small-web-mode)) nil))
(case status
((:input :sensitive-input)
(let ((text (quri:url-encode
(handler-case
(prompt1 :prompt meta
:sources 'prompter:raw-source
:invisible-input-p (eq status :sensitive-input))
(nyxt::prompt-buffer-canceled () "")))))
(buffer-load (str:concat url "?" text) :buffer buffer)))
(:success
(if (str:starts-with-p "text/gemini" meta)
(gemtext-render body buffer)
(values body meta)))
((:redirect :permanent-redirect)
(push url (nyxt/small-web-mode:redirections (find-submode 'small-web-mode)))
(if (< (length (nyxt/small-web-mode:redirections (find-submode 'small-web-mode)))
(nyxt/small-web-mode:allowed-redirections-count (find-submode 'small-web-mode)))
(buffer-load (quri:merge-uris (quri:uri meta) (quri:uri url)) :buffer buffer)
(error-help
"Error"
(format nil "The server has caused too many (~a+) redirections.~& ~a~{ -> ~a~}"
(nyxt/small-web-mode:allowed-redirections-count (find-submode 'small-web-mode))
(alex:lastcar (nyxt/small-web-mode:redirections (find-submode 'small-web-mode)))
(butlast (nyxt/small-web-mode:redirections (find-submode 'small-web-mode)))))))
((:temporary-failure :server-unavailable :cgi-error :proxy-error
:permanent-failure :not-found :gone :proxy-request-refused :bad-request)
(error-help "Error" meta))
(:slow-down
(error-help
"Slow down error"
(format nil "Try reloading the page in ~a seconds." meta)))
((:client-certificate-required :certificate-not-authorised :certificate-not-valid)
(error-help "Certificate error" meta))))
(gemini::malformed-response (e)
(error-help
"Malformed response"
(format nil "The response for the URL you're requesting (~s) is malformed:~2%~a" url e)))
(usocket:ns-condition (condition)
(error-help (format nil "Error resolving ~s" url)
(format nil "Original text of ~a:~%~a" (type-of condition) condition)))
(usocket:socket-condition (condition)
(error-help (format nil "Socket malfunction when accessing ~s" url)
(format nil "Original text of ~a:~%~a" (type-of condition) condition)))
(condition (condition)
(error-help "Unknown error"
(format nil "Original text of ~a:~%~a" (type-of condition) condition))))))
(define-auto-rule '(match-scheme "gopher" "gemini")
:included '(small-web-mode))
|
514ea291889ddd4bdfa7f293d3900c7b6ce0ea1acb074d85f0867834e03d8251 | CryptoKami/cryptokami-core | Holders.hs | | This module provides implementations of " MonadCede " based on
either pure DB or DB+hashmap access .
module Pos.Delegation.Cede.Holders
( DBCede
, runDBCede
, MapCede
, runMapCede
, evalMapCede
) where
import Universum
import Control.Lens (at, (%=))
import Control.Monad.Trans.Identity (IdentityT (..))
import Data.Coerce (coerce)
import qualified Data.HashMap.Strict as HM
import Data.HashSet as HS
import qualified Ether
import Pos.DB.Class (MonadDBRead)
import Pos.Delegation.Cede.Class (MonadCede (..), MonadCedeRead (..))
import Pos.Delegation.Cede.Types (CedeModifier, DlgEdgeAction (..), cmHasPostedThisEpoch,
cmPskMods, dlgEdgeActionIssuer)
import qualified Pos.Delegation.DB as DB
import Pos.Util.Util (ether)
----------------------------------------------------------------------------
-- Pure database-only holder
----------------------------------------------------------------------------
data DBCedeTag
type DBCede = Ether.TaggedTrans DBCedeTag IdentityT
runDBCede :: DBCede m a -> m a
runDBCede = coerce
instance MonadDBRead m => MonadCedeRead (DBCede m) where
getPsk = DB.getPskByIssuer . Right
hasPostedThisEpoch = DB.isIssuerPostedThisEpoch
getAllPostedThisEpoch = DB.getThisEpochPostedKeys
We do n't provide ' MonadCede ' instance as writing into database is
-- performed in batches on block application only.
----------------------------------------------------------------------------
DB + CedeModifier resolving
----------------------------------------------------------------------------
-- | Monad transformer that holds extra layer of modifications to the
underlying set of PSKs ( which can be empty if you want ) .
type MapCede = Ether.LazyStateT' CedeModifier
runMapCede :: CedeModifier -> MapCede m a -> m (a, CedeModifier)
runMapCede = flip Ether.runLazyStateT
evalMapCede :: Monad m => CedeModifier -> MapCede m a -> m a
evalMapCede = flip Ether.evalLazyStateT
instance MonadDBRead m => MonadCedeRead (MapCede m) where
getPsk iPk =
ether $ use (cmPskMods . at iPk) >>= \case
Nothing -> lift $ DB.getPskByIssuer $ Right iPk
Just (DlgEdgeDel _) -> pure Nothing
Just (DlgEdgeAdd psk ) -> pure (Just psk)
hasPostedThisEpoch sId =
ether $ use (cmHasPostedThisEpoch . at sId) >>= \case
Nothing -> lift $ DB.isIssuerPostedThisEpoch sId
Just v -> pure v
getAllPostedThisEpoch = ether $ do
allPostedDb <- lift DB.getThisEpochPostedKeys
mods <- use cmHasPostedThisEpoch
pure $ HM.foldlWithKey'
(\hs k v -> (if v then HS.insert else HS.delete) k hs)
allPostedDb
mods
instance MonadDBRead m => MonadCede (MapCede m) where
modPsk eAction = do
let issuer = dlgEdgeActionIssuer eAction
ether $ cmPskMods %= HM.insert issuer eAction
addThisEpochPosted sId = ether $ cmHasPostedThisEpoch %= HM.insert sId True
delThisEpochPosted sId = ether $ cmHasPostedThisEpoch %= HM.insert sId False
| null | https://raw.githubusercontent.com/CryptoKami/cryptokami-core/12ca60a9ad167b6327397b3b2f928c19436ae114/delegation/src/Pos/Delegation/Cede/Holders.hs | haskell | --------------------------------------------------------------------------
Pure database-only holder
--------------------------------------------------------------------------
performed in batches on block application only.
--------------------------------------------------------------------------
--------------------------------------------------------------------------
| Monad transformer that holds extra layer of modifications to the | | This module provides implementations of " MonadCede " based on
either pure DB or DB+hashmap access .
module Pos.Delegation.Cede.Holders
( DBCede
, runDBCede
, MapCede
, runMapCede
, evalMapCede
) where
import Universum
import Control.Lens (at, (%=))
import Control.Monad.Trans.Identity (IdentityT (..))
import Data.Coerce (coerce)
import qualified Data.HashMap.Strict as HM
import Data.HashSet as HS
import qualified Ether
import Pos.DB.Class (MonadDBRead)
import Pos.Delegation.Cede.Class (MonadCede (..), MonadCedeRead (..))
import Pos.Delegation.Cede.Types (CedeModifier, DlgEdgeAction (..), cmHasPostedThisEpoch,
cmPskMods, dlgEdgeActionIssuer)
import qualified Pos.Delegation.DB as DB
import Pos.Util.Util (ether)
data DBCedeTag
type DBCede = Ether.TaggedTrans DBCedeTag IdentityT
runDBCede :: DBCede m a -> m a
runDBCede = coerce
instance MonadDBRead m => MonadCedeRead (DBCede m) where
getPsk = DB.getPskByIssuer . Right
hasPostedThisEpoch = DB.isIssuerPostedThisEpoch
getAllPostedThisEpoch = DB.getThisEpochPostedKeys
We do n't provide ' MonadCede ' instance as writing into database is
DB + CedeModifier resolving
underlying set of PSKs ( which can be empty if you want ) .
type MapCede = Ether.LazyStateT' CedeModifier
runMapCede :: CedeModifier -> MapCede m a -> m (a, CedeModifier)
runMapCede = flip Ether.runLazyStateT
evalMapCede :: Monad m => CedeModifier -> MapCede m a -> m a
evalMapCede = flip Ether.evalLazyStateT
instance MonadDBRead m => MonadCedeRead (MapCede m) where
getPsk iPk =
ether $ use (cmPskMods . at iPk) >>= \case
Nothing -> lift $ DB.getPskByIssuer $ Right iPk
Just (DlgEdgeDel _) -> pure Nothing
Just (DlgEdgeAdd psk ) -> pure (Just psk)
hasPostedThisEpoch sId =
ether $ use (cmHasPostedThisEpoch . at sId) >>= \case
Nothing -> lift $ DB.isIssuerPostedThisEpoch sId
Just v -> pure v
getAllPostedThisEpoch = ether $ do
allPostedDb <- lift DB.getThisEpochPostedKeys
mods <- use cmHasPostedThisEpoch
pure $ HM.foldlWithKey'
(\hs k v -> (if v then HS.insert else HS.delete) k hs)
allPostedDb
mods
instance MonadDBRead m => MonadCede (MapCede m) where
modPsk eAction = do
let issuer = dlgEdgeActionIssuer eAction
ether $ cmPskMods %= HM.insert issuer eAction
addThisEpochPosted sId = ether $ cmHasPostedThisEpoch %= HM.insert sId True
delThisEpochPosted sId = ether $ cmHasPostedThisEpoch %= HM.insert sId False
|
4eb0e61b9777dc371f95dea78eea52315e70096798c40f874c381926b35f95bf | NelosG/fp-tests | Spec.hs | # LANGUAGE TemplateHaskell , NegativeLiterals , BlockArguments ,
StandaloneKindSignatures , ConstraintKinds , GeneralizedNewtypeDeriving ,
DerivingStrategies , FlexibleInstances #
StandaloneKindSignatures, ConstraintKinds, GeneralizedNewtypeDeriving,
DerivingStrategies, FlexibleInstances #-}
import Control.Monad (unless, guard)
import System.Exit (exitFailure)
import Text.Megaparsec (ParseErrorBundle)
import qualified Test.QuickCheck as QC
import qualified Data.Text as Text
import qualified Data.Text.Encoding as Text
import Data.Text (Text)
import Data.Void (Void)
import Data.ByteString (ByteString)
import qualified Data.ByteString as BS
import qualified Data.Sequence as Seq
import Data.Kind (Type, Constraint)
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Functor.Classes (Eq1(liftEq))
import Control.Monad.Trans.State
import Control.Monad.Trans.Maybe
import Data.Maybe (isJust)
import System.Directory (removePathForcibly)
import Control.Exception (catch)
---------------------------
------ NAME CHECKING ------
---------------------------
import HW3.Base (
HiFun (
HiFunDiv,
HiFunMul,
HiFunAdd,
HiFunSub,
HiFunNot,
HiFunAnd,
HiFunOr,
HiFunLessThan,
HiFunGreaterThan,
HiFunEquals,
HiFunNotLessThan,
HiFunNotGreaterThan,
HiFunNotEquals,
HiFunIf,
HiFunLength,
HiFunToUpper,
HiFunToLower,
HiFunReverse,
HiFunTrim,
HiFunList,
HiFunRange,
HiFunFold,
HiFunPackBytes,
HiFunUnpackBytes,
HiFunEncodeUtf8,
HiFunDecodeUtf8,
HiFunZip,
HiFunUnzip,
HiFunSerialise,
HiFunDeserialise,
---------
HiFunEcho
))
import HW3.Base (HiAction (HiActionEcho))
import HW3.Base (HiValue(HiValueNumber, HiValueFunction, HiValueBool, HiValueNull, HiValueString, HiValueList, HiValueBytes, HiValueAction))
import HW3.Base (HiExpr(HiExprValue, HiExprApply, HiExprRun))
import HW3.Base (HiError(HiErrorInvalidArgument, HiErrorInvalidFunction, HiErrorArityMismatch, HiErrorDivideByZero))
import HW3.Base (HiMonad(runAction))
import HW3.Action (HiPermission(AllowRead, AllowWrite))
import HW3.Action (PermissionException(PermissionRequired))
import HW3.Action (HIO(HIO, runHIO))
import HW3.Parser (parse)
import HW3.Evaluator (eval)
import HW3.Pretty (prettyValue)
---------------------------
------ TYPE CHECKING ------
---------------------------
hiActionEcho' :: Text -> HiAction
hiActionEcho' = HiActionEcho
type HiMonad' :: (Type -> Type) -> Constraint
type HiMonad' = HiMonad
runAction' :: HiMonad m => HiAction -> m HiValue
runAction' = runAction
type HiPermission' :: Type
type HiPermission' = HiPermission
_AllowRead' :: HiPermission
_AllowRead' = AllowRead
_AllowWrite' :: HiPermission
_AllowWrite' = AllowWrite
type PermissionException' :: Type
type PermissionException' = PermissionException
_PermissionRequired' :: HiPermission -> PermissionException
_PermissionRequired' = PermissionRequired
type HIO' :: Type -> Type
type HIO' = HIO
_HIO' :: (Set HiPermission -> IO a) -> HIO a
_HIO' = HIO
runHIO' :: HIO a -> Set HiPermission -> IO a
runHIO' = runHIO
hiFunEcho' :: HiFun
hiFunEcho' = HiFunEcho
hiValueAction' :: HiAction -> HiValue
hiValueAction' = HiValueAction
hiExprRun' :: HiExpr -> HiExpr
hiExprRun' = HiExprRun
eval' :: HiMonad m => HiExpr -> m (Either HiError HiValue)
eval' = eval
parse' :: String -> Either (ParseErrorBundle String Void) HiExpr
parse' = parse
---------------------------
------ PROP CHECKING ------
---------------------------
prop_basic_parse_cases :: Bool
prop_basic_parse_cases =
"echo" `parses_to` HiExprValue (HiValueFunction HiFunEcho) &&
"echo(\"message\")!" `parses_to` HiExprRun (applyFn1 HiFunEcho (HiExprValue (HiValueString (Text.pack "message"))))
prop_basic_eval_cases :: Bool
prop_basic_eval_cases =
"echo(\"message\")" `evaluates_to` (HiValueAction (HiActionEcho (Text.pack "message")), []) &&
"echo(\"message\")!" `evaluates_to` (HiValueNull, [Text.pack "message"]) &&
"\"Hello\"(0) || \"Z\"" `evaluates_to` (HiValueString (Text.pack "H"), []) &&
"\"Hello\"(99) || \"Z\"" `evaluates_to` (HiValueString (Text.pack "Z"), []) &&
"if(2 == 2, echo(\"OK\")!, echo(\"WTF\")!)" `evaluates_to` (HiValueNull, [Text.pack "OK"]) &&
"true || echo(\"Don't do this\")!" `evaluates_to` (HiValueBool True, []) &&
"false && echo(\"Don't do this\")!" `evaluates_to` (HiValueBool False, []) &&
"[# 00 ff #] && echo(\"Just do it\")!" `evaluates_to` (HiValueNull, [Text.pack "Just do it"])
prop_eval_div_by_zero :: Bool
prop_eval_div_by_zero =
"if(true, 1, 0/0)" `evaluates_to` (HiValueNumber 1, []) &&
"if(false, 1, 0/0)" `evaluates_to_err` HiErrorDivideByZero
applyFn1 :: HiFun -> HiExpr -> HiExpr
applyFn1 fn arg = HiExprApply (HiExprValue (HiValueFunction fn)) [arg]
parses_to :: String -> HiExpr -> Bool
parses_to str expected =
case parse str of
Left _ -> False
Right e -> eqExpr e expected
newtype EchoLog a = EchoLog (State [Text] a)
deriving newtype (Functor, Applicative, Monad)
runEchoLog :: EchoLog a -> (a, [Text])
runEchoLog (EchoLog m) =
let (a, msgs) = runState m [] in (a, reverse msgs)
instance HiMonad EchoLog where
runAction act =
EchoLog $ case act of
HiActionEcho msg -> do
modify (msg:)
return HiValueNull
_ -> error "EchoLog: unsupported action"
evaluates_to :: String -> (HiValue, [Text]) -> Bool
evaluates_to str (expected_v, expected_msglog) =
case parse str of
Left _ -> False
Right e ->
case runEchoLog (eval e) of
(Left _, _) -> False
(Right v, msglog) ->
eqValue v expected_v &&
msglog == expected_msglog
evaluates_to_err :: String -> HiError -> Bool
evaluates_to_err str expected =
case parse str of
Left _ -> False
Right e ->
case runEchoLog (eval e) of
(Right _, _) -> False
(Left err, _) -> eqError err expected
eqResult :: Either HiError HiValue -> Either HiError HiValue -> Bool
eqResult (Left err1) (Left err2) = eqError err1 err2
eqResult (Right v1) (Right v2) = eqValue v1 v2
eqResult _ _ = False
eqError :: HiError -> HiError -> Bool
eqError HiErrorInvalidArgument HiErrorInvalidArgument = True
eqError HiErrorInvalidFunction HiErrorInvalidFunction = True
eqError HiErrorArityMismatch HiErrorArityMismatch = True
eqError HiErrorDivideByZero HiErrorDivideByZero = True
eqError _ _ = False
eqFn :: HiFun -> HiFun -> Bool
eqFn HiFunDiv HiFunDiv = True
eqFn HiFunMul HiFunMul = True
eqFn HiFunAdd HiFunAdd = True
eqFn HiFunSub HiFunSub = True
eqFn HiFunNot HiFunNot = True
eqFn HiFunAnd HiFunAnd = True
eqFn HiFunOr HiFunOr = True
eqFn HiFunLessThan HiFunLessThan = True
eqFn HiFunGreaterThan HiFunGreaterThan = True
eqFn HiFunEquals HiFunEquals = True
eqFn HiFunNotLessThan HiFunNotLessThan = True
eqFn HiFunNotGreaterThan HiFunNotGreaterThan = True
eqFn HiFunNotEquals HiFunNotEquals = True
eqFn HiFunIf HiFunIf = True
eqFn HiFunLength HiFunLength = True
eqFn HiFunToUpper HiFunToUpper = True
eqFn HiFunToLower HiFunToLower = True
eqFn HiFunReverse HiFunReverse = True
eqFn HiFunTrim HiFunTrim = True
eqFn HiFunList HiFunList = True
eqFn HiFunRange HiFunRange = True
eqFn HiFunFold HiFunFold = True
eqFn HiFunPackBytes HiFunPackBytes = True
eqFn HiFunUnpackBytes HiFunUnpackBytes = True
eqFn HiFunEncodeUtf8 HiFunEncodeUtf8 = True
eqFn HiFunDecodeUtf8 HiFunDecodeUtf8 = True
eqFn HiFunZip HiFunZip = True
eqFn HiFunUnzip HiFunUnzip = True
eqFn HiFunSerialise HiFunSerialise = True
eqFn HiFunDeserialise HiFunDeserialise = True
eqFn HiFunEcho HiFunEcho = True
eqFn _ _ = False
eqAction :: HiAction -> HiAction -> Bool
eqAction (HiActionEcho msg1) (HiActionEcho msg2) = msg1 == msg2
eqAction _ _ = False
eqValue :: HiValue -> HiValue -> Bool
eqValue (HiValueNumber x1) (HiValueNumber x2) = x1 == x2
eqValue (HiValueFunction fn1) (HiValueFunction fn2) = eqFn fn1 fn2
eqValue (HiValueBool b1) (HiValueBool b2) = b1 == b2
eqValue (HiValueString s1) (HiValueString s2) = s1 == s2
eqValue (HiValueList xs1) (HiValueList xs2) = xs1 == xs2
eqValue (HiValueBytes bs1) (HiValueBytes bs2) = bs1 == bs2
eqValue HiValueNull HiValueNull = True
eqValue (HiValueAction act1) (HiValueAction act2) = eqAction act1 act2
eqValue _ _ = False
eqExpr :: HiExpr -> HiExpr -> Bool
eqExpr (HiExprApply fn1 args1) (HiExprApply fn2 args2) =
eqExpr fn1 fn2 && liftEq eqExpr args1 args2
eqExpr (HiExprValue v1) (HiExprValue v2) =
eqValue v1 v2
eqExpr (HiExprRun e1) (HiExprRun e2) =
eqExpr e1 e2
eqExpr _ _ = False
return []
main :: IO ()
main = do
ok <- $(QC.quickCheckAll)
unless ok exitFailure
| null | https://raw.githubusercontent.com/NelosG/fp-tests/2997fc0d4cf08fa17dffa00242369ac039e709aa/hw3/baseTests/T10/Spec.hs | haskell | -------------------------
---- NAME CHECKING ------
-------------------------
-------
-------------------------
---- TYPE CHECKING ------
-------------------------
-------------------------
---- PROP CHECKING ------
------------------------- | # LANGUAGE TemplateHaskell , NegativeLiterals , BlockArguments ,
StandaloneKindSignatures , ConstraintKinds , GeneralizedNewtypeDeriving ,
DerivingStrategies , FlexibleInstances #
StandaloneKindSignatures, ConstraintKinds, GeneralizedNewtypeDeriving,
DerivingStrategies, FlexibleInstances #-}
import Control.Monad (unless, guard)
import System.Exit (exitFailure)
import Text.Megaparsec (ParseErrorBundle)
import qualified Test.QuickCheck as QC
import qualified Data.Text as Text
import qualified Data.Text.Encoding as Text
import Data.Text (Text)
import Data.Void (Void)
import Data.ByteString (ByteString)
import qualified Data.ByteString as BS
import qualified Data.Sequence as Seq
import Data.Kind (Type, Constraint)
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Functor.Classes (Eq1(liftEq))
import Control.Monad.Trans.State
import Control.Monad.Trans.Maybe
import Data.Maybe (isJust)
import System.Directory (removePathForcibly)
import Control.Exception (catch)
import HW3.Base (
HiFun (
HiFunDiv,
HiFunMul,
HiFunAdd,
HiFunSub,
HiFunNot,
HiFunAnd,
HiFunOr,
HiFunLessThan,
HiFunGreaterThan,
HiFunEquals,
HiFunNotLessThan,
HiFunNotGreaterThan,
HiFunNotEquals,
HiFunIf,
HiFunLength,
HiFunToUpper,
HiFunToLower,
HiFunReverse,
HiFunTrim,
HiFunList,
HiFunRange,
HiFunFold,
HiFunPackBytes,
HiFunUnpackBytes,
HiFunEncodeUtf8,
HiFunDecodeUtf8,
HiFunZip,
HiFunUnzip,
HiFunSerialise,
HiFunDeserialise,
HiFunEcho
))
import HW3.Base (HiAction (HiActionEcho))
import HW3.Base (HiValue(HiValueNumber, HiValueFunction, HiValueBool, HiValueNull, HiValueString, HiValueList, HiValueBytes, HiValueAction))
import HW3.Base (HiExpr(HiExprValue, HiExprApply, HiExprRun))
import HW3.Base (HiError(HiErrorInvalidArgument, HiErrorInvalidFunction, HiErrorArityMismatch, HiErrorDivideByZero))
import HW3.Base (HiMonad(runAction))
import HW3.Action (HiPermission(AllowRead, AllowWrite))
import HW3.Action (PermissionException(PermissionRequired))
import HW3.Action (HIO(HIO, runHIO))
import HW3.Parser (parse)
import HW3.Evaluator (eval)
import HW3.Pretty (prettyValue)
hiActionEcho' :: Text -> HiAction
hiActionEcho' = HiActionEcho
type HiMonad' :: (Type -> Type) -> Constraint
type HiMonad' = HiMonad
runAction' :: HiMonad m => HiAction -> m HiValue
runAction' = runAction
type HiPermission' :: Type
type HiPermission' = HiPermission
_AllowRead' :: HiPermission
_AllowRead' = AllowRead
_AllowWrite' :: HiPermission
_AllowWrite' = AllowWrite
type PermissionException' :: Type
type PermissionException' = PermissionException
_PermissionRequired' :: HiPermission -> PermissionException
_PermissionRequired' = PermissionRequired
type HIO' :: Type -> Type
type HIO' = HIO
_HIO' :: (Set HiPermission -> IO a) -> HIO a
_HIO' = HIO
runHIO' :: HIO a -> Set HiPermission -> IO a
runHIO' = runHIO
hiFunEcho' :: HiFun
hiFunEcho' = HiFunEcho
hiValueAction' :: HiAction -> HiValue
hiValueAction' = HiValueAction
hiExprRun' :: HiExpr -> HiExpr
hiExprRun' = HiExprRun
eval' :: HiMonad m => HiExpr -> m (Either HiError HiValue)
eval' = eval
parse' :: String -> Either (ParseErrorBundle String Void) HiExpr
parse' = parse
prop_basic_parse_cases :: Bool
prop_basic_parse_cases =
"echo" `parses_to` HiExprValue (HiValueFunction HiFunEcho) &&
"echo(\"message\")!" `parses_to` HiExprRun (applyFn1 HiFunEcho (HiExprValue (HiValueString (Text.pack "message"))))
prop_basic_eval_cases :: Bool
prop_basic_eval_cases =
"echo(\"message\")" `evaluates_to` (HiValueAction (HiActionEcho (Text.pack "message")), []) &&
"echo(\"message\")!" `evaluates_to` (HiValueNull, [Text.pack "message"]) &&
"\"Hello\"(0) || \"Z\"" `evaluates_to` (HiValueString (Text.pack "H"), []) &&
"\"Hello\"(99) || \"Z\"" `evaluates_to` (HiValueString (Text.pack "Z"), []) &&
"if(2 == 2, echo(\"OK\")!, echo(\"WTF\")!)" `evaluates_to` (HiValueNull, [Text.pack "OK"]) &&
"true || echo(\"Don't do this\")!" `evaluates_to` (HiValueBool True, []) &&
"false && echo(\"Don't do this\")!" `evaluates_to` (HiValueBool False, []) &&
"[# 00 ff #] && echo(\"Just do it\")!" `evaluates_to` (HiValueNull, [Text.pack "Just do it"])
prop_eval_div_by_zero :: Bool
prop_eval_div_by_zero =
"if(true, 1, 0/0)" `evaluates_to` (HiValueNumber 1, []) &&
"if(false, 1, 0/0)" `evaluates_to_err` HiErrorDivideByZero
applyFn1 :: HiFun -> HiExpr -> HiExpr
applyFn1 fn arg = HiExprApply (HiExprValue (HiValueFunction fn)) [arg]
parses_to :: String -> HiExpr -> Bool
parses_to str expected =
case parse str of
Left _ -> False
Right e -> eqExpr e expected
newtype EchoLog a = EchoLog (State [Text] a)
deriving newtype (Functor, Applicative, Monad)
runEchoLog :: EchoLog a -> (a, [Text])
runEchoLog (EchoLog m) =
let (a, msgs) = runState m [] in (a, reverse msgs)
instance HiMonad EchoLog where
runAction act =
EchoLog $ case act of
HiActionEcho msg -> do
modify (msg:)
return HiValueNull
_ -> error "EchoLog: unsupported action"
evaluates_to :: String -> (HiValue, [Text]) -> Bool
evaluates_to str (expected_v, expected_msglog) =
case parse str of
Left _ -> False
Right e ->
case runEchoLog (eval e) of
(Left _, _) -> False
(Right v, msglog) ->
eqValue v expected_v &&
msglog == expected_msglog
evaluates_to_err :: String -> HiError -> Bool
evaluates_to_err str expected =
case parse str of
Left _ -> False
Right e ->
case runEchoLog (eval e) of
(Right _, _) -> False
(Left err, _) -> eqError err expected
eqResult :: Either HiError HiValue -> Either HiError HiValue -> Bool
eqResult (Left err1) (Left err2) = eqError err1 err2
eqResult (Right v1) (Right v2) = eqValue v1 v2
eqResult _ _ = False
eqError :: HiError -> HiError -> Bool
eqError HiErrorInvalidArgument HiErrorInvalidArgument = True
eqError HiErrorInvalidFunction HiErrorInvalidFunction = True
eqError HiErrorArityMismatch HiErrorArityMismatch = True
eqError HiErrorDivideByZero HiErrorDivideByZero = True
eqError _ _ = False
eqFn :: HiFun -> HiFun -> Bool
eqFn HiFunDiv HiFunDiv = True
eqFn HiFunMul HiFunMul = True
eqFn HiFunAdd HiFunAdd = True
eqFn HiFunSub HiFunSub = True
eqFn HiFunNot HiFunNot = True
eqFn HiFunAnd HiFunAnd = True
eqFn HiFunOr HiFunOr = True
eqFn HiFunLessThan HiFunLessThan = True
eqFn HiFunGreaterThan HiFunGreaterThan = True
eqFn HiFunEquals HiFunEquals = True
eqFn HiFunNotLessThan HiFunNotLessThan = True
eqFn HiFunNotGreaterThan HiFunNotGreaterThan = True
eqFn HiFunNotEquals HiFunNotEquals = True
eqFn HiFunIf HiFunIf = True
eqFn HiFunLength HiFunLength = True
eqFn HiFunToUpper HiFunToUpper = True
eqFn HiFunToLower HiFunToLower = True
eqFn HiFunReverse HiFunReverse = True
eqFn HiFunTrim HiFunTrim = True
eqFn HiFunList HiFunList = True
eqFn HiFunRange HiFunRange = True
eqFn HiFunFold HiFunFold = True
eqFn HiFunPackBytes HiFunPackBytes = True
eqFn HiFunUnpackBytes HiFunUnpackBytes = True
eqFn HiFunEncodeUtf8 HiFunEncodeUtf8 = True
eqFn HiFunDecodeUtf8 HiFunDecodeUtf8 = True
eqFn HiFunZip HiFunZip = True
eqFn HiFunUnzip HiFunUnzip = True
eqFn HiFunSerialise HiFunSerialise = True
eqFn HiFunDeserialise HiFunDeserialise = True
eqFn HiFunEcho HiFunEcho = True
eqFn _ _ = False
eqAction :: HiAction -> HiAction -> Bool
eqAction (HiActionEcho msg1) (HiActionEcho msg2) = msg1 == msg2
eqAction _ _ = False
eqValue :: HiValue -> HiValue -> Bool
eqValue (HiValueNumber x1) (HiValueNumber x2) = x1 == x2
eqValue (HiValueFunction fn1) (HiValueFunction fn2) = eqFn fn1 fn2
eqValue (HiValueBool b1) (HiValueBool b2) = b1 == b2
eqValue (HiValueString s1) (HiValueString s2) = s1 == s2
eqValue (HiValueList xs1) (HiValueList xs2) = xs1 == xs2
eqValue (HiValueBytes bs1) (HiValueBytes bs2) = bs1 == bs2
eqValue HiValueNull HiValueNull = True
eqValue (HiValueAction act1) (HiValueAction act2) = eqAction act1 act2
eqValue _ _ = False
eqExpr :: HiExpr -> HiExpr -> Bool
eqExpr (HiExprApply fn1 args1) (HiExprApply fn2 args2) =
eqExpr fn1 fn2 && liftEq eqExpr args1 args2
eqExpr (HiExprValue v1) (HiExprValue v2) =
eqValue v1 v2
eqExpr (HiExprRun e1) (HiExprRun e2) =
eqExpr e1 e2
eqExpr _ _ = False
return []
main :: IO ()
main = do
ok <- $(QC.quickCheckAll)
unless ok exitFailure
|
322d1230a3227f11c80dd42f193398481ccb18b4c9913cc22bc7ad68a37c5bf7 | bjornbm/astro | At.hs | module Astro.Time.At where
import Control.Applicative
import Data.Foldable
import Data.Traversable
import Astro.Time (E)
-- | Data type tagging some value x with a specific time. Typically
use is @x ` At ` t@.
Isomorphic to @(E t a , x)@ ( also true for the ' Functor ' instance ) .
data At t a x = At { value :: x
, epoch :: !(E t a)
} deriving (Show, Eq)
instance (Ord a, Ord x) => Ord (At t a x) where
Order by time first , value second .
compare (x1`At`t1) (x2`At`t2) = case compare t1 t2 of EQ -> compare x1 x2
o -> o
instance Functor (At t a) where fmap f (x `At` t) = f x `At` t
instance Foldable (At t a) where
foldMap f (x `At` _) = f x
instance Traversable (At t a) where
traverse f (x `At` t) = (`At` t) <$> f x
-- | A flipped 'At', in other words @t `tA` x == x `At` t@.
tA :: E t a -> x -> At t a x
tA = flip At
| Convert the tuple ( t , x ) into @x ` At ` t@.
asAt :: (E t a, x) -> At t a x
asAt (t, x) = x `At` t
-- | Convert @x `At` t@ into the tuple (t, x).
unAt :: At t a x -> (E t a, x)
unAt (x `At` t) = (t, x)
-- | Kind of like an epoch-dependent 'fmap'.
appAt :: (At t a x -> y) -> At t a x -> At t a y
appAt f at = at { value = f at }
-- | Maps 'appAt f'.
mapAt :: (At t a x -> y) -> [At t a x] -> [At t a y]
mapAt f = map (appAt f)
| \"Zips\ " two time series with matching times . The time series should be
-- ordered. Values that do not match up (in time) with a value in the other
-- series are dropped.
zipAt :: Ord a => [At t a x] -> [At t a y] -> [At t a (x,y)]
zipAt = zipAtWith (,)
-- | Applies a binary function to the values in both series, returning a
-- single series with the results. The time series should be ordered. Values
-- that do not match up (in time) with a value in the other series are
-- dropped.
zipAtWith :: Ord a => (x -> y -> z) -> [At t a x] -> [At t a y] -> [At t a z]
zipAtWith f (x`At`t:txs) (y`At`t':tys) = case t `compare` t' of
LT -> zipAtWith f txs (y`At`t':tys)
EQ -> (f x y `At` t : zipAtWith f txs tys)
GT -> zipAtWith f (x`At`t:txs) tys
zipAtWith _ _ _ = []
| null | https://raw.githubusercontent.com/bjornbm/astro/f4fb2c4b739a0a8f68f51aa154285120d2230c30/src/Astro/Time/At.hs | haskell | | Data type tagging some value x with a specific time. Typically
| A flipped 'At', in other words @t `tA` x == x `At` t@.
| Convert @x `At` t@ into the tuple (t, x).
| Kind of like an epoch-dependent 'fmap'.
| Maps 'appAt f'.
ordered. Values that do not match up (in time) with a value in the other
series are dropped.
| Applies a binary function to the values in both series, returning a
single series with the results. The time series should be ordered. Values
that do not match up (in time) with a value in the other series are
dropped. | module Astro.Time.At where
import Control.Applicative
import Data.Foldable
import Data.Traversable
import Astro.Time (E)
use is @x ` At ` t@.
Isomorphic to @(E t a , x)@ ( also true for the ' Functor ' instance ) .
data At t a x = At { value :: x
, epoch :: !(E t a)
} deriving (Show, Eq)
instance (Ord a, Ord x) => Ord (At t a x) where
Order by time first , value second .
compare (x1`At`t1) (x2`At`t2) = case compare t1 t2 of EQ -> compare x1 x2
o -> o
instance Functor (At t a) where fmap f (x `At` t) = f x `At` t
instance Foldable (At t a) where
foldMap f (x `At` _) = f x
instance Traversable (At t a) where
traverse f (x `At` t) = (`At` t) <$> f x
tA :: E t a -> x -> At t a x
tA = flip At
| Convert the tuple ( t , x ) into @x ` At ` t@.
asAt :: (E t a, x) -> At t a x
asAt (t, x) = x `At` t
unAt :: At t a x -> (E t a, x)
unAt (x `At` t) = (t, x)
appAt :: (At t a x -> y) -> At t a x -> At t a y
appAt f at = at { value = f at }
mapAt :: (At t a x -> y) -> [At t a x] -> [At t a y]
mapAt f = map (appAt f)
| \"Zips\ " two time series with matching times . The time series should be
zipAt :: Ord a => [At t a x] -> [At t a y] -> [At t a (x,y)]
zipAt = zipAtWith (,)
zipAtWith :: Ord a => (x -> y -> z) -> [At t a x] -> [At t a y] -> [At t a z]
zipAtWith f (x`At`t:txs) (y`At`t':tys) = case t `compare` t' of
LT -> zipAtWith f txs (y`At`t':tys)
EQ -> (f x y `At` t : zipAtWith f txs tys)
GT -> zipAtWith f (x`At`t:txs) tys
zipAtWith _ _ _ = []
|
e91e3206068a49e56163e5f45804c1f3777019a79baf39329671a05dabcdfa46 | broom-lang/broom | Ast.mli | type 'a with_pos = 'a Util.with_pos
module Primop : AstSigs.PRIMOP
module rec Expr : (AstSigs.EXPR
with type primop = Primop.t
with type stmt = Stmt.t
with type decl = Decl.t)
and Stmt : (AstSigs.STMT
with type expr = Expr.t)
and Decl : (AstSigs.DECL
with type expr = Expr.t)
module Program : AstSigs.PROGRAM
with module Stmt = Stmt
with module Expr = Expr
| null | https://raw.githubusercontent.com/broom-lang/broom/a355c229575bccc853b9acb98437b0b767221971/compiler/lib/Ast/Ast.mli | ocaml | type 'a with_pos = 'a Util.with_pos
module Primop : AstSigs.PRIMOP
module rec Expr : (AstSigs.EXPR
with type primop = Primop.t
with type stmt = Stmt.t
with type decl = Decl.t)
and Stmt : (AstSigs.STMT
with type expr = Expr.t)
and Decl : (AstSigs.DECL
with type expr = Expr.t)
module Program : AstSigs.PROGRAM
with module Stmt = Stmt
with module Expr = Expr
|
|
ecf0f564882ff64e6bcdf7ea44890b38d0140bf84a88322c5ce42bc45b10f218 | ml4tp/tcoq | hook.ml | (************************************************************************)
v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2017
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(************************************************************************)
type 'a content =
| Unset
| Default of 'a
| Set of 'a
type 'a t = 'a content ref
type 'a value = 'a t
let get (hook : 'a value) = match !hook with
| Unset -> assert false
| Default data | Set data -> data
let set (hook : 'a t) data = match !hook with
| Unset | Default _ -> hook := Set data
| Set _ -> assert false
let make ?default () =
let data = match default with
| None -> Unset
| Some data -> Default data
in
let ans = ref data in
(ans, ans)
| null | https://raw.githubusercontent.com/ml4tp/tcoq/7a78c31df480fba721648f277ab0783229c8bece/lib/hook.ml | ocaml | **********************************************************************
// * This file is distributed under the terms of the
* GNU Lesser General Public License Version 2.1
********************************************************************** | v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2017
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
type 'a content =
| Unset
| Default of 'a
| Set of 'a
type 'a t = 'a content ref
type 'a value = 'a t
let get (hook : 'a value) = match !hook with
| Unset -> assert false
| Default data | Set data -> data
let set (hook : 'a t) data = match !hook with
| Unset | Default _ -> hook := Set data
| Set _ -> assert false
let make ?default () =
let data = match default with
| None -> Unset
| Some data -> Default data
in
let ans = ref data in
(ans, ans)
|
35cf3a0b91b4414ece625ca80301b80b58db2fd7878850ea8ba890bb3bc89a2d | monadbobo/ocaml-core | service_command.ml | open Core.Std
let command ~lock_file ~name main =
let start_main () =
let release_parent = Daemon.daemonize_wait () in
(* lock file created after [daemonize_wait] so that *child* pid is written
to the lock file rather than the parent pid *)
if Lock_file.create ~close_on_exec:true ~unlink_on_exit:true lock_file
(* this writes our pid in the file *) then begin
(* we release the daemon's parent *after* the lock file is created
so that any error messages during lock file creation happen
prior to severing the daemon's connection to std{out,err} *)
release_parent ();
main ()
end;
0
in
let check_lock_file () =
if Lock_file.is_locked lock_file then begin
let pid = Pid.t_of_sexp (Sexp.load_sexp lock_file) in
`Running_with_pid pid
end else
`Not_running
in
let still_alive pid =
(* receiving [Signal.zero] is a no-op, but sending it gives info
about whether there a running process with that pid *)
match Signal.send Signal.zero (`Pid pid) with
| `Ok -> true
| `No_such_process -> false
in
let status_main () =
begin match check_lock_file () with
| `Not_running -> printf "%s is not running\n%!" name
| `Running_with_pid pid ->
if still_alive pid then
printf "%s is running with pid %s\n%!" name (Pid.to_string pid)
else
printf "%s is not running, even though we saw pid %s in its lockfile\n%!"
name (Pid.to_string pid)
end;
0
in
let stop_aux ~stop_signal =
let was_not_running () =
eprintf "%s was not running\n%!" name;
`Was_not_running
in
match check_lock_file () with
| `Not_running -> was_not_running ()
| `Running_with_pid pid ->
let timeout_span = sec 10. in
let deadline = Time.add (Time.now ()) timeout_span in
match Signal.send stop_signal (`Pid pid) with
| `No_such_process -> was_not_running ()
| `Ok ->
let rec wait_loop () =
if Time.(>=) (Time.now ()) deadline then begin
eprintf "failed to observe %s die after %s\n%!" name
(Time.Span.to_string timeout_span);
`Did_not_die
end else if still_alive pid then begin
Time.pause (sec 0.2);
wait_loop ()
end else
`Died
in
wait_loop ()
in
let stop_main ~stop_signal =
match stop_aux ~stop_signal with
| `Was_not_running | `Did_not_die -> 1
| `Died -> 0
in
let restart_main ~stop_signal =
match stop_aux ~stop_signal with
| `Did_not_die -> 1
| `Was_not_running | `Died -> start_main ()
in
let summary ~verb = sprintf "%s %s" verb name in
let assert_no_anons anons =
match anons with
| [] -> ()
| anons ->
failwithf "expected 0 anonymous arguments but found %d\n%!"
(List.length anons) ()
in
let base_cmd ~verb main =
Command.create (fun () -> exit (main ()))
~summary:(summary ~verb)
~usage_arg:""
~init:Fn.id
~flags:[]
~final:(fun () anons -> assert_no_anons anons)
in
let stop_cmd ~verb main =
Command.create (fun stop_signal -> exit (main ~stop_signal))
~summary:(summary ~verb)
~usage_arg:"[-kill]"
~init:(Fn.const Signal.term)
~flags:[
Command.Flag.noarg_acc "-kill" (Fn.const Signal.kill)
~doc:" send SIGKILL instead of SIGTERM"
]
~final:(fun signal anons -> assert_no_anons anons; signal)
in
Command.group ~summary:(summary ~verb:"manage") [
("start", base_cmd ~verb:"start" start_main);
("stop", stop_cmd ~verb:"stop" stop_main);
("restart", stop_cmd ~verb:"restart" restart_main);
("status", base_cmd ~verb:"check status of" status_main);
]
| null | https://raw.githubusercontent.com/monadbobo/ocaml-core/9c1c06e7a1af7e15b6019a325d7dbdbd4cdb4020/base/core/extended/lib/service_command.ml | ocaml | lock file created after [daemonize_wait] so that *child* pid is written
to the lock file rather than the parent pid
this writes our pid in the file
we release the daemon's parent *after* the lock file is created
so that any error messages during lock file creation happen
prior to severing the daemon's connection to std{out,err}
receiving [Signal.zero] is a no-op, but sending it gives info
about whether there a running process with that pid | open Core.Std
let command ~lock_file ~name main =
let start_main () =
let release_parent = Daemon.daemonize_wait () in
if Lock_file.create ~close_on_exec:true ~unlink_on_exit:true lock_file
release_parent ();
main ()
end;
0
in
let check_lock_file () =
if Lock_file.is_locked lock_file then begin
let pid = Pid.t_of_sexp (Sexp.load_sexp lock_file) in
`Running_with_pid pid
end else
`Not_running
in
let still_alive pid =
match Signal.send Signal.zero (`Pid pid) with
| `Ok -> true
| `No_such_process -> false
in
let status_main () =
begin match check_lock_file () with
| `Not_running -> printf "%s is not running\n%!" name
| `Running_with_pid pid ->
if still_alive pid then
printf "%s is running with pid %s\n%!" name (Pid.to_string pid)
else
printf "%s is not running, even though we saw pid %s in its lockfile\n%!"
name (Pid.to_string pid)
end;
0
in
let stop_aux ~stop_signal =
let was_not_running () =
eprintf "%s was not running\n%!" name;
`Was_not_running
in
match check_lock_file () with
| `Not_running -> was_not_running ()
| `Running_with_pid pid ->
let timeout_span = sec 10. in
let deadline = Time.add (Time.now ()) timeout_span in
match Signal.send stop_signal (`Pid pid) with
| `No_such_process -> was_not_running ()
| `Ok ->
let rec wait_loop () =
if Time.(>=) (Time.now ()) deadline then begin
eprintf "failed to observe %s die after %s\n%!" name
(Time.Span.to_string timeout_span);
`Did_not_die
end else if still_alive pid then begin
Time.pause (sec 0.2);
wait_loop ()
end else
`Died
in
wait_loop ()
in
let stop_main ~stop_signal =
match stop_aux ~stop_signal with
| `Was_not_running | `Did_not_die -> 1
| `Died -> 0
in
let restart_main ~stop_signal =
match stop_aux ~stop_signal with
| `Did_not_die -> 1
| `Was_not_running | `Died -> start_main ()
in
let summary ~verb = sprintf "%s %s" verb name in
let assert_no_anons anons =
match anons with
| [] -> ()
| anons ->
failwithf "expected 0 anonymous arguments but found %d\n%!"
(List.length anons) ()
in
let base_cmd ~verb main =
Command.create (fun () -> exit (main ()))
~summary:(summary ~verb)
~usage_arg:""
~init:Fn.id
~flags:[]
~final:(fun () anons -> assert_no_anons anons)
in
let stop_cmd ~verb main =
Command.create (fun stop_signal -> exit (main ~stop_signal))
~summary:(summary ~verb)
~usage_arg:"[-kill]"
~init:(Fn.const Signal.term)
~flags:[
Command.Flag.noarg_acc "-kill" (Fn.const Signal.kill)
~doc:" send SIGKILL instead of SIGTERM"
]
~final:(fun signal anons -> assert_no_anons anons; signal)
in
Command.group ~summary:(summary ~verb:"manage") [
("start", base_cmd ~verb:"start" start_main);
("stop", stop_cmd ~verb:"stop" stop_main);
("restart", stop_cmd ~verb:"restart" restart_main);
("status", base_cmd ~verb:"check status of" status_main);
]
|
90edba4ed0702fcaf0c73136abcc00641ae0871d3064d43400836e9ccdc961f7 | uw-unsat/serval | irreader.rkt | #lang racket/base
(require ffi/unsafe
ffi/unsafe/alloc
"core.rkt")
(provide LLVMParseIRInContext)
; allocate a new _LLVMMemoryBufferRef, which is consumed by this function
(define-llvm LLVMParseIRInContext
(_fun [_LLVMContextRef = (LLVMGetGlobalContext)]
[data : _?]
[_LLVMMemoryBufferRef = (LLVMCreateMemoryBufferWithMemoryRangeCopy data "" 0)]
[m : (_ptr o (_or-null _LLVMModuleRef))]
[msg : (_ptr o _pointer)]
-> [r : _LLVMBool]
-> (begin (check r msg) m))
#:wrap (allocator LLVMDisposeModule))
; no allocator here
(define-llvm LLVMCreateMemoryBufferWithMemoryRangeCopy
(_fun [data : _bytes]
[length : _size = (bytes-length data)]
[buffer-name : _string]
[requires-null-terminator? : _LLVMBool]
-> _LLVMMemoryBufferRef))
| null | https://raw.githubusercontent.com/uw-unsat/serval/be11ecccf03f81b8bd0557acf8385a6a5d4f51ed/serval/llvm/capi/irreader.rkt | racket | allocate a new _LLVMMemoryBufferRef, which is consumed by this function
no allocator here | #lang racket/base
(require ffi/unsafe
ffi/unsafe/alloc
"core.rkt")
(provide LLVMParseIRInContext)
(define-llvm LLVMParseIRInContext
(_fun [_LLVMContextRef = (LLVMGetGlobalContext)]
[data : _?]
[_LLVMMemoryBufferRef = (LLVMCreateMemoryBufferWithMemoryRangeCopy data "" 0)]
[m : (_ptr o (_or-null _LLVMModuleRef))]
[msg : (_ptr o _pointer)]
-> [r : _LLVMBool]
-> (begin (check r msg) m))
#:wrap (allocator LLVMDisposeModule))
(define-llvm LLVMCreateMemoryBufferWithMemoryRangeCopy
(_fun [data : _bytes]
[length : _size = (bytes-length data)]
[buffer-name : _string]
[requires-null-terminator? : _LLVMBool]
-> _LLVMMemoryBufferRef))
|
1ab2bb7b45dd4f8df1f2e262bcb0fac710d572ed39c6bf6c506ef015a6cd275d | rtoy/cmucl | print.lisp | ;;; -*- Package: C -*-
;;;
;;; **********************************************************************
This code was written as part of the CMU Common Lisp project at
Carnegie Mellon University , and has been placed in the public domain .
;;;
(ext:file-comment
"$Header: src/compiler/mips/print.lisp $")
;;;
;;; **********************************************************************
;;;
;;; This file contains temporary printing utilities and similar noise.
;;;
Written by .
(in-package "MIPS")
(define-vop (print)
(:args (object :scs (descriptor-reg) :target a0))
(:results (result :scs (descriptor-reg)))
(:save-p t)
(:temporary (:sc any-reg :offset cfunc-offset :target result :to (:result 0))
cfunc)
(:temporary (:sc descriptor-reg :offset 4 :from (:argument 0)) a0)
(:temporary (:sc control-stack :offset nfp-save-offset) nfp-save)
(:vop-var vop)
(:generator 0
(let ((cur-nfp (current-nfp-tn vop)))
(move a0 object)
(when cur-nfp
(store-stack-tn nfp-save cur-nfp))
(inst li cfunc (make-fixup "debug_print" :foreign))
(inst jal (make-fixup "call_into_c" :foreign))
(inst addu nsp-tn nsp-tn -16)
(inst addu nsp-tn nsp-tn 16)
(when cur-nfp
(load-stack-tn cur-nfp nfp-save))
(move result cfunc))))
| null | https://raw.githubusercontent.com/rtoy/cmucl/9b1abca53598f03a5b39ded4185471a5b8777dea/src/compiler/mips/print.lisp | lisp | -*- Package: C -*-
**********************************************************************
**********************************************************************
This file contains temporary printing utilities and similar noise.
| This code was written as part of the CMU Common Lisp project at
Carnegie Mellon University , and has been placed in the public domain .
(ext:file-comment
"$Header: src/compiler/mips/print.lisp $")
Written by .
(in-package "MIPS")
(define-vop (print)
(:args (object :scs (descriptor-reg) :target a0))
(:results (result :scs (descriptor-reg)))
(:save-p t)
(:temporary (:sc any-reg :offset cfunc-offset :target result :to (:result 0))
cfunc)
(:temporary (:sc descriptor-reg :offset 4 :from (:argument 0)) a0)
(:temporary (:sc control-stack :offset nfp-save-offset) nfp-save)
(:vop-var vop)
(:generator 0
(let ((cur-nfp (current-nfp-tn vop)))
(move a0 object)
(when cur-nfp
(store-stack-tn nfp-save cur-nfp))
(inst li cfunc (make-fixup "debug_print" :foreign))
(inst jal (make-fixup "call_into_c" :foreign))
(inst addu nsp-tn nsp-tn -16)
(inst addu nsp-tn nsp-tn 16)
(when cur-nfp
(load-stack-tn cur-nfp nfp-save))
(move result cfunc))))
|
bf8bd74a73251ae9339c9ee4104ca1fb54733f1339f23074c4bfbaece17cd157 | degree9/enterprise | storage.cljs | (ns degree9.browser.storage
(:refer-clojure :exclude [key get assoc dissoc empty])
(:require [degree9.browser.window :as bom]))
(defprotocol IStorage
"Interface for interacting with Web Storage API."
(key [this index] "Returns name of nth key.")
(get-item [this key] "Return keys value or null.")
(set-item [this key value] "Adds key to storage or updates it's value.")
(remove-item [this key] "Removes keys from storage if it exists.")
(clear [this] "Clears all keys from storage."))
(extend-protocol IStorage
js/Storage
(key [this index] (.key this index))
(get-item [this index] (.getItem this index))
(set-item [this index value] (.setItem this index value))
(remove-item [this index] (.removeItem this index))
(clear [this] (.clear this)))
(defn local-storage []
(bom/localStorage js/window))
(defn session-storage []
(bom/sessionStorage js/window))
(defn get [store key & [default]]
(or (js->clj (get-item store (name key))) default))
(defn assoc [store key value]
(set-item store (name key) (clj->js value)))
(defn dissoc [store key]
(remove-item store (name key)))
(defn empty [store]
(clear store))
| null | https://raw.githubusercontent.com/degree9/enterprise/65737c347e513d0a0bf94f2d4374935c7270185d/src/degree9/browser/storage.cljs | clojure | (ns degree9.browser.storage
(:refer-clojure :exclude [key get assoc dissoc empty])
(:require [degree9.browser.window :as bom]))
(defprotocol IStorage
"Interface for interacting with Web Storage API."
(key [this index] "Returns name of nth key.")
(get-item [this key] "Return keys value or null.")
(set-item [this key value] "Adds key to storage or updates it's value.")
(remove-item [this key] "Removes keys from storage if it exists.")
(clear [this] "Clears all keys from storage."))
(extend-protocol IStorage
js/Storage
(key [this index] (.key this index))
(get-item [this index] (.getItem this index))
(set-item [this index value] (.setItem this index value))
(remove-item [this index] (.removeItem this index))
(clear [this] (.clear this)))
(defn local-storage []
(bom/localStorage js/window))
(defn session-storage []
(bom/sessionStorage js/window))
(defn get [store key & [default]]
(or (js->clj (get-item store (name key))) default))
(defn assoc [store key value]
(set-item store (name key) (clj->js value)))
(defn dissoc [store key]
(remove-item store (name key)))
(defn empty [store]
(clear store))
|
|
7a3d96c55a26ec6a1129210231859ff6aeb10eca72835d850faacdf54b976595 | 5outh/chaosbox | AABB.hs | -- | Minimally axis-aligned bounding boxes
module ChaosBox.AABB
( HasAABB(..)
, AABB(..)
, boundary
, aabbContains
)
where
import ChaosBox.Geometry.Class
import ChaosBox.Geometry.P2
import Control.Lens ( (^.) )
import Data.List.NonEmpty
import Linear.V2
-- | An Axis-Aligned Bounding Box
data AABB = AABB
{ aabbTopLeft :: P2
, aabbW :: Double
, aabbH :: Double
}
deriving stock (Show, Eq, Ord)
| Class of types that can be minimally bounded by an ' '
class HasAABB shape where
aabb :: shape -> AABB
instance HasAABB AABB where
aabb = id
-- | Get the bounds of a list of positioned objects.
boundary :: HasP2 a => NonEmpty a -> AABB
boundary xs = AABB tl w h
where
l = toList xs
tl = minimum $ fmap (^. _V2) l
br = maximum $ fmap (^. _V2) l
(V2 w h) = br - tl
| Check if an ' ' contains some 2d point ( ' P2 ' )
aabbContains :: AABB -> P2 -> Bool
aabbContains AABB {..} (P2 x y) =
x >= x0 && x < x0 + aabbW && y >= y0 && y < y0 + aabbH
where V2 x0 y0 = aabbTopLeft
instance Boundary AABB where
containsPoint = aabbContains
| null | https://raw.githubusercontent.com/5outh/chaosbox/991ca3db48d8828287567302ba3293314b9127bd/src/ChaosBox/AABB.hs | haskell | | Minimally axis-aligned bounding boxes
| An Axis-Aligned Bounding Box
| Get the bounds of a list of positioned objects. | module ChaosBox.AABB
( HasAABB(..)
, AABB(..)
, boundary
, aabbContains
)
where
import ChaosBox.Geometry.Class
import ChaosBox.Geometry.P2
import Control.Lens ( (^.) )
import Data.List.NonEmpty
import Linear.V2
data AABB = AABB
{ aabbTopLeft :: P2
, aabbW :: Double
, aabbH :: Double
}
deriving stock (Show, Eq, Ord)
| Class of types that can be minimally bounded by an ' '
class HasAABB shape where
aabb :: shape -> AABB
instance HasAABB AABB where
aabb = id
boundary :: HasP2 a => NonEmpty a -> AABB
boundary xs = AABB tl w h
where
l = toList xs
tl = minimum $ fmap (^. _V2) l
br = maximum $ fmap (^. _V2) l
(V2 w h) = br - tl
| Check if an ' ' contains some 2d point ( ' P2 ' )
aabbContains :: AABB -> P2 -> Bool
aabbContains AABB {..} (P2 x y) =
x >= x0 && x < x0 + aabbW && y >= y0 && y < y0 + aabbH
where V2 x0 y0 = aabbTopLeft
instance Boundary AABB where
containsPoint = aabbContains
|
e65fc0b6b0dcfe11219852a1b77cebba7e5c56d7c63dcf01a34869da540ebc3f | HunterYIboHu/htdp2-solution | ex433-checked-bundle.rkt | The first three lines of this file were inserted by . They record metadata
;; about the language level of this file in a form that our tools can easily process.
#reader(lib "htdp-intermediate-lambda-reader.ss" "lang")((modname ex433-checked-bundle) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f)))
; [List-of 1String] N -> [List-of String]
; bundles chunks of s into strings of length n.
; termination (bundle s 0) loops unless s is '().
(check-expect (bundle (explode "abcdefgh") 2)
'("ab" "cd" "ef" "gh"))
(check-expect (bundle (explode "abcdefgh") 3)
'("abc" "def" "gh"))
(check-expect (bundle '("a" "b") 3)
'("ab"))
(check-expect (bundle '() 3) '())
(check-expect (bundle '() 0) '())
(check-error (bundle (explode "abc") 0))
(define (bundle s n)
(cond [(empty? s) '()]
[(zero? n)
(error "the function won't terminate when n is given 0.")]
[else (cons (implode (take s n))
(bundle (drop s n) n))]))
; [List-of X] N -> [List-of X]
keep the first n items from l is possible or everything .
(define (take l n)
(cond [(zero? n) '()]
[(empty? l) '()]
[else (cons (first l)
(take (rest l) (sub1 n)))]))
; [List-of X] N -> [List-of X]
remove the first n items from l if possible or everything .
(define (drop l n)
(cond [(zero? n) l]
[(empty? l) l]
[else (drop (rest l) (sub1 n))]))
| null | https://raw.githubusercontent.com/HunterYIboHu/htdp2-solution/6182b4c2ef650ac7059f3c143f639d09cd708516/Chapter5/Section26-design-algorithm/ex433-checked-bundle.rkt | racket | about the language level of this file in a form that our tools can easily process.
[List-of 1String] N -> [List-of String]
bundles chunks of s into strings of length n.
termination (bundle s 0) loops unless s is '().
[List-of X] N -> [List-of X]
[List-of X] N -> [List-of X] | The first three lines of this file were inserted by . They record metadata
#reader(lib "htdp-intermediate-lambda-reader.ss" "lang")((modname ex433-checked-bundle) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f)))
(check-expect (bundle (explode "abcdefgh") 2)
'("ab" "cd" "ef" "gh"))
(check-expect (bundle (explode "abcdefgh") 3)
'("abc" "def" "gh"))
(check-expect (bundle '("a" "b") 3)
'("ab"))
(check-expect (bundle '() 3) '())
(check-expect (bundle '() 0) '())
(check-error (bundle (explode "abc") 0))
(define (bundle s n)
(cond [(empty? s) '()]
[(zero? n)
(error "the function won't terminate when n is given 0.")]
[else (cons (implode (take s n))
(bundle (drop s n) n))]))
keep the first n items from l is possible or everything .
(define (take l n)
(cond [(zero? n) '()]
[(empty? l) '()]
[else (cons (first l)
(take (rest l) (sub1 n)))]))
remove the first n items from l if possible or everything .
(define (drop l n)
(cond [(zero? n) l]
[(empty? l) l]
[else (drop (rest l) (sub1 n))]))
|
95018fe27e706b92e11f36f2a7523f620eddbbdb976a9e9c5b11edd09af08120 | electric-sql/vaxine | test_utils.erl | %% -------------------------------------------------------------------
%%
Copyright < 2013 - 2018 > <
Technische Universität Kaiserslautern , Germany
, France
Universidade NOVA de Lisboa , Portugal
Université catholique de Louvain ( UCL ) , Belgique
, Portugal
%% >
%%
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 expressed or implied. See the License for the
%% specific language governing permissions and limitations
%% under the License.
%%
List of the contributors to the development of Antidote : see file .
%% Description and complete License: see LICENSE file.
%% -------------------------------------------------------------------
-module(test_utils).
-export([
at_init_testsuite/0,
pmap/2,
bucket/1,
init_single_dc/2,
init_multi_dc/2,
get_node_name/1,
web_ports/1,
restart_nodes/2,
partition_cluster/2,
heal_cluster/2,
set_up_clusters_common/1,
unpack/1
]).
%% ===========================================
%% Node utilities
%% ===========================================
-export([
start_node/2,
init_node/2,
kill_nodes/1,
kill_and_restart_nodes/2,
brutal_kill_nodes/1
]).
%% ===========================================
%% Common Test Initialization
%% ===========================================
init_single_dc(Suite, Config) ->
ct:pal("[~p]", [Suite]),
test_utils:at_init_testsuite(),
StartDCs = fun(Nodes) ->
test_utils:pmap(fun(N) -> {_Status, Node} = test_utils:start_node(N, Config), Node end, Nodes)
end,
[Nodes] = test_utils:pmap( fun(N) -> StartDCs(N) end, [[dev1]] ),
[Node] = Nodes,
[{clusters, [Nodes]} | [{nodes, Nodes} | [{node, Node} | Config]]].
init_multi_dc(Suite, Config) ->
ct:pal("[~p]", [Suite]),
at_init_testsuite(),
Clusters = test_utils:set_up_clusters_common([{suite_name, ?MODULE} | Config]),
Nodes = hd(Clusters),
[{clusters, Clusters} | [{nodes, Nodes} | Config]].
at_init_testsuite() ->
{ok, Hostname} = inet:gethostname(),
case net_kernel:start([list_to_atom("runner@" ++ Hostname), shortnames]) of
{ok, _} -> ok;
{error, {already_started, _}} -> ok;
{error, {{already_started, _}, _}} -> ok
end.
%% ===========================================
%% Node utilities
%% ===========================================
start_node(Name, Config) ->
%% have the slave nodes monitor the runner node, so they can't outlive it
NodeConfig = [{monitor_master, true}],
case ct_slave:start(Name, NodeConfig) of
{ok, Node} ->
%% code path for compiled dependencies
CodePath = lists:filter(fun filelib:is_dir/1, code:get_path()) ,
lists:foreach(fun(P) -> rpc:call(Node, code, add_patha, [P]) end, CodePath),
{ok, _} = init_node(Name, Node),
{connect, Node};
{error, already_started, Node} ->
ct:log("Node ~p already started, reusing node", [Node]),
{ready, Node};
{error, Reason, Node} ->
ct:pal("Error starting node ~w, reason ~w, will retry", [Node, Reason]),
ct_slave:stop(Name),
time_utils:wait_until_offline(Node),
start_node(Name, Config)
end.
init_node(Name, Node) ->
% load application to allow for configuring the environment before starting
ok = rpc:call(Node, application, load, [riak_core]),
ok = rpc:call(Node, application, load, [antidote_stats]),
ok = rpc:call(Node, application, load, [ranch]),
ok = rpc:call(Node, application, load, [antidote]),
%% get remote working dir of node
{ok, NodeWorkingDir} = rpc:call(Node, file, get_cwd, []),
%% DATA DIRS
ok = rpc:call(Node, application, set_env, [antidote, data_dir, filename:join([NodeWorkingDir, Node, "antidote-data"])]),
ok = rpc:call(Node, application, set_env, [riak_core, ring_state_dir, filename:join([NodeWorkingDir, Node, "data"])]),
ok = rpc:call(Node, application, set_env, [riak_core, platform_data_dir, filename:join([NodeWorkingDir, Node, "data"])]),
PORTS
Port = web_ports(Name),
ok = rpc:call(Node, application, set_env, [antidote, logreader_port, Port]),
ok = rpc:call(Node, application, set_env, [antidote, pubsub_port, Port + 1]),
ok = rpc:call(Node, application, set_env, [ranch, pb_port, Port + 2]),
ok = rpc:call(Node, application, set_env, [riak_core, handoff_port, Port + 3]),
ok = rpc:call(Node, application, set_env, [antidote_stats, metrics_port, Port + 4]),
%% LOGGING Configuration
%% add additional logging handlers to ensure easy access to remote node logs
%% for each logging level
LogRoot = filename:join([NodeWorkingDir, Node, "logs"]),
%% set the logger configuration
ok = rpc:call(Node, application, set_env, [antidote, logger, log_config(LogRoot)]),
%% set primary output level, no filter
rpc:call(Node, logger, set_primary_config, [level, all]),
%% load additional logger handlers at remote node
rpc:call(Node, logger, add_handlers, [antidote]),
%% redirect slave logs to ct_master logs
ok = rpc:call(Node, application, set_env, [antidote, ct_master, node()]),
ConfLog = #{level => debug, formatter => {logger_formatter, #{single_line => true, max_size => 2048}}, config => #{type => standard_io}},
_ = rpc:call(Node, logger, add_handler, [antidote_redirect_ct, ct_redirect_handler, ConfLog]),
%% ANTIDOTE Configuration
reduce number of actual log files created to 4 , reduces start - up time of node
ok = rpc:call(Node, application, set_env, [riak_core, ring_creation_size, 4]),
ok = rpc:call(Node, application, set_env, [antidote, sync_log, true]),
{ok, Apps} = rpc:call(Node, application, ensure_all_started, [antidote]),
ct:pal("Node ~p started with ports ~p-~p", [Node, Port, Port + 4]),
{ok, Apps}.
%% @doc Forces shutdown of nodes and restarts them again with given configuration
-spec kill_and_restart_nodes([node()], [tuple()]) -> [node()].
kill_and_restart_nodes(NodeList, Config) ->
NewNodeList = brutal_kill_nodes(NodeList),
restart_nodes(NewNodeList, Config).
@doc Kills all given nodes , crashes if one node can not be stopped
-spec kill_nodes([node()]) -> [node()].
kill_nodes(NodeList) ->
lists:map(fun(Node) -> {ok, Name} = ct_slave:stop(get_node_name(Node)), Name end, NodeList).
%% @doc Send force kill signals to all given nodes
-spec brutal_kill_nodes([node()]) -> [node()].
brutal_kill_nodes(NodeList) ->
lists:map(fun(Node) ->
ct:pal("Killing node ~p", [Node]),
OSPidToKill = rpc:call(Node, os, getpid, []),
try a normal kill first , but set a timer to
kill -9 after X seconds just in case
%% rpc:cast(Node, timer, apply_after,
[ ? , os , cmd , [ io_lib : format("kill -9 ~s " , [ OSPidToKill ] ) ] ] ) ,
ct_slave:stop(get_node_name(Node)),
rpc:cast(Node, os, cmd, [io_lib:format("kill -15 ~s", [OSPidToKill])]),
Node
end, NodeList).
%% @doc Restart nodes with given configuration
-spec restart_nodes([node()], [tuple()]) -> [node()].
restart_nodes(NodeList, Config) ->
pmap(fun(Node) ->
ct:pal("Restarting node ~p", [Node]),
ct:log("Starting and waiting until vnodes are restarted at node ~w", [Node]),
start_node(get_node_name(Node), Config),
ct:log("Waiting until ring converged @ ~p", [Node]),
riak_utils:wait_until_ring_converged([Node]),
ct:log("Waiting until ready @ ~p", [Node]),
time_utils:wait_until(Node, fun wait_init:check_ready/1),
Node
end, NodeList).
%% @doc Convert node to node atom
-spec get_node_name(node()) -> atom().
get_node_name(NodeAtom) ->
Node = atom_to_list(NodeAtom),
{match, [{Pos, _Len}]} = re:run(Node, "@"),
list_to_atom(string:substr(Node, 1, Pos)).
@doc TODO
-spec pmap(fun(), list()) -> list().
pmap(F, L) ->
Parent = self(),
lists:foldl(
fun(X, N) ->
spawn_link(fun() ->
Parent ! {pmap, N, F(X)}
end),
N+1
end, 0, L),
L2 = [receive {pmap, N, R} -> {N, R} end || _ <- L],
{_, L3} = lists:unzip(lists:keysort(1, L2)),
L3.
partition_cluster(ANodes, BNodes) ->
pmap(fun({Node1, Node2}) ->
true = rpc:call(Node1, erlang, set_cookie, [Node2, canttouchthis]),
true = rpc:call(Node1, erlang, disconnect_node, [Node2]),
ok = time_utils:wait_until_disconnected(Node1, Node2)
end,
[{Node1, Node2} || Node1 <- ANodes, Node2 <- BNodes]),
ok.
heal_cluster(ANodes, BNodes) ->
GoodCookie = erlang:get_cookie(),
pmap(fun({Node1, Node2}) ->
true = rpc:call(Node1, erlang, set_cookie, [Node2, GoodCookie]),
ok = time_utils:wait_until_connected(Node1, Node2)
end,
[{Node1, Node2} || Node1 <- ANodes, Node2 <- BNodes]),
ok.
web_ports(dev1) -> 10015;
web_ports(dev2) -> 10025;
web_ports(dev3) -> 10035;
web_ports(dev4) -> 10045;
web_ports(clusterdev1) -> 10115;
web_ports(clusterdev2) -> 10125;
web_ports(clusterdev3) -> 10135;
web_ports(clusterdev4) -> 10145;
web_ports(clusterdev5) -> 10155;
web_ports(clusterdev6) -> 10165;
web_ports(dcdev1) -> 10215;
web_ports(dcdev2) -> 10225;
web_ports(dcdev3) -> 10235.
%% Build clusters for all test suites.
set_up_clusters_common(Config) ->
ClusterAndDcConfiguration = [[dev1, dev2], [dev3], [dev4]],
StartDCs =
fun(Nodes) ->
%% start each node
Cl = pmap(fun(N) -> start_node(N, Config) end, Nodes),
[{Status, Claimant} | OtherNodes] = Cl,
%% check if node was reused or not
case Status of
ready -> ok;
connect ->
ct:pal("Creating a ring for claimant ~p and other nodes ~p",
[Claimant, unpack(OtherNodes)]),
ok = rpc:call(Claimant, antidote_dc_manager,
add_nodes_to_dc, [unpack(Cl)])
end,
Cl
end,
Clusters = pmap(fun(Cluster) -> StartDCs(Cluster) end, ClusterAndDcConfiguration),
%% DCs started, but not connected yet
pmap(fun([{Status, MainNode} | _] = CurrentCluster) ->
case Status of
ready -> ok;
connect ->
ct:pal("~p of ~p subscribing to other external DCs",
[MainNode, unpack(CurrentCluster)]),
Descriptors =
lists:map(
fun([{_Status, FirstNode} | _]) ->
{ok, Descriptor} =
rpc:call(FirstNode, antidote_dc_manager,
get_connection_descriptor, []),
Descriptor
end, Clusters),
ct:pal("descriptors: ~p", [Descriptors]),
subscribe to descriptors of other
ok = rpc:call(MainNode, antidote_dc_manager,
subscribe_updates_from, [Descriptors])
end
end, Clusters),
ct:log("Clusters joined and data centers connected connected: ~p",
[ClusterAndDcConfiguration]),
[unpack(DC) || DC <- Clusters].
bucket(BucketBaseAtom) ->
BucketRandomSuffix = [rand:uniform(127)],
Bucket = list_to_atom(atom_to_list(BucketBaseAtom) ++ BucketRandomSuffix),
ct:log("Using random bucket: ~p", [Bucket]),
Bucket.
%% logger configuration for each level
%% see
log_config(LogDir) ->
DebugConfig = #{level => debug,
formatter => {logger_formatter, #{single_line => true, max_size => 2048}},
config => #{type => {file, filename:join(LogDir, "debug.log")}}},
InfoConfig = #{level => info,
formatter => {logger_formatter, #{single_line => true, max_size => 2048}},
config => #{type => {file, filename:join(LogDir, "info.log")}}},
NoticeConfig = #{level => notice,
formatter => {logger_formatter, #{single_line => true, max_size => 2048}},
config => #{type => {file, filename:join(LogDir, "notice.log")}}},
WarningConfig = #{level => warning,
formatter => {logger_formatter, #{single_line => true, max_size => 2048}},
config => #{type => {file, filename:join(LogDir, "warning.log")}}},
ErrorConfig = #{level => error,
formatter => {logger_formatter, #{single_line => true, max_size => 2048}},
config => #{type => {file, filename:join(LogDir, "error.log")}}},
[
{handler, debug_antidote, logger_std_h, DebugConfig},
{handler, info_antidote, logger_std_h, InfoConfig},
{handler, notice_antidote, logger_std_h, NoticeConfig},
{handler, warning_antidote, logger_std_h, WarningConfig},
{handler, error_antidote, logger_std_h, ErrorConfig}
].
-spec unpack([{ready | connect, atom()}]) -> [atom()].
unpack(NodesWithStatus) ->
[Node || {_Status, Node} <- NodesWithStatus].
| null | https://raw.githubusercontent.com/electric-sql/vaxine/5f88829a513a076e9928f389995d913ea381ccb6/apps/antidote/test/utils/test_utils.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 expressed or implied. See the License for the
specific language governing permissions and limitations
under the License.
Description and complete License: see LICENSE file.
-------------------------------------------------------------------
===========================================
Node utilities
===========================================
===========================================
Common Test Initialization
===========================================
===========================================
Node utilities
===========================================
have the slave nodes monitor the runner node, so they can't outlive it
code path for compiled dependencies
load application to allow for configuring the environment before starting
get remote working dir of node
DATA DIRS
LOGGING Configuration
add additional logging handlers to ensure easy access to remote node logs
for each logging level
set the logger configuration
set primary output level, no filter
load additional logger handlers at remote node
redirect slave logs to ct_master logs
ANTIDOTE Configuration
@doc Forces shutdown of nodes and restarts them again with given configuration
@doc Send force kill signals to all given nodes
rpc:cast(Node, timer, apply_after,
@doc Restart nodes with given configuration
@doc Convert node to node atom
Build clusters for all test suites.
start each node
check if node was reused or not
DCs started, but not connected yet
logger configuration for each level
see | Copyright < 2013 - 2018 > <
Technische Universität Kaiserslautern , Germany
, France
Universidade NOVA de Lisboa , Portugal
Université catholique de Louvain ( UCL ) , Belgique
, Portugal
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
List of the contributors to the development of Antidote : see file .
-module(test_utils).
-export([
at_init_testsuite/0,
pmap/2,
bucket/1,
init_single_dc/2,
init_multi_dc/2,
get_node_name/1,
web_ports/1,
restart_nodes/2,
partition_cluster/2,
heal_cluster/2,
set_up_clusters_common/1,
unpack/1
]).
-export([
start_node/2,
init_node/2,
kill_nodes/1,
kill_and_restart_nodes/2,
brutal_kill_nodes/1
]).
init_single_dc(Suite, Config) ->
ct:pal("[~p]", [Suite]),
test_utils:at_init_testsuite(),
StartDCs = fun(Nodes) ->
test_utils:pmap(fun(N) -> {_Status, Node} = test_utils:start_node(N, Config), Node end, Nodes)
end,
[Nodes] = test_utils:pmap( fun(N) -> StartDCs(N) end, [[dev1]] ),
[Node] = Nodes,
[{clusters, [Nodes]} | [{nodes, Nodes} | [{node, Node} | Config]]].
init_multi_dc(Suite, Config) ->
ct:pal("[~p]", [Suite]),
at_init_testsuite(),
Clusters = test_utils:set_up_clusters_common([{suite_name, ?MODULE} | Config]),
Nodes = hd(Clusters),
[{clusters, Clusters} | [{nodes, Nodes} | Config]].
at_init_testsuite() ->
{ok, Hostname} = inet:gethostname(),
case net_kernel:start([list_to_atom("runner@" ++ Hostname), shortnames]) of
{ok, _} -> ok;
{error, {already_started, _}} -> ok;
{error, {{already_started, _}, _}} -> ok
end.
start_node(Name, Config) ->
NodeConfig = [{monitor_master, true}],
case ct_slave:start(Name, NodeConfig) of
{ok, Node} ->
CodePath = lists:filter(fun filelib:is_dir/1, code:get_path()) ,
lists:foreach(fun(P) -> rpc:call(Node, code, add_patha, [P]) end, CodePath),
{ok, _} = init_node(Name, Node),
{connect, Node};
{error, already_started, Node} ->
ct:log("Node ~p already started, reusing node", [Node]),
{ready, Node};
{error, Reason, Node} ->
ct:pal("Error starting node ~w, reason ~w, will retry", [Node, Reason]),
ct_slave:stop(Name),
time_utils:wait_until_offline(Node),
start_node(Name, Config)
end.
init_node(Name, Node) ->
ok = rpc:call(Node, application, load, [riak_core]),
ok = rpc:call(Node, application, load, [antidote_stats]),
ok = rpc:call(Node, application, load, [ranch]),
ok = rpc:call(Node, application, load, [antidote]),
{ok, NodeWorkingDir} = rpc:call(Node, file, get_cwd, []),
ok = rpc:call(Node, application, set_env, [antidote, data_dir, filename:join([NodeWorkingDir, Node, "antidote-data"])]),
ok = rpc:call(Node, application, set_env, [riak_core, ring_state_dir, filename:join([NodeWorkingDir, Node, "data"])]),
ok = rpc:call(Node, application, set_env, [riak_core, platform_data_dir, filename:join([NodeWorkingDir, Node, "data"])]),
PORTS
Port = web_ports(Name),
ok = rpc:call(Node, application, set_env, [antidote, logreader_port, Port]),
ok = rpc:call(Node, application, set_env, [antidote, pubsub_port, Port + 1]),
ok = rpc:call(Node, application, set_env, [ranch, pb_port, Port + 2]),
ok = rpc:call(Node, application, set_env, [riak_core, handoff_port, Port + 3]),
ok = rpc:call(Node, application, set_env, [antidote_stats, metrics_port, Port + 4]),
LogRoot = filename:join([NodeWorkingDir, Node, "logs"]),
ok = rpc:call(Node, application, set_env, [antidote, logger, log_config(LogRoot)]),
rpc:call(Node, logger, set_primary_config, [level, all]),
rpc:call(Node, logger, add_handlers, [antidote]),
ok = rpc:call(Node, application, set_env, [antidote, ct_master, node()]),
ConfLog = #{level => debug, formatter => {logger_formatter, #{single_line => true, max_size => 2048}}, config => #{type => standard_io}},
_ = rpc:call(Node, logger, add_handler, [antidote_redirect_ct, ct_redirect_handler, ConfLog]),
reduce number of actual log files created to 4 , reduces start - up time of node
ok = rpc:call(Node, application, set_env, [riak_core, ring_creation_size, 4]),
ok = rpc:call(Node, application, set_env, [antidote, sync_log, true]),
{ok, Apps} = rpc:call(Node, application, ensure_all_started, [antidote]),
ct:pal("Node ~p started with ports ~p-~p", [Node, Port, Port + 4]),
{ok, Apps}.
-spec kill_and_restart_nodes([node()], [tuple()]) -> [node()].
kill_and_restart_nodes(NodeList, Config) ->
NewNodeList = brutal_kill_nodes(NodeList),
restart_nodes(NewNodeList, Config).
@doc Kills all given nodes , crashes if one node can not be stopped
-spec kill_nodes([node()]) -> [node()].
kill_nodes(NodeList) ->
lists:map(fun(Node) -> {ok, Name} = ct_slave:stop(get_node_name(Node)), Name end, NodeList).
-spec brutal_kill_nodes([node()]) -> [node()].
brutal_kill_nodes(NodeList) ->
lists:map(fun(Node) ->
ct:pal("Killing node ~p", [Node]),
OSPidToKill = rpc:call(Node, os, getpid, []),
try a normal kill first , but set a timer to
kill -9 after X seconds just in case
[ ? , os , cmd , [ io_lib : format("kill -9 ~s " , [ OSPidToKill ] ) ] ] ) ,
ct_slave:stop(get_node_name(Node)),
rpc:cast(Node, os, cmd, [io_lib:format("kill -15 ~s", [OSPidToKill])]),
Node
end, NodeList).
-spec restart_nodes([node()], [tuple()]) -> [node()].
restart_nodes(NodeList, Config) ->
pmap(fun(Node) ->
ct:pal("Restarting node ~p", [Node]),
ct:log("Starting and waiting until vnodes are restarted at node ~w", [Node]),
start_node(get_node_name(Node), Config),
ct:log("Waiting until ring converged @ ~p", [Node]),
riak_utils:wait_until_ring_converged([Node]),
ct:log("Waiting until ready @ ~p", [Node]),
time_utils:wait_until(Node, fun wait_init:check_ready/1),
Node
end, NodeList).
-spec get_node_name(node()) -> atom().
get_node_name(NodeAtom) ->
Node = atom_to_list(NodeAtom),
{match, [{Pos, _Len}]} = re:run(Node, "@"),
list_to_atom(string:substr(Node, 1, Pos)).
@doc TODO
-spec pmap(fun(), list()) -> list().
pmap(F, L) ->
Parent = self(),
lists:foldl(
fun(X, N) ->
spawn_link(fun() ->
Parent ! {pmap, N, F(X)}
end),
N+1
end, 0, L),
L2 = [receive {pmap, N, R} -> {N, R} end || _ <- L],
{_, L3} = lists:unzip(lists:keysort(1, L2)),
L3.
partition_cluster(ANodes, BNodes) ->
pmap(fun({Node1, Node2}) ->
true = rpc:call(Node1, erlang, set_cookie, [Node2, canttouchthis]),
true = rpc:call(Node1, erlang, disconnect_node, [Node2]),
ok = time_utils:wait_until_disconnected(Node1, Node2)
end,
[{Node1, Node2} || Node1 <- ANodes, Node2 <- BNodes]),
ok.
heal_cluster(ANodes, BNodes) ->
GoodCookie = erlang:get_cookie(),
pmap(fun({Node1, Node2}) ->
true = rpc:call(Node1, erlang, set_cookie, [Node2, GoodCookie]),
ok = time_utils:wait_until_connected(Node1, Node2)
end,
[{Node1, Node2} || Node1 <- ANodes, Node2 <- BNodes]),
ok.
web_ports(dev1) -> 10015;
web_ports(dev2) -> 10025;
web_ports(dev3) -> 10035;
web_ports(dev4) -> 10045;
web_ports(clusterdev1) -> 10115;
web_ports(clusterdev2) -> 10125;
web_ports(clusterdev3) -> 10135;
web_ports(clusterdev4) -> 10145;
web_ports(clusterdev5) -> 10155;
web_ports(clusterdev6) -> 10165;
web_ports(dcdev1) -> 10215;
web_ports(dcdev2) -> 10225;
web_ports(dcdev3) -> 10235.
set_up_clusters_common(Config) ->
ClusterAndDcConfiguration = [[dev1, dev2], [dev3], [dev4]],
StartDCs =
fun(Nodes) ->
Cl = pmap(fun(N) -> start_node(N, Config) end, Nodes),
[{Status, Claimant} | OtherNodes] = Cl,
case Status of
ready -> ok;
connect ->
ct:pal("Creating a ring for claimant ~p and other nodes ~p",
[Claimant, unpack(OtherNodes)]),
ok = rpc:call(Claimant, antidote_dc_manager,
add_nodes_to_dc, [unpack(Cl)])
end,
Cl
end,
Clusters = pmap(fun(Cluster) -> StartDCs(Cluster) end, ClusterAndDcConfiguration),
pmap(fun([{Status, MainNode} | _] = CurrentCluster) ->
case Status of
ready -> ok;
connect ->
ct:pal("~p of ~p subscribing to other external DCs",
[MainNode, unpack(CurrentCluster)]),
Descriptors =
lists:map(
fun([{_Status, FirstNode} | _]) ->
{ok, Descriptor} =
rpc:call(FirstNode, antidote_dc_manager,
get_connection_descriptor, []),
Descriptor
end, Clusters),
ct:pal("descriptors: ~p", [Descriptors]),
subscribe to descriptors of other
ok = rpc:call(MainNode, antidote_dc_manager,
subscribe_updates_from, [Descriptors])
end
end, Clusters),
ct:log("Clusters joined and data centers connected connected: ~p",
[ClusterAndDcConfiguration]),
[unpack(DC) || DC <- Clusters].
bucket(BucketBaseAtom) ->
BucketRandomSuffix = [rand:uniform(127)],
Bucket = list_to_atom(atom_to_list(BucketBaseAtom) ++ BucketRandomSuffix),
ct:log("Using random bucket: ~p", [Bucket]),
Bucket.
log_config(LogDir) ->
DebugConfig = #{level => debug,
formatter => {logger_formatter, #{single_line => true, max_size => 2048}},
config => #{type => {file, filename:join(LogDir, "debug.log")}}},
InfoConfig = #{level => info,
formatter => {logger_formatter, #{single_line => true, max_size => 2048}},
config => #{type => {file, filename:join(LogDir, "info.log")}}},
NoticeConfig = #{level => notice,
formatter => {logger_formatter, #{single_line => true, max_size => 2048}},
config => #{type => {file, filename:join(LogDir, "notice.log")}}},
WarningConfig = #{level => warning,
formatter => {logger_formatter, #{single_line => true, max_size => 2048}},
config => #{type => {file, filename:join(LogDir, "warning.log")}}},
ErrorConfig = #{level => error,
formatter => {logger_formatter, #{single_line => true, max_size => 2048}},
config => #{type => {file, filename:join(LogDir, "error.log")}}},
[
{handler, debug_antidote, logger_std_h, DebugConfig},
{handler, info_antidote, logger_std_h, InfoConfig},
{handler, notice_antidote, logger_std_h, NoticeConfig},
{handler, warning_antidote, logger_std_h, WarningConfig},
{handler, error_antidote, logger_std_h, ErrorConfig}
].
-spec unpack([{ready | connect, atom()}]) -> [atom()].
unpack(NodesWithStatus) ->
[Node || {_Status, Node} <- NodesWithStatus].
|
ae615c47ef958535262441b31c44ecb16c5a9c6de0fb64bab447a131a34f91b7 | nilern/monnit | state_macros.clj | (ns monnit.impl.state-macros
(:require [monnit.core :as m]))
(defmacro defstatetype [name fields & impls]
(concat
`(deftype ~name ~fields ~@impls)
'(m/Functor
(-fmap [self f] (->FMap1 f self))
(-fmap [self f b] (->FMap2 f self b))
(-fmap [self f b c] (->FMap3 f self b c))
(-fmap [self f b c d] (->FMap4 f self b c d))
(-fmap [self f b c d args] (->FMapN f self b c d args))
m/Monad
(bind [self f] (->Bind self f)))))
| null | https://raw.githubusercontent.com/nilern/monnit/cc5fe2a031ef8540c4f77bb620d05a0f0564292b/src/monnit/impl/state_macros.clj | clojure | (ns monnit.impl.state-macros
(:require [monnit.core :as m]))
(defmacro defstatetype [name fields & impls]
(concat
`(deftype ~name ~fields ~@impls)
'(m/Functor
(-fmap [self f] (->FMap1 f self))
(-fmap [self f b] (->FMap2 f self b))
(-fmap [self f b c] (->FMap3 f self b c))
(-fmap [self f b c d] (->FMap4 f self b c d))
(-fmap [self f b c d args] (->FMapN f self b c d args))
m/Monad
(bind [self f] (->Bind self f)))))
|
|
33f38d2570f913f999550bf696ae36878dedefa4205ff21d47e116577a0d3d64 | clojure-interop/aws-api | AWSSecretsManagerClientBuilder.clj | (ns com.amazonaws.services.secretsmanager.AWSSecretsManagerClientBuilder
"Fluent builder for AWSSecretsManager. Use of the builder is preferred
over using constructors of the client class."
(:refer-clojure :only [require comment defn ->])
(:import [com.amazonaws.services.secretsmanager AWSSecretsManagerClientBuilder]))
(defn *standard
"returns: Create new instance of builder with all defaults set. - `com.amazonaws.services.secretsmanager.AWSSecretsManagerClientBuilder`"
(^com.amazonaws.services.secretsmanager.AWSSecretsManagerClientBuilder []
(AWSSecretsManagerClientBuilder/standard )))
(defn *default-client
"returns: Default client using the DefaultAWSCredentialsProviderChain and
DefaultAwsRegionProviderChain chain - `com.amazonaws.services.secretsmanager.AWSSecretsManager`"
(^com.amazonaws.services.secretsmanager.AWSSecretsManager []
(AWSSecretsManagerClientBuilder/defaultClient )))
| null | https://raw.githubusercontent.com/clojure-interop/aws-api/59249b43d3bfaff0a79f5f4f8b7bc22518a3bf14/com.amazonaws.services.secretsmanager/src/com/amazonaws/services/secretsmanager/AWSSecretsManagerClientBuilder.clj | clojure | (ns com.amazonaws.services.secretsmanager.AWSSecretsManagerClientBuilder
"Fluent builder for AWSSecretsManager. Use of the builder is preferred
over using constructors of the client class."
(:refer-clojure :only [require comment defn ->])
(:import [com.amazonaws.services.secretsmanager AWSSecretsManagerClientBuilder]))
(defn *standard
"returns: Create new instance of builder with all defaults set. - `com.amazonaws.services.secretsmanager.AWSSecretsManagerClientBuilder`"
(^com.amazonaws.services.secretsmanager.AWSSecretsManagerClientBuilder []
(AWSSecretsManagerClientBuilder/standard )))
(defn *default-client
"returns: Default client using the DefaultAWSCredentialsProviderChain and
DefaultAwsRegionProviderChain chain - `com.amazonaws.services.secretsmanager.AWSSecretsManager`"
(^com.amazonaws.services.secretsmanager.AWSSecretsManager []
(AWSSecretsManagerClientBuilder/defaultClient )))
|
|
84bda211e74165c48e38719f575d338e513667d56cae08f99ee437e6d2af73b9 | grin-compiler/ghc-wpc-sample-programs | Constraints.hs | # LANGUAGE NondecreasingIndentation #
module Agda.TypeChecking.Constraints where
import Prelude hiding (null)
import Control.Monad
import qualified Data.List as List
import qualified Data.Set as Set
import Agda.Syntax.Internal
import Agda.TypeChecking.Monad
import Agda.TypeChecking.InstanceArguments
import Agda.TypeChecking.Pretty
import Agda.TypeChecking.Reduce
import Agda.TypeChecking.LevelConstraints
import Agda.TypeChecking.SizedTypes
import Agda.TypeChecking.Sort
import Agda.TypeChecking.MetaVars.Mention
import Agda.TypeChecking.Warnings
import {-# SOURCE #-} Agda.TypeChecking.Rules.Application
import {-# SOURCE #-} Agda.TypeChecking.Rules.Def
import {-# SOURCE #-} Agda.TypeChecking.Rules.Term
import {-# SOURCE #-} Agda.TypeChecking.Conversion
import {-# SOURCE #-} Agda.TypeChecking.MetaVars
import {-# SOURCE #-} Agda.TypeChecking.Empty
import Agda.Utils.Except ( MonadError(throwError) )
import Agda.Utils.Maybe
import Agda.Utils.Monad
import Agda.Utils.Null
import Agda.Utils.Pretty (prettyShow)
import Agda.Utils.Impossible
instance MonadConstraint TCM where
catchPatternErr = catchPatternErrTCM
addConstraint = addConstraintTCM
addAwakeConstraint = addAwakeConstraint'
solveConstraint = solveConstraintTCM
solveSomeAwakeConstraints = solveSomeAwakeConstraintsTCM
wakeConstraints = wakeConstraintsTCM
stealConstraints = stealConstraintsTCM
modifyAwakeConstraints = modifyTC . mapAwakeConstraints
modifySleepingConstraints = modifyTC . mapSleepingConstraints
catchPatternErrTCM :: TCM a -> TCM a -> TCM a
catchPatternErrTCM handle v =
catchError_ v $ \err ->
case err of
-- Not putting s (which should really be the what's already there) makes things go
a lot slower ( +20 % total time on standard library ) . How is that possible ? ?
-- The problem is most likely that there are internal catchErrors which forgets the
state . should preserve the state on pattern violations .
PatternErr{} -> handle
_ -> throwError err
addConstraintTCM :: Constraint -> TCM ()
addConstraintTCM c = do
pids <- asksTC envActiveProblems
reportSDoc "tc.constr.add" 20 $ hsep
[ "adding constraint"
, text (show $ Set.toList pids)
, prettyTCM c ]
-- Need to reduce to reveal possibly blocking metas
c <- reduce =<< instantiateFull c
caseMaybeM (simpl c) {-no-} (addConstraint' c) $ {-yes-} \ cs -> do
reportSDoc "tc.constr.add" 20 $ " simplified:" <+> prettyList (map prettyTCM cs)
mapM_ solveConstraint_ cs
-- The added constraint can cause instance constraints to be solved,
-- but only the constraints which aren’t blocked on an uninstantiated meta.
unless (isInstanceConstraint c) $
wakeConstraints' (isWakeableInstanceConstraint . clValue . theConstraint)
where
isWakeableInstanceConstraint :: Constraint -> TCM Bool
isWakeableInstanceConstraint = \case
FindInstance _ b _ -> maybe (return True) isInstantiatedMeta b
_ -> return False
isLvl LevelCmp{} = True
isLvl _ = False
-- Try to simplify a level constraint
simpl :: Constraint -> TCM (Maybe [Constraint])
simpl c
| isLvl c = do
-- Get all level constraints.
lvlcs <- instantiateFull =<< do
List.filter (isLvl . clValue) . map theConstraint <$> getAllConstraints
unless (null lvlcs) $ do
reportSDoc "tc.constr.lvl" 40 $ vcat
[ "simplifying level constraint" <+> prettyTCM c
, nest 2 $ hang "using" 2 $ prettyTCM lvlcs
]
Try to simplify @c@ using the other constraints .
return $ simplifyLevelConstraint c $ map clValue lvlcs
| otherwise = return Nothing
wakeConstraintsTCM :: (ProblemConstraint-> TCM Bool) -> TCM ()
wakeConstraintsTCM wake = do
c <- useR stSleepingConstraints
(wakeup, sleepin) <- partitionM wake c
reportSLn "tc.constr.wake" 50 $
"waking up " ++ show (List.map (Set.toList . constraintProblems) wakeup) ++ "\n" ++
" still sleeping: " ++ show (List.map (Set.toList . constraintProblems) sleepin)
modifySleepingConstraints $ const sleepin
modifyAwakeConstraints (++ wakeup)
-- | Add all constraints belonging to the given problem to the current problem(s).
stealConstraintsTCM :: ProblemId -> TCM ()
stealConstraintsTCM pid = do
current <- asksTC envActiveProblems
reportSLn "tc.constr.steal" 50 $ "problem " ++ show (Set.toList current) ++ " is stealing problem " ++ show pid ++ "'s constraints!"
-- Add current to any constraint in pid.
let rename pc@(PConstr pids c) | Set.member pid pids = PConstr (Set.union current pids) c
| otherwise = pc
-- We should never steal from an active problem.
whenM (Set.member pid <$> asksTC envActiveProblems) __IMPOSSIBLE__
modifyAwakeConstraints $ List.map rename
modifySleepingConstraints $ List.map rename
-- | Don't allow the argument to produce any blocking constraints.
noConstraints
:: (MonadConstraint m, MonadWarning m, MonadError TCErr m, MonadFresh ProblemId m)
=> m a -> m a
noConstraints problem = do
(pid, x) <- newProblem problem
cs <- getConstraintsForProblem pid
unless (null cs) $ do
w <- warning_ (UnsolvedConstraints cs)
typeError $ NonFatalErrors [ w ]
return x
-- | Create a fresh problem for the given action.
newProblem
:: (MonadFresh ProblemId m, MonadConstraint m)
=> m a -> m (ProblemId, a)
newProblem action = do
pid <- fresh
-- Don't get distracted by other constraints while working on the problem
x <- nowSolvingConstraints $ solvingProblem pid action
-- Now we can check any woken constraints
solveAwakeConstraints
return (pid, x)
newProblem_
:: (MonadFresh ProblemId m, MonadConstraint m)
=> m a -> m ProblemId
newProblem_ action = fst <$> newProblem action
ifNoConstraints :: TCM a -> (a -> TCM b) -> (ProblemId -> a -> TCM b) -> TCM b
ifNoConstraints check ifNo ifCs = do
(pid, x) <- newProblem check
ifM (isProblemSolved pid) (ifNo x) (ifCs pid x)
ifNoConstraints_ :: TCM () -> TCM a -> (ProblemId -> TCM a) -> TCM a
ifNoConstraints_ check ifNo ifCs = ifNoConstraints check (const ifNo) (\pid _ -> ifCs pid)
| @guardConstraint c blocker@ tries to solve @blocker@ first .
If successful without constraints , it moves on to solve @c@ , otherwise it
-- adds a @Guarded c cs@ constraint
to the @blocker@-generated constraints @cs@.
guardConstraint :: Constraint -> TCM () -> TCM ()
guardConstraint c blocker =
ifNoConstraints_ blocker (solveConstraint c) (addConstraint . Guarded c)
whenConstraints :: TCM () -> TCM () -> TCM ()
whenConstraints action handler =
ifNoConstraints_ action (return ()) $ \pid -> do
stealConstraints pid
handler
-- | Wake constraints matching the given predicate (and aren't instance
-- constraints if 'shouldPostponeInstanceSearch').
wakeConstraints' :: (ProblemConstraint -> TCM Bool) -> TCM ()
wakeConstraints' p = do
skipInstance <- shouldPostponeInstanceSearch
wakeConstraints (\ c -> (&&) (not $ skipInstance && isInstanceConstraint (clValue $ theConstraint c)) <$> p c)
-- | Wake up the constraints depending on the given meta.
wakeupConstraints :: MetaId -> TCM ()
wakeupConstraints x = do
wakeConstraints' (return . mentionsMeta x)
solveAwakeConstraints
-- | Wake up all constraints.
wakeupConstraints_ :: TCM ()
wakeupConstraints_ = do
wakeConstraints' (return . const True)
solveAwakeConstraints
solveAwakeConstraints :: (MonadConstraint m) => m ()
solveAwakeConstraints = solveAwakeConstraints' False
solveAwakeConstraints' :: (MonadConstraint m) => Bool -> m ()
solveAwakeConstraints' = solveSomeAwakeConstraints (const True)
| Solve awake constraints matching the predicate . If the second argument is
-- True solve constraints even if already 'isSolvingConstraints'.
solveSomeAwakeConstraintsTCM :: (ProblemConstraint -> Bool) -> Bool -> TCM ()
solveSomeAwakeConstraintsTCM solveThis force = do
verboseS "profile.constraints" 10 $ liftTCM $ tickMax "max-open-constraints" . List.genericLength =<< getAllConstraints
whenM ((force ||) . not <$> isSolvingConstraints) $ nowSolvingConstraints $ do
solveSizeConstraints -- , 2012 - 09 - 27 attacks size too early
Ulf , 2016 - 12 - 06 : Do n't inherit problems here ! Stored constraints
-- already contain all their dependencies.
locallyTC eActiveProblems (const Set.empty) solve
where
solve = do
reportSDoc "tc.constr.solve" 10 $ hsep [ "Solving awake constraints."
, text . show . length =<< getAwakeConstraints
, "remaining." ]
whenJustM (takeAwakeConstraint' solveThis) $ \ c -> do
withConstraint solveConstraint c
solve
solveConstraintTCM :: Constraint -> TCM ()
solveConstraintTCM c = do
verboseS "profile.constraints" 10 $ liftTCM $ tick "attempted-constraints"
verboseBracket "tc.constr.solve" 20 "solving constraint" $ do
pids <- asksTC envActiveProblems
reportSDoc "tc.constr.solve.constr" 20 $ text (show $ Set.toList pids) <+> prettyTCM c
solveConstraint_ c
solveConstraint_ :: Constraint -> TCM ()
solveConstraint_ (ValueCmp cmp a u v) = compareAs cmp a u v
solveConstraint_ (ValueCmpOnFace cmp p a u v) = compareTermOnFace cmp p a u v
solveConstraint_ (ElimCmp cmp fs a e u v) = compareElims cmp fs a e u v
solveConstraint_ (TelCmp a b cmp tela telb) = compareTel a b cmp tela telb
solveConstraint_ (SortCmp cmp s1 s2) = compareSort cmp s1 s2
solveConstraint_ (LevelCmp cmp a b) = compareLevel cmp a b
solveConstraint_ c0@(Guarded c pid) = do
ifM (isProblemSolved pid)
{-then-} (do
reportSLn "tc.constr.solve" 50 $ "Guarding problem " ++ show pid ++ " is solved, moving on..."
solveConstraint_ c)
{-else-} $ do
reportSLn "tc.constr.solve" 50 $ "Guarding problem " ++ show pid ++ " is still unsolved."
addConstraint c0
solveConstraint_ (IsEmpty r t) = ensureEmptyType r t
solveConstraint_ (CheckSizeLtSat t) = checkSizeLtSat t
solveConstraint_ (UnquoteTactic _ tac hole goal) = unquoteTactic tac hole goal
solveConstraint_ (UnBlock m) =
ifM (isFrozen m `or2M` (not <$> asksTC envAssignMetas)) (addConstraint $ UnBlock m) $ do
inst <- mvInstantiation <$> lookupMeta m
reportSDoc "tc.constr.unblock" 15 $ text ("unblocking a metavar yields the constraint: " ++ show inst)
case inst of
BlockedConst t -> do
reportSDoc "tc.constr.blocked" 15 $
text ("blocked const " ++ prettyShow m ++ " :=") <+> prettyTCM t
assignTerm m [] t
PostponedTypeCheckingProblem cl unblock -> enterClosure cl $ \prob -> do
ifNotM unblock (addConstraint $ UnBlock m) $ do
tel <- getContextTelescope
v <- liftTCM $ checkTypeCheckingProblem prob
assignTerm m (telToArgs tel) v
, 2009 - 02 - 09 , the following were IMPOSSIBLE cases
-- somehow they pop up in the context of sized types
--
-- already solved metavariables: should only happen for size
metas ( not sure why it does , ? )
, 2017 - 07 - 11 :
-- I think this is because the size solver instantiates
some metas with infinity but does not clean up the UnBlock constraints .
See also issue # 2637 .
Ulf , 2018 - 04 - 30 : The size solver should n't touch blocked terms ! They have
-- a twin meta that it's safe to solve.
InstV{} -> __IMPOSSIBLE__
-- Open (whatever that means)
Open -> __IMPOSSIBLE__
OpenInstance -> __IMPOSSIBLE__
solveConstraint_ (FindInstance m b cands) = findInstance m cands
solveConstraint_ (CheckFunDef d i q cs) = withoutCache $
re # 3498 : checking a fundef would normally be cached , but here it 's
-- happening out of order so it would only corrupt the caching log.
checkFunDef d i q cs
solveConstraint_ (HasBiggerSort a) = hasBiggerSort a
solveConstraint_ (HasPTSRule a b) = hasPTSRule a b
solveConstraint_ (CheckMetaInst m) = checkMetaInst m
checkTypeCheckingProblem :: TypeCheckingProblem -> TCM Term
checkTypeCheckingProblem p = case p of
CheckExpr cmp e t -> checkExpr' cmp e t
CheckArgs eh r args t0 t1 k -> checkArguments eh r args t0 t1 k
CheckProjAppToKnownPrincipalArg cmp e o ds args t k v0 pt ->
checkProjAppToKnownPrincipalArg cmp e o ds args t k v0 pt
CheckLambda cmp args body target -> checkPostponedLambda cmp args body target
DoQuoteTerm cmp et t -> doQuoteTerm cmp et t
debugConstraints :: TCM ()
debugConstraints = verboseS "tc.constr" 50 $ do
awake <- useTC stAwakeConstraints
sleeping <- useTC stSleepingConstraints
reportSDoc "tc.constr" 50 $ vcat
[ "Current constraints"
, nest 2 $ vcat [ "awake " <+> vcat (map prettyTCM awake)
, "asleep" <+> vcat (map prettyTCM sleeping) ] ]
| null | https://raw.githubusercontent.com/grin-compiler/ghc-wpc-sample-programs/0e3a9b8b7cc3fa0da7c77fb7588dd4830fb087f7/Agda-2.6.1/src/full/Agda/TypeChecking/Constraints.hs | haskell | # SOURCE #
# SOURCE #
# SOURCE #
# SOURCE #
# SOURCE #
# SOURCE #
Not putting s (which should really be the what's already there) makes things go
The problem is most likely that there are internal catchErrors which forgets the
Need to reduce to reveal possibly blocking metas
no
yes
The added constraint can cause instance constraints to be solved,
but only the constraints which aren’t blocked on an uninstantiated meta.
Try to simplify a level constraint
Get all level constraints.
| Add all constraints belonging to the given problem to the current problem(s).
Add current to any constraint in pid.
We should never steal from an active problem.
| Don't allow the argument to produce any blocking constraints.
| Create a fresh problem for the given action.
Don't get distracted by other constraints while working on the problem
Now we can check any woken constraints
adds a @Guarded c cs@ constraint
| Wake constraints matching the given predicate (and aren't instance
constraints if 'shouldPostponeInstanceSearch').
| Wake up the constraints depending on the given meta.
| Wake up all constraints.
True solve constraints even if already 'isSolvingConstraints'.
, 2012 - 09 - 27 attacks size too early
already contain all their dependencies.
then
else
somehow they pop up in the context of sized types
already solved metavariables: should only happen for size
I think this is because the size solver instantiates
a twin meta that it's safe to solve.
Open (whatever that means)
happening out of order so it would only corrupt the caching log. | # LANGUAGE NondecreasingIndentation #
module Agda.TypeChecking.Constraints where
import Prelude hiding (null)
import Control.Monad
import qualified Data.List as List
import qualified Data.Set as Set
import Agda.Syntax.Internal
import Agda.TypeChecking.Monad
import Agda.TypeChecking.InstanceArguments
import Agda.TypeChecking.Pretty
import Agda.TypeChecking.Reduce
import Agda.TypeChecking.LevelConstraints
import Agda.TypeChecking.SizedTypes
import Agda.TypeChecking.Sort
import Agda.TypeChecking.MetaVars.Mention
import Agda.TypeChecking.Warnings
import Agda.Utils.Except ( MonadError(throwError) )
import Agda.Utils.Maybe
import Agda.Utils.Monad
import Agda.Utils.Null
import Agda.Utils.Pretty (prettyShow)
import Agda.Utils.Impossible
instance MonadConstraint TCM where
catchPatternErr = catchPatternErrTCM
addConstraint = addConstraintTCM
addAwakeConstraint = addAwakeConstraint'
solveConstraint = solveConstraintTCM
solveSomeAwakeConstraints = solveSomeAwakeConstraintsTCM
wakeConstraints = wakeConstraintsTCM
stealConstraints = stealConstraintsTCM
modifyAwakeConstraints = modifyTC . mapAwakeConstraints
modifySleepingConstraints = modifyTC . mapSleepingConstraints
catchPatternErrTCM :: TCM a -> TCM a -> TCM a
catchPatternErrTCM handle v =
catchError_ v $ \err ->
case err of
a lot slower ( +20 % total time on standard library ) . How is that possible ? ?
state . should preserve the state on pattern violations .
PatternErr{} -> handle
_ -> throwError err
addConstraintTCM :: Constraint -> TCM ()
addConstraintTCM c = do
pids <- asksTC envActiveProblems
reportSDoc "tc.constr.add" 20 $ hsep
[ "adding constraint"
, text (show $ Set.toList pids)
, prettyTCM c ]
c <- reduce =<< instantiateFull c
reportSDoc "tc.constr.add" 20 $ " simplified:" <+> prettyList (map prettyTCM cs)
mapM_ solveConstraint_ cs
unless (isInstanceConstraint c) $
wakeConstraints' (isWakeableInstanceConstraint . clValue . theConstraint)
where
isWakeableInstanceConstraint :: Constraint -> TCM Bool
isWakeableInstanceConstraint = \case
FindInstance _ b _ -> maybe (return True) isInstantiatedMeta b
_ -> return False
isLvl LevelCmp{} = True
isLvl _ = False
simpl :: Constraint -> TCM (Maybe [Constraint])
simpl c
| isLvl c = do
lvlcs <- instantiateFull =<< do
List.filter (isLvl . clValue) . map theConstraint <$> getAllConstraints
unless (null lvlcs) $ do
reportSDoc "tc.constr.lvl" 40 $ vcat
[ "simplifying level constraint" <+> prettyTCM c
, nest 2 $ hang "using" 2 $ prettyTCM lvlcs
]
Try to simplify @c@ using the other constraints .
return $ simplifyLevelConstraint c $ map clValue lvlcs
| otherwise = return Nothing
wakeConstraintsTCM :: (ProblemConstraint-> TCM Bool) -> TCM ()
wakeConstraintsTCM wake = do
c <- useR stSleepingConstraints
(wakeup, sleepin) <- partitionM wake c
reportSLn "tc.constr.wake" 50 $
"waking up " ++ show (List.map (Set.toList . constraintProblems) wakeup) ++ "\n" ++
" still sleeping: " ++ show (List.map (Set.toList . constraintProblems) sleepin)
modifySleepingConstraints $ const sleepin
modifyAwakeConstraints (++ wakeup)
stealConstraintsTCM :: ProblemId -> TCM ()
stealConstraintsTCM pid = do
current <- asksTC envActiveProblems
reportSLn "tc.constr.steal" 50 $ "problem " ++ show (Set.toList current) ++ " is stealing problem " ++ show pid ++ "'s constraints!"
let rename pc@(PConstr pids c) | Set.member pid pids = PConstr (Set.union current pids) c
| otherwise = pc
whenM (Set.member pid <$> asksTC envActiveProblems) __IMPOSSIBLE__
modifyAwakeConstraints $ List.map rename
modifySleepingConstraints $ List.map rename
noConstraints
:: (MonadConstraint m, MonadWarning m, MonadError TCErr m, MonadFresh ProblemId m)
=> m a -> m a
noConstraints problem = do
(pid, x) <- newProblem problem
cs <- getConstraintsForProblem pid
unless (null cs) $ do
w <- warning_ (UnsolvedConstraints cs)
typeError $ NonFatalErrors [ w ]
return x
newProblem
:: (MonadFresh ProblemId m, MonadConstraint m)
=> m a -> m (ProblemId, a)
newProblem action = do
pid <- fresh
x <- nowSolvingConstraints $ solvingProblem pid action
solveAwakeConstraints
return (pid, x)
newProblem_
:: (MonadFresh ProblemId m, MonadConstraint m)
=> m a -> m ProblemId
newProblem_ action = fst <$> newProblem action
ifNoConstraints :: TCM a -> (a -> TCM b) -> (ProblemId -> a -> TCM b) -> TCM b
ifNoConstraints check ifNo ifCs = do
(pid, x) <- newProblem check
ifM (isProblemSolved pid) (ifNo x) (ifCs pid x)
ifNoConstraints_ :: TCM () -> TCM a -> (ProblemId -> TCM a) -> TCM a
ifNoConstraints_ check ifNo ifCs = ifNoConstraints check (const ifNo) (\pid _ -> ifCs pid)
| @guardConstraint c blocker@ tries to solve @blocker@ first .
If successful without constraints , it moves on to solve @c@ , otherwise it
to the @blocker@-generated constraints @cs@.
guardConstraint :: Constraint -> TCM () -> TCM ()
guardConstraint c blocker =
ifNoConstraints_ blocker (solveConstraint c) (addConstraint . Guarded c)
whenConstraints :: TCM () -> TCM () -> TCM ()
whenConstraints action handler =
ifNoConstraints_ action (return ()) $ \pid -> do
stealConstraints pid
handler
wakeConstraints' :: (ProblemConstraint -> TCM Bool) -> TCM ()
wakeConstraints' p = do
skipInstance <- shouldPostponeInstanceSearch
wakeConstraints (\ c -> (&&) (not $ skipInstance && isInstanceConstraint (clValue $ theConstraint c)) <$> p c)
wakeupConstraints :: MetaId -> TCM ()
wakeupConstraints x = do
wakeConstraints' (return . mentionsMeta x)
solveAwakeConstraints
wakeupConstraints_ :: TCM ()
wakeupConstraints_ = do
wakeConstraints' (return . const True)
solveAwakeConstraints
solveAwakeConstraints :: (MonadConstraint m) => m ()
solveAwakeConstraints = solveAwakeConstraints' False
solveAwakeConstraints' :: (MonadConstraint m) => Bool -> m ()
solveAwakeConstraints' = solveSomeAwakeConstraints (const True)
| Solve awake constraints matching the predicate . If the second argument is
solveSomeAwakeConstraintsTCM :: (ProblemConstraint -> Bool) -> Bool -> TCM ()
solveSomeAwakeConstraintsTCM solveThis force = do
verboseS "profile.constraints" 10 $ liftTCM $ tickMax "max-open-constraints" . List.genericLength =<< getAllConstraints
whenM ((force ||) . not <$> isSolvingConstraints) $ nowSolvingConstraints $ do
Ulf , 2016 - 12 - 06 : Do n't inherit problems here ! Stored constraints
locallyTC eActiveProblems (const Set.empty) solve
where
solve = do
reportSDoc "tc.constr.solve" 10 $ hsep [ "Solving awake constraints."
, text . show . length =<< getAwakeConstraints
, "remaining." ]
whenJustM (takeAwakeConstraint' solveThis) $ \ c -> do
withConstraint solveConstraint c
solve
solveConstraintTCM :: Constraint -> TCM ()
solveConstraintTCM c = do
verboseS "profile.constraints" 10 $ liftTCM $ tick "attempted-constraints"
verboseBracket "tc.constr.solve" 20 "solving constraint" $ do
pids <- asksTC envActiveProblems
reportSDoc "tc.constr.solve.constr" 20 $ text (show $ Set.toList pids) <+> prettyTCM c
solveConstraint_ c
solveConstraint_ :: Constraint -> TCM ()
solveConstraint_ (ValueCmp cmp a u v) = compareAs cmp a u v
solveConstraint_ (ValueCmpOnFace cmp p a u v) = compareTermOnFace cmp p a u v
solveConstraint_ (ElimCmp cmp fs a e u v) = compareElims cmp fs a e u v
solveConstraint_ (TelCmp a b cmp tela telb) = compareTel a b cmp tela telb
solveConstraint_ (SortCmp cmp s1 s2) = compareSort cmp s1 s2
solveConstraint_ (LevelCmp cmp a b) = compareLevel cmp a b
solveConstraint_ c0@(Guarded c pid) = do
ifM (isProblemSolved pid)
reportSLn "tc.constr.solve" 50 $ "Guarding problem " ++ show pid ++ " is solved, moving on..."
solveConstraint_ c)
reportSLn "tc.constr.solve" 50 $ "Guarding problem " ++ show pid ++ " is still unsolved."
addConstraint c0
solveConstraint_ (IsEmpty r t) = ensureEmptyType r t
solveConstraint_ (CheckSizeLtSat t) = checkSizeLtSat t
solveConstraint_ (UnquoteTactic _ tac hole goal) = unquoteTactic tac hole goal
solveConstraint_ (UnBlock m) =
ifM (isFrozen m `or2M` (not <$> asksTC envAssignMetas)) (addConstraint $ UnBlock m) $ do
inst <- mvInstantiation <$> lookupMeta m
reportSDoc "tc.constr.unblock" 15 $ text ("unblocking a metavar yields the constraint: " ++ show inst)
case inst of
BlockedConst t -> do
reportSDoc "tc.constr.blocked" 15 $
text ("blocked const " ++ prettyShow m ++ " :=") <+> prettyTCM t
assignTerm m [] t
PostponedTypeCheckingProblem cl unblock -> enterClosure cl $ \prob -> do
ifNotM unblock (addConstraint $ UnBlock m) $ do
tel <- getContextTelescope
v <- liftTCM $ checkTypeCheckingProblem prob
assignTerm m (telToArgs tel) v
, 2009 - 02 - 09 , the following were IMPOSSIBLE cases
metas ( not sure why it does , ? )
, 2017 - 07 - 11 :
some metas with infinity but does not clean up the UnBlock constraints .
See also issue # 2637 .
Ulf , 2018 - 04 - 30 : The size solver should n't touch blocked terms ! They have
InstV{} -> __IMPOSSIBLE__
Open -> __IMPOSSIBLE__
OpenInstance -> __IMPOSSIBLE__
solveConstraint_ (FindInstance m b cands) = findInstance m cands
solveConstraint_ (CheckFunDef d i q cs) = withoutCache $
re # 3498 : checking a fundef would normally be cached , but here it 's
checkFunDef d i q cs
solveConstraint_ (HasBiggerSort a) = hasBiggerSort a
solveConstraint_ (HasPTSRule a b) = hasPTSRule a b
solveConstraint_ (CheckMetaInst m) = checkMetaInst m
checkTypeCheckingProblem :: TypeCheckingProblem -> TCM Term
checkTypeCheckingProblem p = case p of
CheckExpr cmp e t -> checkExpr' cmp e t
CheckArgs eh r args t0 t1 k -> checkArguments eh r args t0 t1 k
CheckProjAppToKnownPrincipalArg cmp e o ds args t k v0 pt ->
checkProjAppToKnownPrincipalArg cmp e o ds args t k v0 pt
CheckLambda cmp args body target -> checkPostponedLambda cmp args body target
DoQuoteTerm cmp et t -> doQuoteTerm cmp et t
debugConstraints :: TCM ()
debugConstraints = verboseS "tc.constr" 50 $ do
awake <- useTC stAwakeConstraints
sleeping <- useTC stSleepingConstraints
reportSDoc "tc.constr" 50 $ vcat
[ "Current constraints"
, nest 2 $ vcat [ "awake " <+> vcat (map prettyTCM awake)
, "asleep" <+> vcat (map prettyTCM sleeping) ] ]
|
096ab6a967da051b3d8b4a4c501b2b0c27a7136b2be9357c7017f3254ab73945 | vaibhavsagar/experiments | CallIn.hs | --
Demonstrating explicit calling in to from
-- .NET code (directly via the Hugs Server API).
--
-- The external code calling in can be found in print.cs
--
module CallIn where
import Dotnet
foreign import dotnet
"static [print.dll]Print.p"
printIt :: Object () -> IO ()
callIn :: IO ()
callIn = do
mildly bogus to create Hugs . Server object , since
-- its methods are all static..
serv <- new "Hugs.Server"
print serv
printIt serv
( invokeStatic " [ print.dll]Print " " p " serv ) : : IO ( Object )
putStrLn "done"
-- the entry point that will be called from Print.p()
greeting = putStrLn "In Haskell: Greetings from Hugs98.NET"
| null | https://raw.githubusercontent.com/vaibhavsagar/experiments/378d7ba97eabfc7bbeaa4116380369ea6612bfeb/hugs/dotnet/examples/callin/CallIn.hs | haskell |
.NET code (directly via the Hugs Server API).
The external code calling in can be found in print.cs
its methods are all static..
the entry point that will be called from Print.p() | Demonstrating explicit calling in to from
module CallIn where
import Dotnet
foreign import dotnet
"static [print.dll]Print.p"
printIt :: Object () -> IO ()
callIn :: IO ()
callIn = do
mildly bogus to create Hugs . Server object , since
serv <- new "Hugs.Server"
print serv
printIt serv
( invokeStatic " [ print.dll]Print " " p " serv ) : : IO ( Object )
putStrLn "done"
greeting = putStrLn "In Haskell: Greetings from Hugs98.NET"
|
d41abd99e0cb645031d7d658ac56c0e463041c705fad441918196930e5e14ad5 | clojure-interop/aws-api | AmazonElasticFileSystemAsyncClient.clj | (ns com.amazonaws.services.elasticfilesystem.AmazonElasticFileSystemAsyncClient
"Client for accessing EFS asynchronously. Each asynchronous method will return a Java Future object representing the
overloads which accept an AsyncHandler can be used to receive notification when an
asynchronous operation completes.
Amazon Elastic File System
Amazon Elastic File System (Amazon EFS) provides simple, scalable file storage for use with Amazon EC2 instances in
the AWS Cloud. With Amazon EFS, storage capacity is elastic, growing and shrinking automatically as you add and
remove files, so your applications have the storage they need, when they need it. For more information, see the User Guide."
(:refer-clojure :only [require comment defn ->])
(:import [com.amazonaws.services.elasticfilesystem AmazonElasticFileSystemAsyncClient]))
(defn ->amazon-elastic-file-system-async-client
"Constructor.
Deprecated. use AwsClientBuilder.withCredentials(AWSCredentialsProvider) and
AwsClientBuilder.withClientConfiguration(ClientConfiguration) and
AwsAsyncClientBuilder.withExecutorFactory(com.amazonaws.client.builder.ExecutorFactory)
aws-credentials - The AWS credentials (access key ID and secret key) to use when authenticating with AWS services. - `com.amazonaws.auth.AWSCredentials`
client-configuration - Client configuration options (ex: max retry limit, proxy settings, etc). - `com.amazonaws.ClientConfiguration`
executor-service - The executor service by which all asynchronous requests will be executed. - `java.util.concurrent.ExecutorService`"
(^AmazonElasticFileSystemAsyncClient [^com.amazonaws.auth.AWSCredentials aws-credentials ^com.amazonaws.ClientConfiguration client-configuration ^java.util.concurrent.ExecutorService executor-service]
(new AmazonElasticFileSystemAsyncClient aws-credentials client-configuration executor-service))
(^AmazonElasticFileSystemAsyncClient [^com.amazonaws.auth.AWSCredentials aws-credentials ^java.util.concurrent.ExecutorService executor-service]
(new AmazonElasticFileSystemAsyncClient aws-credentials executor-service))
(^AmazonElasticFileSystemAsyncClient [^com.amazonaws.ClientConfiguration client-configuration]
(new AmazonElasticFileSystemAsyncClient client-configuration))
(^AmazonElasticFileSystemAsyncClient []
(new AmazonElasticFileSystemAsyncClient )))
(defn *async-builder
"returns: `com.amazonaws.services.elasticfilesystem.AmazonElasticFileSystemAsyncClientBuilder`"
(^com.amazonaws.services.elasticfilesystem.AmazonElasticFileSystemAsyncClientBuilder []
(AmazonElasticFileSystemAsyncClient/asyncBuilder )))
(defn update-file-system-async
"Description copied from interface: AmazonElasticFileSystemAsync
request - `com.amazonaws.services.elasticfilesystem.model.UpdateFileSystemRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the UpdateFileSystem operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.elasticfilesystem.model.UpdateFileSystemResult>`"
(^java.util.concurrent.Future [^AmazonElasticFileSystemAsyncClient this ^com.amazonaws.services.elasticfilesystem.model.UpdateFileSystemRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.updateFileSystemAsync request async-handler)))
(^java.util.concurrent.Future [^AmazonElasticFileSystemAsyncClient this ^com.amazonaws.services.elasticfilesystem.model.UpdateFileSystemRequest request]
(-> this (.updateFileSystemAsync request))))
(defn get-executor-service
"Returns the executor service used by this client to execute async requests.
returns: The executor service used by this client to execute async requests. - `java.util.concurrent.ExecutorService`"
(^java.util.concurrent.ExecutorService [^AmazonElasticFileSystemAsyncClient this]
(-> this (.getExecutorService))))
(defn delete-tags-async
"Description copied from interface: AmazonElasticFileSystemAsync
request - `com.amazonaws.services.elasticfilesystem.model.DeleteTagsRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the DeleteTags operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.elasticfilesystem.model.DeleteTagsResult>`"
(^java.util.concurrent.Future [^AmazonElasticFileSystemAsyncClient this ^com.amazonaws.services.elasticfilesystem.model.DeleteTagsRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.deleteTagsAsync request async-handler)))
(^java.util.concurrent.Future [^AmazonElasticFileSystemAsyncClient this ^com.amazonaws.services.elasticfilesystem.model.DeleteTagsRequest request]
(-> this (.deleteTagsAsync request))))
(defn describe-lifecycle-configuration-async
"Description copied from interface: AmazonElasticFileSystemAsync
request - `com.amazonaws.services.elasticfilesystem.model.DescribeLifecycleConfigurationRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the DescribeLifecycleConfiguration operation returned by the
service. - `java.util.concurrent.Future<com.amazonaws.services.elasticfilesystem.model.DescribeLifecycleConfigurationResult>`"
(^java.util.concurrent.Future [^AmazonElasticFileSystemAsyncClient this ^com.amazonaws.services.elasticfilesystem.model.DescribeLifecycleConfigurationRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.describeLifecycleConfigurationAsync request async-handler)))
(^java.util.concurrent.Future [^AmazonElasticFileSystemAsyncClient this ^com.amazonaws.services.elasticfilesystem.model.DescribeLifecycleConfigurationRequest request]
(-> this (.describeLifecycleConfigurationAsync request))))
(defn shutdown
"Shuts down the client, releasing all managed resources. This includes forcibly terminating all pending
asynchronous service calls. Clients who wish to give pending asynchronous service calls time to complete should
call getExecutorService().shutdown() followed by getExecutorService().awaitTermination() prior to
calling this method."
([^AmazonElasticFileSystemAsyncClient this]
(-> this (.shutdown))))
(defn delete-mount-target-async
"Description copied from interface: AmazonElasticFileSystemAsync
request - `com.amazonaws.services.elasticfilesystem.model.DeleteMountTargetRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the DeleteMountTarget operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.elasticfilesystem.model.DeleteMountTargetResult>`"
(^java.util.concurrent.Future [^AmazonElasticFileSystemAsyncClient this ^com.amazonaws.services.elasticfilesystem.model.DeleteMountTargetRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.deleteMountTargetAsync request async-handler)))
(^java.util.concurrent.Future [^AmazonElasticFileSystemAsyncClient this ^com.amazonaws.services.elasticfilesystem.model.DeleteMountTargetRequest request]
(-> this (.deleteMountTargetAsync request))))
(defn put-lifecycle-configuration-async
"Description copied from interface: AmazonElasticFileSystemAsync
request - `com.amazonaws.services.elasticfilesystem.model.PutLifecycleConfigurationRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the PutLifecycleConfiguration operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.elasticfilesystem.model.PutLifecycleConfigurationResult>`"
(^java.util.concurrent.Future [^AmazonElasticFileSystemAsyncClient this ^com.amazonaws.services.elasticfilesystem.model.PutLifecycleConfigurationRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.putLifecycleConfigurationAsync request async-handler)))
(^java.util.concurrent.Future [^AmazonElasticFileSystemAsyncClient this ^com.amazonaws.services.elasticfilesystem.model.PutLifecycleConfigurationRequest request]
(-> this (.putLifecycleConfigurationAsync request))))
(defn modify-mount-target-security-groups-async
"Description copied from interface: AmazonElasticFileSystemAsync
request - `com.amazonaws.services.elasticfilesystem.model.ModifyMountTargetSecurityGroupsRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the ModifyMountTargetSecurityGroups operation returned by the
service. - `java.util.concurrent.Future<com.amazonaws.services.elasticfilesystem.model.ModifyMountTargetSecurityGroupsResult>`"
(^java.util.concurrent.Future [^AmazonElasticFileSystemAsyncClient this ^com.amazonaws.services.elasticfilesystem.model.ModifyMountTargetSecurityGroupsRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.modifyMountTargetSecurityGroupsAsync request async-handler)))
(^java.util.concurrent.Future [^AmazonElasticFileSystemAsyncClient this ^com.amazonaws.services.elasticfilesystem.model.ModifyMountTargetSecurityGroupsRequest request]
(-> this (.modifyMountTargetSecurityGroupsAsync request))))
(defn create-file-system-async
"Description copied from interface: AmazonElasticFileSystemAsync
request - `com.amazonaws.services.elasticfilesystem.model.CreateFileSystemRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the CreateFileSystem operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.elasticfilesystem.model.CreateFileSystemResult>`"
(^java.util.concurrent.Future [^AmazonElasticFileSystemAsyncClient this ^com.amazonaws.services.elasticfilesystem.model.CreateFileSystemRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.createFileSystemAsync request async-handler)))
(^java.util.concurrent.Future [^AmazonElasticFileSystemAsyncClient this ^com.amazonaws.services.elasticfilesystem.model.CreateFileSystemRequest request]
(-> this (.createFileSystemAsync request))))
(defn describe-mount-targets-async
"Description copied from interface: AmazonElasticFileSystemAsync
request - `com.amazonaws.services.elasticfilesystem.model.DescribeMountTargetsRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the DescribeMountTargets operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.elasticfilesystem.model.DescribeMountTargetsResult>`"
(^java.util.concurrent.Future [^AmazonElasticFileSystemAsyncClient this ^com.amazonaws.services.elasticfilesystem.model.DescribeMountTargetsRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.describeMountTargetsAsync request async-handler)))
(^java.util.concurrent.Future [^AmazonElasticFileSystemAsyncClient this ^com.amazonaws.services.elasticfilesystem.model.DescribeMountTargetsRequest request]
(-> this (.describeMountTargetsAsync request))))
(defn create-tags-async
"Description copied from interface: AmazonElasticFileSystemAsync
request - `com.amazonaws.services.elasticfilesystem.model.CreateTagsRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the CreateTags operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.elasticfilesystem.model.CreateTagsResult>`"
(^java.util.concurrent.Future [^AmazonElasticFileSystemAsyncClient this ^com.amazonaws.services.elasticfilesystem.model.CreateTagsRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.createTagsAsync request async-handler)))
(^java.util.concurrent.Future [^AmazonElasticFileSystemAsyncClient this ^com.amazonaws.services.elasticfilesystem.model.CreateTagsRequest request]
(-> this (.createTagsAsync request))))
(defn delete-file-system-async
"Description copied from interface: AmazonElasticFileSystemAsync
request - `com.amazonaws.services.elasticfilesystem.model.DeleteFileSystemRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the DeleteFileSystem operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.elasticfilesystem.model.DeleteFileSystemResult>`"
(^java.util.concurrent.Future [^AmazonElasticFileSystemAsyncClient this ^com.amazonaws.services.elasticfilesystem.model.DeleteFileSystemRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.deleteFileSystemAsync request async-handler)))
(^java.util.concurrent.Future [^AmazonElasticFileSystemAsyncClient this ^com.amazonaws.services.elasticfilesystem.model.DeleteFileSystemRequest request]
(-> this (.deleteFileSystemAsync request))))
(defn describe-file-systems-async
"Description copied from interface: AmazonElasticFileSystemAsync
request - `com.amazonaws.services.elasticfilesystem.model.DescribeFileSystemsRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the DescribeFileSystems operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.elasticfilesystem.model.DescribeFileSystemsResult>`"
(^java.util.concurrent.Future [^AmazonElasticFileSystemAsyncClient this ^com.amazonaws.services.elasticfilesystem.model.DescribeFileSystemsRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.describeFileSystemsAsync request async-handler)))
(^java.util.concurrent.Future [^AmazonElasticFileSystemAsyncClient this ^com.amazonaws.services.elasticfilesystem.model.DescribeFileSystemsRequest request]
(-> this (.describeFileSystemsAsync request)))
(^java.util.concurrent.Future [^AmazonElasticFileSystemAsyncClient this]
(-> this (.describeFileSystemsAsync))))
(defn describe-tags-async
"Description copied from interface: AmazonElasticFileSystemAsync
request - `com.amazonaws.services.elasticfilesystem.model.DescribeTagsRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the DescribeTags operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.elasticfilesystem.model.DescribeTagsResult>`"
(^java.util.concurrent.Future [^AmazonElasticFileSystemAsyncClient this ^com.amazonaws.services.elasticfilesystem.model.DescribeTagsRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.describeTagsAsync request async-handler)))
(^java.util.concurrent.Future [^AmazonElasticFileSystemAsyncClient this ^com.amazonaws.services.elasticfilesystem.model.DescribeTagsRequest request]
(-> this (.describeTagsAsync request))))
(defn create-mount-target-async
"Description copied from interface: AmazonElasticFileSystemAsync
request - `com.amazonaws.services.elasticfilesystem.model.CreateMountTargetRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the CreateMountTarget operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.elasticfilesystem.model.CreateMountTargetResult>`"
(^java.util.concurrent.Future [^AmazonElasticFileSystemAsyncClient this ^com.amazonaws.services.elasticfilesystem.model.CreateMountTargetRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.createMountTargetAsync request async-handler)))
(^java.util.concurrent.Future [^AmazonElasticFileSystemAsyncClient this ^com.amazonaws.services.elasticfilesystem.model.CreateMountTargetRequest request]
(-> this (.createMountTargetAsync request))))
(defn describe-mount-target-security-groups-async
"Description copied from interface: AmazonElasticFileSystemAsync
request - `com.amazonaws.services.elasticfilesystem.model.DescribeMountTargetSecurityGroupsRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the DescribeMountTargetSecurityGroups operation returned by the
service. - `java.util.concurrent.Future<com.amazonaws.services.elasticfilesystem.model.DescribeMountTargetSecurityGroupsResult>`"
(^java.util.concurrent.Future [^AmazonElasticFileSystemAsyncClient this ^com.amazonaws.services.elasticfilesystem.model.DescribeMountTargetSecurityGroupsRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.describeMountTargetSecurityGroupsAsync request async-handler)))
(^java.util.concurrent.Future [^AmazonElasticFileSystemAsyncClient this ^com.amazonaws.services.elasticfilesystem.model.DescribeMountTargetSecurityGroupsRequest request]
(-> this (.describeMountTargetSecurityGroupsAsync request))))
| null | https://raw.githubusercontent.com/clojure-interop/aws-api/59249b43d3bfaff0a79f5f4f8b7bc22518a3bf14/com.amazonaws.services.elasticfilesystem/src/com/amazonaws/services/elasticfilesystem/AmazonElasticFileSystemAsyncClient.clj | clojure | (ns com.amazonaws.services.elasticfilesystem.AmazonElasticFileSystemAsyncClient
"Client for accessing EFS asynchronously. Each asynchronous method will return a Java Future object representing the
overloads which accept an AsyncHandler can be used to receive notification when an
asynchronous operation completes.
Amazon Elastic File System
Amazon Elastic File System (Amazon EFS) provides simple, scalable file storage for use with Amazon EC2 instances in
the AWS Cloud. With Amazon EFS, storage capacity is elastic, growing and shrinking automatically as you add and
remove files, so your applications have the storage they need, when they need it. For more information, see the User Guide."
(:refer-clojure :only [require comment defn ->])
(:import [com.amazonaws.services.elasticfilesystem AmazonElasticFileSystemAsyncClient]))
(defn ->amazon-elastic-file-system-async-client
"Constructor.
Deprecated. use AwsClientBuilder.withCredentials(AWSCredentialsProvider) and
AwsClientBuilder.withClientConfiguration(ClientConfiguration) and
AwsAsyncClientBuilder.withExecutorFactory(com.amazonaws.client.builder.ExecutorFactory)
aws-credentials - The AWS credentials (access key ID and secret key) to use when authenticating with AWS services. - `com.amazonaws.auth.AWSCredentials`
client-configuration - Client configuration options (ex: max retry limit, proxy settings, etc). - `com.amazonaws.ClientConfiguration`
executor-service - The executor service by which all asynchronous requests will be executed. - `java.util.concurrent.ExecutorService`"
(^AmazonElasticFileSystemAsyncClient [^com.amazonaws.auth.AWSCredentials aws-credentials ^com.amazonaws.ClientConfiguration client-configuration ^java.util.concurrent.ExecutorService executor-service]
(new AmazonElasticFileSystemAsyncClient aws-credentials client-configuration executor-service))
(^AmazonElasticFileSystemAsyncClient [^com.amazonaws.auth.AWSCredentials aws-credentials ^java.util.concurrent.ExecutorService executor-service]
(new AmazonElasticFileSystemAsyncClient aws-credentials executor-service))
(^AmazonElasticFileSystemAsyncClient [^com.amazonaws.ClientConfiguration client-configuration]
(new AmazonElasticFileSystemAsyncClient client-configuration))
(^AmazonElasticFileSystemAsyncClient []
(new AmazonElasticFileSystemAsyncClient )))
(defn *async-builder
"returns: `com.amazonaws.services.elasticfilesystem.AmazonElasticFileSystemAsyncClientBuilder`"
(^com.amazonaws.services.elasticfilesystem.AmazonElasticFileSystemAsyncClientBuilder []
(AmazonElasticFileSystemAsyncClient/asyncBuilder )))
(defn update-file-system-async
"Description copied from interface: AmazonElasticFileSystemAsync
request - `com.amazonaws.services.elasticfilesystem.model.UpdateFileSystemRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the UpdateFileSystem operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.elasticfilesystem.model.UpdateFileSystemResult>`"
(^java.util.concurrent.Future [^AmazonElasticFileSystemAsyncClient this ^com.amazonaws.services.elasticfilesystem.model.UpdateFileSystemRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.updateFileSystemAsync request async-handler)))
(^java.util.concurrent.Future [^AmazonElasticFileSystemAsyncClient this ^com.amazonaws.services.elasticfilesystem.model.UpdateFileSystemRequest request]
(-> this (.updateFileSystemAsync request))))
(defn get-executor-service
"Returns the executor service used by this client to execute async requests.
returns: The executor service used by this client to execute async requests. - `java.util.concurrent.ExecutorService`"
(^java.util.concurrent.ExecutorService [^AmazonElasticFileSystemAsyncClient this]
(-> this (.getExecutorService))))
(defn delete-tags-async
"Description copied from interface: AmazonElasticFileSystemAsync
request - `com.amazonaws.services.elasticfilesystem.model.DeleteTagsRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the DeleteTags operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.elasticfilesystem.model.DeleteTagsResult>`"
(^java.util.concurrent.Future [^AmazonElasticFileSystemAsyncClient this ^com.amazonaws.services.elasticfilesystem.model.DeleteTagsRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.deleteTagsAsync request async-handler)))
(^java.util.concurrent.Future [^AmazonElasticFileSystemAsyncClient this ^com.amazonaws.services.elasticfilesystem.model.DeleteTagsRequest request]
(-> this (.deleteTagsAsync request))))
(defn describe-lifecycle-configuration-async
"Description copied from interface: AmazonElasticFileSystemAsync
request - `com.amazonaws.services.elasticfilesystem.model.DescribeLifecycleConfigurationRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the DescribeLifecycleConfiguration operation returned by the
service. - `java.util.concurrent.Future<com.amazonaws.services.elasticfilesystem.model.DescribeLifecycleConfigurationResult>`"
(^java.util.concurrent.Future [^AmazonElasticFileSystemAsyncClient this ^com.amazonaws.services.elasticfilesystem.model.DescribeLifecycleConfigurationRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.describeLifecycleConfigurationAsync request async-handler)))
(^java.util.concurrent.Future [^AmazonElasticFileSystemAsyncClient this ^com.amazonaws.services.elasticfilesystem.model.DescribeLifecycleConfigurationRequest request]
(-> this (.describeLifecycleConfigurationAsync request))))
(defn shutdown
"Shuts down the client, releasing all managed resources. This includes forcibly terminating all pending
asynchronous service calls. Clients who wish to give pending asynchronous service calls time to complete should
call getExecutorService().shutdown() followed by getExecutorService().awaitTermination() prior to
calling this method."
([^AmazonElasticFileSystemAsyncClient this]
(-> this (.shutdown))))
(defn delete-mount-target-async
"Description copied from interface: AmazonElasticFileSystemAsync
request - `com.amazonaws.services.elasticfilesystem.model.DeleteMountTargetRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the DeleteMountTarget operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.elasticfilesystem.model.DeleteMountTargetResult>`"
(^java.util.concurrent.Future [^AmazonElasticFileSystemAsyncClient this ^com.amazonaws.services.elasticfilesystem.model.DeleteMountTargetRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.deleteMountTargetAsync request async-handler)))
(^java.util.concurrent.Future [^AmazonElasticFileSystemAsyncClient this ^com.amazonaws.services.elasticfilesystem.model.DeleteMountTargetRequest request]
(-> this (.deleteMountTargetAsync request))))
(defn put-lifecycle-configuration-async
"Description copied from interface: AmazonElasticFileSystemAsync
request - `com.amazonaws.services.elasticfilesystem.model.PutLifecycleConfigurationRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the PutLifecycleConfiguration operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.elasticfilesystem.model.PutLifecycleConfigurationResult>`"
(^java.util.concurrent.Future [^AmazonElasticFileSystemAsyncClient this ^com.amazonaws.services.elasticfilesystem.model.PutLifecycleConfigurationRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.putLifecycleConfigurationAsync request async-handler)))
(^java.util.concurrent.Future [^AmazonElasticFileSystemAsyncClient this ^com.amazonaws.services.elasticfilesystem.model.PutLifecycleConfigurationRequest request]
(-> this (.putLifecycleConfigurationAsync request))))
(defn modify-mount-target-security-groups-async
"Description copied from interface: AmazonElasticFileSystemAsync
request - `com.amazonaws.services.elasticfilesystem.model.ModifyMountTargetSecurityGroupsRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the ModifyMountTargetSecurityGroups operation returned by the
service. - `java.util.concurrent.Future<com.amazonaws.services.elasticfilesystem.model.ModifyMountTargetSecurityGroupsResult>`"
(^java.util.concurrent.Future [^AmazonElasticFileSystemAsyncClient this ^com.amazonaws.services.elasticfilesystem.model.ModifyMountTargetSecurityGroupsRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.modifyMountTargetSecurityGroupsAsync request async-handler)))
(^java.util.concurrent.Future [^AmazonElasticFileSystemAsyncClient this ^com.amazonaws.services.elasticfilesystem.model.ModifyMountTargetSecurityGroupsRequest request]
(-> this (.modifyMountTargetSecurityGroupsAsync request))))
(defn create-file-system-async
"Description copied from interface: AmazonElasticFileSystemAsync
request - `com.amazonaws.services.elasticfilesystem.model.CreateFileSystemRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the CreateFileSystem operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.elasticfilesystem.model.CreateFileSystemResult>`"
(^java.util.concurrent.Future [^AmazonElasticFileSystemAsyncClient this ^com.amazonaws.services.elasticfilesystem.model.CreateFileSystemRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.createFileSystemAsync request async-handler)))
(^java.util.concurrent.Future [^AmazonElasticFileSystemAsyncClient this ^com.amazonaws.services.elasticfilesystem.model.CreateFileSystemRequest request]
(-> this (.createFileSystemAsync request))))
(defn describe-mount-targets-async
"Description copied from interface: AmazonElasticFileSystemAsync
request - `com.amazonaws.services.elasticfilesystem.model.DescribeMountTargetsRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the DescribeMountTargets operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.elasticfilesystem.model.DescribeMountTargetsResult>`"
(^java.util.concurrent.Future [^AmazonElasticFileSystemAsyncClient this ^com.amazonaws.services.elasticfilesystem.model.DescribeMountTargetsRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.describeMountTargetsAsync request async-handler)))
(^java.util.concurrent.Future [^AmazonElasticFileSystemAsyncClient this ^com.amazonaws.services.elasticfilesystem.model.DescribeMountTargetsRequest request]
(-> this (.describeMountTargetsAsync request))))
(defn create-tags-async
"Description copied from interface: AmazonElasticFileSystemAsync
request - `com.amazonaws.services.elasticfilesystem.model.CreateTagsRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the CreateTags operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.elasticfilesystem.model.CreateTagsResult>`"
(^java.util.concurrent.Future [^AmazonElasticFileSystemAsyncClient this ^com.amazonaws.services.elasticfilesystem.model.CreateTagsRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.createTagsAsync request async-handler)))
(^java.util.concurrent.Future [^AmazonElasticFileSystemAsyncClient this ^com.amazonaws.services.elasticfilesystem.model.CreateTagsRequest request]
(-> this (.createTagsAsync request))))
(defn delete-file-system-async
"Description copied from interface: AmazonElasticFileSystemAsync
request - `com.amazonaws.services.elasticfilesystem.model.DeleteFileSystemRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the DeleteFileSystem operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.elasticfilesystem.model.DeleteFileSystemResult>`"
(^java.util.concurrent.Future [^AmazonElasticFileSystemAsyncClient this ^com.amazonaws.services.elasticfilesystem.model.DeleteFileSystemRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.deleteFileSystemAsync request async-handler)))
(^java.util.concurrent.Future [^AmazonElasticFileSystemAsyncClient this ^com.amazonaws.services.elasticfilesystem.model.DeleteFileSystemRequest request]
(-> this (.deleteFileSystemAsync request))))
(defn describe-file-systems-async
"Description copied from interface: AmazonElasticFileSystemAsync
request - `com.amazonaws.services.elasticfilesystem.model.DescribeFileSystemsRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the DescribeFileSystems operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.elasticfilesystem.model.DescribeFileSystemsResult>`"
(^java.util.concurrent.Future [^AmazonElasticFileSystemAsyncClient this ^com.amazonaws.services.elasticfilesystem.model.DescribeFileSystemsRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.describeFileSystemsAsync request async-handler)))
(^java.util.concurrent.Future [^AmazonElasticFileSystemAsyncClient this ^com.amazonaws.services.elasticfilesystem.model.DescribeFileSystemsRequest request]
(-> this (.describeFileSystemsAsync request)))
(^java.util.concurrent.Future [^AmazonElasticFileSystemAsyncClient this]
(-> this (.describeFileSystemsAsync))))
(defn describe-tags-async
"Description copied from interface: AmazonElasticFileSystemAsync
request - `com.amazonaws.services.elasticfilesystem.model.DescribeTagsRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the DescribeTags operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.elasticfilesystem.model.DescribeTagsResult>`"
(^java.util.concurrent.Future [^AmazonElasticFileSystemAsyncClient this ^com.amazonaws.services.elasticfilesystem.model.DescribeTagsRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.describeTagsAsync request async-handler)))
(^java.util.concurrent.Future [^AmazonElasticFileSystemAsyncClient this ^com.amazonaws.services.elasticfilesystem.model.DescribeTagsRequest request]
(-> this (.describeTagsAsync request))))
(defn create-mount-target-async
"Description copied from interface: AmazonElasticFileSystemAsync
request - `com.amazonaws.services.elasticfilesystem.model.CreateMountTargetRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the CreateMountTarget operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.elasticfilesystem.model.CreateMountTargetResult>`"
(^java.util.concurrent.Future [^AmazonElasticFileSystemAsyncClient this ^com.amazonaws.services.elasticfilesystem.model.CreateMountTargetRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.createMountTargetAsync request async-handler)))
(^java.util.concurrent.Future [^AmazonElasticFileSystemAsyncClient this ^com.amazonaws.services.elasticfilesystem.model.CreateMountTargetRequest request]
(-> this (.createMountTargetAsync request))))
(defn describe-mount-target-security-groups-async
"Description copied from interface: AmazonElasticFileSystemAsync
request - `com.amazonaws.services.elasticfilesystem.model.DescribeMountTargetSecurityGroupsRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the DescribeMountTargetSecurityGroups operation returned by the
service. - `java.util.concurrent.Future<com.amazonaws.services.elasticfilesystem.model.DescribeMountTargetSecurityGroupsResult>`"
(^java.util.concurrent.Future [^AmazonElasticFileSystemAsyncClient this ^com.amazonaws.services.elasticfilesystem.model.DescribeMountTargetSecurityGroupsRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.describeMountTargetSecurityGroupsAsync request async-handler)))
(^java.util.concurrent.Future [^AmazonElasticFileSystemAsyncClient this ^com.amazonaws.services.elasticfilesystem.model.DescribeMountTargetSecurityGroupsRequest request]
(-> this (.describeMountTargetSecurityGroupsAsync request))))
|
|
77082c808ef8f48079325944ffd9a0cd92681595c2016bd962e744cd39f54d93 | metaocaml/ber-metaocaml | pr5906.ml | (* TEST
* expect
*)
type _ constant =
| Int: int -> int constant
| Bool: bool -> bool constant
type (_, _, _) binop =
| Eq: ('a, 'a, bool) binop
| Leq: ('a, 'a, bool) binop
| Add: (int, int, int) binop
let eval (type a) (type b) (type c) (bop:(a,b,c) binop) (x:a constant)
(y:b constant) : c constant =
match bop, x, y with
| Eq, Bool x, Bool y -> Bool (if x then y else not y)
| Leq, Int x, Int y -> Bool (x <= y)
| Leq, Bool x, Bool y -> Bool (x <= y)
| Add, Int x, Int y -> Int (x + y)
let _ = eval Eq (Int 2) (Int 3)
[%%expect{|
type _ constant = Int : int -> int constant | Bool : bool -> bool constant
type (_, _, _) binop =
Eq : ('a, 'a, bool) binop
| Leq : ('a, 'a, bool) binop
| Add : (int, int, int) binop
Lines 12-16, characters 2-36:
12 | ..match bop, x, y with
13 | | Eq, Bool x, Bool y -> Bool (if x then y else not y)
14 | | Leq, Int x, Int y -> Bool (x <= y)
15 | | Leq, Bool x, Bool y -> Bool (x <= y)
16 | | Add, Int x, Int y -> Int (x + y)
Warning 8: this pattern-matching is not exhaustive.
Here is an example of a case that is not matched:
(Eq, Int _, _)
val eval : ('a, 'b, 'c) binop -> 'a constant -> 'b constant -> 'c constant =
<fun>
Exception: Match_failure ("", 12, 2).
|}];;
| null | https://raw.githubusercontent.com/metaocaml/ber-metaocaml/4992d1f87fc08ccb958817926cf9d1d739caf3a2/testsuite/tests/typing-gadts/pr5906.ml | ocaml | TEST
* expect
|
type _ constant =
| Int: int -> int constant
| Bool: bool -> bool constant
type (_, _, _) binop =
| Eq: ('a, 'a, bool) binop
| Leq: ('a, 'a, bool) binop
| Add: (int, int, int) binop
let eval (type a) (type b) (type c) (bop:(a,b,c) binop) (x:a constant)
(y:b constant) : c constant =
match bop, x, y with
| Eq, Bool x, Bool y -> Bool (if x then y else not y)
| Leq, Int x, Int y -> Bool (x <= y)
| Leq, Bool x, Bool y -> Bool (x <= y)
| Add, Int x, Int y -> Int (x + y)
let _ = eval Eq (Int 2) (Int 3)
[%%expect{|
type _ constant = Int : int -> int constant | Bool : bool -> bool constant
type (_, _, _) binop =
Eq : ('a, 'a, bool) binop
| Leq : ('a, 'a, bool) binop
| Add : (int, int, int) binop
Lines 12-16, characters 2-36:
12 | ..match bop, x, y with
13 | | Eq, Bool x, Bool y -> Bool (if x then y else not y)
14 | | Leq, Int x, Int y -> Bool (x <= y)
15 | | Leq, Bool x, Bool y -> Bool (x <= y)
16 | | Add, Int x, Int y -> Int (x + y)
Warning 8: this pattern-matching is not exhaustive.
Here is an example of a case that is not matched:
(Eq, Int _, _)
val eval : ('a, 'b, 'c) binop -> 'a constant -> 'b constant -> 'c constant =
<fun>
Exception: Match_failure ("", 12, 2).
|}];;
|
e2e006509f39dd2c1d9ed851e7bb1c6d0c0c9c623084fc2c651edc7ca09da937 | csabahruska/jhc-components | CanType.hs | module Support.CanType where
import Control.Monad.Error()
-- This is a simple routine meant to do the minimum amount of work to get the type of something
class CanType a where
type TypeOf a
getType :: a -> (TypeOf a)
instance CanType e => CanType [e] where
type TypeOf [e] = [TypeOf e]
getType es = map getType es
instance CanType e => CanType (Maybe e) where
type TypeOf (Maybe e) = Maybe (TypeOf e)
getType Nothing = Nothing
getType (Just x) = Just (getType x)
instance (CanType e1, CanType e2) => CanType (Either e1 e2) where
type TypeOf (Either e1 e2) = Either (TypeOf e1) (TypeOf e2)
getType (Left x) = Left $ getType x
getType (Right x) = Right $ getType x
| null | https://raw.githubusercontent.com/csabahruska/jhc-components/a7dace481d017f5a83fbfc062bdd2d099133adf1/jhc-common/src/Support/CanType.hs | haskell | This is a simple routine meant to do the minimum amount of work to get the type of something | module Support.CanType where
import Control.Monad.Error()
class CanType a where
type TypeOf a
getType :: a -> (TypeOf a)
instance CanType e => CanType [e] where
type TypeOf [e] = [TypeOf e]
getType es = map getType es
instance CanType e => CanType (Maybe e) where
type TypeOf (Maybe e) = Maybe (TypeOf e)
getType Nothing = Nothing
getType (Just x) = Just (getType x)
instance (CanType e1, CanType e2) => CanType (Either e1 e2) where
type TypeOf (Either e1 e2) = Either (TypeOf e1) (TypeOf e2)
getType (Left x) = Left $ getType x
getType (Right x) = Right $ getType x
|
5eeb3d3084c4a47b88c58773075217d7e34a85d3c9fd14fbb119678f449fb807 | racket/math | poisson-dist.rkt | #lang typed/racket/base
(require racket/performance-hint
racket/promise
"../../flonum.rkt"
"../../vector.rkt"
"../unsafe.rkt"
"../functions/incomplete-gamma.rkt"
(prefix-in impl: "impl/poisson-pdf.rkt")
"impl/poisson-random.rkt"
"normal-dist.rkt"
"dist-struct.rkt"
"utils.rkt")
(provide flpoisson-pdf
flpoisson-cdf
flpoisson-inv-cdf
flpoisson-sample
flpoisson-median
Poisson-Dist poisson-dist poisson-dist-mean)
(: flpoisson-pdf (Flonum Flonum Any -> Flonum))
(define (flpoisson-pdf l k log?)
(cond [(or (l . fl< . 0.0) (not (integer? k))) +nan.0]
[log? (impl:flpoisson-log-pdf l k)]
[else (impl:flpoisson-pdf l k)]))
(: flpoisson-cdf (Flonum Flonum Any Any -> Flonum))
(define (flpoisson-cdf l k log? 1-p?)
(cond [(l . fl< . 0.0) +nan.0]
[log? (fllog-gamma-inc (flfloor (fl+ k 1.0)) l (not 1-p?) #t)]
[else (flgamma-inc (flfloor (fl+ k 1.0)) l (not 1-p?) #t)]))
(: flpoisson-inv-cdf (Flonum Flonum Any Any -> Flonum))
(define (flpoisson-inv-cdf l p log? 1-p?)
(cond [(l . fl< . 0.0) +nan.0]
[(not (flprobability? p log?)) +nan.0]
[(flprobability-one? p log? 1-p?) +inf.0]
[(flprobability-zero? p log? 1-p?) 0.0]
[1-p? (flfind-least-integer
(λ: ([k : Flonum]) ((flpoisson-cdf l k log? 1-p?) . fl< . p))
0.0 +inf.0
(flmax 0.0 (flnormal-inv-cdf l (flsqrt l) p log? 1-p?)))]
[else (flfind-least-integer
(λ: ([k : Flonum]) ((flpoisson-cdf l k log? 1-p?) . fl>= . p))
0.0 +inf.0
(flmax 0.0 (flnormal-inv-cdf l (flsqrt l) p log? 1-p?)))]))
(: flpoisson-median (Flonum -> Flonum))
(define (flpoisson-median l)
(cond [(l . fl< . 0.0) +nan.0]
[else
(define k (flfloor (fl+ l #i1/3)))
(cond [(fl= k 0.0) k]
[else (if ((flpoisson-cdf l (- k 1.0) #f #f) . fl< . 0.5) k (- k 1.0))])]))
(define-real-dist: poisson-dist Poisson-Dist
poisson-dist-struct ([mean : Flonum]))
(begin-encourage-inline
(: poisson-dist (case-> (-> Poisson-Dist)
(Real -> Poisson-Dist)))
(define (poisson-dist [l 0.5])
(let ([l (fl l)])
(define pdf (opt-lambda: ([k : Real] [log? : Any #f])
(flpoisson-pdf l (fl k) log?)))
(define cdf (opt-lambda: ([k : Real] [log? : Any #f] [1-p? : Any #f])
(flpoisson-cdf l (fl k) log? 1-p?)))
(define inv-cdf (opt-lambda: ([p : Real] [log? : Any #f] [1-p? : Any #f])
(flpoisson-inv-cdf l (fl p) log? 1-p?)))
(define sample (case-lambda:
[() (unsafe-flvector-ref (flpoisson-sample l 1) 0)]
[([n : Integer]) (flvector->list (flpoisson-sample l n))]))
(poisson-dist-struct pdf sample cdf inv-cdf 0.0 +inf.0 (delay (flpoisson-median l)) l)))
)
| null | https://raw.githubusercontent.com/racket/math/dcd2ea1893dc5b45b26c8312997917a15fcd1c4a/math-lib/math/private/distributions/poisson-dist.rkt | racket | #lang typed/racket/base
(require racket/performance-hint
racket/promise
"../../flonum.rkt"
"../../vector.rkt"
"../unsafe.rkt"
"../functions/incomplete-gamma.rkt"
(prefix-in impl: "impl/poisson-pdf.rkt")
"impl/poisson-random.rkt"
"normal-dist.rkt"
"dist-struct.rkt"
"utils.rkt")
(provide flpoisson-pdf
flpoisson-cdf
flpoisson-inv-cdf
flpoisson-sample
flpoisson-median
Poisson-Dist poisson-dist poisson-dist-mean)
(: flpoisson-pdf (Flonum Flonum Any -> Flonum))
(define (flpoisson-pdf l k log?)
(cond [(or (l . fl< . 0.0) (not (integer? k))) +nan.0]
[log? (impl:flpoisson-log-pdf l k)]
[else (impl:flpoisson-pdf l k)]))
(: flpoisson-cdf (Flonum Flonum Any Any -> Flonum))
(define (flpoisson-cdf l k log? 1-p?)
(cond [(l . fl< . 0.0) +nan.0]
[log? (fllog-gamma-inc (flfloor (fl+ k 1.0)) l (not 1-p?) #t)]
[else (flgamma-inc (flfloor (fl+ k 1.0)) l (not 1-p?) #t)]))
(: flpoisson-inv-cdf (Flonum Flonum Any Any -> Flonum))
(define (flpoisson-inv-cdf l p log? 1-p?)
(cond [(l . fl< . 0.0) +nan.0]
[(not (flprobability? p log?)) +nan.0]
[(flprobability-one? p log? 1-p?) +inf.0]
[(flprobability-zero? p log? 1-p?) 0.0]
[1-p? (flfind-least-integer
(λ: ([k : Flonum]) ((flpoisson-cdf l k log? 1-p?) . fl< . p))
0.0 +inf.0
(flmax 0.0 (flnormal-inv-cdf l (flsqrt l) p log? 1-p?)))]
[else (flfind-least-integer
(λ: ([k : Flonum]) ((flpoisson-cdf l k log? 1-p?) . fl>= . p))
0.0 +inf.0
(flmax 0.0 (flnormal-inv-cdf l (flsqrt l) p log? 1-p?)))]))
(: flpoisson-median (Flonum -> Flonum))
(define (flpoisson-median l)
(cond [(l . fl< . 0.0) +nan.0]
[else
(define k (flfloor (fl+ l #i1/3)))
(cond [(fl= k 0.0) k]
[else (if ((flpoisson-cdf l (- k 1.0) #f #f) . fl< . 0.5) k (- k 1.0))])]))
(define-real-dist: poisson-dist Poisson-Dist
poisson-dist-struct ([mean : Flonum]))
(begin-encourage-inline
(: poisson-dist (case-> (-> Poisson-Dist)
(Real -> Poisson-Dist)))
(define (poisson-dist [l 0.5])
(let ([l (fl l)])
(define pdf (opt-lambda: ([k : Real] [log? : Any #f])
(flpoisson-pdf l (fl k) log?)))
(define cdf (opt-lambda: ([k : Real] [log? : Any #f] [1-p? : Any #f])
(flpoisson-cdf l (fl k) log? 1-p?)))
(define inv-cdf (opt-lambda: ([p : Real] [log? : Any #f] [1-p? : Any #f])
(flpoisson-inv-cdf l (fl p) log? 1-p?)))
(define sample (case-lambda:
[() (unsafe-flvector-ref (flpoisson-sample l 1) 0)]
[([n : Integer]) (flvector->list (flpoisson-sample l n))]))
(poisson-dist-struct pdf sample cdf inv-cdf 0.0 +inf.0 (delay (flpoisson-median l)) l)))
)
|
|
039914e4c0f2e7167d84dfd81384dc5a4cc6c13453caaeb66df7f6ec8397cafa | goldfirere/singletons | Lambdas.hs | {-# OPTIONS_GHC -Wno-unused-matches -Wno-name-shadowing #-}
We expect unused binds and name shadowing in test .
module Singletons.Lambdas where
import Data.Proxy
import Data.Singletons.Base.TH
$(singletons [d|
-- nothing in scope
foo0 :: a -> b -> a
foo0 = (\x y -> x)
-- eta-reduced function
foo1 :: a -> b -> a
foo1 x = (\_ -> x)
-- same as before, but without eta-reduction
foo2 :: a -> b -> a
foo2 x y = (\_ -> x) y
foo3 :: a -> a
foo3 x = (\y -> y) x
-- more lambda parameters + returning in-scope variable
foo4 :: a -> b -> c -> a
foo4 x y z = (\_ _ -> x) y z
-- name shadowing
-- Note: due to -dsuppress-uniques output of this test does not really
-- prove that the result is correct. Compiling this file manually and
examining dumped splise of relevant reveals that indeed that Lambda
-- returns its last parameter (ie. y passed in a call) rather than the
-- first one (ie. x that is shadowed by the binder in a lambda).
foo5 :: a -> b -> b
foo5 x y = (\x -> x) y
nested
foo6 :: a -> b -> a
foo6 a b = (\x -> \_ -> x) a b
-- tuple patterns
foo7 :: a -> b -> b
foo7 x y = (\(_, b) -> b) (x, y)
-- constructor patters=ns
data Foo a b = Foo a b
foo8 :: Foo a b -> a
foo8 x = (\(Foo a _) -> a) x
|])
foo1a :: Proxy (Foo1 Int Char)
foo1a = Proxy
foo1b :: Proxy Int
foo1b = foo1a
foo2a :: Proxy (Foo2 Int Char)
foo2a = Proxy
foo2b :: Proxy Int
foo2b = foo2a
foo3a :: Proxy (Foo3 Int)
foo3a = Proxy
foo3b :: Proxy Int
foo3b = foo3a
foo4a :: Proxy (Foo4 Int Char Bool)
foo4a = Proxy
foo4b :: Proxy Int
foo4b = foo4a
foo5a :: Proxy (Foo5 Int Bool)
foo5a = Proxy
foo5b :: Proxy Bool
foo5b = foo5a
foo6a :: Proxy (Foo6 Int Char)
foo6a = Proxy
foo6b :: Proxy Int
foo6b = foo6a
foo7a :: Proxy (Foo7 Int Char)
foo7a = Proxy
foo7b :: Proxy Char
foo7b = foo7a
| null | https://raw.githubusercontent.com/goldfirere/singletons/a169d3f6c0c8e962ea2983f60ed74e507bca9b2b/singletons-base/tests/compile-and-dump/Singletons/Lambdas.hs | haskell | # OPTIONS_GHC -Wno-unused-matches -Wno-name-shadowing #
nothing in scope
eta-reduced function
same as before, but without eta-reduction
more lambda parameters + returning in-scope variable
name shadowing
Note: due to -dsuppress-uniques output of this test does not really
prove that the result is correct. Compiling this file manually and
returns its last parameter (ie. y passed in a call) rather than the
first one (ie. x that is shadowed by the binder in a lambda).
tuple patterns
constructor patters=ns |
We expect unused binds and name shadowing in test .
module Singletons.Lambdas where
import Data.Proxy
import Data.Singletons.Base.TH
$(singletons [d|
foo0 :: a -> b -> a
foo0 = (\x y -> x)
foo1 :: a -> b -> a
foo1 x = (\_ -> x)
foo2 :: a -> b -> a
foo2 x y = (\_ -> x) y
foo3 :: a -> a
foo3 x = (\y -> y) x
foo4 :: a -> b -> c -> a
foo4 x y z = (\_ _ -> x) y z
examining dumped splise of relevant reveals that indeed that Lambda
foo5 :: a -> b -> b
foo5 x y = (\x -> x) y
nested
foo6 :: a -> b -> a
foo6 a b = (\x -> \_ -> x) a b
foo7 :: a -> b -> b
foo7 x y = (\(_, b) -> b) (x, y)
data Foo a b = Foo a b
foo8 :: Foo a b -> a
foo8 x = (\(Foo a _) -> a) x
|])
foo1a :: Proxy (Foo1 Int Char)
foo1a = Proxy
foo1b :: Proxy Int
foo1b = foo1a
foo2a :: Proxy (Foo2 Int Char)
foo2a = Proxy
foo2b :: Proxy Int
foo2b = foo2a
foo3a :: Proxy (Foo3 Int)
foo3a = Proxy
foo3b :: Proxy Int
foo3b = foo3a
foo4a :: Proxy (Foo4 Int Char Bool)
foo4a = Proxy
foo4b :: Proxy Int
foo4b = foo4a
foo5a :: Proxy (Foo5 Int Bool)
foo5a = Proxy
foo5b :: Proxy Bool
foo5b = foo5a
foo6a :: Proxy (Foo6 Int Char)
foo6a = Proxy
foo6b :: Proxy Int
foo6b = foo6a
foo7a :: Proxy (Foo7 Int Char)
foo7a = Proxy
foo7b :: Proxy Char
foo7b = foo7a
|
cf449ff3b7f9530a24c09f9e4f8ecb9f204f4ed71c0925fed30e08a1fa9d0b49 | Frechmatz/cl-synthesizer | vco.lisp | (in-package :cl-synthesizer-modules-vco)
(defun make-module (name environment &key
base-frequency
v-peak
(cv-lin-hz-v 0.0)
(duty-cycle 0.5)
(phase-offset 0.0)
(f-max 12000.0)
(wave-forms nil)
(sync-threshold 2.5))
"Creates a Voltage Controlled Oscillator module with 1V/Octave and linear frequency modulation
inputs. The oscillator has through-zero support.
<p>The function has the following parameters:
<ul>
<li>name Name of the module.</li>
<li>environment The synthesizer environment.</li>
<li>:base-frequency The frequency emitted by the oscillator when all frequency control
voltages are 0.</li>
<li>:f-max Absolute value of the maximum frequency of the oscillator. f-max must be greater than 0.</li>
<li>:cv-lin-hz-v Frequency/Volt setting for the linear frequency modulation input :cv-lin.</li>
<li>:v-peak Absolute value of the output peak voltage emitted by the oscillator.</li>
<li>:duty-cycle The duty cycle of the square wave. 0 <= duty-cycle <= 1.</li>
<li>:phase-offset Phase offset in radians.</li>
<li>:wave-forms A list of keywords that declares the wave forms that are to be exposed by
the module. Each keyword must be one of :sine, :saw, :triangle or :square. By default
the module exposes all wave forms. Declaring the required wave forms is highly recommended
as this can improve the execution speed of the module significantly (up to 50%).</li>
<li>:sync-threshold Minimum value of the :sync input that indicates
that a phase reset is to be applied.</li>
</ul></p>
<p>The module has the following inputs:
<ul>
<li>:cv-exp Exponential frequency control voltage. For a given base-frequency of 440Hz a
control voltage of 1.0 results in a frequency of 880Hz and a control
voltage of -1.0 results in a frequency of 220Hz.
</li>
<li>:cv-lin Bipolar linear frequency control voltage. Example: If the :cv-lin-hz-v setting
of the oscillator is 77Hz a :cv-lin input value of 2.0V results in a frequency of 154Hz and
a :cv-lin input value of -2.0V results in a frequency of -154Hz.</li>
<li>:sync A trigger signal that resets the phase.</li>
</ul>
The frequency of the oscillator is calculated by adding the frequencies resulting from the
:cv-lin and :cv-exp inputs. The frequency is clipped according to the :f-max setting.</p>
<p>The module has the following outputs (depending on the :wave-forms parameter):
<ul>
<li>:sine A sine wave.</li>
<li>:triangle A triangle wave.</li>
<li>:saw A saw wave.</li>
<li>:square A square wave.</li>
</ul></p>
<p>The module exposes the following states via the state function:
<ul>
<li>:frequency The current frequency of the module.</li>
<li>:linear-frequency The current linear frequency portion of the module.</li>
<li>:exponential-frequency The current exponential frequency portion of the module.</li>
<li>:phase The current phase in radians (0..2PI).</li>
</ul>
</p>"
(let ((base-frequency (coerce base-frequency 'single-float))
(f-max (coerce f-max 'single-float))
(v-peak (coerce v-peak 'single-float))
(cv-lin-hz-v (coerce cv-lin-hz-v 'single-float))
(phase-offset (coerce phase-offset 'single-float))
(duty-cycle (coerce duty-cycle 'single-float))
(sync-threshold (coerce sync-threshold 'single-float)))
(declare (type single-float base-frequency f-max v-peak cv-lin-hz-v phase-offset duty-cycle sync-threshold))
(if (not wave-forms)
(setf wave-forms (list :sine :saw :square :triangle)))
(if (> 0.0 f-max)
(error
'cl-synthesizer:assembly-error
:format-control "f-max of VCO '~a' must be greater than 0: '~a'"
:format-arguments (list name f-max)))
(if (>= 0.0 v-peak)
(error
'cl-synthesizer:assembly-error
:format-control "v-peak of VCO '~a' must be greater than 0: '~a'"
:format-arguments (list name v-peak)))
(if (< duty-cycle 0)
(error
'cl-synthesizer:assembly-error
:format-control "duty-cycle of VCO '~a' must not be negative: '~a'"
:format-arguments (list name duty-cycle)))
(if (< 1.0 duty-cycle)
(error
'cl-synthesizer:assembly-error
:format-control "duty-cycle of VCO '~a' must not be greater than 1: '~a'"
:format-arguments (list name duty-cycle)))
(let* ((sample-rate (getf environment :sample-rate))
(input-cv-exp nil) (input-cv-lin nil) (input-sync nil)
(cur-frequency 0.0)
(cur-lin-frequency 0.0)
(cur-exp-frequency 0.0)
(cur-phi 0.0)
(cur-sine-output 1.0)
(cur-triangle-output 1.0)
(cur-saw-output 1.0)
(cur-square-output 1.0)
(initial-sync t)
(lin-converter
(lambda (cv)
(declare (type single-float cv))
(* cv cv-lin-hz-v)))
(exp-converter
(lambda (cv)
(declare (type single-float cv))
(* base-frequency (expt 2.0 cv)))))
(multiple-value-bind (phase-generator phase-reset)
(cl-synthesizer-util:phase-generator sample-rate)
(flet ((clip-frequency (f)
(declare (type single-float f))
(if (> (abs f) f-max)
(* f-max (signum f))
f))
(get-frequency (cv-exp cv-lin)
(declare (type single-float cv-exp cv-lin))
(setf cur-lin-frequency (funcall lin-converter cv-lin))
(setf cur-exp-frequency (funcall exp-converter cv-exp))
(+ cur-lin-frequency cur-exp-frequency)))
(let ((inputs (list
:cv-exp (lambda(value) (setf input-cv-exp value))
:cv-lin (lambda(value) (setf input-cv-lin value))
:sync (lambda(value) (setf input-sync value))))
(outputs nil)
(update-functions (make-array (length wave-forms))))
(let ((index nil) (added-wave-forms nil))
(dolist (wave-form wave-forms)
(setf index (if (not index) 0 (+ index 1)))
(if (find wave-form added-wave-forms)
(error
'cl-synthesizer:assembly-error
:format-control "VCO '~a': wave-forms must be unique: '~a'"
:format-arguments (list name wave-forms)))
(push wave-form added-wave-forms)
(cond
((eq wave-form :sine)
(push (lambda() cur-sine-output) outputs)
(push :sine outputs)
(setf (elt update-functions index)
(lambda()
(declare (inline cl-synthesizer-util:phase-sine-converter))
(setf cur-sine-output
(* v-peak
(cl-synthesizer-util:phase-sine-converter
cur-phi phase-offset))))))
((eq wave-form :saw)
(push (lambda() cur-saw-output) outputs)
(push :saw outputs)
(setf (elt update-functions index)
(lambda()
(declare (inline cl-synthesizer-util:phase-saw-converter))
(setf cur-saw-output
(* v-peak (cl-synthesizer-util:phase-saw-converter
cur-phi phase-offset))))))
((eq wave-form :square)
(push (lambda() cur-square-output) outputs)
(push :square outputs)
(setf (elt update-functions index)
(lambda()
(declare (inline cl-synthesizer-util:phase-square-converter))
(setf cur-square-output
(* v-peak (cl-synthesizer-util:phase-square-converter
cur-phi phase-offset duty-cycle))))))
((eq wave-form :triangle)
(push (lambda() cur-triangle-output) outputs)
(push :triangle outputs)
(setf (elt update-functions index)
(lambda()
(declare (inline cl-synthesizer-util:phase-triangle-converter))
(setf cur-triangle-output
(* v-peak (cl-synthesizer-util:phase-triangle-converter
cur-phi phase-offset))))))
(t
(error
'cl-synthesizer:assembly-error
:format-control "Invalid wave-form identifier '~a' passed to VCO '~a'"
:format-arguments (list wave-form name))))))
(list
:inputs (lambda () inputs)
:outputs (lambda () outputs)
:update (lambda ()
(if (not input-cv-exp)
(setf input-cv-exp 0.0))
(if (not input-cv-lin)
(setf input-cv-lin 0.0))
(if (not input-sync)
(setf input-sync 0.0))
(let ((f (clip-frequency (get-frequency input-cv-exp input-cv-lin)))
(phi nil))
(if (or (<= sync-threshold input-sync) initial-sync)
(progn
(setf phi (funcall phase-reset))
(setf initial-sync nil))
(progn
(setf phi (funcall phase-generator f))))
(setf cur-frequency f)
(setf cur-phi phi)
(dotimes (i (length update-functions))
(funcall (elt update-functions i)))))
:state (lambda (key)
(cond
((eq key :frequency)
cur-frequency)
((eq key :linear-frequency)
cur-lin-frequency)
((eq key :exponential-frequency)
cur-exp-frequency)
((eq key :phase)
cur-phi)
(t nil))))))))))
| null | https://raw.githubusercontent.com/Frechmatz/cl-synthesizer/7490d12f0f1e744fa1f71e014627551ebc4388c7/src/modules/vco/vco.lisp | lisp | (in-package :cl-synthesizer-modules-vco)
(defun make-module (name environment &key
base-frequency
v-peak
(cv-lin-hz-v 0.0)
(duty-cycle 0.5)
(phase-offset 0.0)
(f-max 12000.0)
(wave-forms nil)
(sync-threshold 2.5))
"Creates a Voltage Controlled Oscillator module with 1V/Octave and linear frequency modulation
inputs. The oscillator has through-zero support.
<p>The function has the following parameters:
<ul>
<li>name Name of the module.</li>
<li>environment The synthesizer environment.</li>
<li>:base-frequency The frequency emitted by the oscillator when all frequency control
voltages are 0.</li>
<li>:f-max Absolute value of the maximum frequency of the oscillator. f-max must be greater than 0.</li>
<li>:cv-lin-hz-v Frequency/Volt setting for the linear frequency modulation input :cv-lin.</li>
<li>:v-peak Absolute value of the output peak voltage emitted by the oscillator.</li>
<li>:duty-cycle The duty cycle of the square wave. 0 <= duty-cycle <= 1.</li>
<li>:phase-offset Phase offset in radians.</li>
<li>:wave-forms A list of keywords that declares the wave forms that are to be exposed by
the module. Each keyword must be one of :sine, :saw, :triangle or :square. By default
the module exposes all wave forms. Declaring the required wave forms is highly recommended
as this can improve the execution speed of the module significantly (up to 50%).</li>
<li>:sync-threshold Minimum value of the :sync input that indicates
that a phase reset is to be applied.</li>
</ul></p>
<p>The module has the following inputs:
<ul>
<li>:cv-exp Exponential frequency control voltage. For a given base-frequency of 440Hz a
control voltage of 1.0 results in a frequency of 880Hz and a control
voltage of -1.0 results in a frequency of 220Hz.
</li>
<li>:cv-lin Bipolar linear frequency control voltage. Example: If the :cv-lin-hz-v setting
of the oscillator is 77Hz a :cv-lin input value of 2.0V results in a frequency of 154Hz and
a :cv-lin input value of -2.0V results in a frequency of -154Hz.</li>
<li>:sync A trigger signal that resets the phase.</li>
</ul>
The frequency of the oscillator is calculated by adding the frequencies resulting from the
:cv-lin and :cv-exp inputs. The frequency is clipped according to the :f-max setting.</p>
<p>The module has the following outputs (depending on the :wave-forms parameter):
<ul>
<li>:sine A sine wave.</li>
<li>:triangle A triangle wave.</li>
<li>:saw A saw wave.</li>
<li>:square A square wave.</li>
</ul></p>
<p>The module exposes the following states via the state function:
<ul>
<li>:frequency The current frequency of the module.</li>
<li>:linear-frequency The current linear frequency portion of the module.</li>
<li>:exponential-frequency The current exponential frequency portion of the module.</li>
<li>:phase The current phase in radians (0..2PI).</li>
</ul>
</p>"
(let ((base-frequency (coerce base-frequency 'single-float))
(f-max (coerce f-max 'single-float))
(v-peak (coerce v-peak 'single-float))
(cv-lin-hz-v (coerce cv-lin-hz-v 'single-float))
(phase-offset (coerce phase-offset 'single-float))
(duty-cycle (coerce duty-cycle 'single-float))
(sync-threshold (coerce sync-threshold 'single-float)))
(declare (type single-float base-frequency f-max v-peak cv-lin-hz-v phase-offset duty-cycle sync-threshold))
(if (not wave-forms)
(setf wave-forms (list :sine :saw :square :triangle)))
(if (> 0.0 f-max)
(error
'cl-synthesizer:assembly-error
:format-control "f-max of VCO '~a' must be greater than 0: '~a'"
:format-arguments (list name f-max)))
(if (>= 0.0 v-peak)
(error
'cl-synthesizer:assembly-error
:format-control "v-peak of VCO '~a' must be greater than 0: '~a'"
:format-arguments (list name v-peak)))
(if (< duty-cycle 0)
(error
'cl-synthesizer:assembly-error
:format-control "duty-cycle of VCO '~a' must not be negative: '~a'"
:format-arguments (list name duty-cycle)))
(if (< 1.0 duty-cycle)
(error
'cl-synthesizer:assembly-error
:format-control "duty-cycle of VCO '~a' must not be greater than 1: '~a'"
:format-arguments (list name duty-cycle)))
(let* ((sample-rate (getf environment :sample-rate))
(input-cv-exp nil) (input-cv-lin nil) (input-sync nil)
(cur-frequency 0.0)
(cur-lin-frequency 0.0)
(cur-exp-frequency 0.0)
(cur-phi 0.0)
(cur-sine-output 1.0)
(cur-triangle-output 1.0)
(cur-saw-output 1.0)
(cur-square-output 1.0)
(initial-sync t)
(lin-converter
(lambda (cv)
(declare (type single-float cv))
(* cv cv-lin-hz-v)))
(exp-converter
(lambda (cv)
(declare (type single-float cv))
(* base-frequency (expt 2.0 cv)))))
(multiple-value-bind (phase-generator phase-reset)
(cl-synthesizer-util:phase-generator sample-rate)
(flet ((clip-frequency (f)
(declare (type single-float f))
(if (> (abs f) f-max)
(* f-max (signum f))
f))
(get-frequency (cv-exp cv-lin)
(declare (type single-float cv-exp cv-lin))
(setf cur-lin-frequency (funcall lin-converter cv-lin))
(setf cur-exp-frequency (funcall exp-converter cv-exp))
(+ cur-lin-frequency cur-exp-frequency)))
(let ((inputs (list
:cv-exp (lambda(value) (setf input-cv-exp value))
:cv-lin (lambda(value) (setf input-cv-lin value))
:sync (lambda(value) (setf input-sync value))))
(outputs nil)
(update-functions (make-array (length wave-forms))))
(let ((index nil) (added-wave-forms nil))
(dolist (wave-form wave-forms)
(setf index (if (not index) 0 (+ index 1)))
(if (find wave-form added-wave-forms)
(error
'cl-synthesizer:assembly-error
:format-control "VCO '~a': wave-forms must be unique: '~a'"
:format-arguments (list name wave-forms)))
(push wave-form added-wave-forms)
(cond
((eq wave-form :sine)
(push (lambda() cur-sine-output) outputs)
(push :sine outputs)
(setf (elt update-functions index)
(lambda()
(declare (inline cl-synthesizer-util:phase-sine-converter))
(setf cur-sine-output
(* v-peak
(cl-synthesizer-util:phase-sine-converter
cur-phi phase-offset))))))
((eq wave-form :saw)
(push (lambda() cur-saw-output) outputs)
(push :saw outputs)
(setf (elt update-functions index)
(lambda()
(declare (inline cl-synthesizer-util:phase-saw-converter))
(setf cur-saw-output
(* v-peak (cl-synthesizer-util:phase-saw-converter
cur-phi phase-offset))))))
((eq wave-form :square)
(push (lambda() cur-square-output) outputs)
(push :square outputs)
(setf (elt update-functions index)
(lambda()
(declare (inline cl-synthesizer-util:phase-square-converter))
(setf cur-square-output
(* v-peak (cl-synthesizer-util:phase-square-converter
cur-phi phase-offset duty-cycle))))))
((eq wave-form :triangle)
(push (lambda() cur-triangle-output) outputs)
(push :triangle outputs)
(setf (elt update-functions index)
(lambda()
(declare (inline cl-synthesizer-util:phase-triangle-converter))
(setf cur-triangle-output
(* v-peak (cl-synthesizer-util:phase-triangle-converter
cur-phi phase-offset))))))
(t
(error
'cl-synthesizer:assembly-error
:format-control "Invalid wave-form identifier '~a' passed to VCO '~a'"
:format-arguments (list wave-form name))))))
(list
:inputs (lambda () inputs)
:outputs (lambda () outputs)
:update (lambda ()
(if (not input-cv-exp)
(setf input-cv-exp 0.0))
(if (not input-cv-lin)
(setf input-cv-lin 0.0))
(if (not input-sync)
(setf input-sync 0.0))
(let ((f (clip-frequency (get-frequency input-cv-exp input-cv-lin)))
(phi nil))
(if (or (<= sync-threshold input-sync) initial-sync)
(progn
(setf phi (funcall phase-reset))
(setf initial-sync nil))
(progn
(setf phi (funcall phase-generator f))))
(setf cur-frequency f)
(setf cur-phi phi)
(dotimes (i (length update-functions))
(funcall (elt update-functions i)))))
:state (lambda (key)
(cond
((eq key :frequency)
cur-frequency)
((eq key :linear-frequency)
cur-lin-frequency)
((eq key :exponential-frequency)
cur-exp-frequency)
((eq key :phase)
cur-phi)
(t nil))))))))))
|
|
9c36a0f28b34dc5f13f42628d87bc6b80a1c0922b7f2c331d46331132dd001d7 | plai-group/daphne | linalg_test.clj | (ns daphne.linalg-test
(:require [clojure.test :refer [deftest testing is]]
[daphne.linalg :refer [foppl-linalg]]
[daphne.core :refer [code->graph]]))
#_(deftest convolution-test
(testing "Test convolution function."
;; pytorch conv2d validated
[[[2.202277681399303 2.8281133363421826]
[2.230589302485512 1.7424331895209988]]
[[1.4150513754814487 1.5241574765307004]
[1.3686725762513385 1.2358384037379724]]]
(is (= [[[2.201277681399303 2.8271133363421828]
[2.229589302485512 1.741433189520999]]
[[1.4130513754814487 1.5221574765307004]
[1.3666725762513385 1.2338384037379724]]]
(last
(code->graph
(concat foppl-linalg
'((let [w1 [[[[0.8097745873461849, 0.9027974133677656],
[0.9937591748266679, 0.6899363139420105]],
[[0.09797226233334677, 0.02146334941825967],
[0.13535254818829612, 0.5766735975714063]]],
[[[0.21673669826346842, 0.4318042477853944],
[0.6986981163149986, 0.10796200682913093]],
[[0.4354448007571432, 0.5948937288685611],
[0.10808562241514497, 0.10665190515628087]]]]
b1 [0.001, 0.002]
x [[[0.4287027640286398, 0.5976520946846761, 0.8412232029516122, 0.843736605231717]
[0.564107482170524, 0.8311282657110909, 0.6649508631095007, 0.18790346905566147]
[0.9061368614009218, 0.4177246719504131, 0.7508225882288696, 0.24750179094034197]
[0.5116059526254529, 0.06562150286776547, 0.4562421518588141, 0.24021920534487728]],
[[0.05876861913939957, 0.8392780098655948, 0.2159165110183996, 0.37296811984042133]
[0.29292562830682534, 0.20312029690945455, 0.8465110915686057, 0.7803549289269531]
[0.14643684731359985, 0.6894799714557894, 0.6801510765311485, 0.3989642366533286]
[0.6300020585310742, 0.7813718161440676, 0.5554317792622283, 0.24360960738915194]]]
]
(conv2d x w1 b1 2)
))
)))))))
| null | https://raw.githubusercontent.com/plai-group/daphne/a8b27d3c7ceedc26b922bb32793a78ede3472669/test/daphne/linalg_test.clj | clojure | pytorch conv2d validated | (ns daphne.linalg-test
(:require [clojure.test :refer [deftest testing is]]
[daphne.linalg :refer [foppl-linalg]]
[daphne.core :refer [code->graph]]))
#_(deftest convolution-test
(testing "Test convolution function."
[[[2.202277681399303 2.8281133363421826]
[2.230589302485512 1.7424331895209988]]
[[1.4150513754814487 1.5241574765307004]
[1.3686725762513385 1.2358384037379724]]]
(is (= [[[2.201277681399303 2.8271133363421828]
[2.229589302485512 1.741433189520999]]
[[1.4130513754814487 1.5221574765307004]
[1.3666725762513385 1.2338384037379724]]]
(last
(code->graph
(concat foppl-linalg
'((let [w1 [[[[0.8097745873461849, 0.9027974133677656],
[0.9937591748266679, 0.6899363139420105]],
[[0.09797226233334677, 0.02146334941825967],
[0.13535254818829612, 0.5766735975714063]]],
[[[0.21673669826346842, 0.4318042477853944],
[0.6986981163149986, 0.10796200682913093]],
[[0.4354448007571432, 0.5948937288685611],
[0.10808562241514497, 0.10665190515628087]]]]
b1 [0.001, 0.002]
x [[[0.4287027640286398, 0.5976520946846761, 0.8412232029516122, 0.843736605231717]
[0.564107482170524, 0.8311282657110909, 0.6649508631095007, 0.18790346905566147]
[0.9061368614009218, 0.4177246719504131, 0.7508225882288696, 0.24750179094034197]
[0.5116059526254529, 0.06562150286776547, 0.4562421518588141, 0.24021920534487728]],
[[0.05876861913939957, 0.8392780098655948, 0.2159165110183996, 0.37296811984042133]
[0.29292562830682534, 0.20312029690945455, 0.8465110915686057, 0.7803549289269531]
[0.14643684731359985, 0.6894799714557894, 0.6801510765311485, 0.3989642366533286]
[0.6300020585310742, 0.7813718161440676, 0.5554317792622283, 0.24360960738915194]]]
]
(conv2d x w1 b1 2)
))
)))))))
|