_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)

Dataset Card for Dataset Name

Dataset Description

Collection of functional programming languages from GitHub.

  • Point of Contact: dhuck

Dataset Summary

This dataset is a collection of code examples of functional programming languages for code generation tasks. It was collected over a week long period in March 2023 as part of project in program synthesis.

Dataset Structure

Data Instances

{
  'id': str
  'repository': str
  'filename': str
  'license': str or Empty
  'language': str
  'content': str
}

Data Fields

  • id: SHA256 has of the content field. This ID scheme ensure that duplicate code examples via forks or other duplications are removed from the dataset.
  • 'repository': The repository that the file was pulled from. This can be used for any attribution or to check updated licensing issues for the code example.
  • 'filename': Filename of the code example from within the repository.
  • 'license': Licensing information of the repository. This can be empty and further work is likely necessary to parse licensing information from individual files.
  • 'language': Programming language of the file. For example, Haskell, Clojure, Lisp, etc...
  • 'content': Source code of the file. This is full text of the source with some cleaning as described in the Curation section below. While many examples are short, others can be extremely long. This field will like require preprocessing for end tasks.

Data Splits

More information to be provided at a later date. There are 157,218 test examples and 628,869 training examples. The split was created using scikit-learn' test_train_split function.

Dataset Creation

Curation Rationale

This dataset was put together for Programming Synthesis tasks. The majority of available datasets consist of imperative programming languages, while the program synthesis community has a rich history of methods using functional languages. This dataset aims to unify the two approaches by making a large training corpus of functional languages available to researchers.

Source Data

Initial Data Collection and Normalization

Code examples were collected in a similar manner to other existing programming language datasets. Each example was pulled from public repositories on GitHub over a week in March 2023. I performed this task by searching common file extensions of the target languages (Clojure, Elixir, Haskell, Lisp, OCAML, Racket and Scheme). The full source is included for each coding example, so padding or truncation will be necessary for any training tasks. Significant effort was made to remove any personal information from each coding example. For each code example, I removed any email address or websites using simple regex pattern matching. Spacy NER was used to identify proper names in the comments only. Any token which spanned a name was simply replaced with the token PERSON while email addresses and websites were dropped from each comment. Organizations and other information were left intact.

Who are the source language producers?

Each example contains the repository the code originated from, identifying the source of each example.

Personal and Sensitive Information

While great care was taken to remove proper names, email addresses, and websites, there may exist examples where pattern matching did not work. While I used the best spacy models available, I did witness false negatives on other tasks on other datasets. To ensure no personal information makes it into training data, it is advisable to remove all comments if the training task does not require them. I made several PR to the comment_parser python library to support the languages in this dataset. My version of the parsing library can be found at https://github.com/d-huck/comment_parser

Considerations for Using the Data

Social Impact of Dataset

[More Information Needed]

Discussion of Biases

While code itself may not contain bias, programmers can use offensive, racist, homophobic, transphobic, misogynistic, etc words for variable names. Further updates to this dataset library will investigate and address these issues. Comments in the code examples could also contain hateful speech. Models trained on this dataset may need additional training on toxicity to remove these tendencies from the output.

Other Known Limitations

The code present in this dataset has not been checked for quality in any way. It is possible and probable that several of the coding examples are of poor quality and do not actually compile or run in their target language. Furthermore, there exists a chance that some examples are not the language they claim to be, since github search matching is dependent only on the file extension and not the actual contents of any file.

Downloads last month
179