_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
b8022a955a3bd20bf7175f67b56c39a62d7948dea64c9ff9172b1d31ca58b103
tonyrog/can
can_probe.erl
%%%---- BEGIN COPYRIGHT -------------------------------------------------------- %%% Copyright ( C ) 2007 - 2012 , Rogvall Invest AB , < > %%% %%% This software is licensed as described in the file COPYRIGHT, which %%% you should have received as part of this distribution. The terms %%% are also available at . %%% %%% You may opt to use, copy, modify, merge, publish, distribute and/or sell copies of the Software , and permit persons to whom the Software is %%% furnished to do so, under the terms of the COPYRIGHT file. %%% This software is distributed on an " AS IS " basis , WITHOUT WARRANTY OF ANY %%% KIND, either express or implied. %%% %%%---- END COPYRIGHT ---------------------------------------------------------- @author < > ( C ) 2010 , %%% @doc %%% CAN frame probe %%% @end Created : 12 Jun 2010 by < > -module(can_probe). -export([start/0,start/1,stop/1,init/1]). -export([format_frame/1]). -include_lib("can/include/can.hrl"). start() -> start([]). start(Opts) -> can:start(), spawn_link(?MODULE, init, [Opts]). stop(Pid) -> Pid ! stop. init(Opts) -> can_router:attach(), case proplists:get_value(max_time, Opts, infinity) of infinity -> ok; Time -> erlang:start_timer(Time, self(), done) end, MaxFrames = proplists:get_value(max_frame, Opts, -1), T0 = os:timestamp(), loop(T0, MaxFrames). loop(_T, 0) -> ok; loop(T0, FrameCount) -> receive Frame = #can_frame {} -> print_frame(timer:now_diff(os:timestamp(),T0), Frame), loop(T0, FrameCount - 1); {timeout, _Ref, done} -> ok; stop -> ok end. format_frame(Frame) -> ["id: ", if ?is_can_frame_eff(Frame) -> io_lib:format("~8.16.0B", [Frame#can_frame.id band ?CAN_EFF_MASK]); true -> io_lib:format("~3.16.0B", [Frame#can_frame.id band ?CAN_SFF_MASK]) end, " len:", io_lib:format("~w", [Frame#can_frame.len]), if ?is_can_frame_eff(Frame) -> " ext"; true -> "" end, if ?is_can_frame_fd(Frame) -> " fd"; true -> "" end, if Frame#can_frame.intf>0 -> [" intf:", io_lib:format("~w", [Frame#can_frame.intf])]; true -> [] end, if ?is_can_frame_rtr(Frame) -> " rtr"; true -> [" data:", format_data(Frame#can_frame.data)] end, if ?is_can_valid_timestamp(Frame) -> ["ts:", io_lib:format("~w", [Frame#can_frame.ts])]; true -> [] end ]. format_data(<<H,T/binary>>) -> [io_lib:format("~2.16.0B", [H]) | format_data(T)]; format_data(<<>>) -> []. print_frame(T, Frame) -> S = T div 1000000, Us = T rem 1000000, io:format("~w.~w: ~s\n", [S,Us,format_frame(Frame)]).
null
https://raw.githubusercontent.com/tonyrog/can/9f76fd57198e5531978791e0528e1798a9c08693/src/can_probe.erl
erlang
---- BEGIN COPYRIGHT -------------------------------------------------------- This software is licensed as described in the file COPYRIGHT, which you should have received as part of this distribution. The terms are also available at . You may opt to use, copy, modify, merge, publish, distribute and/or sell furnished to do so, under the terms of the COPYRIGHT file. KIND, either express or implied. ---- END COPYRIGHT ---------------------------------------------------------- @doc CAN frame probe @end
Copyright ( C ) 2007 - 2012 , Rogvall Invest AB , < > copies of the Software , and permit persons to whom the Software is This software is distributed on an " AS IS " basis , WITHOUT WARRANTY OF ANY @author < > ( C ) 2010 , Created : 12 Jun 2010 by < > -module(can_probe). -export([start/0,start/1,stop/1,init/1]). -export([format_frame/1]). -include_lib("can/include/can.hrl"). start() -> start([]). start(Opts) -> can:start(), spawn_link(?MODULE, init, [Opts]). stop(Pid) -> Pid ! stop. init(Opts) -> can_router:attach(), case proplists:get_value(max_time, Opts, infinity) of infinity -> ok; Time -> erlang:start_timer(Time, self(), done) end, MaxFrames = proplists:get_value(max_frame, Opts, -1), T0 = os:timestamp(), loop(T0, MaxFrames). loop(_T, 0) -> ok; loop(T0, FrameCount) -> receive Frame = #can_frame {} -> print_frame(timer:now_diff(os:timestamp(),T0), Frame), loop(T0, FrameCount - 1); {timeout, _Ref, done} -> ok; stop -> ok end. format_frame(Frame) -> ["id: ", if ?is_can_frame_eff(Frame) -> io_lib:format("~8.16.0B", [Frame#can_frame.id band ?CAN_EFF_MASK]); true -> io_lib:format("~3.16.0B", [Frame#can_frame.id band ?CAN_SFF_MASK]) end, " len:", io_lib:format("~w", [Frame#can_frame.len]), if ?is_can_frame_eff(Frame) -> " ext"; true -> "" end, if ?is_can_frame_fd(Frame) -> " fd"; true -> "" end, if Frame#can_frame.intf>0 -> [" intf:", io_lib:format("~w", [Frame#can_frame.intf])]; true -> [] end, if ?is_can_frame_rtr(Frame) -> " rtr"; true -> [" data:", format_data(Frame#can_frame.data)] end, if ?is_can_valid_timestamp(Frame) -> ["ts:", io_lib:format("~w", [Frame#can_frame.ts])]; true -> [] end ]. format_data(<<H,T/binary>>) -> [io_lib:format("~2.16.0B", [H]) | format_data(T)]; format_data(<<>>) -> []. print_frame(T, Frame) -> S = T div 1000000, Us = T rem 1000000, io:format("~w.~w: ~s\n", [S,Us,format_frame(Frame)]).
ca0797889aea232e61a0e5706b7531b3f43f860eb77fdafcdfeabbe443d11a69
racket/data
union-find.rkt
#lang racket/base (require racket/contract) (provide uf-set? uf-new) (provide (contract-out [uf-union! (-> uf-set? uf-set? void?)] [uf-find (-> uf-set? any/c)] [uf-set-canonical! (-> uf-set? any/c void?)] [uf-same-set? (-> uf-set? uf-set? boolean?)])) (struct uf-set (x rank) #:mutable #:methods gen:custom-write [(define write-proc (λ (uf port mode) (write-string "#<uf-set: " port) (define recur (case mode [(#t) write] [(#f) display] [else (λ (p port) (print p port mode))])) (recur (uf-find uf) port) (write-string ">" port)))]) (define (uf-new x) (uf-set (box x) 0)) (define (uf-union! _a _b) (define a (uf-get-root _a)) (define b (uf-get-root _b)) (unless (eq? a b) (define a-rank (uf-set-rank a)) (define b-rank (uf-set-rank b)) (cond [(< a-rank b-rank) (set-uf-set-x! a b)] [else (set-uf-set-x! b a) (when (= a-rank b-rank) (set-uf-set-rank! a (+ a-rank 1)))]))) (define (uf-find a) (unbox (uf-get-box a))) (define (uf-set-canonical! a b) (set-box! (uf-get-box a) b)) (define (uf-same-set? a b) (eq? (uf-get-box a) (uf-get-box b))) (define (uf-get-box a) (uf-set-x (uf-get-root a))) (define (uf-get-root a) (let loop ([c a] [p (uf-set-x a)]) (cond [(box? p) c] [else (define fnd (loop p (uf-set-x p))) (set-uf-set-x! c fnd) fnd]))) (module+ test (require rackunit racket/pretty racket/set) (check-equal? (uf-find (uf-new 1)) 1) (check-equal? (let ([a (uf-new 1)] [b (uf-new 2)]) (uf-union! a b) (uf-find a)) 1) (check-equal? (let ([a (uf-new 1)] [b (uf-new 2)]) (uf-union! a b) (uf-find b)) 1) (check-equal? (let ([a (uf-new 1)] [b (uf-new 2)]) (uf-union! a b) (uf-find a) (uf-find a)) 1) (check-equal? (let ([a (uf-new 1)] [b (uf-new 2)]) (uf-union! a b) (uf-find b) (uf-find b)) 1) (check-equal? (let ([a (uf-new 1)]) (uf-union! a a) (uf-find a)) 1) (check-equal? (uf-same-set? (uf-new 1) (uf-new 2)) #f) (check-equal? (uf-same-set? (uf-new 1) (uf-new 1)) #f) (check-equal? (let ([a (uf-new 1)] [b (uf-new 1)]) (uf-union! a b) (uf-same-set? a b)) #t) (check-equal? (let ([sp (open-output-string)]) (display (uf-new "x") sp) (get-output-string sp)) "#<uf-set: x>") (check-equal? (let ([sp (open-output-string)]) (write (uf-new "x") sp) (get-output-string sp)) "#<uf-set: \"x\">") (check-equal? (let ([sp (open-output-string)]) (print (uf-new "x") sp) (get-output-string sp)) "#<uf-set: \"x\">") (check-equal? (let ([sp (open-output-string)]) (define x (vector 1)) (define a (uf-new x)) (vector-set! x 0 a) (write x sp) (get-output-string sp)) "#0=#(#<uf-set: #0#>)") (check-equal? (let ([sp (open-output-string)]) (define a (uf-new #f)) (uf-set-canonical! a a) (write a sp) (get-output-string sp)) "#0=#<uf-set: #0#>") (let ([a (uf-new 1)] [b (uf-new 2)] [c (uf-new 3)] [d (uf-new 4)] [e (uf-new 5)]) (uf-union! a b) (uf-union! c d) (uf-union! b d) (uf-union! c e) (check-equal? (uf-find a) (uf-find e))) (let ([a (uf-new 1)] [b (uf-new 2)] [c (uf-new 3)] [d (uf-new 4)] [e (uf-new 5)]) (uf-union! a b) (uf-union! c d) (uf-union! a c) (uf-union! c e) (check-equal? (uf-find a) (uf-find e))) (let ([a (uf-new 1)] [b (uf-new 2)] [c (uf-new 3)] [d (uf-new 4)] [e (uf-new 5)]) (uf-union! a b) (uf-union! c d) (uf-union! a d) (uf-union! c e) (check-equal? (uf-find a) (uf-find e))) (let ([a (uf-new 1)] [b (uf-new 2)] [c (uf-new 3)] [d (uf-new 4)] [e (uf-new 5)]) (uf-union! a b) (uf-union! c d) (uf-union! b c) (uf-union! c e) (check-equal? (uf-find a) (uf-find e))) (check-equal? (let ([a (uf-new 1)] [b (uf-new 2)] [c (uf-new 3)] [d (uf-new 4)]) (uf-union! a b) (uf-union! c d) (uf-union! a c) (max (uf-set-rank a) (uf-set-rank b) (uf-set-rank c) (uf-set-rank d))) 2) (let ((uf-sets (for/list ((x (in-range 8))) (uf-new x)))) (uf-union! (list-ref uf-sets 5) (list-ref uf-sets 7)) (uf-union! (list-ref uf-sets 1) (list-ref uf-sets 6)) (uf-union! (list-ref uf-sets 6) (list-ref uf-sets 5)) (uf-union! (list-ref uf-sets 4) (list-ref uf-sets 7)) (uf-union! (list-ref uf-sets 2) (list-ref uf-sets 0)) (uf-union! (list-ref uf-sets 2) (list-ref uf-sets 5)) (check-equal? (uf-find (list-ref uf-sets 4)) (uf-find (list-ref uf-sets 7)))) (define (run-random-tests) (define (make-random-sets num-sets) (define uf-sets (for/list ([x (in-range num-sets)]) (uf-new x))) (define edges (make-hash (build-list num-sets (λ (x) (cons x (set)))))) (define (add-edge a-num b-num) (hash-set! edges a-num (set-add (hash-ref edges a-num) b-num))) (define ops '()) (for ([op (in-range (random 10))]) (define a-num (random num-sets)) (define b-num (random num-sets)) (define a (list-ref uf-sets a-num)) (define b (list-ref uf-sets b-num)) (set! ops (cons `(uf-union! (list-ref uf-sets ,a-num) (list-ref uf-sets ,b-num)) ops)) (uf-union! a b) (add-edge a-num b-num) (add-edge b-num a-num)) (define code `(let ([uf-sets (for/list ([x (in-range ,num-sets)]) (uf-new x))]) ,@(reverse ops))) (values uf-sets edges code)) (define (check-canonical-has-path uf-sets edges code) (for ([set (in-list uf-sets)] [i (in-naturals)]) (define canon (uf-find set)) (define visited (make-hash)) (define found? (let loop ([node i]) (cond [(= node canon) #t] [(hash-ref visited node #f) #f] [else (hash-set! visited node #t) (for/or ([neighbor (in-set (hash-ref edges node))]) (loop neighbor))]))) (unless found? (pretty-print code (current-error-port)) (error 'union-find.rkt "mismatch; expected a link from ~s to ~s, didn't find it" i canon)))) (define (check-edges-share-canonical uf-sets edges code) (for ([(src dests) (in-hash edges)]) (for ([dest (in-set dests)]) (define sc (uf-find (list-ref uf-sets src))) (define dc (uf-find (list-ref uf-sets dest))) (unless (= sc dc) (pretty-print code (current-error-port)) (error 'union-find.rkt "mismatch; expected sets ~s and ~s to have the same canonical element, got ~s and ~s" src dest sc dc))))) (for ([x (in-range 10000)]) (define-values (sets edges code) (make-random-sets (+ 2 (random (+ 1 (floor (/ x 100))))))) (check-canonical-has-path sets edges code) (check-edges-share-canonical sets edges code))) (run-random-tests) (random-seed 0) (time (run-random-tests)))
null
https://raw.githubusercontent.com/racket/data/1fe6cb389ad9a817c6abaff2d8f5ef407b5a16a2/data-lib/data/union-find.rkt
racket
#lang racket/base (require racket/contract) (provide uf-set? uf-new) (provide (contract-out [uf-union! (-> uf-set? uf-set? void?)] [uf-find (-> uf-set? any/c)] [uf-set-canonical! (-> uf-set? any/c void?)] [uf-same-set? (-> uf-set? uf-set? boolean?)])) (struct uf-set (x rank) #:mutable #:methods gen:custom-write [(define write-proc (λ (uf port mode) (write-string "#<uf-set: " port) (define recur (case mode [(#t) write] [(#f) display] [else (λ (p port) (print p port mode))])) (recur (uf-find uf) port) (write-string ">" port)))]) (define (uf-new x) (uf-set (box x) 0)) (define (uf-union! _a _b) (define a (uf-get-root _a)) (define b (uf-get-root _b)) (unless (eq? a b) (define a-rank (uf-set-rank a)) (define b-rank (uf-set-rank b)) (cond [(< a-rank b-rank) (set-uf-set-x! a b)] [else (set-uf-set-x! b a) (when (= a-rank b-rank) (set-uf-set-rank! a (+ a-rank 1)))]))) (define (uf-find a) (unbox (uf-get-box a))) (define (uf-set-canonical! a b) (set-box! (uf-get-box a) b)) (define (uf-same-set? a b) (eq? (uf-get-box a) (uf-get-box b))) (define (uf-get-box a) (uf-set-x (uf-get-root a))) (define (uf-get-root a) (let loop ([c a] [p (uf-set-x a)]) (cond [(box? p) c] [else (define fnd (loop p (uf-set-x p))) (set-uf-set-x! c fnd) fnd]))) (module+ test (require rackunit racket/pretty racket/set) (check-equal? (uf-find (uf-new 1)) 1) (check-equal? (let ([a (uf-new 1)] [b (uf-new 2)]) (uf-union! a b) (uf-find a)) 1) (check-equal? (let ([a (uf-new 1)] [b (uf-new 2)]) (uf-union! a b) (uf-find b)) 1) (check-equal? (let ([a (uf-new 1)] [b (uf-new 2)]) (uf-union! a b) (uf-find a) (uf-find a)) 1) (check-equal? (let ([a (uf-new 1)] [b (uf-new 2)]) (uf-union! a b) (uf-find b) (uf-find b)) 1) (check-equal? (let ([a (uf-new 1)]) (uf-union! a a) (uf-find a)) 1) (check-equal? (uf-same-set? (uf-new 1) (uf-new 2)) #f) (check-equal? (uf-same-set? (uf-new 1) (uf-new 1)) #f) (check-equal? (let ([a (uf-new 1)] [b (uf-new 1)]) (uf-union! a b) (uf-same-set? a b)) #t) (check-equal? (let ([sp (open-output-string)]) (display (uf-new "x") sp) (get-output-string sp)) "#<uf-set: x>") (check-equal? (let ([sp (open-output-string)]) (write (uf-new "x") sp) (get-output-string sp)) "#<uf-set: \"x\">") (check-equal? (let ([sp (open-output-string)]) (print (uf-new "x") sp) (get-output-string sp)) "#<uf-set: \"x\">") (check-equal? (let ([sp (open-output-string)]) (define x (vector 1)) (define a (uf-new x)) (vector-set! x 0 a) (write x sp) (get-output-string sp)) "#0=#(#<uf-set: #0#>)") (check-equal? (let ([sp (open-output-string)]) (define a (uf-new #f)) (uf-set-canonical! a a) (write a sp) (get-output-string sp)) "#0=#<uf-set: #0#>") (let ([a (uf-new 1)] [b (uf-new 2)] [c (uf-new 3)] [d (uf-new 4)] [e (uf-new 5)]) (uf-union! a b) (uf-union! c d) (uf-union! b d) (uf-union! c e) (check-equal? (uf-find a) (uf-find e))) (let ([a (uf-new 1)] [b (uf-new 2)] [c (uf-new 3)] [d (uf-new 4)] [e (uf-new 5)]) (uf-union! a b) (uf-union! c d) (uf-union! a c) (uf-union! c e) (check-equal? (uf-find a) (uf-find e))) (let ([a (uf-new 1)] [b (uf-new 2)] [c (uf-new 3)] [d (uf-new 4)] [e (uf-new 5)]) (uf-union! a b) (uf-union! c d) (uf-union! a d) (uf-union! c e) (check-equal? (uf-find a) (uf-find e))) (let ([a (uf-new 1)] [b (uf-new 2)] [c (uf-new 3)] [d (uf-new 4)] [e (uf-new 5)]) (uf-union! a b) (uf-union! c d) (uf-union! b c) (uf-union! c e) (check-equal? (uf-find a) (uf-find e))) (check-equal? (let ([a (uf-new 1)] [b (uf-new 2)] [c (uf-new 3)] [d (uf-new 4)]) (uf-union! a b) (uf-union! c d) (uf-union! a c) (max (uf-set-rank a) (uf-set-rank b) (uf-set-rank c) (uf-set-rank d))) 2) (let ((uf-sets (for/list ((x (in-range 8))) (uf-new x)))) (uf-union! (list-ref uf-sets 5) (list-ref uf-sets 7)) (uf-union! (list-ref uf-sets 1) (list-ref uf-sets 6)) (uf-union! (list-ref uf-sets 6) (list-ref uf-sets 5)) (uf-union! (list-ref uf-sets 4) (list-ref uf-sets 7)) (uf-union! (list-ref uf-sets 2) (list-ref uf-sets 0)) (uf-union! (list-ref uf-sets 2) (list-ref uf-sets 5)) (check-equal? (uf-find (list-ref uf-sets 4)) (uf-find (list-ref uf-sets 7)))) (define (run-random-tests) (define (make-random-sets num-sets) (define uf-sets (for/list ([x (in-range num-sets)]) (uf-new x))) (define edges (make-hash (build-list num-sets (λ (x) (cons x (set)))))) (define (add-edge a-num b-num) (hash-set! edges a-num (set-add (hash-ref edges a-num) b-num))) (define ops '()) (for ([op (in-range (random 10))]) (define a-num (random num-sets)) (define b-num (random num-sets)) (define a (list-ref uf-sets a-num)) (define b (list-ref uf-sets b-num)) (set! ops (cons `(uf-union! (list-ref uf-sets ,a-num) (list-ref uf-sets ,b-num)) ops)) (uf-union! a b) (add-edge a-num b-num) (add-edge b-num a-num)) (define code `(let ([uf-sets (for/list ([x (in-range ,num-sets)]) (uf-new x))]) ,@(reverse ops))) (values uf-sets edges code)) (define (check-canonical-has-path uf-sets edges code) (for ([set (in-list uf-sets)] [i (in-naturals)]) (define canon (uf-find set)) (define visited (make-hash)) (define found? (let loop ([node i]) (cond [(= node canon) #t] [(hash-ref visited node #f) #f] [else (hash-set! visited node #t) (for/or ([neighbor (in-set (hash-ref edges node))]) (loop neighbor))]))) (unless found? (pretty-print code (current-error-port)) (error 'union-find.rkt "mismatch; expected a link from ~s to ~s, didn't find it" i canon)))) (define (check-edges-share-canonical uf-sets edges code) (for ([(src dests) (in-hash edges)]) (for ([dest (in-set dests)]) (define sc (uf-find (list-ref uf-sets src))) (define dc (uf-find (list-ref uf-sets dest))) (unless (= sc dc) (pretty-print code (current-error-port)) (error 'union-find.rkt "mismatch; expected sets ~s and ~s to have the same canonical element, got ~s and ~s" src dest sc dc))))) (for ([x (in-range 10000)]) (define-values (sets edges code) (make-random-sets (+ 2 (random (+ 1 (floor (/ x 100))))))) (check-canonical-has-path sets edges code) (check-edges-share-canonical sets edges code))) (run-random-tests) (random-seed 0) (time (run-random-tests)))
e9da5ef8242e3375f14da8d0c41936fb23155f51e31d2917f6f5389c2cdb585f
knupfer/type-of-html
ExampleTypeOfHtml.hs
# OPTIONS_GHC -fno - warn - missing - signatures -fno - warn - unused - do - bind -fno - warn - name - shadowing # # LANGUAGE RebindableSyntax # module ExampleTypeOfHtml (hackageUpload) where import Prelude import Html import Html.Obsolete [ 2020 - 11 - 07 ] hackageUpload title = let (>>) = (#) in do DOCTYPE Html :> do Head :> do Meta :@ (NameA "viewport" # ContentA "width=device-width, initial-scale=1") Link :@ (HrefA "+Sans:400,400i,700" # RelA "stylesheet") Link :@ (RelA "stylesheet" # HrefA "/static/hackage.css" # TypeA "text/css") Link :@ (RelA "icon" # TypeA "image/png" # HrefA "/static/favicon.png") Link :@ (RelA "search" # TypeA "application/opensearchdescription+xml" # TitleA "Hackage" # HrefA "/packages/opensearch.xml") Raw "<!-- Global site tag (gtag.js) - Google Analytics -->" Script :@ (AsyncA # SrcA "-83290513-3") Script :> do Raw $ unlines [ "window.dataLayer = window.dataLayer || [];" , "function gtag(){dataLayer.push(arguments);}" , "gtag('js', new Date());" , "gtag('config', 'UA-83290513-3');" ] " Uploading packages and package candidates " Body :> do Div :@ IdA "page-header" :> do A :@ (ClassA "caption" # HrefA "/") :> "Hackage :: [Package]" Ul :@ (ClassA "links" # IdA "page-menu") :> do Li :> do Form :@ (ActionA "/packages/search" # MethodA "get" # ClassA "search") Button :@ TypeA "submit" :> "Search&nbsp;" Input :@ (TypeA "text" # NameA "terms") Li :> do A :@ HrefA "/packages/browse" :> "Browse" Li :> do A :@ HrefA "/packages/recent" :> "What's new" Li :> do A :@ HrefA "/upload" :> "Upload" Li :> do A :@ HrefA "/accounts" :> "User accounts" Div :@ IdA "content" :> do H2 :> "Uploading packages" Div :@ StyleA "font-size: large; text-align: center;" :> do "Upload and publish a package " Strong :> "permanently" ": " A :@ HrefA "/packages/upload" :> "Upload" P :> do "Uploading a package puts it in the " A :@ HrefA "/packages/browse" :> "package index" "so that anyone can download it and view information about it. " Strong :> "You can only upload a package version once and this cannot be undone" ", so try to get it right the first time! To reduce the risk of mistakes it's recommended to use the " A :@ HrefA "#candidates" :> "package candidates feature" " described below." P :> do "Because each package added to the main package index has a cost of operation and maintenance associated to it, " Strong :> "your package should strive to provide value for the community by being intended to be useful to others" ", which entails giving your package a meaningful synopsis/description as well as ensuring your package is installable by helping with providing accurate meta-data." P :> do "Packages must be in the form produced by Cabal's " A :@ HrefA "-guide/installing-packages.html#setup-sdist" :> "sdist" " command: a gzipped tar file " Em :> "package" "-" Em :> "version" Tt :> ".tar.gz" " comprising a directory " Em :> "package" "-" Em :> "version" " containing a package of that name and version, including " Em :> "package" Tt :> ".cabal" ". See the notes at the bottom of the page." H3 :@ IdA "versioning_and_curation" :> "Package versioning and curation" P :> do "By default, uploaded packages are " I :> "curated" " which means that both maintainers and hackage trustees may revise their metadata (particularly involving version bounds) to guide build tools in producing install-plans. (For more information on revisions, see the " A :@ HrefA "-infra/hackage-trustees/blob/master/revisions-information.md" :> "FAQ" ")." P :> do "In order to ensure the integrity and well-functioning of the Hackage/Cabal ecosystem, all curated packages " Abbr :@ TitleA "[RFC2119] The word 'should' is intended to denote that there may exist valid reasons in particular circumstances to ignore a particular item, but the full implications MUST be understood and carefully weighed before choosing a different course" :> "should" " follow Haskell's " A :@ HrefA "/":>"Package Versioning Policy (PVP)" "." P :> do "In particular, be aware that although the " A :@ HrefA "/" :> "PVP" " and " A :@ HrefA "/" :> "SemVer" " are based on the same concepts they differ significantly in structure and consequently are " Em :> "not compatible" " with each other. Please consult the " A :@ HrefA "/#semver" :> "PVP/SemVer FAQ section" " for more details about the differences and related issues." P :> do "Further, an important property of the PVP contract is that it can only be effective and provide strong enough guarantees if it is followed not only by an individual package, but also by that package's transitive dependencies. Consequently, packages which are curated should aim to depend only on other curated packages." P :> do "In the course of the curation process, the " A :@ HrefA "/packages/trustees" :> "Hackage Trustees" " need to be able to contact package maintainers, to inform them about and help to resolve issues with their packages (including its meta-data) which affect the Hackage ecosystem." P :> do "Package uploaders may choose to exclude individual package uploads from curation, by setting the " Tt :> "x-curation:" " field of the package's cabal file to " Tt :> "uncurated" ". Packages which are uncurated have no expectations on them regarding versioning policy. Trustees or maintainers may " I :> "adopt" " uncurated packages into the curated layer through metadata revisions. Metadata revisions must not set the value of the" Tt :> "x-curation" " field to any variant of " Tt :> "uncurated" "." P :> do "Two variants of the " Tt :> "uncurated" " property are supported. First, " Tt :> "uncurated-no-trustee-contact" ", which indicates that maintainers do not wish to be contacted by trustees regarding any metadata issues with the package. (Contact may still occur over issues that are not related to curation, such as licensing, etc.). Second, " Tt :> "uncurated-seeking-adoption" ", which indicates that maintainers would like their package to be adopted in the curated layer, but currently some issue prevents this, which they would like assistance with." P :> "In the future, metadata regarding curation will be made available in the UI of Hackage, and different derived indexes will be provided for the uncurated and curated layers of packages." H3 :> "Open source licenses" P :> do "The code and other material you upload and distribute via this site must be under an " Em :> "open source license" ". This is a service operated for the benefit of the community and that is our policy. It is also so that we can operate the service in compliance with copyright laws." P :> do "The Hackage operators do not want to be in the business of making judgements on what is and is not a valid open source license, but we retain the right to remove packages that are not under licenses that are open source in spirit, or that conflict with our ability to operate this service. (If you want advice, see the ones " A :@ HrefA "/package/Cabal/docs/Distribution-License.html" :> "Cabal recommends" ".)" P :> do "The Hackage operators do " Em :> "not" " need and are " Em :> "not" " asking for any rights beyond those granted by the open source license you choose to use. All normal open source licenses grant enough rights to be able to operate this service." P :> do "In particular, we expect as a consequence of the license that:" Ol :> do Li :> do "we have the right to distribute what you have uploaded to other people" Li :> do "we have the right to distribute certain derivatives and format conversions, including but not limited to:" Ul :> do Li :> do "documentation derived from the package" Li :> do "alternative presentations and formats of code (e.g. html markup)" Li :> do "excerpts and presentation of package metadataw" Li :> do "modified versions of package metadata" P :> "Please make sure that you comply with the license of all code and other material that you upload. For example, check that your tarball includes the license files of any 3rd party code that you include." H3 :> "Privileges" P :> do "To upload a package, you'll need a Hackage " A :@ HrefA "/accounts" :> "username" " and password." P :> "If you upload a package or package candidate and no other versions exist in the package database, you become part of the maintainer group for that package, and you can add other maintainers if you wish. If a maintainer group exists for a package, only its members can upload new versions of that package." P :> do "If there is no maintainer, the uploader can remove themselves from the group, and a " A :@ HrefA "/packages/trustees" :> "package trustee" " can add anyone who wishes to assume the responsibility. The " Code :> "Maintainer" " field of the Cabal file should be " Code :> "None" " in this case. If a package is being maintained, any release not approved and supported by the maintainer should use a different package name. Then use the " Code :> "Maintainer" " field as above either to commit to supporting the fork yourself or to mark it as unsupported." H3 :@ IdA "candidates" :> "Package Candidates" P :> do A :@ HrefA "/packages/candidates" :> do "Package " Em :> "candidates" " are a way to preview the package page, view any warnings or possible errors you might encounter, and let others install it before publishing it to the main index. (Note: you can view these warnings with 'cabal check'.) You can have multiple candidates for each package at the same time so long as they each have different versions. Finally, you can publish a candidate to the main index if it's not there already." P :> do "Package candidates have not yet been fully implemented and are still being improved; see " A :@ HrefA "-server/projects/1" :> "Package Candidates Project Dashboard" " for an overview of what still needs to be done." Div :@ StyleA "font-size: large; text-align: center;" :> do A :@ HrefA "/packages/candidates/upload" :> "Upload a package candidate" H3 :> "Notes" Ul :> do Li :> do "You should check that your source bundle builds, including the haddock documentation if it's a library." Li :> do "Categories are determined by whatever you put in the " Code :> "Category" " field. You should try to pick existing categories when possible. You can have more than one category, separated by commas. If no other versions of the package exist, the categories automatically become the package's tags." Li :> do "Occasional changes to the GHC base package can mean that some work needs to be done to make packages compatible across a range of versions. See " A :@ HrefA "-infra/hackage-trustees/blob/master/cookbook.md" :> "these notes" " for some tips in how to do so. There are some notes for upgrading" A :@ HrefA "" :> "much older" " packages as well." Li :> do "The hackage-server attempts to build documentation for library packages, but this can fail. Maintainers can generate their own documentation and upload it by using something along the lines of the shell script below (note that the last two commands are the key ones):" Pre :> do Raw $ unlines [ "#!/bin/sh" , "set -e" , "" , "dir=$(mktemp -d dist-docs.XXXXXX)" , "trap 'rm -r \"$dir\"' EXIT" , "# assumes cabal 2.4 or later" , "cabal v2-haddock --builddir=\"$dir\" --haddock-for-hackage --enable-doc" , "cabal upload -d --publish $dir/*-docs.tar.gz" ]
null
https://raw.githubusercontent.com/knupfer/type-of-html/981e2c2c4f90e57a55e00e18db6f6c0623292851/bench/ExampleTypeOfHtml.hs
haskell
# OPTIONS_GHC -fno - warn - missing - signatures -fno - warn - unused - do - bind -fno - warn - name - shadowing # # LANGUAGE RebindableSyntax # module ExampleTypeOfHtml (hackageUpload) where import Prelude import Html import Html.Obsolete [ 2020 - 11 - 07 ] hackageUpload title = let (>>) = (#) in do DOCTYPE Html :> do Head :> do Meta :@ (NameA "viewport" # ContentA "width=device-width, initial-scale=1") Link :@ (HrefA "+Sans:400,400i,700" # RelA "stylesheet") Link :@ (RelA "stylesheet" # HrefA "/static/hackage.css" # TypeA "text/css") Link :@ (RelA "icon" # TypeA "image/png" # HrefA "/static/favicon.png") Link :@ (RelA "search" # TypeA "application/opensearchdescription+xml" # TitleA "Hackage" # HrefA "/packages/opensearch.xml") Raw "<!-- Global site tag (gtag.js) - Google Analytics -->" Script :@ (AsyncA # SrcA "-83290513-3") Script :> do Raw $ unlines [ "window.dataLayer = window.dataLayer || [];" , "function gtag(){dataLayer.push(arguments);}" , "gtag('js', new Date());" , "gtag('config', 'UA-83290513-3');" ] " Uploading packages and package candidates " Body :> do Div :@ IdA "page-header" :> do A :@ (ClassA "caption" # HrefA "/") :> "Hackage :: [Package]" Ul :@ (ClassA "links" # IdA "page-menu") :> do Li :> do Form :@ (ActionA "/packages/search" # MethodA "get" # ClassA "search") Button :@ TypeA "submit" :> "Search&nbsp;" Input :@ (TypeA "text" # NameA "terms") Li :> do A :@ HrefA "/packages/browse" :> "Browse" Li :> do A :@ HrefA "/packages/recent" :> "What's new" Li :> do A :@ HrefA "/upload" :> "Upload" Li :> do A :@ HrefA "/accounts" :> "User accounts" Div :@ IdA "content" :> do H2 :> "Uploading packages" Div :@ StyleA "font-size: large; text-align: center;" :> do "Upload and publish a package " Strong :> "permanently" ": " A :@ HrefA "/packages/upload" :> "Upload" P :> do "Uploading a package puts it in the " A :@ HrefA "/packages/browse" :> "package index" "so that anyone can download it and view information about it. " Strong :> "You can only upload a package version once and this cannot be undone" ", so try to get it right the first time! To reduce the risk of mistakes it's recommended to use the " A :@ HrefA "#candidates" :> "package candidates feature" " described below." P :> do "Because each package added to the main package index has a cost of operation and maintenance associated to it, " Strong :> "your package should strive to provide value for the community by being intended to be useful to others" ", which entails giving your package a meaningful synopsis/description as well as ensuring your package is installable by helping with providing accurate meta-data." P :> do "Packages must be in the form produced by Cabal's " A :@ HrefA "-guide/installing-packages.html#setup-sdist" :> "sdist" " command: a gzipped tar file " Em :> "package" "-" Em :> "version" Tt :> ".tar.gz" " comprising a directory " Em :> "package" "-" Em :> "version" " containing a package of that name and version, including " Em :> "package" Tt :> ".cabal" ". See the notes at the bottom of the page." H3 :@ IdA "versioning_and_curation" :> "Package versioning and curation" P :> do "By default, uploaded packages are " I :> "curated" " which means that both maintainers and hackage trustees may revise their metadata (particularly involving version bounds) to guide build tools in producing install-plans. (For more information on revisions, see the " A :@ HrefA "-infra/hackage-trustees/blob/master/revisions-information.md" :> "FAQ" ")." P :> do "In order to ensure the integrity and well-functioning of the Hackage/Cabal ecosystem, all curated packages " Abbr :@ TitleA "[RFC2119] The word 'should' is intended to denote that there may exist valid reasons in particular circumstances to ignore a particular item, but the full implications MUST be understood and carefully weighed before choosing a different course" :> "should" " follow Haskell's " A :@ HrefA "/":>"Package Versioning Policy (PVP)" "." P :> do "In particular, be aware that although the " A :@ HrefA "/" :> "PVP" " and " A :@ HrefA "/" :> "SemVer" " are based on the same concepts they differ significantly in structure and consequently are " Em :> "not compatible" " with each other. Please consult the " A :@ HrefA "/#semver" :> "PVP/SemVer FAQ section" " for more details about the differences and related issues." P :> do "Further, an important property of the PVP contract is that it can only be effective and provide strong enough guarantees if it is followed not only by an individual package, but also by that package's transitive dependencies. Consequently, packages which are curated should aim to depend only on other curated packages." P :> do "In the course of the curation process, the " A :@ HrefA "/packages/trustees" :> "Hackage Trustees" " need to be able to contact package maintainers, to inform them about and help to resolve issues with their packages (including its meta-data) which affect the Hackage ecosystem." P :> do "Package uploaders may choose to exclude individual package uploads from curation, by setting the " Tt :> "x-curation:" " field of the package's cabal file to " Tt :> "uncurated" ". Packages which are uncurated have no expectations on them regarding versioning policy. Trustees or maintainers may " I :> "adopt" " uncurated packages into the curated layer through metadata revisions. Metadata revisions must not set the value of the" Tt :> "x-curation" " field to any variant of " Tt :> "uncurated" "." P :> do "Two variants of the " Tt :> "uncurated" " property are supported. First, " Tt :> "uncurated-no-trustee-contact" ", which indicates that maintainers do not wish to be contacted by trustees regarding any metadata issues with the package. (Contact may still occur over issues that are not related to curation, such as licensing, etc.). Second, " Tt :> "uncurated-seeking-adoption" ", which indicates that maintainers would like their package to be adopted in the curated layer, but currently some issue prevents this, which they would like assistance with." P :> "In the future, metadata regarding curation will be made available in the UI of Hackage, and different derived indexes will be provided for the uncurated and curated layers of packages." H3 :> "Open source licenses" P :> do "The code and other material you upload and distribute via this site must be under an " Em :> "open source license" ". This is a service operated for the benefit of the community and that is our policy. It is also so that we can operate the service in compliance with copyright laws." P :> do "The Hackage operators do not want to be in the business of making judgements on what is and is not a valid open source license, but we retain the right to remove packages that are not under licenses that are open source in spirit, or that conflict with our ability to operate this service. (If you want advice, see the ones " A :@ HrefA "/package/Cabal/docs/Distribution-License.html" :> "Cabal recommends" ".)" P :> do "The Hackage operators do " Em :> "not" " need and are " Em :> "not" " asking for any rights beyond those granted by the open source license you choose to use. All normal open source licenses grant enough rights to be able to operate this service." P :> do "In particular, we expect as a consequence of the license that:" Ol :> do Li :> do "we have the right to distribute what you have uploaded to other people" Li :> do "we have the right to distribute certain derivatives and format conversions, including but not limited to:" Ul :> do Li :> do "documentation derived from the package" Li :> do "alternative presentations and formats of code (e.g. html markup)" Li :> do "excerpts and presentation of package metadataw" Li :> do "modified versions of package metadata" P :> "Please make sure that you comply with the license of all code and other material that you upload. For example, check that your tarball includes the license files of any 3rd party code that you include." H3 :> "Privileges" P :> do "To upload a package, you'll need a Hackage " A :@ HrefA "/accounts" :> "username" " and password." P :> "If you upload a package or package candidate and no other versions exist in the package database, you become part of the maintainer group for that package, and you can add other maintainers if you wish. If a maintainer group exists for a package, only its members can upload new versions of that package." P :> do "If there is no maintainer, the uploader can remove themselves from the group, and a " A :@ HrefA "/packages/trustees" :> "package trustee" " can add anyone who wishes to assume the responsibility. The " Code :> "Maintainer" " field of the Cabal file should be " Code :> "None" " in this case. If a package is being maintained, any release not approved and supported by the maintainer should use a different package name. Then use the " Code :> "Maintainer" " field as above either to commit to supporting the fork yourself or to mark it as unsupported." H3 :@ IdA "candidates" :> "Package Candidates" P :> do A :@ HrefA "/packages/candidates" :> do "Package " Em :> "candidates" " are a way to preview the package page, view any warnings or possible errors you might encounter, and let others install it before publishing it to the main index. (Note: you can view these warnings with 'cabal check'.) You can have multiple candidates for each package at the same time so long as they each have different versions. Finally, you can publish a candidate to the main index if it's not there already." P :> do "Package candidates have not yet been fully implemented and are still being improved; see " A :@ HrefA "-server/projects/1" :> "Package Candidates Project Dashboard" " for an overview of what still needs to be done." Div :@ StyleA "font-size: large; text-align: center;" :> do A :@ HrefA "/packages/candidates/upload" :> "Upload a package candidate" H3 :> "Notes" Ul :> do Li :> do "You should check that your source bundle builds, including the haddock documentation if it's a library." Li :> do "Categories are determined by whatever you put in the " Code :> "Category" " field. You should try to pick existing categories when possible. You can have more than one category, separated by commas. If no other versions of the package exist, the categories automatically become the package's tags." Li :> do "Occasional changes to the GHC base package can mean that some work needs to be done to make packages compatible across a range of versions. See " A :@ HrefA "-infra/hackage-trustees/blob/master/cookbook.md" :> "these notes" " for some tips in how to do so. There are some notes for upgrading" A :@ HrefA "" :> "much older" " packages as well." Li :> do "The hackage-server attempts to build documentation for library packages, but this can fail. Maintainers can generate their own documentation and upload it by using something along the lines of the shell script below (note that the last two commands are the key ones):" Pre :> do Raw $ unlines [ "#!/bin/sh" , "set -e" , "" , "dir=$(mktemp -d dist-docs.XXXXXX)" , "trap 'rm -r \"$dir\"' EXIT" , "# assumes cabal 2.4 or later" , "cabal v2-haddock --builddir=\"$dir\" --haddock-for-hackage --enable-doc" , "cabal upload -d --publish $dir/*-docs.tar.gz" ]
b5414be537b6bba3424711cb90814afe12784d7599c14c3a869b5418147b354d
spechub/Hets
SymMapAna.hs
| Module : ./CspCASL / SymMapAna.hs Description : symbol map analysis for the CspCASL logic . Copyright : ( c ) , DFKI GmbH 2011 License : GPLv2 or higher , see LICENSE.txt Maintainer : Stability : provisional Portability : portable Module : ./CspCASL/SymMapAna.hs Description : symbol map analysis for the CspCASL logic. Copyright : (c) Christian Maeder, DFKI GmbH 2011 License : GPLv2 or higher, see LICENSE.txt Maintainer : Stability : provisional Portability : portable -} module CspCASL.SymMapAna where import CspCASL.AS_CspCASL_Process import CspCASL.Morphism import CspCASL.SignCSP import CspCASL.SymbItems import CspCASL.Symbol import CASL.Sign import CASL.AS_Basic_CASL import CASL.Morphism import CASL.SymbolMapAnalysis import Common.DocUtils import Common.ExtSign import Common.Id import Common.Result import qualified Common.Lib.Rel as Rel import qualified Common.Lib.MapSet as MapSet import qualified Data.Map as Map import qualified Data.Set as Set import Data.List (partition) import Data.Maybe type CspRawMap = Map.Map CspRawSymbol CspRawSymbol cspInducedFromToMorphism :: CspRawMap -> ExtSign CspCASLSign CspSymbol -> ExtSign CspCASLSign CspSymbol -> Result CspCASLMorphism cspInducedFromToMorphism rmap (ExtSign sSig sy) (ExtSign tSig tSy) = let (crm, rm) = splitSymbolMap rmap in if Map.null rm then inducedFromToMorphismExt inducedCspSign (constMorphExt emptyCspAddMorphism) composeMorphismExtension isCspSubSign diffCspSig crm (ExtSign sSig $ getCASLSymbols sy) $ ExtSign tSig $ getCASLSymbols tSy else do mor <- cspInducedFromMorphism rmap sSig let iSig = mtarget mor if isSubSig isCspSubSign iSig tSig then do incl <- sigInclusion emptyCspAddMorphism iSig tSig composeM composeMorphismExtension mor incl else fatal_error ("No signature morphism for csp symbol map found.\n" ++ "The following mapped symbols are missing in the target signature:\n" ++ showDoc (diffSig diffCspSig iSig tSig) "") $ concatMapRange getRange $ Map.keys rmap cspInducedFromMorphism :: CspRawMap -> CspCASLSign -> Result CspCASLMorphism cspInducedFromMorphism rmap sigma = do let (crm, _) = splitSymbolMap rmap m <- inducedFromMorphism emptyCspAddMorphism crm sigma let sm = sort_map m om = op_map m pm = pred_map m csig = extendedInfo sigma newSRel = Rel.transClosure . sortRel $ mtarget m -- compute the channel name map (as a Map) cm <- Map.foldrWithKey (chanFun sigma rmap sm) (return Map.empty) (MapSet.toMap $ chans csig) -- compute the process name map (as a Map) proc_Map <- Map.foldrWithKey (procFun sigma rmap sm newSRel cm) (return Map.empty) (MapSet.toMap $ procSet csig) let em = emptyCspAddMorphism { channelMap = cm , processMap = proc_Map } return (embedMorphism em sigma $ closeSortRel $ inducedSignAux inducedCspSign sm om pm em sigma) { sort_map = sm , op_map = om , pred_map = pm } chanFun :: CspCASLSign -> CspRawMap -> Sort_map -> Id -> Set.Set SORT -> Result ChanMap -> Result ChanMap chanFun sig rmap sm cn ss m = let sls = Rel.partSet (relatedSorts sig) ss m1 = foldr (directChanMap rmap sm cn) m sls in case (Map.lookup (CspKindedSymb ChannelKind cn) rmap, Map.lookup (CspKindedSymb (CaslKind Implicit) cn) rmap) of (Just rsy1, Just rsy2) -> let m2 = Set.fold (insertChanSym sm cn rsy1) m1 ss in Set.fold (insertChanSym sm cn rsy2) m2 ss (Just rsy, Nothing) -> Set.fold (insertChanSym sm cn rsy) m1 ss (Nothing, Just rsy) -> Set.fold (insertChanSym sm cn rsy) m1 ss -- Anything not mapped explicitly is left unchanged (Nothing, Nothing) -> m1 directChanMap :: CspRawMap -> Sort_map -> Id -> Set.Set SORT -> Result ChanMap -> Result ChanMap directChanMap rmap sm cn ss m = let sl = Set.toList ss rl = map (\ s -> Map.lookup (ACspSymbol $ toChanSymbol (cn, s)) rmap) sl (ms, ps) = partition (isJust . fst) $ zip rl sl in case ms of l@((Just rsy, _) : rs) -> foldr (\ (_, s) -> insertChanSym sm cn (ACspSymbol $ toChanSymbol (rawId rsy, mapSort sm s)) s) (foldr (\ (rsy2, s) -> insertChanSym sm cn (fromJust rsy2) s) m l) $ rs ++ ps _ -> m insertChanSym :: Sort_map -> Id -> CspRawSymbol -> SORT -> Result ChanMap -> Result ChanMap insertChanSym sm cn rsy s m = do m1 <- m c1 <- mappedChanSym sm cn s rsy let ptsy = CspSymbol cn $ ChanAsItemType s pos = getRange rsy m2 = Map.insert (cn, s) c1 m1 case Map.lookup (cn, s) m1 of Nothing -> if cn == c1 then case rsy of ACspSymbol _ -> return m1 _ -> hint m1 ("identity mapping of " ++ showDoc ptsy "") pos else return m2 Just c2 -> if c1 == c2 then warning m1 ("ignoring duplicate mapping of " ++ showDoc ptsy "") pos else plain_error m1 ("conflicting mapping of " ++ showDoc ptsy " to " ++ show c1 ++ " and " ++ show c2) pos mappedChanSym :: Sort_map -> Id -> SORT -> CspRawSymbol -> Result Id mappedChanSym sm cn s rsy = let chanSym = "channel symbol " ++ showDoc (toChanSymbol (cn, s)) " is mapped to " in case rsy of ACspSymbol (CspSymbol ide (ChanAsItemType s1)) -> let s2 = mapSort sm s in if s1 == s2 then return ide else plain_error cn (chanSym ++ "sort " ++ showDoc s1 " but should be mapped to type " ++ showDoc s2 "") $ getRange rsy CspKindedSymb k ide | elem k [CaslKind Implicit, ChannelKind] -> return ide _ -> plain_error cn (chanSym ++ "symbol of wrong kind: " ++ showDoc rsy "") $ getRange rsy procFun :: CspCASLSign -> CspRawMap -> Sort_map -> Rel.Rel SORT -> ChanMap -> Id -> Set.Set ProcProfile -> Result ProcessMap -> Result ProcessMap procFun sig rmap sm rel cm pn ps m = let pls = Rel.partSet (relatedProcs sig) ps m1 = foldr (directProcMap rmap sm rel cm pn) m pls -- now try the remaining ones with (un)kinded raw symbol in case (Map.lookup (CspKindedSymb ProcessKind pn) rmap, Map.lookup (CspKindedSymb (CaslKind Implicit) pn) rmap) of (Just rsy1, Just rsy2) -> let m2 = Set.fold (insertProcSym sm rel cm pn rsy1) m1 ps in Set.fold (insertProcSym sm rel cm pn rsy2) m2 ps (Just rsy, Nothing) -> Set.fold (insertProcSym sm rel cm pn rsy) m1 ps (Nothing, Just rsy) -> Set.fold (insertProcSym sm rel cm pn rsy) m1 ps -- Anything not mapped explicitly is left unchanged (Nothing, Nothing) -> m1 directProcMap :: CspRawMap -> Sort_map -> Rel.Rel SORT -> ChanMap -> Id -> Set.Set ProcProfile -> Result ProcessMap -> Result ProcessMap directProcMap rmap sm rel cm pn ps m = let pl = Set.toList ps rl = map (lookupProcSymbol rmap pn) pl (ms, os) = partition (isJust . fst) $ zip rl pl in case ms of l@((Just rsy, _) : rs) -> foldr (\ (_, p) -> insertProcSym sm rel cm pn (ACspSymbol $ toProcSymbol (rawId rsy, mapProcProfile sm cm p)) p) (foldr (\ (rsy2, p) -> insertProcSym sm rel cm pn (fromJust rsy2) p) m l) $ rs ++ os _ -> m lookupProcSymbol :: CspRawMap -> Id -> ProcProfile -> Maybe CspRawSymbol lookupProcSymbol rmap pn p = case filter (\ (k, _) -> case k of ACspSymbol (CspSymbol i (ProcAsItemType pf)) -> i == pn && matchProcTypes p pf _ -> False) $ Map.toList rmap of [(_, r)] -> Just r [] -> Nothing -- in case of ambiguities try to find an exact match l -> lookup (ACspSymbol $ toProcSymbol (pn, p)) l insertProcSym :: Sort_map -> Rel.Rel SORT -> ChanMap -> Id -> CspRawSymbol -> ProcProfile -> Result ProcessMap -> Result ProcessMap insertProcSym sm rel cm pn rsy pf@(ProcProfile _ al) m = do m1 <- m (p1, al1) <- mappedProcSym sm rel cm pn pf rsy let otsy = toProcSymbol (pn, pf) pos = getRange rsy m2 = Map.insert (pn, pf) p1 m1 case Map.lookup (pn, pf) m1 of Nothing -> if pn == p1 && al == al1 then case rsy of ACspSymbol _ -> return m1 _ -> hint m1 ("identity mapping of " ++ showDoc otsy "") pos else return m2 Just p2 -> if p1 == p2 then warning m1 ("ignoring duplicate mapping of " ++ showDoc otsy "") pos else plain_error m1 ("conflicting mapping of " ++ showDoc otsy " to " ++ show p1 ++ " and " ++ show p2) pos mappedProcSym :: Sort_map -> Rel.Rel SORT -> ChanMap -> Id -> ProcProfile -> CspRawSymbol -> Result (Id, CommAlpha) mappedProcSym sm rel cm pn pfSrc rsy = let procSym = "process symbol " ++ showDoc (toProcSymbol (pn, pfSrc)) " is mapped to " pfMapped@(ProcProfile _ al2) = reduceProcProfile rel $ mapProcProfile sm cm pfSrc in case rsy of ACspSymbol (CspSymbol ide (ProcAsItemType pf)) -> let pfTar@(ProcProfile _ al1) = reduceProcProfile rel pf in if compatibleProcTypes rel pfMapped pfTar then return (ide, al1) else plain_error (pn, al2) (procSym ++ "type " ++ showDoc pfTar "\nbut should be mapped to type " ++ showDoc pfMapped "\npossibly using a sub-alphabet of " ++ showDoc (closeCspCommAlpha rel al2) ".") $ getRange rsy CspKindedSymb k ide | elem k [CaslKind Implicit, ProcessKind] -> return (ide, al2) _ -> plain_error (pn, al2) (procSym ++ "symbol of wrong kind: " ++ showDoc rsy "") $ getRange rsy compatibleProcTypes :: Rel.Rel SORT -> ProcProfile -> ProcProfile -> Bool compatibleProcTypes rel (ProcProfile l1 al1) (ProcProfile l2 al2) = l1 == l2 && liamsRelatedCommAlpha rel al1 al2 liamsRelatedCommAlpha :: Rel.Rel SORT -> CommAlpha -> CommAlpha -> Bool liamsRelatedCommAlpha rel al1 al2 = all (\ a2 -> any (\ a1 -> liamsRelatedCommTypes rel a1 a2) $ Set.toList al1) $ Set.toList al2 liamsRelatedCommTypes :: Rel.Rel SORT -> CommType -> CommType -> Bool liamsRelatedCommTypes rel ct1 ct2 = case (ct1, ct2) of (CommTypeSort s1, CommTypeSort s2) -> s1 == s2 || s1 `Set.member` Rel.succs rel s2 (CommTypeChan (TypedChanName c1 s1), CommTypeChan (TypedChanName c2 s2)) -> c1 == c2 && s1 == s2 _ -> False matchProcTypes :: ProcProfile -> ProcProfile -> Bool matchProcTypes (ProcProfile l1 al1) (ProcProfile l2 al2) = l1 == l2 && (Set.null al2 || Set.null al1 || not (Set.null $ Set.intersection al1 al2)) cspMatches :: CspSymbol -> CspRawSymbol -> Bool cspMatches (CspSymbol i t) rsy = case rsy of ACspSymbol (CspSymbol j t2) -> i == j && case (t, t2) of (CaslSymbType t1, CaslSymbType t3) -> matches (Symbol i t1) $ ASymbol $ Symbol j t3 (ChanAsItemType s1, ChanAsItemType s2) -> s1 == s2 (ProcAsItemType p1, ProcAsItemType p2) -> matchProcTypes p1 p2 _ -> False CspKindedSymb k j -> let res = i == j in case (k, t) of (CaslKind ck, CaslSymbType t1) -> matches (Symbol i t1) $ AKindedSymb ck j (ChannelKind, ChanAsItemType _) -> res (ProcessKind, ProcAsItemType _) -> res (CaslKind Implicit, _) -> res _ -> False procProfile2Sorts :: ProcProfile -> Set.Set SORT procProfile2Sorts (ProcProfile sorts al) = Set.union (Set.fromList sorts) $ Set.map commType2Sort al cspRevealSym :: CspSymbol -> CspCASLSign -> CspCASLSign cspRevealSym sy sig = let n = cspSymName sy r = sortRel sig ext = extendedInfo sig cs = chans ext in case cspSymbType sy of CaslSymbType t -> revealSym (Symbol n t) sig ChanAsItemType s -> sig { sortRel = Rel.insertKey s r , extendedInfo = ext { chans = MapSet.insert n s cs }} ProcAsItemType p@(ProcProfile _ al) -> sig { sortRel = Rel.union (Rel.fromKeysSet $ procProfile2Sorts p) r , extendedInfo = ext { chans = Set.fold (\ ct -> case ct of CommTypeSort _ -> id CommTypeChan (TypedChanName c s) -> MapSet.insert c s) cs al , procSet = MapSet.insert n p $ procSet ext } } cspGeneratedSign :: Set.Set CspSymbol -> CspCASLSign -> Result CspCASLMorphism cspGeneratedSign sys sigma = let symset = Set.unions $ symSets sigma sigma1 = Set.fold cspRevealSym sigma { sortRel = Rel.empty , opMap = MapSet.empty , predMap = MapSet.empty , extendedInfo = emptyCspSign } sys sigma2 = sigma1 { sortRel = sortRel sigma `Rel.restrict` sortSet sigma1 , emptySortSet = Set.intersection (sortSet sigma1) $ emptySortSet sigma } in if not $ Set.isSubsetOf sys symset then let diffsyms = sys Set.\\ symset in fatal_error ("Revealing: The following symbols " ++ showDoc diffsyms " are not in the signature") $ getRange diffsyms else cspSubsigInclusion sigma2 sigma cspCogeneratedSign :: Set.Set CspSymbol -> CspCASLSign -> Result CspCASLMorphism cspCogeneratedSign symset sigma = let symset0 = Set.unions $ symSets sigma symset1 = Set.fold cspHideSym symset0 symset in if Set.isSubsetOf symset symset0 then cspGeneratedSign symset1 sigma else let diffsyms = symset Set.\\ symset0 in fatal_error ("Hiding: The following symbols " ++ showDoc diffsyms " are not in the signature") $ getRange diffsyms cspHideSym :: CspSymbol -> Set.Set CspSymbol -> Set.Set CspSymbol cspHideSym sy set1 = let set2 = Set.delete sy set1 n = cspSymName sy in case cspSymbType sy of CaslSymbType SortAsItemType -> Set.filter (not . cspProfileContains n . cspSymbType) set2 ChanAsItemType s -> Set.filter (unusedChan n s) set2 _ -> set2 cspProfileContains :: Id -> CspSymbType -> Bool cspProfileContains s ty = case ty of CaslSymbType t -> profileContainsSort s t ChanAsItemType s2 -> s == s2 ProcAsItemType p -> Set.member s $ procProfile2Sorts p unusedChan :: Id -> SORT -> CspSymbol -> Bool unusedChan c s sy = case cspSymbType sy of ProcAsItemType (ProcProfile _ al) -> Set.fold (\ ct b -> case ct of CommTypeSort _ -> b CommTypeChan (TypedChanName c2 s2) -> b && (c, s) /= (c2, s2)) True al _ -> True
null
https://raw.githubusercontent.com/spechub/Hets/bbaa9dd2d2e5eb1f2fd3ec6c799a6dde7dee6da2/CspCASL/SymMapAna.hs
haskell
compute the channel name map (as a Map) compute the process name map (as a Map) Anything not mapped explicitly is left unchanged now try the remaining ones with (un)kinded raw symbol Anything not mapped explicitly is left unchanged in case of ambiguities try to find an exact match
| Module : ./CspCASL / SymMapAna.hs Description : symbol map analysis for the CspCASL logic . Copyright : ( c ) , DFKI GmbH 2011 License : GPLv2 or higher , see LICENSE.txt Maintainer : Stability : provisional Portability : portable Module : ./CspCASL/SymMapAna.hs Description : symbol map analysis for the CspCASL logic. Copyright : (c) Christian Maeder, DFKI GmbH 2011 License : GPLv2 or higher, see LICENSE.txt Maintainer : Stability : provisional Portability : portable -} module CspCASL.SymMapAna where import CspCASL.AS_CspCASL_Process import CspCASL.Morphism import CspCASL.SignCSP import CspCASL.SymbItems import CspCASL.Symbol import CASL.Sign import CASL.AS_Basic_CASL import CASL.Morphism import CASL.SymbolMapAnalysis import Common.DocUtils import Common.ExtSign import Common.Id import Common.Result import qualified Common.Lib.Rel as Rel import qualified Common.Lib.MapSet as MapSet import qualified Data.Map as Map import qualified Data.Set as Set import Data.List (partition) import Data.Maybe type CspRawMap = Map.Map CspRawSymbol CspRawSymbol cspInducedFromToMorphism :: CspRawMap -> ExtSign CspCASLSign CspSymbol -> ExtSign CspCASLSign CspSymbol -> Result CspCASLMorphism cspInducedFromToMorphism rmap (ExtSign sSig sy) (ExtSign tSig tSy) = let (crm, rm) = splitSymbolMap rmap in if Map.null rm then inducedFromToMorphismExt inducedCspSign (constMorphExt emptyCspAddMorphism) composeMorphismExtension isCspSubSign diffCspSig crm (ExtSign sSig $ getCASLSymbols sy) $ ExtSign tSig $ getCASLSymbols tSy else do mor <- cspInducedFromMorphism rmap sSig let iSig = mtarget mor if isSubSig isCspSubSign iSig tSig then do incl <- sigInclusion emptyCspAddMorphism iSig tSig composeM composeMorphismExtension mor incl else fatal_error ("No signature morphism for csp symbol map found.\n" ++ "The following mapped symbols are missing in the target signature:\n" ++ showDoc (diffSig diffCspSig iSig tSig) "") $ concatMapRange getRange $ Map.keys rmap cspInducedFromMorphism :: CspRawMap -> CspCASLSign -> Result CspCASLMorphism cspInducedFromMorphism rmap sigma = do let (crm, _) = splitSymbolMap rmap m <- inducedFromMorphism emptyCspAddMorphism crm sigma let sm = sort_map m om = op_map m pm = pred_map m csig = extendedInfo sigma newSRel = Rel.transClosure . sortRel $ mtarget m cm <- Map.foldrWithKey (chanFun sigma rmap sm) (return Map.empty) (MapSet.toMap $ chans csig) proc_Map <- Map.foldrWithKey (procFun sigma rmap sm newSRel cm) (return Map.empty) (MapSet.toMap $ procSet csig) let em = emptyCspAddMorphism { channelMap = cm , processMap = proc_Map } return (embedMorphism em sigma $ closeSortRel $ inducedSignAux inducedCspSign sm om pm em sigma) { sort_map = sm , op_map = om , pred_map = pm } chanFun :: CspCASLSign -> CspRawMap -> Sort_map -> Id -> Set.Set SORT -> Result ChanMap -> Result ChanMap chanFun sig rmap sm cn ss m = let sls = Rel.partSet (relatedSorts sig) ss m1 = foldr (directChanMap rmap sm cn) m sls in case (Map.lookup (CspKindedSymb ChannelKind cn) rmap, Map.lookup (CspKindedSymb (CaslKind Implicit) cn) rmap) of (Just rsy1, Just rsy2) -> let m2 = Set.fold (insertChanSym sm cn rsy1) m1 ss in Set.fold (insertChanSym sm cn rsy2) m2 ss (Just rsy, Nothing) -> Set.fold (insertChanSym sm cn rsy) m1 ss (Nothing, Just rsy) -> Set.fold (insertChanSym sm cn rsy) m1 ss (Nothing, Nothing) -> m1 directChanMap :: CspRawMap -> Sort_map -> Id -> Set.Set SORT -> Result ChanMap -> Result ChanMap directChanMap rmap sm cn ss m = let sl = Set.toList ss rl = map (\ s -> Map.lookup (ACspSymbol $ toChanSymbol (cn, s)) rmap) sl (ms, ps) = partition (isJust . fst) $ zip rl sl in case ms of l@((Just rsy, _) : rs) -> foldr (\ (_, s) -> insertChanSym sm cn (ACspSymbol $ toChanSymbol (rawId rsy, mapSort sm s)) s) (foldr (\ (rsy2, s) -> insertChanSym sm cn (fromJust rsy2) s) m l) $ rs ++ ps _ -> m insertChanSym :: Sort_map -> Id -> CspRawSymbol -> SORT -> Result ChanMap -> Result ChanMap insertChanSym sm cn rsy s m = do m1 <- m c1 <- mappedChanSym sm cn s rsy let ptsy = CspSymbol cn $ ChanAsItemType s pos = getRange rsy m2 = Map.insert (cn, s) c1 m1 case Map.lookup (cn, s) m1 of Nothing -> if cn == c1 then case rsy of ACspSymbol _ -> return m1 _ -> hint m1 ("identity mapping of " ++ showDoc ptsy "") pos else return m2 Just c2 -> if c1 == c2 then warning m1 ("ignoring duplicate mapping of " ++ showDoc ptsy "") pos else plain_error m1 ("conflicting mapping of " ++ showDoc ptsy " to " ++ show c1 ++ " and " ++ show c2) pos mappedChanSym :: Sort_map -> Id -> SORT -> CspRawSymbol -> Result Id mappedChanSym sm cn s rsy = let chanSym = "channel symbol " ++ showDoc (toChanSymbol (cn, s)) " is mapped to " in case rsy of ACspSymbol (CspSymbol ide (ChanAsItemType s1)) -> let s2 = mapSort sm s in if s1 == s2 then return ide else plain_error cn (chanSym ++ "sort " ++ showDoc s1 " but should be mapped to type " ++ showDoc s2 "") $ getRange rsy CspKindedSymb k ide | elem k [CaslKind Implicit, ChannelKind] -> return ide _ -> plain_error cn (chanSym ++ "symbol of wrong kind: " ++ showDoc rsy "") $ getRange rsy procFun :: CspCASLSign -> CspRawMap -> Sort_map -> Rel.Rel SORT -> ChanMap -> Id -> Set.Set ProcProfile -> Result ProcessMap -> Result ProcessMap procFun sig rmap sm rel cm pn ps m = let pls = Rel.partSet (relatedProcs sig) ps m1 = foldr (directProcMap rmap sm rel cm pn) m pls in case (Map.lookup (CspKindedSymb ProcessKind pn) rmap, Map.lookup (CspKindedSymb (CaslKind Implicit) pn) rmap) of (Just rsy1, Just rsy2) -> let m2 = Set.fold (insertProcSym sm rel cm pn rsy1) m1 ps in Set.fold (insertProcSym sm rel cm pn rsy2) m2 ps (Just rsy, Nothing) -> Set.fold (insertProcSym sm rel cm pn rsy) m1 ps (Nothing, Just rsy) -> Set.fold (insertProcSym sm rel cm pn rsy) m1 ps (Nothing, Nothing) -> m1 directProcMap :: CspRawMap -> Sort_map -> Rel.Rel SORT -> ChanMap -> Id -> Set.Set ProcProfile -> Result ProcessMap -> Result ProcessMap directProcMap rmap sm rel cm pn ps m = let pl = Set.toList ps rl = map (lookupProcSymbol rmap pn) pl (ms, os) = partition (isJust . fst) $ zip rl pl in case ms of l@((Just rsy, _) : rs) -> foldr (\ (_, p) -> insertProcSym sm rel cm pn (ACspSymbol $ toProcSymbol (rawId rsy, mapProcProfile sm cm p)) p) (foldr (\ (rsy2, p) -> insertProcSym sm rel cm pn (fromJust rsy2) p) m l) $ rs ++ os _ -> m lookupProcSymbol :: CspRawMap -> Id -> ProcProfile -> Maybe CspRawSymbol lookupProcSymbol rmap pn p = case filter (\ (k, _) -> case k of ACspSymbol (CspSymbol i (ProcAsItemType pf)) -> i == pn && matchProcTypes p pf _ -> False) $ Map.toList rmap of [(_, r)] -> Just r [] -> Nothing l -> lookup (ACspSymbol $ toProcSymbol (pn, p)) l insertProcSym :: Sort_map -> Rel.Rel SORT -> ChanMap -> Id -> CspRawSymbol -> ProcProfile -> Result ProcessMap -> Result ProcessMap insertProcSym sm rel cm pn rsy pf@(ProcProfile _ al) m = do m1 <- m (p1, al1) <- mappedProcSym sm rel cm pn pf rsy let otsy = toProcSymbol (pn, pf) pos = getRange rsy m2 = Map.insert (pn, pf) p1 m1 case Map.lookup (pn, pf) m1 of Nothing -> if pn == p1 && al == al1 then case rsy of ACspSymbol _ -> return m1 _ -> hint m1 ("identity mapping of " ++ showDoc otsy "") pos else return m2 Just p2 -> if p1 == p2 then warning m1 ("ignoring duplicate mapping of " ++ showDoc otsy "") pos else plain_error m1 ("conflicting mapping of " ++ showDoc otsy " to " ++ show p1 ++ " and " ++ show p2) pos mappedProcSym :: Sort_map -> Rel.Rel SORT -> ChanMap -> Id -> ProcProfile -> CspRawSymbol -> Result (Id, CommAlpha) mappedProcSym sm rel cm pn pfSrc rsy = let procSym = "process symbol " ++ showDoc (toProcSymbol (pn, pfSrc)) " is mapped to " pfMapped@(ProcProfile _ al2) = reduceProcProfile rel $ mapProcProfile sm cm pfSrc in case rsy of ACspSymbol (CspSymbol ide (ProcAsItemType pf)) -> let pfTar@(ProcProfile _ al1) = reduceProcProfile rel pf in if compatibleProcTypes rel pfMapped pfTar then return (ide, al1) else plain_error (pn, al2) (procSym ++ "type " ++ showDoc pfTar "\nbut should be mapped to type " ++ showDoc pfMapped "\npossibly using a sub-alphabet of " ++ showDoc (closeCspCommAlpha rel al2) ".") $ getRange rsy CspKindedSymb k ide | elem k [CaslKind Implicit, ProcessKind] -> return (ide, al2) _ -> plain_error (pn, al2) (procSym ++ "symbol of wrong kind: " ++ showDoc rsy "") $ getRange rsy compatibleProcTypes :: Rel.Rel SORT -> ProcProfile -> ProcProfile -> Bool compatibleProcTypes rel (ProcProfile l1 al1) (ProcProfile l2 al2) = l1 == l2 && liamsRelatedCommAlpha rel al1 al2 liamsRelatedCommAlpha :: Rel.Rel SORT -> CommAlpha -> CommAlpha -> Bool liamsRelatedCommAlpha rel al1 al2 = all (\ a2 -> any (\ a1 -> liamsRelatedCommTypes rel a1 a2) $ Set.toList al1) $ Set.toList al2 liamsRelatedCommTypes :: Rel.Rel SORT -> CommType -> CommType -> Bool liamsRelatedCommTypes rel ct1 ct2 = case (ct1, ct2) of (CommTypeSort s1, CommTypeSort s2) -> s1 == s2 || s1 `Set.member` Rel.succs rel s2 (CommTypeChan (TypedChanName c1 s1), CommTypeChan (TypedChanName c2 s2)) -> c1 == c2 && s1 == s2 _ -> False matchProcTypes :: ProcProfile -> ProcProfile -> Bool matchProcTypes (ProcProfile l1 al1) (ProcProfile l2 al2) = l1 == l2 && (Set.null al2 || Set.null al1 || not (Set.null $ Set.intersection al1 al2)) cspMatches :: CspSymbol -> CspRawSymbol -> Bool cspMatches (CspSymbol i t) rsy = case rsy of ACspSymbol (CspSymbol j t2) -> i == j && case (t, t2) of (CaslSymbType t1, CaslSymbType t3) -> matches (Symbol i t1) $ ASymbol $ Symbol j t3 (ChanAsItemType s1, ChanAsItemType s2) -> s1 == s2 (ProcAsItemType p1, ProcAsItemType p2) -> matchProcTypes p1 p2 _ -> False CspKindedSymb k j -> let res = i == j in case (k, t) of (CaslKind ck, CaslSymbType t1) -> matches (Symbol i t1) $ AKindedSymb ck j (ChannelKind, ChanAsItemType _) -> res (ProcessKind, ProcAsItemType _) -> res (CaslKind Implicit, _) -> res _ -> False procProfile2Sorts :: ProcProfile -> Set.Set SORT procProfile2Sorts (ProcProfile sorts al) = Set.union (Set.fromList sorts) $ Set.map commType2Sort al cspRevealSym :: CspSymbol -> CspCASLSign -> CspCASLSign cspRevealSym sy sig = let n = cspSymName sy r = sortRel sig ext = extendedInfo sig cs = chans ext in case cspSymbType sy of CaslSymbType t -> revealSym (Symbol n t) sig ChanAsItemType s -> sig { sortRel = Rel.insertKey s r , extendedInfo = ext { chans = MapSet.insert n s cs }} ProcAsItemType p@(ProcProfile _ al) -> sig { sortRel = Rel.union (Rel.fromKeysSet $ procProfile2Sorts p) r , extendedInfo = ext { chans = Set.fold (\ ct -> case ct of CommTypeSort _ -> id CommTypeChan (TypedChanName c s) -> MapSet.insert c s) cs al , procSet = MapSet.insert n p $ procSet ext } } cspGeneratedSign :: Set.Set CspSymbol -> CspCASLSign -> Result CspCASLMorphism cspGeneratedSign sys sigma = let symset = Set.unions $ symSets sigma sigma1 = Set.fold cspRevealSym sigma { sortRel = Rel.empty , opMap = MapSet.empty , predMap = MapSet.empty , extendedInfo = emptyCspSign } sys sigma2 = sigma1 { sortRel = sortRel sigma `Rel.restrict` sortSet sigma1 , emptySortSet = Set.intersection (sortSet sigma1) $ emptySortSet sigma } in if not $ Set.isSubsetOf sys symset then let diffsyms = sys Set.\\ symset in fatal_error ("Revealing: The following symbols " ++ showDoc diffsyms " are not in the signature") $ getRange diffsyms else cspSubsigInclusion sigma2 sigma cspCogeneratedSign :: Set.Set CspSymbol -> CspCASLSign -> Result CspCASLMorphism cspCogeneratedSign symset sigma = let symset0 = Set.unions $ symSets sigma symset1 = Set.fold cspHideSym symset0 symset in if Set.isSubsetOf symset symset0 then cspGeneratedSign symset1 sigma else let diffsyms = symset Set.\\ symset0 in fatal_error ("Hiding: The following symbols " ++ showDoc diffsyms " are not in the signature") $ getRange diffsyms cspHideSym :: CspSymbol -> Set.Set CspSymbol -> Set.Set CspSymbol cspHideSym sy set1 = let set2 = Set.delete sy set1 n = cspSymName sy in case cspSymbType sy of CaslSymbType SortAsItemType -> Set.filter (not . cspProfileContains n . cspSymbType) set2 ChanAsItemType s -> Set.filter (unusedChan n s) set2 _ -> set2 cspProfileContains :: Id -> CspSymbType -> Bool cspProfileContains s ty = case ty of CaslSymbType t -> profileContainsSort s t ChanAsItemType s2 -> s == s2 ProcAsItemType p -> Set.member s $ procProfile2Sorts p unusedChan :: Id -> SORT -> CspSymbol -> Bool unusedChan c s sy = case cspSymbType sy of ProcAsItemType (ProcProfile _ al) -> Set.fold (\ ct b -> case ct of CommTypeSort _ -> b CommTypeChan (TypedChanName c2 s2) -> b && (c, s) /= (c2, s2)) True al _ -> True
5d9d3a5dd5966499e040222ee4e568bdbf7437fb39767da44e29c35cdbe04309
smucclaw/dsl
SVG.hs
{-# LANGUAGE OverloadedStrings #-} # LANGUAGE RecordWildCards # # LANGUAGE DerivingStrategies # # LANGUAGE GeneralizedNewtypeDeriving # | transpiler to SVG visualization of the AnyAll and/or trees . Largely a wrapper . Most of the functionality is in the ` AnyAll ` lib . Largely a wrapper. Most of the functionality is in the `AnyAll` lib. -} module LS.XPile.SVG where import LS import AnyAll as AA import qualified Data.Map as Map import qualified Data.Text as T -- import Debug.Trace (trace) -- | extract the tree-structured rules from Interpreter -- for each rule, print as svg according to options we were given asAAsvg :: AAVConfig -> Interpreted -> [Rule] -> Map.Map RuleName (SVGElement, SVGElement, BoolStructT, QTree T.Text) asAAsvg aavc l4i _rs = Map.fromList [ ( concat names , (svgtiny, svgfull, bs, qtree) ) | (names, bs) <- qaHornsT l4i , isInteresting bs , let qtree = softnormal (getMarkings l4i) bs svgtiny = makeSvg $ q2svg' aavc { cscale = Tiny } qtree svgfull = makeSvg $ q2svg' aavc { cscale = Full } qtree ] where -- | don't show SVG diagrams if they only have a single element isInteresting :: BoolStruct lbl a -> Bool isInteresting (AA.Leaf _) = False isInteresting (AA.Not (AA.Leaf _)) = False isInteresting _ = True
null
https://raw.githubusercontent.com/smucclaw/dsl/4849bbf12418817e8ca30ddf64c1fc563ffe945d/lib/haskell/natural4/src/LS/XPile/SVG.hs
haskell
# LANGUAGE OverloadedStrings # import Debug.Trace (trace) | extract the tree-structured rules from Interpreter for each rule, print as svg according to options we were given | don't show SVG diagrams if they only have a single element
# LANGUAGE RecordWildCards # # LANGUAGE DerivingStrategies # # LANGUAGE GeneralizedNewtypeDeriving # | transpiler to SVG visualization of the AnyAll and/or trees . Largely a wrapper . Most of the functionality is in the ` AnyAll ` lib . Largely a wrapper. Most of the functionality is in the `AnyAll` lib. -} module LS.XPile.SVG where import LS import AnyAll as AA import qualified Data.Map as Map import qualified Data.Text as T asAAsvg :: AAVConfig -> Interpreted -> [Rule] -> Map.Map RuleName (SVGElement, SVGElement, BoolStructT, QTree T.Text) asAAsvg aavc l4i _rs = Map.fromList [ ( concat names , (svgtiny, svgfull, bs, qtree) ) | (names, bs) <- qaHornsT l4i , isInteresting bs , let qtree = softnormal (getMarkings l4i) bs svgtiny = makeSvg $ q2svg' aavc { cscale = Tiny } qtree svgfull = makeSvg $ q2svg' aavc { cscale = Full } qtree ] where isInteresting :: BoolStruct lbl a -> Bool isInteresting (AA.Leaf _) = False isInteresting (AA.Not (AA.Leaf _)) = False isInteresting _ = True
3802798334c9558fdc59d31788339b6a11a62a3aa0feb72ff5203f8e02dc15f5
gsakkas/rite
20060408-22:49:00-d7677aecaf225da83dfe298659b3af98.seminal.ml
* * * * * Note : Problem 1 does not use ; see the assignment * * * * exception Unimplemented exception RuntimeTypeError exception BadSourceProgram exception BadPrecomputation # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # let empty_set = [] let add str lst = if List.mem str lst then lst else str::lst let remove str lst = List.filter (fun x -> x <> str) lst let rec union lst1 lst2 = match lst1 with [] -> lst2 | hd::tl -> add hd (union tl lst2) # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # type exp = Var of string last part for problem3 | Apply of exp * exp | Closure of string * exp * env | Int of int | Plus of exp * exp | If of exp * exp * exp | Pair of exp * exp | First of exp | Second of exp and env = (string * exp) list * * * * * * Problem 2 : complete this function * * * * * * * * # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ################################################ *) let rec interp f env e = let interp = interp f in match e with # # # # # # # # # # # # # | Lam(s,e2,opt) -> Closure(s,e2,f env opt) (*store env!*) # # # # # # # # # # # # # # # # # # # | Apply(e1,e2) -> let v1 = interp env e1 in let v2 = interp env e2 in (match v1 with Closure(s,e3,env2) -> interp((s,v2)::env2) e3 | _ -> raise RuntimeTypeError) # # # # # # # # # # # # # # # # # # # | Plus(e1,e2) -> let v1 = interp env e1 in let v2 = interp env e2 in (match (v1,v2) with | (Int i1,Int i2) -> Int (i1 + i2) | _ -> raise RuntimeTypeError) | If(e1,e2,e3) -> let v1 = interp env e1 in (match v1 with | Int(0) -> interp env e3 | Int _ -> interp env e2 | _ -> raise RuntimeTypeError) # # # # # # # # # # # # # # # # | First(e1) -> let v1 = interp env e1 in (match v1 with | Pair(e2,_) -> e2 | _ -> raise RuntimeTypeError) | Second(e1) -> let v1 = interp env e1 in (match v1 with | Pair(_,e2) -> e2 | _ -> raise RuntimeTypeError) let interp1 = interp (fun x _ -> x) * * * * * Problem 3 : complete this function * * * * * * let rec computeFreeVars e = raise Unimplemented let interp2 = interp (fun (env:env) opt -> match opt with None -> raise BadPrecomputation | Some lst -> List.map (fun s -> (s, List.assoc s env)) lst) * * * * * * Problem 4 : not programming ( see assignment ) * * * * * * * * * * * * * Problem 5a : explain this function * * * * * * * * let interp3 = interp (fun (env:env) _ -> []) * * * * * Problem 5b ( EXTRA CREDIT ): explain the next two functions * * * * * let rec depthToExp s varlist exp = match varlist with [] -> raise BadSourceProgram | hd::tl -> if s=hd then First exp else depthToExp s tl (Second exp) let rec translate varlist exp = match exp with Var s -> depthToExp s varlist (Var "arg") | Lam(s,e2,_) -> Pair(Lam("arg",translate (s::varlist) e2, None), match varlist with [] -> Int 0 | _ -> Var "arg") | Closure _ -> raise BadSourceProgram | Apply(e1,e2) -> let e1' = translate varlist e1 in let e2' = translate varlist e2 in # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # Apply(Lam("f",Apply(First(First(Var "f")), Pair(Second(Var "f"),Second(First(Var "f")))),None), Pair(e1',e2')) | Int _ -> exp | Pair(e1,e2) -> Pair(translate varlist e1, translate varlist e2) | Plus(e1,e2) -> Plus(translate varlist e1, translate varlist e2) | First(e1) -> First(translate varlist e1) | Second(e1) -> Second(translate varlist e1) | If(e1,e2,e3) -> If(translate varlist e1, translate varlist e2, translate varlist e3) (********** examples and testing ***********) # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ############################# ########################################################### ############################################ *) # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # let ex1 = (Apply(Apply(Lam("x",Lam("y", Plus(Var"x",Var "y"),None),None), Int 17), Int 19)) # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ################################# *) # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # let lam x e = Lam(x,e,None) let app e1 e2 = Apply(e1,e2) let vx = Var "x" let vy = Var "y" let vf = Var "f" # # # # # # # # # # # # # # # # # # # # # # # # # # # let fix = let e = lam "x" (app vf (lam "y" (app (app vx vx) vy))) in lam "f" (app e e) # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # let sum = lam "f" (lam "x" (If(vx, Plus(vx, app vf (Plus(vx, Int (-1)))), Int 0))) # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # let ex2 = (app (app fix sum) (Int 1000)) # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # let ans1 = interp1 [] ex1 let ans2 = interp1 [] ex2 ;; print_newline ans1;; print_newline ans2;; # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ################################################# ################################################# ######################################## ######################################## *)
null
https://raw.githubusercontent.com/gsakkas/rite/958a0ad2460e15734447bc07bd181f5d35956d3b/features/data/seminal/20060408-22%3A49%3A00-d7677aecaf225da83dfe298659b3af98.seminal.ml
ocaml
store env! ********* examples and testing **********
* * * * * Note : Problem 1 does not use ; see the assignment * * * * exception Unimplemented exception RuntimeTypeError exception BadSourceProgram exception BadPrecomputation # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # let empty_set = [] let add str lst = if List.mem str lst then lst else str::lst let remove str lst = List.filter (fun x -> x <> str) lst let rec union lst1 lst2 = match lst1 with [] -> lst2 | hd::tl -> add hd (union tl lst2) # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # type exp = Var of string last part for problem3 | Apply of exp * exp | Closure of string * exp * env | Int of int | Plus of exp * exp | If of exp * exp * exp | Pair of exp * exp | First of exp | Second of exp and env = (string * exp) list * * * * * * Problem 2 : complete this function * * * * * * * * # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ################################################ *) let rec interp f env e = let interp = interp f in match e with # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # | Apply(e1,e2) -> let v1 = interp env e1 in let v2 = interp env e2 in (match v1 with Closure(s,e3,env2) -> interp((s,v2)::env2) e3 | _ -> raise RuntimeTypeError) # # # # # # # # # # # # # # # # # # # | Plus(e1,e2) -> let v1 = interp env e1 in let v2 = interp env e2 in (match (v1,v2) with | (Int i1,Int i2) -> Int (i1 + i2) | _ -> raise RuntimeTypeError) | If(e1,e2,e3) -> let v1 = interp env e1 in (match v1 with | Int(0) -> interp env e3 | Int _ -> interp env e2 | _ -> raise RuntimeTypeError) # # # # # # # # # # # # # # # # | First(e1) -> let v1 = interp env e1 in (match v1 with | Pair(e2,_) -> e2 | _ -> raise RuntimeTypeError) | Second(e1) -> let v1 = interp env e1 in (match v1 with | Pair(_,e2) -> e2 | _ -> raise RuntimeTypeError) let interp1 = interp (fun x _ -> x) * * * * * Problem 3 : complete this function * * * * * * let rec computeFreeVars e = raise Unimplemented let interp2 = interp (fun (env:env) opt -> match opt with None -> raise BadPrecomputation | Some lst -> List.map (fun s -> (s, List.assoc s env)) lst) * * * * * * Problem 4 : not programming ( see assignment ) * * * * * * * * * * * * * Problem 5a : explain this function * * * * * * * * let interp3 = interp (fun (env:env) _ -> []) * * * * * Problem 5b ( EXTRA CREDIT ): explain the next two functions * * * * * let rec depthToExp s varlist exp = match varlist with [] -> raise BadSourceProgram | hd::tl -> if s=hd then First exp else depthToExp s tl (Second exp) let rec translate varlist exp = match exp with Var s -> depthToExp s varlist (Var "arg") | Lam(s,e2,_) -> Pair(Lam("arg",translate (s::varlist) e2, None), match varlist with [] -> Int 0 | _ -> Var "arg") | Closure _ -> raise BadSourceProgram | Apply(e1,e2) -> let e1' = translate varlist e1 in let e2' = translate varlist e2 in # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # Apply(Lam("f",Apply(First(First(Var "f")), Pair(Second(Var "f"),Second(First(Var "f")))),None), Pair(e1',e2')) | Int _ -> exp | Pair(e1,e2) -> Pair(translate varlist e1, translate varlist e2) | Plus(e1,e2) -> Plus(translate varlist e1, translate varlist e2) | First(e1) -> First(translate varlist e1) | Second(e1) -> Second(translate varlist e1) | If(e1,e2,e3) -> If(translate varlist e1, translate varlist e2, translate varlist e3) # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ############################# ########################################################### ############################################ *) # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # let ex1 = (Apply(Apply(Lam("x",Lam("y", Plus(Var"x",Var "y"),None),None), Int 17), Int 19)) # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ################################# *) # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # let lam x e = Lam(x,e,None) let app e1 e2 = Apply(e1,e2) let vx = Var "x" let vy = Var "y" let vf = Var "f" # # # # # # # # # # # # # # # # # # # # # # # # # # # let fix = let e = lam "x" (app vf (lam "y" (app (app vx vx) vy))) in lam "f" (app e e) # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # let sum = lam "f" (lam "x" (If(vx, Plus(vx, app vf (Plus(vx, Int (-1)))), Int 0))) # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # let ex2 = (app (app fix sum) (Int 1000)) # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # let ans1 = interp1 [] ex1 let ans2 = interp1 [] ex2 ;; print_newline ans1;; print_newline ans2;; # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ################################################# ################################################# ######################################## ######################################## *)
c9dac207cecaa7095c794b70e0bbbbc9813898c509402c904b4c7373ee3356db
keera-studios/keera-hails
Reactive.hs
-- | -- Copyright : ( C ) Keera Studios Ltd , 2013 -- License : BSD3 Maintainer : module Graphics.UI.Gtk.Reactive (module Exported) where import Graphics.UI.Gtk.Reactive.ColorButton as Exported import Graphics.UI.Gtk.Reactive.Button as Exported import Graphics.UI.Gtk.Reactive.Entry as Exported import Graphics.UI.Gtk.Reactive.CheckMenuItem as Exported import Graphics.UI.Gtk.Reactive.Image as Exported import Graphics.UI.Gtk.Reactive.Label as Exported import Graphics.UI.Gtk.Reactive.MenuItem as Exported import Graphics.UI.Gtk.Reactive.Scale as Exported import Graphics.UI.Gtk.Reactive.SpinButton as Exported import Graphics.UI.Gtk.Reactive.StatusIcon as Exported import Graphics.UI.Gtk.Reactive.TextView as Exported import Graphics.UI.Gtk.Reactive.ToolButton as Exported import Graphics.UI.Gtk.Reactive.ToggleButton as Exported import Graphics.UI.Gtk.Reactive.TreeView as Exported import Graphics.UI.Gtk.Reactive.Widget as Exported import Graphics.UI.Gtk.Reactive.Window as Exported import Graphics . UI.Gtk . Reactive . TypedComboBoxUnsafe as Exported
null
https://raw.githubusercontent.com/keera-studios/keera-hails/bf069e5aafc85a1f55fa119ae45a025a2bd4a3d0/keera-hails-reactive-gtk/src/Graphics/UI/Gtk/Reactive.hs
haskell
| License : BSD3
Copyright : ( C ) Keera Studios Ltd , 2013 Maintainer : module Graphics.UI.Gtk.Reactive (module Exported) where import Graphics.UI.Gtk.Reactive.ColorButton as Exported import Graphics.UI.Gtk.Reactive.Button as Exported import Graphics.UI.Gtk.Reactive.Entry as Exported import Graphics.UI.Gtk.Reactive.CheckMenuItem as Exported import Graphics.UI.Gtk.Reactive.Image as Exported import Graphics.UI.Gtk.Reactive.Label as Exported import Graphics.UI.Gtk.Reactive.MenuItem as Exported import Graphics.UI.Gtk.Reactive.Scale as Exported import Graphics.UI.Gtk.Reactive.SpinButton as Exported import Graphics.UI.Gtk.Reactive.StatusIcon as Exported import Graphics.UI.Gtk.Reactive.TextView as Exported import Graphics.UI.Gtk.Reactive.ToolButton as Exported import Graphics.UI.Gtk.Reactive.ToggleButton as Exported import Graphics.UI.Gtk.Reactive.TreeView as Exported import Graphics.UI.Gtk.Reactive.Widget as Exported import Graphics.UI.Gtk.Reactive.Window as Exported import Graphics . UI.Gtk . Reactive . TypedComboBoxUnsafe as Exported
3bcbd9e94ff8e8f07a5850c498c7bfa2e7b097e659b1f6d4256efa7e09e26479
keera-studios/keera-hails
Builder.hs
-- | -- Copyright : ( C ) Keera Studios Ltd , 2013 -- License : BSD3 Maintainer : module Hails.MVC.View.Gtk.Builder (loadDefaultInterface) where import Graphics.UI.Gtk import Graphics.UI.Gtk.Extra.Builder -- | Returns a builder from which the objects in this part of the interface -- can be accessed. loadDefaultInterface :: (String -> IO String) -> IO Builder loadDefaultInterface getDataFileName = loadInterface =<< getDataFileName "Interface.glade"
null
https://raw.githubusercontent.com/keera-studios/keera-hails/bf069e5aafc85a1f55fa119ae45a025a2bd4a3d0/keera-hails-mvc-view-gtk3/src/Hails/MVC/View/Gtk/Builder.hs
haskell
| License : BSD3 | Returns a builder from which the objects in this part of the interface can be accessed.
Copyright : ( C ) Keera Studios Ltd , 2013 Maintainer : module Hails.MVC.View.Gtk.Builder (loadDefaultInterface) where import Graphics.UI.Gtk import Graphics.UI.Gtk.Extra.Builder loadDefaultInterface :: (String -> IO String) -> IO Builder loadDefaultInterface getDataFileName = loadInterface =<< getDataFileName "Interface.glade"
6eef0bf844bc6b608ba155bf60b49eadb08cdbc7a957c16f282550b9ae1f06b8
hoelzl/Snark
trie-index.lisp
;;; -*- Mode: Lisp; Syntax: Common-Lisp; Package: snark -*- ;;; File: trie-index.lisp The contents of this file are subject to the Mozilla Public License ;;; Version 1.1 (the "License"); you may not use this file except in ;;; compliance with the License. You may obtain a copy of the License at ;;; / ;;; Software distributed under the License is distributed on an " AS IS " ;;; basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the ;;; License for the specific language governing rights and limitations ;;; under the License. ;;; The Original Code is SNARK . The Initial Developer of the Original Code is SRI International . Portions created by the Initial Developer are Copyright ( C ) 1981 - 2012 . All Rights Reserved . ;;; Contributor(s ): < > . (in-package :snark) (defvar *trie-index*) (defstruct (trie-index (:constructor make-trie-index0 (entry-constructor)) (:copier nil)) (entry-constructor nil :read-only t) ;term->entry function for new entry insertion (node-counter (make-counter 1) :read-only t) (entry-counter (make-counter) :read-only t) (top-node (make-trie-index-internal-node) :read-only t) (retrieve-generalization-calls 0 :type integer) ;number of generalization retrieval calls (retrieve-generalization-count 0 :type integer) (retrieve-instance-calls 0 :type integer) ; " instance " (retrieve-instance-count 0 :type integer) (retrieve-unifiable-calls 0 :type integer) ; " unifiable " (retrieve-unifiable-count 0 :type integer) (retrieve-variant-calls 0 :type integer) ; " variant " (retrieve-variant-count 0 :type integer) (retrieve-all-calls 0 :type integer) ; " all " (retrieve-all-count 0 :type integer)) (defstruct (trie-index-internal-node (:copier nil)) (variable-child-node nil) ;nil or node (constant-indexed-child-nodes nil) ;constant# -> node sparse-vector (function-indexed-child-nodes nil)) ;function# -> node sparse-vector (defstruct (trie-index-leaf-node (:include sparse-vector (snark-sparse-array::default-value0 none :read-only t)) (:copier nil)) ) (defmacro trie-index-leaf-node-entries (n) n) (defstruct (index-entry (:constructor make-index-entry (term)) (:copier nil)) (term nil :read-only t)) (defun make-trie-index (&key (entry-constructor #'make-index-entry)) (setf *trie-index* (make-trie-index0 entry-constructor))) (definline trie-index-internal-node-variable-indexed-child-node (node &optional create internal) (or (trie-index-internal-node-variable-child-node node) (and create (progn (increment-counter (trie-index-node-counter *trie-index*)) (setf (trie-index-internal-node-variable-child-node node) (if internal (make-trie-index-internal-node) (make-trie-index-leaf-node))))))) (definline trie-index-internal-node-constant-indexed-child-node (const node &optional create internal) (let ((children (trie-index-internal-node-constant-indexed-child-nodes node))) (unless children (when create (setf children (setf (trie-index-internal-node-constant-indexed-child-nodes node) (make-sparse-vector))))) (and children (let ((const# (constant-number const))) (or (sparef children const#) (and create (progn (increment-counter (trie-index-node-counter *trie-index*)) (setf (sparef children const#) (if internal (make-trie-index-internal-node) (make-trie-index-leaf-node)))))))))) (definline trie-index-internal-node-function-indexed-child-node (fn node &optional create internal) (let ((children (trie-index-internal-node-function-indexed-child-nodes node))) (unless children (when create (setf children (setf (trie-index-internal-node-function-indexed-child-nodes node) (make-sparse-vector))))) (and children (let ((fn# (function-number fn))) (or (sparef children fn#) (and create (progn (increment-counter (trie-index-node-counter *trie-index*)) (setf (sparef children fn#) (if internal (make-trie-index-internal-node) (make-trie-index-leaf-node)))))))))) (definline function-trie-index-lookup-args (fn term) ;; fn = (head term) unless term is nil (not specified) (ecase (function-index-type fn) ((nil) (cond ((function-unify-code fn) nil) (t (let ((arity (function-arity fn))) (if (eq :any arity) (list (args term)) (args term)))))) (:commute index all arguments , lookup with first two in order and commuted ( a b c d ) - > 4 , ( c d a b ) , ( c d ( % index - or ( a b ) ( b a ) ) ) for arity 4 ;; (a b c d) -> 3, ((c d) a b), ((c d) (%index-or (a b) (b a))) for arity :any (let ((arity (function-arity fn))) (let* ((args (args term)) (l (rest (rest args))) (a (first args)) (b (second args)) (v (list (list '%index-or (if l (list a b) args) (list b a))))) (cond ((eq :any arity) (cons l v)) (l (append l v)) (t v))))) (:jepd index only first two arguments , lookup with first two in order and commuted ( a b c ) - > 2 , ( a b ) , ( ( % index - or ( a b ) ( b a ) ) ) (let* ((args (args term)) (a (first args)) (b (second args))) (list (list '%index-or (list a b) (list b a))))) (:hash-but-dont-index nil))) (definline function-trie-index-args (fn term) (ecase (function-index-type fn) ((nil) (cond ((function-unify-code fn) nil) (t (let ((arity (function-arity fn))) (if (eq :any arity) (list (args term)) (args term)))))) (:commute (let ((arity (function-arity fn))) (let* ((args (args term)) (l (rest (rest args))) (v (if l (list (first args) (second args)) args))) (cond ((eq :any arity) (cons l v)) (l (append l v)) (t v))))) (:jepd (let ((args (args term))) (list (first args) (second args)))) (:hash-but-dont-index nil))) (definline function-trie-index-arity (fn) (ecase (function-index-type fn) ((nil) (cond ((function-unify-code fn) 0) (t (let ((arity (function-arity fn))) (if (eq :any arity) 1 arity))))) (:commute (let ((arity (function-arity fn))) (if (eq :any arity) 3 arity))) (:jepd 2) (:hash-but-dont-index 0))) (defun simply-indexed-p (term &optional subst) (dereference term subst :if-variable t :if-constant t :if-compound-cons (and (simply-indexed-p (carc term)) (simply-indexed-p (cdrc term))) :if-compound-appl (and (let ((fn (heada term))) (ecase (function-index-type fn) ((nil) (null (function-unify-code fn))) (:commute nil) (:hash-but-dont-index t) (:jepd nil))) (dolist (arg (argsa term) t) (unless (simply-indexed-p arg subst) (return nil)))))) (definline trie-index-build-path-for-terms (terms node internal) (if internal (dolist (x terms node) (setf node (trie-index-build-path-for-term x node t))) (dotails (l terms node) (setf node (trie-index-build-path-for-term (first l) node (rest l)))))) (defun trie-index-build-path-for-term (term node &optional internal) (dereference term nil :if-variable (trie-index-internal-node-variable-indexed-child-node node t internal) :if-constant (trie-index-internal-node-constant-indexed-child-node term node t internal) :if-compound (let* ((head (head term)) (args (function-trie-index-args head term))) (if (null args) (trie-index-internal-node-function-indexed-child-node head node t internal) (trie-index-build-path-for-terms args (trie-index-internal-node-function-indexed-child-node head node t t) internal))))) (definline trie-index-path-for-terms (terms path) (dolist (x terms path) (when (null (setf path (trie-index-path-for-term x path))) (return nil)))) (defun trie-index-path-for-term (term path) (let ((node (first path))) (dereference term nil :if-variable (let ((n (trie-index-internal-node-variable-indexed-child-node node))) (and n (list* n 'variable path))) :if-constant (let ((n (trie-index-internal-node-constant-indexed-child-node term node))) (and n (list* n 'constant term path))) :if-compound (let* ((head (head term)) (n (trie-index-internal-node-function-indexed-child-node head node))) (and n (let ((args (function-trie-index-args head term))) (if (null args) (list* n 'function head path) (trie-index-path-for-terms args (list* n 'function head path))))))))) (defun trie-index-insert (term &optional entry) (let* ((trie-index *trie-index*) (entries (trie-index-leaf-node-entries (trie-index-build-path-for-term term (trie-index-top-node trie-index))))) (cond ((null entry) (prog-> (map-sparse-vector entries :reverse t ->* e) (when (or (eql term (index-entry-term e)) (and (test-option38?) (equal-p term (index-entry-term e)))) (return-from trie-index-insert e))) (setf entry (funcall (trie-index-entry-constructor trie-index) term))) (t (cl:assert (eql term (index-entry-term entry))) (prog-> (map-sparse-vector entries :reverse t ->* e) (when (eq entry e) (return-from trie-index-insert e)) (when (or (eql term (index-entry-term e)) (and (test-option38?) (equal-p term (index-entry-term e)))) (error "There is already a trie-index entry for term ~A." term))))) (increment-counter (trie-index-entry-counter trie-index)) (setf (sparef entries (nonce)) entry))) (defun trie-index-delete (term &optional entry) (let* ((trie-index *trie-index*) (path (trie-index-path-for-term term (list (trie-index-top-node trie-index))))) (when path (let* ((entries (trie-index-leaf-node-entries (pop path))) (k (cond ((null entry) (prog-> (map-sparse-vector-with-indexes entries :reverse t ->* e k) (when (eql term (index-entry-term e)) (return-from prog-> k)))) (t (cl:assert (eql term (index-entry-term entry))) (prog-> (map-sparse-vector-with-indexes entries :reverse t ->* e k) (when (eq entry e) (return-from prog-> k))))))) (when k (decrement-counter (trie-index-entry-counter trie-index)) (setf (sparef entries k) none) (when (eql 0 (sparse-vector-count entries)) (let ((node-counter (trie-index-node-counter trie-index)) parent) (loop (ecase (pop path) (function (let ((k (function-number (pop path)))) (setf (sparef (trie-index-internal-node-function-indexed-child-nodes (setf parent (pop path))) k) nil))) (constant (let ((k (constant-number (pop path)))) (setf (sparef (trie-index-internal-node-constant-indexed-child-nodes (setf parent (pop path))) k) nil))) (variable (setf (trie-index-internal-node-variable-child-node (setf parent (pop path))) nil))) (decrement-counter node-counter) (unless (and (rest path) ;not top node (null (trie-index-internal-node-variable-child-node parent)) (eql 0 (sparse-vector-count (trie-index-internal-node-function-indexed-child-nodes parent))) (eql 0 (sparse-vector-count (trie-index-internal-node-constant-indexed-child-nodes parent)))) (return))))) t))))) (defmacro map-trie-index-entries (&key if-variable if-constant if-compound count-call count-entry) (declare (ignorable count-call count-entry)) `(labels ((map-for-term (cc term node) (dereference term subst :if-variable ,if-variable :if-constant ,if-constant :if-compound ,if-compound)) (map-for-terms (cc terms node) (cond ((null terms) (funcall cc node)) (t (let ((term (pop terms))) (cond ((and (consp term) (eq '%index-or (first term))) (cond ((null terms) (prog-> (dolist (rest term) ->* terms1) (map-for-terms terms1 node ->* node) (funcall cc node))) (t (prog-> (dolist (rest term) ->* terms1) (map-for-terms terms1 node ->* node) (map-for-terms terms node ->* node) (funcall cc node))))) (t (cond ((null terms) (prog-> (map-for-term term node ->* node) (funcall cc node))) (t (prog-> (map-for-term term node ->* node) (map-for-terms terms node ->* node) (funcall cc node)))))))))) (skip-terms (cc n node) (declare (type fixnum n)) (cond ((= 1 n) (progn (prog-> (trie-index-internal-node-variable-indexed-child-node node ->nonnil node) (funcall cc node)) (prog-> (trie-index-internal-node-constant-indexed-child-nodes node ->nonnil constant-indexed-children) (map-sparse-vector constant-indexed-children ->* node) (funcall cc node)) (prog-> (trie-index-internal-node-function-indexed-child-nodes node ->nonnil function-indexed-children) (map-sparse-vector-with-indexes function-indexed-children ->* node fn#) (skip-terms (function-trie-index-arity (symbol-numbered fn#)) node ->* node) (funcall cc node)))) ((= 0 n) (funcall cc node)) (t (progn (decf n) (prog-> (trie-index-internal-node-variable-indexed-child-node node ->nonnil node) (skip-terms n node ->* node) (funcall cc node)) (prog-> (trie-index-internal-node-constant-indexed-child-nodes node ->nonnil constant-indexed-children) (map-sparse-vector constant-indexed-children ->* node) (skip-terms n node ->* node) (funcall cc node)) (prog-> (trie-index-internal-node-function-indexed-child-nodes node ->nonnil function-indexed-children) (map-sparse-vector-with-indexes function-indexed-children ->* node fn#) (skip-terms (+ n (function-trie-index-arity (symbol-numbered fn#))) node ->* node) (funcall cc node))))))) (let ((trie-index *trie-index*)) ;; ,count-call (cond ((simply-indexed-p term subst) (prog-> (map-for-term term (trie-index-top-node trie-index) ->* leaf-node) (map-sparse-vector (trie-index-leaf-node-entries leaf-node) :reverse t ->* e) ;; ,count-entry (funcall cc e))) (t (prog-> (quote nil -> seen) (map-for-term term (trie-index-top-node trie-index) ->* leaf-node) (when (do ((s seen (cdrc s))) ;(not (member leaf-node seen)) ((null s) t) (when (eq leaf-node (carc s)) (return nil))) (prog-> (map-sparse-vector (trie-index-leaf-node-entries leaf-node) :reverse t ->* e) ;; ,count-entry (funcall cc e)) (setf seen (cons leaf-node seen))))))) nil)) (defun map-trie-index-instance-entries (cc term subst) (map-trie-index-entries :count-call (incf (trie-index-retrieve-instance-calls trie-index)) :count-entry (incf (trie-index-retrieve-instance-count trie-index)) :if-variable (prog-> (skip-terms 1 node ->* node) (funcall cc node)) :if-constant (prog-> (trie-index-internal-node-constant-indexed-child-node term node ->nonnil node) (funcall cc node)) :if-compound (prog-> (head term -> head) (trie-index-internal-node-function-indexed-child-node head node ->nonnil node) (map-for-terms (function-trie-index-lookup-args head term) node ->* node) (funcall cc node)))) (defun map-trie-index-generalization-entries (cc term subst) in snark-20060805 vs. snark-20060806 test over TPTP , ;; constant and compound lookup before variable lookup outperforms ;; variable lookup before constant and compound lookup (map-trie-index-entries :count-call (incf (trie-index-retrieve-generalization-calls trie-index)) :count-entry (incf (trie-index-retrieve-generalization-count trie-index)) :if-variable (prog-> (trie-index-internal-node-variable-indexed-child-node node ->nonnil node) (funcall cc node)) :if-constant (progn (prog-> (trie-index-internal-node-constant-indexed-child-node term node ->nonnil node) (funcall cc node)) (prog-> (trie-index-internal-node-variable-indexed-child-node node ->nonnil node) (funcall cc node))) :if-compound (progn (prog-> (head term -> head) (trie-index-internal-node-function-indexed-child-node head node ->nonnil node) (map-for-terms (function-trie-index-lookup-args head term) node ->* node) (funcall cc node)) (prog-> (trie-index-internal-node-variable-indexed-child-node node ->nonnil node) (funcall cc node))))) (defun map-trie-index-unifiable-entries (cc term subst) (map-trie-index-entries :count-call (incf (trie-index-retrieve-unifiable-calls trie-index)) :count-entry (incf (trie-index-retrieve-unifiable-count trie-index)) :if-variable (prog-> (skip-terms 1 node ->* node) (funcall cc node)) :if-constant (progn (prog-> (trie-index-internal-node-variable-indexed-child-node node ->nonnil node) (funcall cc node)) (prog-> (trie-index-internal-node-constant-indexed-child-node term node ->nonnil node) (funcall cc node))) :if-compound (progn (prog-> (trie-index-internal-node-variable-indexed-child-node node ->nonnil node) (funcall cc node)) (prog-> (head term -> head) (trie-index-internal-node-function-indexed-child-node head node ->nonnil node) (map-for-terms (function-trie-index-lookup-args head term) node ->* node) (funcall cc node))))) (defun map-trie-index-variant-entries (cc term subst) (map-trie-index-entries :count-call (incf (trie-index-retrieve-variant-calls trie-index)) :count-entry (incf (trie-index-retrieve-variant-count trie-index)) :if-variable (prog-> (trie-index-internal-node-variable-indexed-child-node node ->nonnil node) (funcall cc node)) :if-constant (prog-> (trie-index-internal-node-constant-indexed-child-node term node ->nonnil node) (funcall cc node)) :if-compound (prog-> (head term -> head) (trie-index-internal-node-function-indexed-child-node head node ->nonnil node) (map-for-terms (function-trie-index-lookup-args head term) node ->* node) (funcall cc node)))) (defun map-trie-index-all-entries (cc) (let ((term (make-variable nil 0)) (subst nil)) (map-trie-index-entries :count-call (incf (trie-index-retrieve-all-calls trie-index)) :count-entry (incf (trie-index-retrieve-all-count trie-index)) :if-variable (prog-> (skip-terms 1 node ->* node) (funcall cc node))))) (definline map-trie-index (cc type term &optional subst) (ecase type (:generalization (map-trie-index-generalization-entries cc term subst)) (:instance (map-trie-index-instance-entries cc term subst)) (:unifiable (map-trie-index-unifiable-entries cc term subst)) (:variant (map-trie-index-variant-entries cc term subst)))) (defun print-trie-index (&key terms nodes) (let ((index *trie-index*)) (mvlet (((:values current peak added deleted) (counter-values (trie-index-entry-counter index)))) (format t "~%; Trie-index has ~:D entr~:@P (~:D at peak, ~:D added, ~:D deleted)." current peak added deleted)) (mvlet (((:values current peak added deleted) (counter-values (trie-index-node-counter index)))) (format t "~%; Trie-index has ~:D node~:P (~:D at peak, ~:D added, ~:D deleted)." current peak added deleted)) (unless (eql 0 (trie-index-retrieve-variant-calls index)) (format t "~%; Trie-index retrieved ~:D variant term~:P in ~:D call~:P." (trie-index-retrieve-variant-count index) (trie-index-retrieve-variant-calls index))) (unless (eql 0 (trie-index-retrieve-generalization-calls index)) (format t "~%; Trie-index retrieved ~:D generalization term~:P in ~:D call~:P." (trie-index-retrieve-generalization-count index) (trie-index-retrieve-generalization-calls index))) (unless (eql 0 (trie-index-retrieve-instance-calls index)) (format t "~%; Trie-index retrieved ~:D instance term~:P in ~:D call~:P." (trie-index-retrieve-instance-count index) (trie-index-retrieve-instance-calls index))) (unless (eql 0 (trie-index-retrieve-unifiable-calls index)) (format t "~%; Trie-index retrieved ~:D unifiable term~:P in ~:D call~:P." (trie-index-retrieve-unifiable-count index) (trie-index-retrieve-unifiable-calls index))) (unless (eql 0 (trie-index-retrieve-all-calls index)) (format t "~%; Trie-index retrieved ~:D unrestricted term~:P in ~:D call~:P." (trie-index-retrieve-all-count index) (trie-index-retrieve-all-calls index))) (when (or nodes terms) (print-index* (trie-index-top-node index) nil terms)))) (defun print-index* (node revpath print-terms) (prog-> (map-index-leaf-nodes node revpath ->* node revpath) (print-index-leaf-node node revpath print-terms))) (defgeneric map-index-leaf-nodes (cc node revpath)) (defmethod map-index-leaf-nodes (cc (node trie-index-internal-node) revpath) (prog-> (trie-index-internal-node-variable-indexed-child-node node ->nonnil node) (map-index-leaf-nodes node (cons '? revpath) ->* node revpath) (funcall cc node revpath)) (prog-> (map-sparse-vector-with-indexes (trie-index-internal-node-constant-indexed-child-nodes node) ->* node const#) (map-index-leaf-nodes node (cons (symbol-numbered const#) revpath) ->* node revpath) (funcall cc node revpath)) (prog-> (map-sparse-vector-with-indexes (trie-index-internal-node-function-indexed-child-nodes node) ->* node fn#) (map-index-leaf-nodes node (cons (symbol-numbered fn#) revpath) ->* node revpath) (funcall cc node revpath))) (defmethod map-index-leaf-nodes (cc (node trie-index-leaf-node) revpath) (funcall cc node revpath)) (defgeneric print-index-leaf-node (node revpath print-terms)) (defmethod print-index-leaf-node ((node trie-index-leaf-node) revpath print-terms) (with-standard-io-syntax2 (prog-> (trie-index-leaf-node-entries node -> entries) (format t "~%; Path ~A has ~:D entr~:@P." (reverse revpath) (sparse-vector-count entries)) (when print-terms (map-sparse-vector entries :reverse t ->* entry) (format t "~%; ") (print-term (index-entry-term entry)))))) trie-index.lisp EOF
null
https://raw.githubusercontent.com/hoelzl/Snark/06f86a31f476b2e4c28519765ab1e1519a4cc932/src/trie-index.lisp
lisp
-*- Mode: Lisp; Syntax: Common-Lisp; Package: snark -*- File: trie-index.lisp Version 1.1 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at / basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. term->entry function for new entry insertion number of generalization retrieval calls " instance " " unifiable " " variant " " all " nil or node constant# -> node sparse-vector function# -> node sparse-vector fn = (head term) unless term is nil (not specified) (a b c d) -> 3, ((c d) a b), ((c d) (%index-or (a b) (b a))) for arity :any not top node ,count-call ,count-entry (not (member leaf-node seen)) ,count-entry constant and compound lookup before variable lookup outperforms variable lookup before constant and compound lookup
The contents of this file are subject to the Mozilla Public License Software distributed under the License is distributed on an " AS IS " The Original Code is SNARK . The Initial Developer of the Original Code is SRI International . Portions created by the Initial Developer are Copyright ( C ) 1981 - 2012 . All Rights Reserved . Contributor(s ): < > . (in-package :snark) (defvar *trie-index*) (defstruct (trie-index (:constructor make-trie-index0 (entry-constructor)) (:copier nil)) (node-counter (make-counter 1) :read-only t) (entry-counter (make-counter) :read-only t) (top-node (make-trie-index-internal-node) :read-only t) (retrieve-generalization-count 0 :type integer) (retrieve-instance-count 0 :type integer) (retrieve-unifiable-count 0 :type integer) (retrieve-variant-count 0 :type integer) (retrieve-all-count 0 :type integer)) (defstruct (trie-index-internal-node (:copier nil)) (defstruct (trie-index-leaf-node (:include sparse-vector (snark-sparse-array::default-value0 none :read-only t)) (:copier nil)) ) (defmacro trie-index-leaf-node-entries (n) n) (defstruct (index-entry (:constructor make-index-entry (term)) (:copier nil)) (term nil :read-only t)) (defun make-trie-index (&key (entry-constructor #'make-index-entry)) (setf *trie-index* (make-trie-index0 entry-constructor))) (definline trie-index-internal-node-variable-indexed-child-node (node &optional create internal) (or (trie-index-internal-node-variable-child-node node) (and create (progn (increment-counter (trie-index-node-counter *trie-index*)) (setf (trie-index-internal-node-variable-child-node node) (if internal (make-trie-index-internal-node) (make-trie-index-leaf-node))))))) (definline trie-index-internal-node-constant-indexed-child-node (const node &optional create internal) (let ((children (trie-index-internal-node-constant-indexed-child-nodes node))) (unless children (when create (setf children (setf (trie-index-internal-node-constant-indexed-child-nodes node) (make-sparse-vector))))) (and children (let ((const# (constant-number const))) (or (sparef children const#) (and create (progn (increment-counter (trie-index-node-counter *trie-index*)) (setf (sparef children const#) (if internal (make-trie-index-internal-node) (make-trie-index-leaf-node)))))))))) (definline trie-index-internal-node-function-indexed-child-node (fn node &optional create internal) (let ((children (trie-index-internal-node-function-indexed-child-nodes node))) (unless children (when create (setf children (setf (trie-index-internal-node-function-indexed-child-nodes node) (make-sparse-vector))))) (and children (let ((fn# (function-number fn))) (or (sparef children fn#) (and create (progn (increment-counter (trie-index-node-counter *trie-index*)) (setf (sparef children fn#) (if internal (make-trie-index-internal-node) (make-trie-index-leaf-node)))))))))) (definline function-trie-index-lookup-args (fn term) (ecase (function-index-type fn) ((nil) (cond ((function-unify-code fn) nil) (t (let ((arity (function-arity fn))) (if (eq :any arity) (list (args term)) (args term)))))) (:commute index all arguments , lookup with first two in order and commuted ( a b c d ) - > 4 , ( c d a b ) , ( c d ( % index - or ( a b ) ( b a ) ) ) for arity 4 (let ((arity (function-arity fn))) (let* ((args (args term)) (l (rest (rest args))) (a (first args)) (b (second args)) (v (list (list '%index-or (if l (list a b) args) (list b a))))) (cond ((eq :any arity) (cons l v)) (l (append l v)) (t v))))) (:jepd index only first two arguments , lookup with first two in order and commuted ( a b c ) - > 2 , ( a b ) , ( ( % index - or ( a b ) ( b a ) ) ) (let* ((args (args term)) (a (first args)) (b (second args))) (list (list '%index-or (list a b) (list b a))))) (:hash-but-dont-index nil))) (definline function-trie-index-args (fn term) (ecase (function-index-type fn) ((nil) (cond ((function-unify-code fn) nil) (t (let ((arity (function-arity fn))) (if (eq :any arity) (list (args term)) (args term)))))) (:commute (let ((arity (function-arity fn))) (let* ((args (args term)) (l (rest (rest args))) (v (if l (list (first args) (second args)) args))) (cond ((eq :any arity) (cons l v)) (l (append l v)) (t v))))) (:jepd (let ((args (args term))) (list (first args) (second args)))) (:hash-but-dont-index nil))) (definline function-trie-index-arity (fn) (ecase (function-index-type fn) ((nil) (cond ((function-unify-code fn) 0) (t (let ((arity (function-arity fn))) (if (eq :any arity) 1 arity))))) (:commute (let ((arity (function-arity fn))) (if (eq :any arity) 3 arity))) (:jepd 2) (:hash-but-dont-index 0))) (defun simply-indexed-p (term &optional subst) (dereference term subst :if-variable t :if-constant t :if-compound-cons (and (simply-indexed-p (carc term)) (simply-indexed-p (cdrc term))) :if-compound-appl (and (let ((fn (heada term))) (ecase (function-index-type fn) ((nil) (null (function-unify-code fn))) (:commute nil) (:hash-but-dont-index t) (:jepd nil))) (dolist (arg (argsa term) t) (unless (simply-indexed-p arg subst) (return nil)))))) (definline trie-index-build-path-for-terms (terms node internal) (if internal (dolist (x terms node) (setf node (trie-index-build-path-for-term x node t))) (dotails (l terms node) (setf node (trie-index-build-path-for-term (first l) node (rest l)))))) (defun trie-index-build-path-for-term (term node &optional internal) (dereference term nil :if-variable (trie-index-internal-node-variable-indexed-child-node node t internal) :if-constant (trie-index-internal-node-constant-indexed-child-node term node t internal) :if-compound (let* ((head (head term)) (args (function-trie-index-args head term))) (if (null args) (trie-index-internal-node-function-indexed-child-node head node t internal) (trie-index-build-path-for-terms args (trie-index-internal-node-function-indexed-child-node head node t t) internal))))) (definline trie-index-path-for-terms (terms path) (dolist (x terms path) (when (null (setf path (trie-index-path-for-term x path))) (return nil)))) (defun trie-index-path-for-term (term path) (let ((node (first path))) (dereference term nil :if-variable (let ((n (trie-index-internal-node-variable-indexed-child-node node))) (and n (list* n 'variable path))) :if-constant (let ((n (trie-index-internal-node-constant-indexed-child-node term node))) (and n (list* n 'constant term path))) :if-compound (let* ((head (head term)) (n (trie-index-internal-node-function-indexed-child-node head node))) (and n (let ((args (function-trie-index-args head term))) (if (null args) (list* n 'function head path) (trie-index-path-for-terms args (list* n 'function head path))))))))) (defun trie-index-insert (term &optional entry) (let* ((trie-index *trie-index*) (entries (trie-index-leaf-node-entries (trie-index-build-path-for-term term (trie-index-top-node trie-index))))) (cond ((null entry) (prog-> (map-sparse-vector entries :reverse t ->* e) (when (or (eql term (index-entry-term e)) (and (test-option38?) (equal-p term (index-entry-term e)))) (return-from trie-index-insert e))) (setf entry (funcall (trie-index-entry-constructor trie-index) term))) (t (cl:assert (eql term (index-entry-term entry))) (prog-> (map-sparse-vector entries :reverse t ->* e) (when (eq entry e) (return-from trie-index-insert e)) (when (or (eql term (index-entry-term e)) (and (test-option38?) (equal-p term (index-entry-term e)))) (error "There is already a trie-index entry for term ~A." term))))) (increment-counter (trie-index-entry-counter trie-index)) (setf (sparef entries (nonce)) entry))) (defun trie-index-delete (term &optional entry) (let* ((trie-index *trie-index*) (path (trie-index-path-for-term term (list (trie-index-top-node trie-index))))) (when path (let* ((entries (trie-index-leaf-node-entries (pop path))) (k (cond ((null entry) (prog-> (map-sparse-vector-with-indexes entries :reverse t ->* e k) (when (eql term (index-entry-term e)) (return-from prog-> k)))) (t (cl:assert (eql term (index-entry-term entry))) (prog-> (map-sparse-vector-with-indexes entries :reverse t ->* e k) (when (eq entry e) (return-from prog-> k))))))) (when k (decrement-counter (trie-index-entry-counter trie-index)) (setf (sparef entries k) none) (when (eql 0 (sparse-vector-count entries)) (let ((node-counter (trie-index-node-counter trie-index)) parent) (loop (ecase (pop path) (function (let ((k (function-number (pop path)))) (setf (sparef (trie-index-internal-node-function-indexed-child-nodes (setf parent (pop path))) k) nil))) (constant (let ((k (constant-number (pop path)))) (setf (sparef (trie-index-internal-node-constant-indexed-child-nodes (setf parent (pop path))) k) nil))) (variable (setf (trie-index-internal-node-variable-child-node (setf parent (pop path))) nil))) (decrement-counter node-counter) (null (trie-index-internal-node-variable-child-node parent)) (eql 0 (sparse-vector-count (trie-index-internal-node-function-indexed-child-nodes parent))) (eql 0 (sparse-vector-count (trie-index-internal-node-constant-indexed-child-nodes parent)))) (return))))) t))))) (defmacro map-trie-index-entries (&key if-variable if-constant if-compound count-call count-entry) (declare (ignorable count-call count-entry)) `(labels ((map-for-term (cc term node) (dereference term subst :if-variable ,if-variable :if-constant ,if-constant :if-compound ,if-compound)) (map-for-terms (cc terms node) (cond ((null terms) (funcall cc node)) (t (let ((term (pop terms))) (cond ((and (consp term) (eq '%index-or (first term))) (cond ((null terms) (prog-> (dolist (rest term) ->* terms1) (map-for-terms terms1 node ->* node) (funcall cc node))) (t (prog-> (dolist (rest term) ->* terms1) (map-for-terms terms1 node ->* node) (map-for-terms terms node ->* node) (funcall cc node))))) (t (cond ((null terms) (prog-> (map-for-term term node ->* node) (funcall cc node))) (t (prog-> (map-for-term term node ->* node) (map-for-terms terms node ->* node) (funcall cc node)))))))))) (skip-terms (cc n node) (declare (type fixnum n)) (cond ((= 1 n) (progn (prog-> (trie-index-internal-node-variable-indexed-child-node node ->nonnil node) (funcall cc node)) (prog-> (trie-index-internal-node-constant-indexed-child-nodes node ->nonnil constant-indexed-children) (map-sparse-vector constant-indexed-children ->* node) (funcall cc node)) (prog-> (trie-index-internal-node-function-indexed-child-nodes node ->nonnil function-indexed-children) (map-sparse-vector-with-indexes function-indexed-children ->* node fn#) (skip-terms (function-trie-index-arity (symbol-numbered fn#)) node ->* node) (funcall cc node)))) ((= 0 n) (funcall cc node)) (t (progn (decf n) (prog-> (trie-index-internal-node-variable-indexed-child-node node ->nonnil node) (skip-terms n node ->* node) (funcall cc node)) (prog-> (trie-index-internal-node-constant-indexed-child-nodes node ->nonnil constant-indexed-children) (map-sparse-vector constant-indexed-children ->* node) (skip-terms n node ->* node) (funcall cc node)) (prog-> (trie-index-internal-node-function-indexed-child-nodes node ->nonnil function-indexed-children) (map-sparse-vector-with-indexes function-indexed-children ->* node fn#) (skip-terms (+ n (function-trie-index-arity (symbol-numbered fn#))) node ->* node) (funcall cc node))))))) (let ((trie-index *trie-index*)) (cond ((simply-indexed-p term subst) (prog-> (map-for-term term (trie-index-top-node trie-index) ->* leaf-node) (map-sparse-vector (trie-index-leaf-node-entries leaf-node) :reverse t ->* e) (funcall cc e))) (t (prog-> (quote nil -> seen) (map-for-term term (trie-index-top-node trie-index) ->* leaf-node) ((null s) t) (when (eq leaf-node (carc s)) (return nil))) (prog-> (map-sparse-vector (trie-index-leaf-node-entries leaf-node) :reverse t ->* e) (funcall cc e)) (setf seen (cons leaf-node seen))))))) nil)) (defun map-trie-index-instance-entries (cc term subst) (map-trie-index-entries :count-call (incf (trie-index-retrieve-instance-calls trie-index)) :count-entry (incf (trie-index-retrieve-instance-count trie-index)) :if-variable (prog-> (skip-terms 1 node ->* node) (funcall cc node)) :if-constant (prog-> (trie-index-internal-node-constant-indexed-child-node term node ->nonnil node) (funcall cc node)) :if-compound (prog-> (head term -> head) (trie-index-internal-node-function-indexed-child-node head node ->nonnil node) (map-for-terms (function-trie-index-lookup-args head term) node ->* node) (funcall cc node)))) (defun map-trie-index-generalization-entries (cc term subst) in snark-20060805 vs. snark-20060806 test over TPTP , (map-trie-index-entries :count-call (incf (trie-index-retrieve-generalization-calls trie-index)) :count-entry (incf (trie-index-retrieve-generalization-count trie-index)) :if-variable (prog-> (trie-index-internal-node-variable-indexed-child-node node ->nonnil node) (funcall cc node)) :if-constant (progn (prog-> (trie-index-internal-node-constant-indexed-child-node term node ->nonnil node) (funcall cc node)) (prog-> (trie-index-internal-node-variable-indexed-child-node node ->nonnil node) (funcall cc node))) :if-compound (progn (prog-> (head term -> head) (trie-index-internal-node-function-indexed-child-node head node ->nonnil node) (map-for-terms (function-trie-index-lookup-args head term) node ->* node) (funcall cc node)) (prog-> (trie-index-internal-node-variable-indexed-child-node node ->nonnil node) (funcall cc node))))) (defun map-trie-index-unifiable-entries (cc term subst) (map-trie-index-entries :count-call (incf (trie-index-retrieve-unifiable-calls trie-index)) :count-entry (incf (trie-index-retrieve-unifiable-count trie-index)) :if-variable (prog-> (skip-terms 1 node ->* node) (funcall cc node)) :if-constant (progn (prog-> (trie-index-internal-node-variable-indexed-child-node node ->nonnil node) (funcall cc node)) (prog-> (trie-index-internal-node-constant-indexed-child-node term node ->nonnil node) (funcall cc node))) :if-compound (progn (prog-> (trie-index-internal-node-variable-indexed-child-node node ->nonnil node) (funcall cc node)) (prog-> (head term -> head) (trie-index-internal-node-function-indexed-child-node head node ->nonnil node) (map-for-terms (function-trie-index-lookup-args head term) node ->* node) (funcall cc node))))) (defun map-trie-index-variant-entries (cc term subst) (map-trie-index-entries :count-call (incf (trie-index-retrieve-variant-calls trie-index)) :count-entry (incf (trie-index-retrieve-variant-count trie-index)) :if-variable (prog-> (trie-index-internal-node-variable-indexed-child-node node ->nonnil node) (funcall cc node)) :if-constant (prog-> (trie-index-internal-node-constant-indexed-child-node term node ->nonnil node) (funcall cc node)) :if-compound (prog-> (head term -> head) (trie-index-internal-node-function-indexed-child-node head node ->nonnil node) (map-for-terms (function-trie-index-lookup-args head term) node ->* node) (funcall cc node)))) (defun map-trie-index-all-entries (cc) (let ((term (make-variable nil 0)) (subst nil)) (map-trie-index-entries :count-call (incf (trie-index-retrieve-all-calls trie-index)) :count-entry (incf (trie-index-retrieve-all-count trie-index)) :if-variable (prog-> (skip-terms 1 node ->* node) (funcall cc node))))) (definline map-trie-index (cc type term &optional subst) (ecase type (:generalization (map-trie-index-generalization-entries cc term subst)) (:instance (map-trie-index-instance-entries cc term subst)) (:unifiable (map-trie-index-unifiable-entries cc term subst)) (:variant (map-trie-index-variant-entries cc term subst)))) (defun print-trie-index (&key terms nodes) (let ((index *trie-index*)) (mvlet (((:values current peak added deleted) (counter-values (trie-index-entry-counter index)))) (format t "~%; Trie-index has ~:D entr~:@P (~:D at peak, ~:D added, ~:D deleted)." current peak added deleted)) (mvlet (((:values current peak added deleted) (counter-values (trie-index-node-counter index)))) (format t "~%; Trie-index has ~:D node~:P (~:D at peak, ~:D added, ~:D deleted)." current peak added deleted)) (unless (eql 0 (trie-index-retrieve-variant-calls index)) (format t "~%; Trie-index retrieved ~:D variant term~:P in ~:D call~:P." (trie-index-retrieve-variant-count index) (trie-index-retrieve-variant-calls index))) (unless (eql 0 (trie-index-retrieve-generalization-calls index)) (format t "~%; Trie-index retrieved ~:D generalization term~:P in ~:D call~:P." (trie-index-retrieve-generalization-count index) (trie-index-retrieve-generalization-calls index))) (unless (eql 0 (trie-index-retrieve-instance-calls index)) (format t "~%; Trie-index retrieved ~:D instance term~:P in ~:D call~:P." (trie-index-retrieve-instance-count index) (trie-index-retrieve-instance-calls index))) (unless (eql 0 (trie-index-retrieve-unifiable-calls index)) (format t "~%; Trie-index retrieved ~:D unifiable term~:P in ~:D call~:P." (trie-index-retrieve-unifiable-count index) (trie-index-retrieve-unifiable-calls index))) (unless (eql 0 (trie-index-retrieve-all-calls index)) (format t "~%; Trie-index retrieved ~:D unrestricted term~:P in ~:D call~:P." (trie-index-retrieve-all-count index) (trie-index-retrieve-all-calls index))) (when (or nodes terms) (print-index* (trie-index-top-node index) nil terms)))) (defun print-index* (node revpath print-terms) (prog-> (map-index-leaf-nodes node revpath ->* node revpath) (print-index-leaf-node node revpath print-terms))) (defgeneric map-index-leaf-nodes (cc node revpath)) (defmethod map-index-leaf-nodes (cc (node trie-index-internal-node) revpath) (prog-> (trie-index-internal-node-variable-indexed-child-node node ->nonnil node) (map-index-leaf-nodes node (cons '? revpath) ->* node revpath) (funcall cc node revpath)) (prog-> (map-sparse-vector-with-indexes (trie-index-internal-node-constant-indexed-child-nodes node) ->* node const#) (map-index-leaf-nodes node (cons (symbol-numbered const#) revpath) ->* node revpath) (funcall cc node revpath)) (prog-> (map-sparse-vector-with-indexes (trie-index-internal-node-function-indexed-child-nodes node) ->* node fn#) (map-index-leaf-nodes node (cons (symbol-numbered fn#) revpath) ->* node revpath) (funcall cc node revpath))) (defmethod map-index-leaf-nodes (cc (node trie-index-leaf-node) revpath) (funcall cc node revpath)) (defgeneric print-index-leaf-node (node revpath print-terms)) (defmethod print-index-leaf-node ((node trie-index-leaf-node) revpath print-terms) (with-standard-io-syntax2 (prog-> (trie-index-leaf-node-entries node -> entries) (format t "~%; Path ~A has ~:D entr~:@P." (reverse revpath) (sparse-vector-count entries)) (when print-terms (map-sparse-vector entries :reverse t ->* entry) (format t "~%; ") (print-term (index-entry-term entry)))))) trie-index.lisp EOF
400cb28493eed05b335167ca75298ca229dc2e8e551105201b5edf8b7236e6b7
UU-ComputerScience/uu-cco
Component.hs
# LANGUAGE CPP # ------------------------------------------------------------------------------- -- | -- Module : CCO.Component Copyright : ( c ) 2008 Utrecht University -- License : All rights reserved -- -- Maintainer : -- Stability : provisional Portability : non - portable ( uses CPP ) -- -- An arrow for constructing and composing compiler components. -- ------------------------------------------------------------------------------- module CCO.Component ( -- * Components abstract , instance : Arrow , ArrowChoice -- * Creating components , component -- :: (a -> Feedback b) -> Component a b : : Parser s a - > Component String a -- * Generic components , printer -- :: Printable a => Component a String -- * Wrapping components , ioWrap -- :: Component String String -> IO () , ioRun -- :: Component a b -> a -> IO b ) where import CCO.Feedback (Feedback, runFeedback) import CCO.Lexing (Lexer) import CCO.Parsing (Parser, parse_) import CCO.SourcePos (Source (Stdin)) import CCO.Printing (Doc, render_, Printable (pp)) import Control.Arrow (Arrow (..), ArrowChoice (..)) import System.Exit (exitWith, ExitCode (ExitSuccess), exitFailure) import System.IO (stderr) #ifdef CATEGORY import Control.Category (Category) import qualified Control.Category (Category (id, (.))) #endif ------------------------------------------------------------------------------- -- Components ------------------------------------------------------------------------------- | The @Component@ arrow . A @Component a b@ takes input of type @a@ to output of type @b@. newtype Component a b = C {runComponent :: a -> Feedback b} #ifdef CATEGORY instance Category Component where id = C return C f . C g = C (\x -> g x >>= f) instance Arrow Component where arr f = C (return . f) first (C f) = C (\ ~(x, z) -> f x >>= \y -> return (y, z)) #else instance Arrow Component where arr f = C (return . f) C f >>> C g = C (\x -> f x >>= g) first (C f) = C (\ ~(x, z) -> f x >>= \y -> return (y, z)) #endif instance ArrowChoice Component where left (C f) = C (either (fmap Left . f) (return . Right)) ------------------------------------------------------------------------------- -- Creating components ------------------------------------------------------------------------------- -- | Creates a 'Component' from a 'Feedback' computation. component :: (a -> Feedback b) -> Component a b component = C | Creates a ' Component ' from a ' ' and a ' Parser ' . parser :: Lexer s -> Parser s a -> Component String a parser l p = component (parse_ l p Stdin) ------------------------------------------------------------------------------- Generic components ------------------------------------------------------------------------------- -- | A 'Component' for rendering 'Printable's. printer :: Printable a => Component a String printer = arr (render_ 79 . pp) ------------------------------------------------------------------------------- -- Wrapping components ------------------------------------------------------------------------------- -- | Wraps a 'Component' into a program that provides it with input from the -- standard input channel and relays its output to the standard output channel. ioWrap :: Component String String -> IO () ioWrap c = getContents >>= ioRun c >>= putStrLn >> exitWith ExitSuccess -- | Run a 'Component' in the 'IO' monad. ioRun :: Component a b -> a -> IO b ioRun (C f) input = do result <- runFeedback (f input) 1 1 stderr case result of Nothing -> exitFailure Just output -> return output
null
https://raw.githubusercontent.com/UU-ComputerScience/uu-cco/cca433c8a6f4d27407800404dea80c08fd567093/uu-cco/src/CCO/Component.hs
haskell
----------------------------------------------------------------------------- | Module : CCO.Component License : All rights reserved Maintainer : Stability : provisional An arrow for constructing and composing compiler components. ----------------------------------------------------------------------------- * Components * Creating components :: (a -> Feedback b) -> Component a b * Generic components :: Printable a => Component a String * Wrapping components :: Component String String -> IO () :: Component a b -> a -> IO b ----------------------------------------------------------------------------- Components ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- Creating components ----------------------------------------------------------------------------- | Creates a 'Component' from a 'Feedback' computation. ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- | A 'Component' for rendering 'Printable's. ----------------------------------------------------------------------------- Wrapping components ----------------------------------------------------------------------------- | Wraps a 'Component' into a program that provides it with input from the standard input channel and relays its output to the standard output channel. | Run a 'Component' in the 'IO' monad.
# LANGUAGE CPP # Copyright : ( c ) 2008 Utrecht University Portability : non - portable ( uses CPP ) module CCO.Component ( abstract , instance : Arrow , ArrowChoice : : Parser s a - > Component String a ) where import CCO.Feedback (Feedback, runFeedback) import CCO.Lexing (Lexer) import CCO.Parsing (Parser, parse_) import CCO.SourcePos (Source (Stdin)) import CCO.Printing (Doc, render_, Printable (pp)) import Control.Arrow (Arrow (..), ArrowChoice (..)) import System.Exit (exitWith, ExitCode (ExitSuccess), exitFailure) import System.IO (stderr) #ifdef CATEGORY import Control.Category (Category) import qualified Control.Category (Category (id, (.))) #endif | The @Component@ arrow . A @Component a b@ takes input of type @a@ to output of type @b@. newtype Component a b = C {runComponent :: a -> Feedback b} #ifdef CATEGORY instance Category Component where id = C return C f . C g = C (\x -> g x >>= f) instance Arrow Component where arr f = C (return . f) first (C f) = C (\ ~(x, z) -> f x >>= \y -> return (y, z)) #else instance Arrow Component where arr f = C (return . f) C f >>> C g = C (\x -> f x >>= g) first (C f) = C (\ ~(x, z) -> f x >>= \y -> return (y, z)) #endif instance ArrowChoice Component where left (C f) = C (either (fmap Left . f) (return . Right)) component :: (a -> Feedback b) -> Component a b component = C | Creates a ' Component ' from a ' ' and a ' Parser ' . parser :: Lexer s -> Parser s a -> Component String a parser l p = component (parse_ l p Stdin) Generic components printer :: Printable a => Component a String printer = arr (render_ 79 . pp) ioWrap :: Component String String -> IO () ioWrap c = getContents >>= ioRun c >>= putStrLn >> exitWith ExitSuccess ioRun :: Component a b -> a -> IO b ioRun (C f) input = do result <- runFeedback (f input) 1 1 stderr case result of Nothing -> exitFailure Just output -> return output
d1bafa2afdc6bdadd7efadf6a2eb123f86a6573a2f5e994493a30f7956f60084
DerekCuevas/interview-cake-clj
core.clj
(ns second-largest-in-binary-search-tree.core (:require [second-largest-in-binary-search-tree.binary-tree :as tree]) (:gen-class)) (defn second-largest "O(lgn) time solution." [root] (loop [parent nil {:keys [value left right] :as current} root] (if (nil? right) (if (nil? left) (:value parent) (tree/largest left)) (recur current right))))
null
https://raw.githubusercontent.com/DerekCuevas/interview-cake-clj/f17d3239bb30bcc17ced473f055a9859f9d1fb8d/second-largest-in-binary-search-tree/src/second_largest_in_binary_search_tree/core.clj
clojure
(ns second-largest-in-binary-search-tree.core (:require [second-largest-in-binary-search-tree.binary-tree :as tree]) (:gen-class)) (defn second-largest "O(lgn) time solution." [root] (loop [parent nil {:keys [value left right] :as current} root] (if (nil? right) (if (nil? left) (:value parent) (tree/largest left)) (recur current right))))
84cbe28c54de0f310deda8646056b914080f10523b8954d95e91e7baeee79047
headwinds/reagent-reframe-material-ui
demo-menu.cljs
(ns example.demos.demo-menu (:require [reagent.core :as r] [re-frame.core :as re] ["material-ui" :as mui] ["material-ui-icons" :as mui-icons])) ;;-- State (def setting-selected (r/atom 0)) (defn option-people-click [ev] (re/dispatch [:option-a-click])) (defn option-keys-click [ev] (re/dispatch [:option-a-click])) (defn settings-menu [classes] [:div {:class (.-root classes) :style {:width "200px" :border-right "1px solid #eee" :margin-top 20}} [:> mui/List {:component "nav"} ;;-- People [:> mui/ListItem {:button true :selected (= @setting-selected 0) :on-click (fn [e] (option-people-click e) (reset! setting-selected (.. e -target -value))) } [:> mui-icons/Casino {:style {:marginLeft 5}}] [:> mui/ListItemText {:primary "Bars"} ]] ;;-- Keys [:> mui/ListItem {:button true :selected (= @setting-selected 1) :on-click (fn [e] (option-keys-click e) (reset! setting-selected (.. e -target -value))) } [:> mui-icons/LocalCafe {:style {:marginLeft 5}}] [:> mui/ListItemText {:primary "Speeders"} ]] ] ]) (defn demo-menu [{:keys [classes] :as props}] (let [component-state (r/atom {:selected 0})] (fn [] (let [current-select (get @component-state :selected)] [:div {:style {:display "flex" :flexDirection "column" :position "relative" :margin 50 :alignItems "left" }} [:h2 "Menu"] (settings-menu classes) ] ))))
null
https://raw.githubusercontent.com/headwinds/reagent-reframe-material-ui/8a6fba82a026cfedca38491becac85751be9a9d4/src/example/demos/demo-menu.cljs
clojure
-- State -- People -- Keys
(ns example.demos.demo-menu (:require [reagent.core :as r] [re-frame.core :as re] ["material-ui" :as mui] ["material-ui-icons" :as mui-icons])) (def setting-selected (r/atom 0)) (defn option-people-click [ev] (re/dispatch [:option-a-click])) (defn option-keys-click [ev] (re/dispatch [:option-a-click])) (defn settings-menu [classes] [:div {:class (.-root classes) :style {:width "200px" :border-right "1px solid #eee" :margin-top 20}} [:> mui/List {:component "nav"} [:> mui/ListItem {:button true :selected (= @setting-selected 0) :on-click (fn [e] (option-people-click e) (reset! setting-selected (.. e -target -value))) } [:> mui-icons/Casino {:style {:marginLeft 5}}] [:> mui/ListItemText {:primary "Bars"} ]] [:> mui/ListItem {:button true :selected (= @setting-selected 1) :on-click (fn [e] (option-keys-click e) (reset! setting-selected (.. e -target -value))) } [:> mui-icons/LocalCafe {:style {:marginLeft 5}}] [:> mui/ListItemText {:primary "Speeders"} ]] ] ]) (defn demo-menu [{:keys [classes] :as props}] (let [component-state (r/atom {:selected 0})] (fn [] (let [current-select (get @component-state :selected)] [:div {:style {:display "flex" :flexDirection "column" :position "relative" :margin 50 :alignItems "left" }} [:h2 "Menu"] (settings-menu classes) ] ))))
4eaf330fb99caf0d7bba6dabaec284b7e9a5e0af662442a11d589f9819b4da8c
cloojure/tupelo
safe.cljc
Copyright ( c ) . All rights reserved . The use and distribution terms for this software are covered by the Eclipse Public License 1.0 ; (-1.0.php) which can be found in the file epl-v10.html at ; the root of this distribution. By using this software in any fashion, you are agreeing to be ; bound by the terms of this license. You must not remove this notice, or any other, from this ; software. (ns tupelo.string.safe (:require [clojure.walk :as walk] [tupelo.core :as t] [tupelo.string :as str] )) (defn walk-normalize ; => tupelo.string.safe/walk-normalize "Recursively walks a data structure. For all string values, perform `(str/lower-case (str/whitespace-collapse arg))`, else noop." [data] (walk/postwalk (fn [arg] (t/cond-it-> arg (string? it) (str/lower-case (str/whitespace-collapse it)))) data)) (defn walk-whitespace-collapse "Recursively walks a data structure. For all string values, perform `(str/whitespace-collapse ...)`, else noop." [data] (walk/postwalk (fn [arg] (t/cond-it-> arg (string? it) (str/whitespace-collapse it))) data))
null
https://raw.githubusercontent.com/cloojure/tupelo/485680380b2d10727181b9c3dd198ab1e6299817/src/cljc/tupelo/string/safe.cljc
clojure
(-1.0.php) which can be found in the file epl-v10.html at the root of this distribution. By using this software in any fashion, you are agreeing to be bound by the terms of this license. You must not remove this notice, or any other, from this software. => tupelo.string.safe/walk-normalize
Copyright ( c ) . All rights reserved . The use and distribution terms for this software are covered by the Eclipse Public License 1.0 (ns tupelo.string.safe (:require [clojure.walk :as walk] [tupelo.core :as t] [tupelo.string :as str] )) "Recursively walks a data structure. For all string values, perform `(str/lower-case (str/whitespace-collapse arg))`, else noop." [data] (walk/postwalk (fn [arg] (t/cond-it-> arg (string? it) (str/lower-case (str/whitespace-collapse it)))) data)) (defn walk-whitespace-collapse "Recursively walks a data structure. For all string values, perform `(str/whitespace-collapse ...)`, else noop." [data] (walk/postwalk (fn [arg] (t/cond-it-> arg (string? it) (str/whitespace-collapse it))) data))
e8a7ead3869260a1fb748844f54275f1092728c1ef3ad9695f4f6003df8fc50a
RJ/erlang-spdy
espdy_parser_test.erl
-module(espdy_parser_test). -compile(export_all). etest macros -include_lib("eunit/include/eunit.hrl"). include espdy records -include("espdy.hrl"). test_basic_operation() -> ?assertEqual(1, 1). %% ========================================================= %% Control Frame Tests %% ========================================================= Control Frame Layout : %% +----------------------------------+ Version(15bits ) | Type(16bits ) | %% +----------------------------------+ | Flags ( 8) | Length ( 24 bits ) | %% +----------------------------------+ %% | Data | %% +----------------------------------+ % SETTINGS Control Frame Layout (v2): % +----------------------------------+ |1| 2 | 4 | % +----------------------------------+ | Flags ( 8) | Length ( 24 bits ) | % +----------------------------------+ % | Number of entries | % +----------------------------------+ | ID ( 24 bits ) | ID_Flags ( 8) | < --| ID / Value Pairs , repeats % +----------------------------------+ | for each pair. | Value ( 32 bits ) | < --| % +----------------------------------+ parse_control_frame_settings_v2_test() -> ControlFrameData = <<1:1, % C 2:15/big-unsigned-integer, % Version 4:16/big-unsigned-integer, % Type 2:8/big-unsigned-integer, % Flags 12:24/big-unsigned-integer, % Length size(Data) <<0,0,0,1,4,0,0,0,0,0,3,232>>/binary >>, % Data DesiredControlFrame = #spdy_settings{version=2, flags=2, settings=[#spdy_setting_pair{flags=0, id=4, value=1000}]}, {ControlFrame, _Z} = espdy_parser:parse_frame(ControlFrameData, <<>>), ?assertEqual(DesiredControlFrame, ControlFrame). parse_control_frame_settings_v2_raw_test() -> ControlFrameData = <<128,2,0,4,0,0,0,12,0,0,0,1,4,0,0,0,0,0,3,232>>, DesiredControlFrame = #spdy_settings{version=2, flags=0, settings=[#spdy_setting_pair{flags=0, id=4, value=1000}]}, {ControlFrame, _Z} = espdy_parser:parse_frame(ControlFrameData, <<>>), ?assertEqual(DesiredControlFrame, ControlFrame). build_control_frame_settings_v2_test() -> ControlFrame = #spdy_settings{version=2, flags=2, settings=[#spdy_setting_pair{flags=0, id=4, value=1000}]}, DesiredData = <<1:1, % C 2:15/big-unsigned-integer, % Version 4:16/big-unsigned-integer, % Type 2:8/big-unsigned-integer, % Flags 12:24/big-unsigned-integer, % Length size(Data) <<0,0,0,1,4,0,0,0,0,0,3,232>>/binary >>, % Data ActualData = espdy_parser:build_frame(ControlFrame, undefined), ?assertEqual(DesiredData, ActualData). % SETTINGS Control Frame Layout (v3): % +----------------------------------+ |1| version | 4 | % +----------------------------------+ | Flags ( 8) | Length ( 24 bits ) | % +----------------------------------+ % | Number of entries | % +----------------------------------+ | Flags ( 8 bits ) | ID ( 24 ) | < --| ID / Value Pairs , repeats % +----------------------------------+ | for each pair. | Value ( 32 bits ) | < --| % +----------------------------------+ parse_control_frame_settings_v3_test() -> ControlFrameData = <<1:1, % C 3:15/big-unsigned-integer, % Version 4:16/big-unsigned-integer, % Type 2:8/big-unsigned-integer, % Flags 12:24/big-unsigned-integer, % Length size(Data) 1:32/big-unsigned-integer, % Number of entries 2:8/big-unsigned-integer, % Entry Flags 8:24/big-unsigned-integer, % Entry ID 250:32/big-unsigned-integer >>, % Entry Value DesiredControlFrame = #spdy_settings{version=3, flags=2, settings=[#spdy_setting_pair{flags=2, id=8, value=250}]}, {ControlFrame, _Z} = espdy_parser:parse_frame(ControlFrameData, <<>>), ?assertEqual(DesiredControlFrame, ControlFrame). build_control_frame_settings_v3_test() -> ControlFrame = #spdy_settings{version=3, flags=2, settings=[#spdy_setting_pair{flags=2, id=8, value=250}]}, DesiredData = <<1:1, % C 3:15/big-unsigned-integer, % Version 4:16/big-unsigned-integer, % Type 2:8/big-unsigned-integer, % Flags 12:24/big-unsigned-integer, % Length size(Data) 1:32/big-unsigned-integer, % Number of entries 2:8/big-unsigned-integer, % Entry Flags 8:24/big-unsigned-integer, % Entry ID 250:32/big-unsigned-integer >>, % Entry Value ActualData = espdy_parser:build_frame(ControlFrame, undefined), ?assertEqual(DesiredData, ActualData). % SYN_STREAM Control Frame Layout (v2): % +----------------------------------+ |1| 2 | 1 | % +----------------------------------+ | Flags ( 8) | Length ( 24 bits ) | % +----------------------------------+ |X| Stream - ID ( 31bits ) | % +----------------------------------+ |X|Associated - To - Stream - ID ( 31bits)| % +----------------------------------+ % | Pri | Unused | | % +------------------ | % | Name/value header block | % | ... | parse_control_frame_syn_stream_v2_test() -> DesiredHeaders = [{<<"accept">>, <<"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8">>}, {<<"host">>,<<"localhost:6121">>}, {<<"method">>,<<"GET">>}, {<<"scheme">>,<<"https">>}, {<<"url">>,<<"/">>}, {<<"version">>,<<"HTTP/1.1">>}], Data = <<1:1, 9:31/big-unsigned-integer, % Stream-ID 1:1, 5:31/big-unsigned-integer, % Associated-To-Stream-ID 0:2/big-unsigned-integer, % Priority 0:14/big-unsigned-integer, % Unused (pack_headers(2, DesiredHeaders))/binary >>, % Name/value header block ControlFrameData = <<1:1, % C 2:15/big-unsigned-integer, % Version 1:16/big-unsigned-integer, % Type 2:8/big-unsigned-integer, % Flags (size(Data)):24/big-unsigned-integer, % Length size(Data) Data/binary >>, % Data DesiredControlFrame = #spdy_syn_stream{version=2, flags=2, streamid=9, associd=5, priority=0, headers=DesiredHeaders}, Zinf = new_zlib_context_inflate(), {ControlFrame, _Z} = espdy_parser:parse_frame(ControlFrameData, Zinf), ?assertEqual(DesiredControlFrame, ControlFrame). parse_control_frame_syn_stream_v2_raw_test() -> ControlFrameData = <<128,2,0,1,1,0,1,34,0,0,0,1,0,0,0,0,0,0,56,234,223, 162,81,178,98,224,98,96,131,164,23,6,123,184,11,117, 48,44,214,174,64,23,205,205,177,46,180,53,208,179, 212,209,210,215,2,179,44,24,248,80,115,44,131,156, 103,176,63,212,61,58,96,7,129,213,153,235,64,212,27, 51,240,163,229,105,6,65,144,139,117,160,78,214,41, 78,73,206,128,171,129,37,3,6,190,212,60,221,208,96, 157,212,60,168,165,44,160,60,206,192,7,74,8,57,32, 166,149,153,161,145,33,3,91,46,176,108,201,79,97,96, 118,119,13,97,96,43,6,38,199,220,84,6,214,140,146, 146,130,98,6,102,144,191,25,1,2,72,31,32,128,24,184, 16,153,149,161,204,55,191,42,51,39,39,81,223,84,207, 64,65,195,55,49,57,51,175,36,191,56,195,90,193,19, 152,126,114,20,128,2,10,254,193,10,17,10,134,6,241, 22,241,70,154,10,142,192,160,72,13,79,77,242,206,44, 209,55,53,54,215,51,54,86,208,240,246,8,241,245,209, 81,200,201,204,78,85,112,79,77,206,206,215,84,112, 206,0,22,66,169,250,70,230,122,6,122,134,38,198,70, 64,195,131,19,211,18,139,50,161,154,24,216,161,81, 193,192,1,139,33,0,0,0,0,255,255>>, DesiredHeaders = [{<<"accept">>, <<"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8">>}, {<<"accept-charset">>,<<"ISO-8859-1,utf-8;q=0.7,*;q=0.3">>}, {<<"accept-encoding">>,<<"gzip,deflate,sdch">>}, {<<"accept-language">>,<<"en-US,en;q=0.8">>}, {<<"host">>,<<"localhost:6121">>}, {<<"method">>,<<"GET">>}, {<<"scheme">>,<<"https">>}, {<<"url">>,<<"/">>}, {<<"user-agent">>, <<"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) ", "AppleWebKit/537.33 (KHTML, like Gecko) ", "Chrome/27.0.1432.0 Safari/537.33">>}, {<<"version">>,<<"HTTP/1.1">>}], DesiredControlFrame = #spdy_syn_stream{version=2, flags=1, streamid=1, associd=0, priority=0, slot=undefined, headers=DesiredHeaders}, Zinf = new_zlib_context_inflate(), {ControlFrame, _Z} = espdy_parser:parse_frame(ControlFrameData, Zinf), ?assertEqual(DesiredControlFrame, ControlFrame). parse_control_frame_syn_stream_v2_header_error_test() -> DesiredHeaders = [{<<"accept">>, <<"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8">>}, Duplicate header name {<<"method">>,<<"GET">>}, {<<"url">>,<<"/">>}, {<<"version">>,<<"HTTP/1.1">>}], Data = <<1:1, 9:31/big-unsigned-integer, % Stream-ID 1:1, 5:31/big-unsigned-integer, % Associated-To-Stream-ID 0:2/big-unsigned-integer, % Priority 0:14/big-unsigned-integer, % Unused (pack_headers(2, DesiredHeaders))/binary >>, % Name/value header block ControlFrameData = <<1:1, % C 2:15/big-unsigned-integer, % Version 1:16/big-unsigned-integer, % Type 2:8/big-unsigned-integer, % Flags (size(Data)):24/big-unsigned-integer, % Length size(Data) Data/binary >>, % Data Zinf = new_zlib_context_inflate(), {Error, _Z} = espdy_parser:parse_frame(ControlFrameData, Zinf), DesiredResponse = {error, stream_protocol_error, [{streamid, 9}, {frametype, ?SYN_STREAM}]}, ?assertEqual(DesiredResponse, Error). build_control_frame_syn_stream_v2_test() -> Headers = [{<<"method">>,<<"GET">>}, {<<"url">>,<<"/">>}, {<<"version">>,<<"HTTP/1.1">>}], Frame = #spdy_syn_stream{version=2, flags=1, streamid=65, associd=17, priority=0, headers=Headers}, ?assertEqual(Frame, build_and_parse_frame(2, Frame)). % SYN_STREAM Control Frame Layout (v3): % +------------------------------------+ % |1| version | 1 | % +------------------------------------+ | Flags ( 8) | Length ( 24 bits ) | % +------------------------------------+ |X| Stream - ID ( 31bits ) | % +------------------------------------+ % |X| Associated-To-Stream-ID (31bits) | % +------------------------------------+ % | Pri|Unused | Slot | | % +-------------------+ | % | Number of Name/Value pairs (int32) | <+ % +------------------------------------+ | | Length of name ( int32 ) | | This section is the " Name / Value % +------------------------------------+ | Header Block", and is compressed. % | Name (string) | | % +------------------------------------+ | % | Length of value (int32) | | % +------------------------------------+ | % | Value (string) | | % +------------------------------------+ | % | (repeats) | <+ parse_control_frame_syn_stream_v3_test() -> RawHeaderData = <<3:32/big-unsigned-integer, % Number of Name/Value Pairs 7:32/big-unsigned-integer, % Length of Name (Header 1) <<":method">>/binary, % Name 3:32/big-unsigned-integer, % Length of Value <<"GET">>/binary, % Value Length of Name ( Header 2 ) <<":path">>/binary, % Name 12:32/big-unsigned-integer,% Length of Value <<"/hello_world">>/binary, % Value Length of Name ( Header 3 ) <<":version">>/binary, % Name 8:32/big-unsigned-integer, % Length of Value <<"HTTP/1.1">>/binary >>, % Value Zdef = zlib:open(), ok = zlib:deflateInit(Zdef), zlib:deflateSetDictionary(Zdef, ?HEADERS_ZLIB_DICT_V3), CompressedHeaderData = iolist_to_binary([ zlib:deflate(Zdef, RawHeaderData, full) ]), ControlFrameData = <<0:1, 9:31/big-unsigned-integer, % Stream ID 0:1, 5:31/big-unsigned-integer, % Associated-To-Stream ID 7:3/big-unsigned-integer, % Priority 0:5/big-unsigned-integer, % Unused 0:8/big-unsigned-integer, % Slot CompressedHeaderData/binary >>, % Compressed Headers DataLength = size(ControlFrameData), RawControlFrame = <<1:1, % C 3:15/big-unsigned-integer, % Version 1:16/big-unsigned-integer, % Type 1:8/big-unsigned-integer, % Flags DataLength:24/big-unsigned-integer, % Length ControlFrameData/binary >>, % Data DesiredHeaders = [{<<":method">>,<<"GET">>}, {<<":path">>,<<"/hello_world">>}, {<<":version">>,<<"HTTP/1.1">>}], DesiredControlFrame = #spdy_syn_stream{version=3, flags=1, streamid=9, associd=5, priority=7, slot=0, headers=DesiredHeaders}, Zinf = zlib:open(), ok = zlib:inflateInit(Zinf), {ControlFrame, _Z} = espdy_parser:parse_frame(RawControlFrame, Zinf), ?assertEqual(DesiredControlFrame, ControlFrame). parse_control_frame_syn_stream_v3_header_error_test() -> DesiredHeaders = [{<<":method">>,<<"GET">>}, {<<":path">>,<<"/">>}, {<<":version">>,<<"HTTP/1.1">>}, {<<"accept">>, <<"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8">>}, Duplicate header name Data = <<1:1, 7:31/big-unsigned-integer, % Stream-ID 1:1, 5:31/big-unsigned-integer, % Associated-To-Stream-ID 0:2/big-unsigned-integer, % Priority 0:14/big-unsigned-integer, % Unused (pack_headers(3, DesiredHeaders))/binary >>, % Name/value header block ControlFrameData = <<1:1, % C 3:15/big-unsigned-integer, % Version 1:16/big-unsigned-integer, % Type 1:8/big-unsigned-integer, % Flags (size(Data)):24/big-unsigned-integer, % Length size(Data) Data/binary >>, % Data Zinf = new_zlib_context_inflate(), {Error, _Z} = espdy_parser:parse_frame(ControlFrameData, Zinf), DesiredResponse = {error, stream_protocol_error, [{streamid, 7}, {frametype, ?SYN_STREAM}]}, ?assertEqual(DesiredResponse, Error). build_control_frame_syn_stream_v3_test() -> Headers = [{<<":method">>,<<"GET">>}, {<<":path">>,<<"/hello_world">>}, {<<":version">>,<<"HTTP/1.1">>}], Frame = #spdy_syn_stream{version=3, flags=2, streamid=65, associd=17, priority=7, slot=0, headers=Headers}, ?assertEqual(Frame, build_and_parse_frame(3, Frame)). % PING Control Frame Layout (v2/v3): % +----------------------------------+ |1| version | 6 | % +----------------------------------+ | 0 ( flags ) | 4 ( length ) | % +----------------------------------| % | 32-bit ID | % +----------------------------------+ parse_control_frame_ping_v2_test() -> ControlFrameData = <<1:1, % C 2:15/big-unsigned-integer, % Version 6:16/big-unsigned-integer, % Type 0:8/big-unsigned-integer, % Flags 4:24/big-unsigned-integer, % Length (fixed) 12345:32/big-unsigned-integer >>, % ID DesiredControlFrame = #spdy_ping{version=2, id=12345}, {ControlFrame, _Z} = espdy_parser:parse_frame(ControlFrameData, <<>>), ?assertEqual(DesiredControlFrame, ControlFrame). parse_control_frame_ping_v3_test() -> ControlFrameData = <<1:1, % C 3:15/big-unsigned-integer, % Version 6:16/big-unsigned-integer, % Type 0:8/big-unsigned-integer, % Flags 4:24/big-unsigned-integer, % Length (fixed) 12345:32/big-unsigned-integer >>, % ID DesiredControlFrame = #spdy_ping{version=3, id=12345}, {ControlFrame, _Z} = espdy_parser:parse_frame(ControlFrameData, <<>>), ?assertEqual(DesiredControlFrame, ControlFrame). build_control_frame_ping_v2_test() -> Frame = #spdy_ping{version=2, id=12345}, ?assertEqual(Frame, build_and_parse_frame(2, Frame)). build_control_frame_ping_v3_test() -> Frame = #spdy_ping{version=3, id=12345}, ?assertEqual(Frame, build_and_parse_frame(3, Frame)). % RST_STREAM Control Frame Layout (v2/v3): % +----------------------------------+ |1| version | 3 | % +----------------------------------+ % | Flags (8) | 8 | % +----------------------------------+ |X| Stream - ID ( 31bits ) | % +----------------------------------+ % | Status code | % +----------------------------------+ parse_control_frame_rst_stream_v2_test() -> ControlFrameData = <<1:1, % C 2:15/big-unsigned-integer, % Version 3:16/big-unsigned-integer, % Type 0:8/big-unsigned-integer, % Flags 8:24/big-unsigned-integer, % Length (fixed) 0:1, 543:31/big-unsigned-integer, % Stream-ID 11:32/big-unsigned-integer >>, % Status code DesiredControlFrame = #spdy_rst_stream{version=2, flags=0, streamid=543, statuscode=11}, {ControlFrame, _Z} = espdy_parser:parse_frame(ControlFrameData, <<>>), ?assertEqual(DesiredControlFrame, ControlFrame). parse_control_frame_rst_stream_v3_test() -> ControlFrameData = <<1:1, % C 3:15/big-unsigned-integer, % Version 3:16/big-unsigned-integer, % Type 0:8/big-unsigned-integer, % Flags 8:24/big-unsigned-integer, % Length (fixed) 0:1, 543:31/big-unsigned-integer, % Stream-ID 11:32/big-unsigned-integer >>, % Status code DesiredControlFrame = #spdy_rst_stream{version=3, flags=0, streamid=543, statuscode=11}, {ControlFrame, _Z} = espdy_parser:parse_frame(ControlFrameData, <<>>), ?assertEqual(DesiredControlFrame, ControlFrame). build_control_frame_rst_stream_v2_test() -> Frame = #spdy_rst_stream{version=2, flags=0, streamid=543, statuscode=11}, ?assertEqual(Frame, build_and_parse_frame(2, Frame)). build_control_frame_rst_stream_v3_test() -> Frame = #spdy_rst_stream{version=3, flags=0, streamid=543, statuscode=11}, ?assertEqual(Frame, build_and_parse_frame(3, Frame)). GOAWAY Control Frame Layout ( v2 ): % +----------------------------------+ |1| 2 | 7 | % +----------------------------------+ | 0 ( flags ) | 4 ( length ) | % +----------------------------------| |X| Last - good - stream - ID ( 31 bits ) | % +----------------------------------+ parse_control_frame_goaway_v2_test() -> ControlFrameData = <<1:1, % C 2:15/big-unsigned-integer, % Version 7:16/big-unsigned-integer, % Type 0:8/big-unsigned-integer, % Flags 4:24/big-unsigned-integer, % Length (fixed) 0:1, 543:31/big-unsigned-integer >>, % Last-good-stream-ID DesiredControlFrame = #spdy_goaway{version=2, lastgoodid=543}, {ControlFrame, _Z} = espdy_parser:parse_frame(ControlFrameData, <<>>), ?assertEqual(DesiredControlFrame, ControlFrame). build_control_frame_goaway_v2_test() -> Frame = #spdy_goaway{version=2, lastgoodid=543}, ?assertEqual(Frame, build_and_parse_frame(2, Frame)). GOAWWAY Control Frame Layout ( v3 ): % +----------------------------------+ |1| version | 7 | % +----------------------------------+ | 0 ( flags ) | 8 ( length ) | % +----------------------------------| |X| Last - good - stream - ID ( 31 bits ) | % +----------------------------------+ % | Status code | % +----------------------------------+ parse_control_frame_goaway_v3_test() -> ControlFrameData = <<1:1, % C 3:15/big-unsigned-integer, % Version 7:16/big-unsigned-integer, % Type 0:8/big-unsigned-integer, % Flags 8:24/big-unsigned-integer, % Length (fixed) 0:1, 543:31/big-unsigned-integer, % Last-good-stream-ID 2:32/big-unsigned-integer >>, % Status code DesiredControlFrame = #spdy_goaway{version=3, lastgoodid=543, statuscode=2}, {ControlFrame, _Z} = espdy_parser:parse_frame(ControlFrameData, <<>>), ?assertEqual(DesiredControlFrame, ControlFrame). build_control_frame_goaway_v3_test() -> Frame = #spdy_goaway{version=3, lastgoodid=543, statuscode=2}, ?assertEqual(Frame, build_and_parse_frame(3, Frame)). % HEADERS Control Frame Layout (v2): % +----------------------------------+ 2 | 8 | % +----------------------------------+ | Flags ( 8) | Length ( 24 bits ) | % +----------------------------------+ |X| Stream - ID ( 31bits ) | % +----------------------------------+ | Unused ( 16 bits ) | | |-------------------- | % | Name/value header block | % +----------------------------------+ parse_control_frame_headers_v2_test() -> Headers = [{<<"method">>,<<"GET">>}, {<<"url">>,<<"/">>}, {<<"version">>,<<"HTTP/1.1">>}], Packed = pack_headers(2, Headers), ControlFrameData = <<1:1, % C 2:15/big-unsigned-integer, % Version 8:16/big-unsigned-integer, % Type 1:8/big-unsigned-integer, % Flags (size(Packed)+6):24/big-unsigned-integer, % Length 0:1, 432:31/big-unsigned-integer, % Stream-ID 0:16/big-unsigned-integer, % Unused Packed/binary >>, % Name/value header block DesiredControlFrame = #spdy_headers{version=2, flags=1, streamid=432, headers=Headers}, {ControlFrame, _Z} = espdy_parser:parse_frame(ControlFrameData, new_zlib_context_inflate()), ?assertEqual(DesiredControlFrame, ControlFrame). parse_control_frame_headers_v2_header_error_test() -> Invalid header name ( capitalized ) {<<"url">>,<<"/">>}, {<<"version">>,<<"HTTP/1.1">>}], Packed = pack_headers(2, Headers), ControlFrameData = <<1:1, % C 2:15/big-unsigned-integer, % Version 8:16/big-unsigned-integer, % Type 1:8/big-unsigned-integer, % Flags (size(Packed)+6):24/big-unsigned-integer, % Length 0:1, 432:31/big-unsigned-integer, % Stream-ID 0:16/big-unsigned-integer, % Unused Packed/binary >>, % Name/value header block {Error, _Z} = espdy_parser:parse_frame(ControlFrameData, new_zlib_context_inflate()), DesiredResponse = {error, stream_protocol_error, [{streamid, 432}, {frametype, ?HEADERS}]}, ?assertEqual(DesiredResponse, Error). build_control_frame_headers_v2_test() -> Headers = [{<<"method">>,<<"GET">>}, {<<"url">>,<<"/">>}, {<<"version">>,<<"HTTP/1.1">>}], Frame = #spdy_headers{version=2, flags=1, streamid=432, headers=Headers}, ?assertEqual(Frame, build_and_parse_frame(2, Frame)). % HEADERS Control Frame Layout (v3): % +------------------------------------+ |1| version | 8 | % +------------------------------------+ | Flags ( 8) | Length ( 24 bits ) | % +------------------------------------+ |X| Stream - ID ( 31bits ) | % +------------------------------------+ % | Number of Name/Value pairs (int32) | <+ % +------------------------------------+ | | Length of name ( int32 ) | | This section is the " Name / Value % +------------------------------------+ | Header Block", and is compressed. % | Name (string) | | % +------------------------------------+ | % | Length of value (int32) | | % +------------------------------------+ | % | Value (string) | | % +------------------------------------+ | % | (repeats) | <+ parse_control_frame_headers_v3_test() -> Headers = [{<<":method">>,<<"GET">>}, {<<":path">>,<<"/hello_world">>}, {<<":version">>,<<"HTTP/1.1">>}], Packed = pack_headers(3, Headers), ControlFrameData = <<1:1, % C 3:15/big-unsigned-integer, % Version 8:16/big-unsigned-integer, % Type 1:8/big-unsigned-integer, % Flags (size(Packed)+4):24/big-unsigned-integer, % Length 0:1, 432:31/big-unsigned-integer, % Stream-ID Packed/binary >>, % Name/value header block DesiredControlFrame = #spdy_headers{version=3, flags=1, streamid=432, headers=Headers}, {ControlFrame, _Z} = espdy_parser:parse_frame(ControlFrameData, new_zlib_context_inflate()), ?assertEqual(DesiredControlFrame, ControlFrame). build_control_frame_headers_v3_test() -> Headers = [{<<":method">>,<<"GET">>}, {<<":url">>,<<"/">>}, {<<":version">>,<<"HTTP/1.1">>}], Frame = #spdy_headers{version=3, flags=1, streamid=432, headers=Headers}, ?assertEqual(Frame, build_and_parse_frame(3, Frame)). % SYN_REPLY Control Frame Layout (v2): % +----------------------------------+ |1| 2 | 2 | % +----------------------------------+ | Flags ( 8) | Length ( 24 bits ) | % +----------------------------------+ |X| Stream - ID ( 31bits ) | % +----------------------------------+ % | Unused | | % +---------------- | % | Name/value header block | % | ... | parse_control_frame_syn_reply_v2_test() -> Headers = [{<<"status">>,<<"GET">>}, {<<"version">>,<<"HTTP/1.1">>}, {<<"content-type">>,<<"text/html">>}], Packed = pack_headers(2, Headers), ControlFrameData = <<1:1, % C 2:15/big-unsigned-integer, % Version 2:16/big-unsigned-integer, % Type 1:8/big-unsigned-integer, % Flags (size(Packed)+6):24/big-unsigned-integer, % Length 0:1, 432:31/big-unsigned-integer, % Stream-ID 0:16/big-unsigned-integer, % Unused Packed/binary >>, % Name/value header block DesiredControlFrame = #spdy_syn_reply{version=2, flags=1, streamid=432, headers=Headers}, {ControlFrame, _Z} = espdy_parser:parse_frame(ControlFrameData, new_zlib_context_inflate()), ?assertEqual(DesiredControlFrame, ControlFrame). parse_control_frame_syn_reply_v2_header_error_test() -> Headers = [{<<"status">>,<<"GET">>}, {<<"version">>,<<"HTTP/1.1">>}, {<<"content-type">>,<<"text/html">>}, {<<"content-type">>,<<"text/javascript">>}], % duplicate header Packed = pack_headers(2, Headers), ControlFrameData = <<1:1, % C 2:15/big-unsigned-integer, % Version 2:16/big-unsigned-integer, % Type 1:8/big-unsigned-integer, % Flags (size(Packed)+6):24/big-unsigned-integer, % Length 0:1, 432:31/big-unsigned-integer, % Stream-ID 0:16/big-unsigned-integer, % Unused Packed/binary >>, % Name/value header block {Error, _Z} = espdy_parser:parse_frame(ControlFrameData, new_zlib_context_inflate()), DesiredResponse = {error, stream_protocol_error, [{streamid, 432}, {frametype, ?SYN_REPLY}]}, ?assertEqual(DesiredResponse, Error). build_control_frame_syn_reply_v2_test() -> Headers = [{<<"status">>,<<"GET">>}, {<<"version">>,<<"HTTP/1.1">>}, {<<"content-type">>,<<"text/html">>}], Frame = #spdy_syn_reply{version=2, flags=1, streamid=432, headers=Headers}, ?assertEqual(Frame, build_and_parse_frame(2, Frame)). % SYN_REPLY Control Frame Layout (v3): % +------------------------------------+ % |1| version | 2 | % +------------------------------------+ | Flags ( 8) | Length ( 24 bits ) | % +------------------------------------+ |X| Stream - ID ( 31bits ) | % +------------------------------------+ % | Number of Name/Value pairs (int32) | <+ % +------------------------------------+ | | Length of name ( int32 ) | | This section is the " Name / Value % +------------------------------------+ | Header Block", and is compressed. % | Name (string) | | % +------------------------------------+ | % | Length of value (int32) | | % +------------------------------------+ | % | Value (string) | | % +------------------------------------+ | % | (repeats) | <+ parse_control_frame_syn_reply_v3_test() -> Headers = [{<<":status">>,<<"GET">>}, {<<":version">>,<<"HTTP/1.1">>}, {<<"content-type">>,<<"text/html">>}], Packed = pack_headers(3, Headers), ControlFrameData = <<1:1, % C 3:15/big-unsigned-integer, % Version 2:16/big-unsigned-integer, % Type 1:8/big-unsigned-integer, % Flags (size(Packed)+2):24/big-unsigned-integer, % Length 0:1, 432:31/big-unsigned-integer, % Stream-ID Packed/binary >>, % Name/value header block DesiredControlFrame = #spdy_syn_reply{version=3, flags=1, streamid=432, headers=Headers}, {ControlFrame, _Z} = espdy_parser:parse_frame(ControlFrameData, new_zlib_context_inflate()), ?assertEqual(DesiredControlFrame, ControlFrame). parse_control_frame_syn_reply_v3_header_error_test() -> Headers = [{<<":status">>,<<"GET">>}, {<<":version">>,<<"HTTP/1.1">>}, {<<"content-type">>,<<"text/html">>}, {<<"content-type">>,<<"text/javascript">>}], % duplicate header Packed = pack_headers(3, Headers), ControlFrameData = <<1:1, % C 3:15/big-unsigned-integer, % Version 2:16/big-unsigned-integer, % Type 1:8/big-unsigned-integer, % Flags (size(Packed)+2):24/big-unsigned-integer, % Length 0:1, 438:31/big-unsigned-integer, % Stream-ID Packed/binary >>, % Name/value header block {Error, _Z} = espdy_parser:parse_frame(ControlFrameData, new_zlib_context_inflate()), DesiredResponse = {error, stream_protocol_error, [{streamid, 438}, {frametype, ?SYN_REPLY}]}, ?assertEqual(DesiredResponse, Error). build_control_frame_syn_reply_v3_test() -> Headers = [{<<":status">>,<<"GET">>}, {<<":version">>,<<"HTTP/1.1">>}, {<<"content-type">>,<<"text/html">>}], Frame = #spdy_syn_reply{version=3, flags=1, streamid=432, headers=Headers}, ?assertEqual(Frame, build_and_parse_frame(3, Frame)). WINDOW_UPDATE Control Frame Layout ( v3 ): % +----------------------------------+ |1| version | 9 | % +----------------------------------+ | 0 ( flags ) | 8 ( length ) | % +----------------------------------+ |X| Stream - ID ( 31 - bits ) | % +----------------------------------+ |X| Delta - Window - Size ( 31 - bits ) | % +----------------------------------+ parse_control_frame_window_update_v3_test() -> ControlFrameData = <<1:1, % C 3:15/big-unsigned-integer, % Version 9:16/big-unsigned-integer, % Type 0:8/big-unsigned-integer, % Flags 8:24/big-unsigned-integer, % Length (fixed) 0:1, 835:31/big-unsigned-integer, % Stream-ID Delta - Window - Size DesiredControlFrame = #spdy_window_update{version=3, streamid=835, delta_size=999}, {ControlFrame, _Z} = espdy_parser:parse_frame(ControlFrameData, <<>>), ?assertEqual(DesiredControlFrame, ControlFrame). build_control_frame_window_update_v3_test() -> Frame = #spdy_window_update{version=3, streamid=835, delta_size=999}, ?assertEqual(Frame, build_and_parse_frame(3, Frame)). %% ========================================================= %% Header encoding tests %% ========================================================= encode_name_value_header_v2_test() -> Headers = [{<<"method">>,<<"GET">>}, {<<"url">>,<<"/">>}, {<<"version">>,<<"HTTP/1.1">>}], Desired = <<120,187,223,162,81,178,98,96,102,96,203,5,230,195,252,20,6,102,119, 215,16,6,102,144,32,163,62,3,59,84,13,3,7,76,43,0,0,0,255,255>>, Packed = pack_headers(2, Headers), ?assertEqual(Desired, Packed). encode_name_value_header_v3_test() -> Headers = [{<<":method">>,<<"GET">>}, {<<":path">>,<<"/hello_world">>}, {<<":version">>,<<"HTTP/1.1">>}], Desired = <<120,187,227,198,167,194,2,37,58,80,122,180,66,164,90, 119,215,16,80,6,179,42,72,4,151,77,60,250,25,169,192, 2,50,190,60,191,40,7,156,153,173,176,164,93,0,0,0,0,255,255>>, Packed = pack_headers(3, Headers), ?assertEqual(Desired, Packed). %% ========================================================= %% Header decoding tests %% ========================================================= parse_name_val_pairs_v2_test() -> RawHeaderData = <<6:16/big-unsigned-integer, % Length of Name (Header 1) <<"method">>/binary, % Name 3:16/big-unsigned-integer, % Length of Value <<"GET">>/binary >>, % Value Result = espdy_parser:parse_name_val_pairs(2, 1, RawHeaderData, []), ?assertEqual([{<<"method">>,<<"GET">>}], Result). parse_name_val_pairs_v2_multiple_values_test() -> RawHeaderData = <<15:16/big-unsigned-integer, % Length of Name (Header 1) <<"x-forwarded-for">>/binary, % Name 26:16/big-unsigned-integer, % Length of Value <<"1.2.3.4", 0, "5.6.7.8", 0, "9.10.11.12">>/binary >>, % Value Result = espdy_parser:parse_name_val_pairs(2, 1, RawHeaderData, []), ?assertEqual([{<<"x-forwarded-for">>,[<<"1.2.3.4">>, <<"5.6.7.8">>, <<"9.10.11.12">>]}], Result). parse_name_val_pairs_v2_invalid_header_name_test() -> RawHeaderData = <<6:16/big-unsigned-integer, % Length of Name (Header 1) <<"Method">>/binary, % Name (with a disallowed capital letter) 3:16/big-unsigned-integer, % Length of Value <<"GET">>/binary >>, % Value Result = espdy_parser:parse_name_val_pairs(2, 1, RawHeaderData, []), % Not clear on whether this is the correct type of error for this scenario ?assertEqual({error, stream_protocol_error}, Result). parse_name_val_pairs_v2_zero_length_name_test() -> RawHeaderData = <<0:16/big-unsigned-integer, % Length of Name (Header 1) <<"">>/binary, % Name 3:16/big-unsigned-integer, % Length of Value <<"GET">>/binary >>, % Value Result = espdy_parser:parse_name_val_pairs(2, 1, RawHeaderData, []), ?assertEqual({error, stream_protocol_error}, Result). parse_name_val_pairs_v2_zero_length_value_test() -> RawHeaderData = <<6:16/big-unsigned-integer, % Length of Name (Header 1) <<"method">>/binary, % Name 0:16/big-unsigned-integer, % Length of Value <<"">>/binary >>, % Empty Value Result = espdy_parser:parse_name_val_pairs(2, 1, RawHeaderData, []), ?assertEqual({error, stream_protocol_error}, Result). parse_name_val_pairs_v2_consecutive_nuls_test() -> RawHeaderData = <<6:16/big-unsigned-integer, % Length of Name (Header 1) <<"method">>/binary, % Name 8:16/big-unsigned-integer, % Length of Value <<"omg",0,0,"wtf">>/binary >>, % Invalid Value (consecutive NULs) Result = espdy_parser:parse_name_val_pairs(2, 1, RawHeaderData, []), ?assertEqual({error, stream_protocol_error}, Result). parse_name_val_pairs_v2_duplicate_header_names_test() -> RawHeaderData = <<6:16/big-unsigned-integer, % Length of Name (Header 1) <<"method">>/binary, % Name 3:16/big-unsigned-integer, % Length of Value <<"omg">>/binary, % Value 6:16/big-unsigned-integer, % Length of Name (dupe of Header 1) <<"method">>/binary, % Name 3:16/big-unsigned-integer, % Length of Value <<"wtf">>/binary >>, % Value Result = espdy_parser:parse_name_val_pairs(2, 2, RawHeaderData, []), ?assertEqual({error, stream_protocol_error}, Result). parse_name_val_pairs_v3_test() -> RawHeaderData = <<7:32/big-unsigned-integer, % Length of Name (Header 1) <<":method">>/binary, % Name 3:32/big-unsigned-integer, % Length of Value <<"GET">>/binary >>, % Value Result = espdy_parser:parse_name_val_pairs(3, 1, RawHeaderData, []), ?assertEqual([{<<":method">>,<<"GET">>}], Result). parse_name_val_pairs_v3_multiple_values_test() -> RawHeaderData = <<15:32/big-unsigned-integer, % Length of Name (Header 1) <<"x-forwarded-for">>/binary, % Name 26:32/big-unsigned-integer, % Length of Value <<"1.2.3.4", 0, "5.6.7.8", 0, "9.10.11.12">>/binary >>, % Value Result = espdy_parser:parse_name_val_pairs(3, 1, RawHeaderData, []), ?assertEqual([{<<"x-forwarded-for">>,[<<"1.2.3.4">>, <<"5.6.7.8">>, <<"9.10.11.12">>]}], Result). parse_name_val_pairs_v3_invalid_header_name_test() -> RawHeaderData = <<6:32/big-unsigned-integer, % Length of Name (Header 1) <<"Method">>/binary, % Name (with a disallowed capital letter) 3:32/big-unsigned-integer, % Length of Value <<"GET">>/binary >>, % Value Result = espdy_parser:parse_name_val_pairs(3, 1, RawHeaderData, []), % Not clear on whether this is the correct type of error for this scenario ?assertEqual({error, stream_protocol_error}, Result). parse_name_val_pairs_v3_zero_length_name_test() -> RawHeaderData = <<0:32/big-unsigned-integer, % Length of Name (Header 1) <<"">>/binary, % Name 3:32/big-unsigned-integer, % Length of Value <<"GET">>/binary >>, % Value Result = espdy_parser:parse_name_val_pairs(3, 1, RawHeaderData, []), ?assertEqual({error, stream_protocol_error}, Result). parse_name_val_pairs_v3_zero_length_value_test() -> 0 - length header values are allowed in spdy/3 RawHeaderData = <<6:32/big-unsigned-integer, % Length of Name (Header 1) <<"method">>/binary, % Name 0:32/big-unsigned-integer, % Length of Value <<"">>/binary >>, % Empty Value Result = espdy_parser:parse_name_val_pairs(3, 1, RawHeaderData, []), ?assertEqual([{<<"method">>,<<>>}], Result). parse_name_val_pairs_v3_consecutive_nuls_test() -> RawHeaderData = <<6:32/big-unsigned-integer, % Length of Name (Header 1) <<"method">>/binary, % Name 8:32/big-unsigned-integer, % Length of Value <<"omg",0,0,"wtf">>/binary >>, % Invalid Value (consecutive NULs) Result = espdy_parser:parse_name_val_pairs(3, 1, RawHeaderData, []), ?assertEqual({error, stream_protocol_error}, Result). parse_name_val_pairs_v3_duplicate_header_names_test() -> RawHeaderData = <<6:32/big-unsigned-integer, % Length of Name (Header 1) <<"method">>/binary, % Name 3:32/big-unsigned-integer, % Length of Value <<"omg">>/binary, % Value 6:32/big-unsigned-integer, % Length of Name (dupe of Header 1) <<"method">>/binary, % Name 3:32/big-unsigned-integer, % Length of Value <<"wtf">>/binary >>, % Value Result = espdy_parser:parse_name_val_pairs(3, 2, RawHeaderData, []), ?assertEqual({error, stream_protocol_error}, Result). %% ========================================================= %% Helpers %% ========================================================= build_and_parse_frame(Version, Frame) -> Zdef = new_zlib_context_deflate(Version), CFData = espdy_parser:build_frame(Frame, Zdef), Zinf = new_zlib_context_inflate(), {FrameParsed, _Z} = espdy_parser:parse_frame(CFData, Zinf), FrameParsed. pack_headers(Version, Headers) when Version =:= 2; Version =:= 3 -> Zdef = new_zlib_context_deflate(Version), espdy_parser:encode_name_value_header(Version, Headers, Zdef). new_zlib_context_deflate(V) -> Zdef = zlib:open(), ok = zlib:deflateInit(Zdef), case V of 2 -> zlib:deflateSetDictionary(Zdef, ?HEADERS_ZLIB_DICT); 3 -> zlib:deflateSetDictionary(Zdef, ?HEADERS_ZLIB_DICT_V3) end, Zdef. new_zlib_context_inflate() -> Zinf = zlib:open(), ok = zlib:inflateInit(Zinf), Zinf.
null
https://raw.githubusercontent.com/RJ/erlang-spdy/3a15f26a80db87e0d901e8f1096682f848953d75/test/espdy_parser_test.erl
erlang
========================================================= Control Frame Tests ========================================================= +----------------------------------+ +----------------------------------+ +----------------------------------+ | Data | +----------------------------------+ SETTINGS Control Frame Layout (v2): +----------------------------------+ +----------------------------------+ +----------------------------------+ | Number of entries | +----------------------------------+ +----------------------------------+ | for each pair. +----------------------------------+ C Version Type Flags Length size(Data) Data C Version Type Flags Length size(Data) Data SETTINGS Control Frame Layout (v3): +----------------------------------+ +----------------------------------+ +----------------------------------+ | Number of entries | +----------------------------------+ +----------------------------------+ | for each pair. +----------------------------------+ C Version Type Flags Length size(Data) Number of entries Entry Flags Entry ID Entry Value C Version Type Flags Length size(Data) Number of entries Entry Flags Entry ID Entry Value SYN_STREAM Control Frame Layout (v2): +----------------------------------+ +----------------------------------+ +----------------------------------+ +----------------------------------+ +----------------------------------+ | Pri | Unused | | +------------------ | | Name/value header block | | ... | Stream-ID Associated-To-Stream-ID Priority Unused Name/value header block C Version Type Flags Length size(Data) Data Stream-ID Associated-To-Stream-ID Priority Unused Name/value header block C Version Type Flags Length size(Data) Data SYN_STREAM Control Frame Layout (v3): +------------------------------------+ |1| version | 1 | +------------------------------------+ +------------------------------------+ +------------------------------------+ |X| Associated-To-Stream-ID (31bits) | +------------------------------------+ | Pri|Unused | Slot | | +-------------------+ | | Number of Name/Value pairs (int32) | <+ +------------------------------------+ | +------------------------------------+ | Header Block", and is compressed. | Name (string) | | +------------------------------------+ | | Length of value (int32) | | +------------------------------------+ | | Value (string) | | +------------------------------------+ | | (repeats) | <+ Number of Name/Value Pairs Length of Name (Header 1) Name Length of Value Value Name Length of Value Value Name Length of Value Value Stream ID Associated-To-Stream ID Priority Unused Slot Compressed Headers C Version Type Flags Length Data Stream-ID Associated-To-Stream-ID Priority Unused Name/value header block C Version Type Flags Length size(Data) Data PING Control Frame Layout (v2/v3): +----------------------------------+ +----------------------------------+ +----------------------------------| | 32-bit ID | +----------------------------------+ C Version Type Flags Length (fixed) ID C Version Type Flags Length (fixed) ID RST_STREAM Control Frame Layout (v2/v3): +----------------------------------+ +----------------------------------+ | Flags (8) | 8 | +----------------------------------+ +----------------------------------+ | Status code | +----------------------------------+ C Version Type Flags Length (fixed) Stream-ID Status code C Version Type Flags Length (fixed) Stream-ID Status code +----------------------------------+ +----------------------------------+ +----------------------------------| +----------------------------------+ C Version Type Flags Length (fixed) Last-good-stream-ID +----------------------------------+ +----------------------------------+ +----------------------------------| +----------------------------------+ | Status code | +----------------------------------+ C Version Type Flags Length (fixed) Last-good-stream-ID Status code HEADERS Control Frame Layout (v2): +----------------------------------+ +----------------------------------+ +----------------------------------+ +----------------------------------+ | Name/value header block | +----------------------------------+ C Version Type Flags Length Stream-ID Unused Name/value header block C Version Type Flags Length Stream-ID Unused Name/value header block HEADERS Control Frame Layout (v3): +------------------------------------+ +------------------------------------+ +------------------------------------+ +------------------------------------+ | Number of Name/Value pairs (int32) | <+ +------------------------------------+ | +------------------------------------+ | Header Block", and is compressed. | Name (string) | | +------------------------------------+ | | Length of value (int32) | | +------------------------------------+ | | Value (string) | | +------------------------------------+ | | (repeats) | <+ C Version Type Flags Length Stream-ID Name/value header block SYN_REPLY Control Frame Layout (v2): +----------------------------------+ +----------------------------------+ +----------------------------------+ +----------------------------------+ | Unused | | +---------------- | | Name/value header block | | ... | C Version Type Flags Length Stream-ID Unused Name/value header block duplicate header C Version Type Flags Length Stream-ID Unused Name/value header block SYN_REPLY Control Frame Layout (v3): +------------------------------------+ |1| version | 2 | +------------------------------------+ +------------------------------------+ +------------------------------------+ | Number of Name/Value pairs (int32) | <+ +------------------------------------+ | +------------------------------------+ | Header Block", and is compressed. | Name (string) | | +------------------------------------+ | | Length of value (int32) | | +------------------------------------+ | | Value (string) | | +------------------------------------+ | | (repeats) | <+ C Version Type Flags Length Stream-ID Name/value header block duplicate header C Version Type Flags Length Stream-ID Name/value header block +----------------------------------+ +----------------------------------+ +----------------------------------+ +----------------------------------+ +----------------------------------+ C Version Type Flags Length (fixed) Stream-ID ========================================================= Header encoding tests ========================================================= ========================================================= Header decoding tests ========================================================= Length of Name (Header 1) Name Length of Value Value Length of Name (Header 1) Name Length of Value Value Length of Name (Header 1) Name (with a disallowed capital letter) Length of Value Value Not clear on whether this is the correct type of error for this scenario Length of Name (Header 1) Name Length of Value Value Length of Name (Header 1) Name Length of Value Empty Value Length of Name (Header 1) Name Length of Value Invalid Value (consecutive NULs) Length of Name (Header 1) Name Length of Value Value Length of Name (dupe of Header 1) Name Length of Value Value Length of Name (Header 1) Name Length of Value Value Length of Name (Header 1) Name Length of Value Value Length of Name (Header 1) Name (with a disallowed capital letter) Length of Value Value Not clear on whether this is the correct type of error for this scenario Length of Name (Header 1) Name Length of Value Value Length of Name (Header 1) Name Length of Value Empty Value Length of Name (Header 1) Name Length of Value Invalid Value (consecutive NULs) Length of Name (Header 1) Name Length of Value Value Length of Name (dupe of Header 1) Name Length of Value Value ========================================================= Helpers =========================================================
-module(espdy_parser_test). -compile(export_all). etest macros -include_lib("eunit/include/eunit.hrl"). include espdy records -include("espdy.hrl"). test_basic_operation() -> ?assertEqual(1, 1). Control Frame Layout : Version(15bits ) | Type(16bits ) | | Flags ( 8) | Length ( 24 bits ) | |1| 2 | 4 | | Flags ( 8) | Length ( 24 bits ) | | ID ( 24 bits ) | ID_Flags ( 8) | < --| ID / Value Pairs , repeats | Value ( 32 bits ) | < --| parse_control_frame_settings_v2_test() -> DesiredControlFrame = #spdy_settings{version=2, flags=2, settings=[#spdy_setting_pair{flags=0, id=4, value=1000}]}, {ControlFrame, _Z} = espdy_parser:parse_frame(ControlFrameData, <<>>), ?assertEqual(DesiredControlFrame, ControlFrame). parse_control_frame_settings_v2_raw_test() -> ControlFrameData = <<128,2,0,4,0,0,0,12,0,0,0,1,4,0,0,0,0,0,3,232>>, DesiredControlFrame = #spdy_settings{version=2, flags=0, settings=[#spdy_setting_pair{flags=0, id=4, value=1000}]}, {ControlFrame, _Z} = espdy_parser:parse_frame(ControlFrameData, <<>>), ?assertEqual(DesiredControlFrame, ControlFrame). build_control_frame_settings_v2_test() -> ControlFrame = #spdy_settings{version=2, flags=2, settings=[#spdy_setting_pair{flags=0, id=4, value=1000}]}, ActualData = espdy_parser:build_frame(ControlFrame, undefined), ?assertEqual(DesiredData, ActualData). |1| version | 4 | | Flags ( 8) | Length ( 24 bits ) | | Flags ( 8 bits ) | ID ( 24 ) | < --| ID / Value Pairs , repeats | Value ( 32 bits ) | < --| parse_control_frame_settings_v3_test() -> DesiredControlFrame = #spdy_settings{version=3, flags=2, settings=[#spdy_setting_pair{flags=2, id=8, value=250}]}, {ControlFrame, _Z} = espdy_parser:parse_frame(ControlFrameData, <<>>), ?assertEqual(DesiredControlFrame, ControlFrame). build_control_frame_settings_v3_test() -> ControlFrame = #spdy_settings{version=3, flags=2, settings=[#spdy_setting_pair{flags=2, id=8, value=250}]}, ActualData = espdy_parser:build_frame(ControlFrame, undefined), ?assertEqual(DesiredData, ActualData). |1| 2 | 1 | | Flags ( 8) | Length ( 24 bits ) | |X| Stream - ID ( 31bits ) | |X|Associated - To - Stream - ID ( 31bits)| parse_control_frame_syn_stream_v2_test() -> DesiredHeaders = [{<<"accept">>, <<"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8">>}, {<<"host">>,<<"localhost:6121">>}, {<<"method">>,<<"GET">>}, {<<"scheme">>,<<"https">>}, {<<"url">>,<<"/">>}, {<<"version">>,<<"HTTP/1.1">>}], DesiredControlFrame = #spdy_syn_stream{version=2, flags=2, streamid=9, associd=5, priority=0, headers=DesiredHeaders}, Zinf = new_zlib_context_inflate(), {ControlFrame, _Z} = espdy_parser:parse_frame(ControlFrameData, Zinf), ?assertEqual(DesiredControlFrame, ControlFrame). parse_control_frame_syn_stream_v2_raw_test() -> ControlFrameData = <<128,2,0,1,1,0,1,34,0,0,0,1,0,0,0,0,0,0,56,234,223, 162,81,178,98,224,98,96,131,164,23,6,123,184,11,117, 48,44,214,174,64,23,205,205,177,46,180,53,208,179, 212,209,210,215,2,179,44,24,248,80,115,44,131,156, 103,176,63,212,61,58,96,7,129,213,153,235,64,212,27, 51,240,163,229,105,6,65,144,139,117,160,78,214,41, 78,73,206,128,171,129,37,3,6,190,212,60,221,208,96, 157,212,60,168,165,44,160,60,206,192,7,74,8,57,32, 166,149,153,161,145,33,3,91,46,176,108,201,79,97,96, 118,119,13,97,96,43,6,38,199,220,84,6,214,140,146, 146,130,98,6,102,144,191,25,1,2,72,31,32,128,24,184, 16,153,149,161,204,55,191,42,51,39,39,81,223,84,207, 64,65,195,55,49,57,51,175,36,191,56,195,90,193,19, 152,126,114,20,128,2,10,254,193,10,17,10,134,6,241, 22,241,70,154,10,142,192,160,72,13,79,77,242,206,44, 209,55,53,54,215,51,54,86,208,240,246,8,241,245,209, 81,200,201,204,78,85,112,79,77,206,206,215,84,112, 206,0,22,66,169,250,70,230,122,6,122,134,38,198,70, 64,195,131,19,211,18,139,50,161,154,24,216,161,81, 193,192,1,139,33,0,0,0,0,255,255>>, DesiredHeaders = [{<<"accept">>, <<"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8">>}, {<<"accept-charset">>,<<"ISO-8859-1,utf-8;q=0.7,*;q=0.3">>}, {<<"accept-encoding">>,<<"gzip,deflate,sdch">>}, {<<"accept-language">>,<<"en-US,en;q=0.8">>}, {<<"host">>,<<"localhost:6121">>}, {<<"method">>,<<"GET">>}, {<<"scheme">>,<<"https">>}, {<<"url">>,<<"/">>}, {<<"user-agent">>, <<"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) ", "AppleWebKit/537.33 (KHTML, like Gecko) ", "Chrome/27.0.1432.0 Safari/537.33">>}, {<<"version">>,<<"HTTP/1.1">>}], DesiredControlFrame = #spdy_syn_stream{version=2, flags=1, streamid=1, associd=0, priority=0, slot=undefined, headers=DesiredHeaders}, Zinf = new_zlib_context_inflate(), {ControlFrame, _Z} = espdy_parser:parse_frame(ControlFrameData, Zinf), ?assertEqual(DesiredControlFrame, ControlFrame). parse_control_frame_syn_stream_v2_header_error_test() -> DesiredHeaders = [{<<"accept">>, <<"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8">>}, Duplicate header name {<<"method">>,<<"GET">>}, {<<"url">>,<<"/">>}, {<<"version">>,<<"HTTP/1.1">>}], Zinf = new_zlib_context_inflate(), {Error, _Z} = espdy_parser:parse_frame(ControlFrameData, Zinf), DesiredResponse = {error, stream_protocol_error, [{streamid, 9}, {frametype, ?SYN_STREAM}]}, ?assertEqual(DesiredResponse, Error). build_control_frame_syn_stream_v2_test() -> Headers = [{<<"method">>,<<"GET">>}, {<<"url">>,<<"/">>}, {<<"version">>,<<"HTTP/1.1">>}], Frame = #spdy_syn_stream{version=2, flags=1, streamid=65, associd=17, priority=0, headers=Headers}, ?assertEqual(Frame, build_and_parse_frame(2, Frame)). | Flags ( 8) | Length ( 24 bits ) | |X| Stream - ID ( 31bits ) | | Length of name ( int32 ) | | This section is the " Name / Value parse_control_frame_syn_stream_v3_test() -> Length of Name ( Header 2 ) Length of Name ( Header 3 ) Zdef = zlib:open(), ok = zlib:deflateInit(Zdef), zlib:deflateSetDictionary(Zdef, ?HEADERS_ZLIB_DICT_V3), CompressedHeaderData = iolist_to_binary([ zlib:deflate(Zdef, RawHeaderData, full) ]), DataLength = size(ControlFrameData), DesiredHeaders = [{<<":method">>,<<"GET">>}, {<<":path">>,<<"/hello_world">>}, {<<":version">>,<<"HTTP/1.1">>}], DesiredControlFrame = #spdy_syn_stream{version=3, flags=1, streamid=9, associd=5, priority=7, slot=0, headers=DesiredHeaders}, Zinf = zlib:open(), ok = zlib:inflateInit(Zinf), {ControlFrame, _Z} = espdy_parser:parse_frame(RawControlFrame, Zinf), ?assertEqual(DesiredControlFrame, ControlFrame). parse_control_frame_syn_stream_v3_header_error_test() -> DesiredHeaders = [{<<":method">>,<<"GET">>}, {<<":path">>,<<"/">>}, {<<":version">>,<<"HTTP/1.1">>}, {<<"accept">>, <<"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8">>}, Duplicate header name Zinf = new_zlib_context_inflate(), {Error, _Z} = espdy_parser:parse_frame(ControlFrameData, Zinf), DesiredResponse = {error, stream_protocol_error, [{streamid, 7}, {frametype, ?SYN_STREAM}]}, ?assertEqual(DesiredResponse, Error). build_control_frame_syn_stream_v3_test() -> Headers = [{<<":method">>,<<"GET">>}, {<<":path">>,<<"/hello_world">>}, {<<":version">>,<<"HTTP/1.1">>}], Frame = #spdy_syn_stream{version=3, flags=2, streamid=65, associd=17, priority=7, slot=0, headers=Headers}, ?assertEqual(Frame, build_and_parse_frame(3, Frame)). |1| version | 6 | | 0 ( flags ) | 4 ( length ) | parse_control_frame_ping_v2_test() -> DesiredControlFrame = #spdy_ping{version=2, id=12345}, {ControlFrame, _Z} = espdy_parser:parse_frame(ControlFrameData, <<>>), ?assertEqual(DesiredControlFrame, ControlFrame). parse_control_frame_ping_v3_test() -> DesiredControlFrame = #spdy_ping{version=3, id=12345}, {ControlFrame, _Z} = espdy_parser:parse_frame(ControlFrameData, <<>>), ?assertEqual(DesiredControlFrame, ControlFrame). build_control_frame_ping_v2_test() -> Frame = #spdy_ping{version=2, id=12345}, ?assertEqual(Frame, build_and_parse_frame(2, Frame)). build_control_frame_ping_v3_test() -> Frame = #spdy_ping{version=3, id=12345}, ?assertEqual(Frame, build_and_parse_frame(3, Frame)). |1| version | 3 | |X| Stream - ID ( 31bits ) | parse_control_frame_rst_stream_v2_test() -> DesiredControlFrame = #spdy_rst_stream{version=2, flags=0, streamid=543, statuscode=11}, {ControlFrame, _Z} = espdy_parser:parse_frame(ControlFrameData, <<>>), ?assertEqual(DesiredControlFrame, ControlFrame). parse_control_frame_rst_stream_v3_test() -> DesiredControlFrame = #spdy_rst_stream{version=3, flags=0, streamid=543, statuscode=11}, {ControlFrame, _Z} = espdy_parser:parse_frame(ControlFrameData, <<>>), ?assertEqual(DesiredControlFrame, ControlFrame). build_control_frame_rst_stream_v2_test() -> Frame = #spdy_rst_stream{version=2, flags=0, streamid=543, statuscode=11}, ?assertEqual(Frame, build_and_parse_frame(2, Frame)). build_control_frame_rst_stream_v3_test() -> Frame = #spdy_rst_stream{version=3, flags=0, streamid=543, statuscode=11}, ?assertEqual(Frame, build_and_parse_frame(3, Frame)). GOAWAY Control Frame Layout ( v2 ): |1| 2 | 7 | | 0 ( flags ) | 4 ( length ) | |X| Last - good - stream - ID ( 31 bits ) | parse_control_frame_goaway_v2_test() -> DesiredControlFrame = #spdy_goaway{version=2, lastgoodid=543}, {ControlFrame, _Z} = espdy_parser:parse_frame(ControlFrameData, <<>>), ?assertEqual(DesiredControlFrame, ControlFrame). build_control_frame_goaway_v2_test() -> Frame = #spdy_goaway{version=2, lastgoodid=543}, ?assertEqual(Frame, build_and_parse_frame(2, Frame)). GOAWWAY Control Frame Layout ( v3 ): |1| version | 7 | | 0 ( flags ) | 8 ( length ) | |X| Last - good - stream - ID ( 31 bits ) | parse_control_frame_goaway_v3_test() -> DesiredControlFrame = #spdy_goaway{version=3, lastgoodid=543, statuscode=2}, {ControlFrame, _Z} = espdy_parser:parse_frame(ControlFrameData, <<>>), ?assertEqual(DesiredControlFrame, ControlFrame). build_control_frame_goaway_v3_test() -> Frame = #spdy_goaway{version=3, lastgoodid=543, statuscode=2}, ?assertEqual(Frame, build_and_parse_frame(3, Frame)). 2 | 8 | | Flags ( 8) | Length ( 24 bits ) | |X| Stream - ID ( 31bits ) | | Unused ( 16 bits ) | | |-------------------- | parse_control_frame_headers_v2_test() -> Headers = [{<<"method">>,<<"GET">>}, {<<"url">>,<<"/">>}, {<<"version">>,<<"HTTP/1.1">>}], Packed = pack_headers(2, Headers), DesiredControlFrame = #spdy_headers{version=2, flags=1, streamid=432, headers=Headers}, {ControlFrame, _Z} = espdy_parser:parse_frame(ControlFrameData, new_zlib_context_inflate()), ?assertEqual(DesiredControlFrame, ControlFrame). parse_control_frame_headers_v2_header_error_test() -> Invalid header name ( capitalized ) {<<"url">>,<<"/">>}, {<<"version">>,<<"HTTP/1.1">>}], Packed = pack_headers(2, Headers), {Error, _Z} = espdy_parser:parse_frame(ControlFrameData, new_zlib_context_inflate()), DesiredResponse = {error, stream_protocol_error, [{streamid, 432}, {frametype, ?HEADERS}]}, ?assertEqual(DesiredResponse, Error). build_control_frame_headers_v2_test() -> Headers = [{<<"method">>,<<"GET">>}, {<<"url">>,<<"/">>}, {<<"version">>,<<"HTTP/1.1">>}], Frame = #spdy_headers{version=2, flags=1, streamid=432, headers=Headers}, ?assertEqual(Frame, build_and_parse_frame(2, Frame)). |1| version | 8 | | Flags ( 8) | Length ( 24 bits ) | |X| Stream - ID ( 31bits ) | | Length of name ( int32 ) | | This section is the " Name / Value parse_control_frame_headers_v3_test() -> Headers = [{<<":method">>,<<"GET">>}, {<<":path">>,<<"/hello_world">>}, {<<":version">>,<<"HTTP/1.1">>}], Packed = pack_headers(3, Headers), DesiredControlFrame = #spdy_headers{version=3, flags=1, streamid=432, headers=Headers}, {ControlFrame, _Z} = espdy_parser:parse_frame(ControlFrameData, new_zlib_context_inflate()), ?assertEqual(DesiredControlFrame, ControlFrame). build_control_frame_headers_v3_test() -> Headers = [{<<":method">>,<<"GET">>}, {<<":url">>,<<"/">>}, {<<":version">>,<<"HTTP/1.1">>}], Frame = #spdy_headers{version=3, flags=1, streamid=432, headers=Headers}, ?assertEqual(Frame, build_and_parse_frame(3, Frame)). |1| 2 | 2 | | Flags ( 8) | Length ( 24 bits ) | |X| Stream - ID ( 31bits ) | parse_control_frame_syn_reply_v2_test() -> Headers = [{<<"status">>,<<"GET">>}, {<<"version">>,<<"HTTP/1.1">>}, {<<"content-type">>,<<"text/html">>}], Packed = pack_headers(2, Headers), DesiredControlFrame = #spdy_syn_reply{version=2, flags=1, streamid=432, headers=Headers}, {ControlFrame, _Z} = espdy_parser:parse_frame(ControlFrameData, new_zlib_context_inflate()), ?assertEqual(DesiredControlFrame, ControlFrame). parse_control_frame_syn_reply_v2_header_error_test() -> Headers = [{<<"status">>,<<"GET">>}, {<<"version">>,<<"HTTP/1.1">>}, {<<"content-type">>,<<"text/html">>}, Packed = pack_headers(2, Headers), {Error, _Z} = espdy_parser:parse_frame(ControlFrameData, new_zlib_context_inflate()), DesiredResponse = {error, stream_protocol_error, [{streamid, 432}, {frametype, ?SYN_REPLY}]}, ?assertEqual(DesiredResponse, Error). build_control_frame_syn_reply_v2_test() -> Headers = [{<<"status">>,<<"GET">>}, {<<"version">>,<<"HTTP/1.1">>}, {<<"content-type">>,<<"text/html">>}], Frame = #spdy_syn_reply{version=2, flags=1, streamid=432, headers=Headers}, ?assertEqual(Frame, build_and_parse_frame(2, Frame)). | Flags ( 8) | Length ( 24 bits ) | |X| Stream - ID ( 31bits ) | | Length of name ( int32 ) | | This section is the " Name / Value parse_control_frame_syn_reply_v3_test() -> Headers = [{<<":status">>,<<"GET">>}, {<<":version">>,<<"HTTP/1.1">>}, {<<"content-type">>,<<"text/html">>}], Packed = pack_headers(3, Headers), DesiredControlFrame = #spdy_syn_reply{version=3, flags=1, streamid=432, headers=Headers}, {ControlFrame, _Z} = espdy_parser:parse_frame(ControlFrameData, new_zlib_context_inflate()), ?assertEqual(DesiredControlFrame, ControlFrame). parse_control_frame_syn_reply_v3_header_error_test() -> Headers = [{<<":status">>,<<"GET">>}, {<<":version">>,<<"HTTP/1.1">>}, {<<"content-type">>,<<"text/html">>}, Packed = pack_headers(3, Headers), {Error, _Z} = espdy_parser:parse_frame(ControlFrameData, new_zlib_context_inflate()), DesiredResponse = {error, stream_protocol_error, [{streamid, 438}, {frametype, ?SYN_REPLY}]}, ?assertEqual(DesiredResponse, Error). build_control_frame_syn_reply_v3_test() -> Headers = [{<<":status">>,<<"GET">>}, {<<":version">>,<<"HTTP/1.1">>}, {<<"content-type">>,<<"text/html">>}], Frame = #spdy_syn_reply{version=3, flags=1, streamid=432, headers=Headers}, ?assertEqual(Frame, build_and_parse_frame(3, Frame)). WINDOW_UPDATE Control Frame Layout ( v3 ): |1| version | 9 | | 0 ( flags ) | 8 ( length ) | |X| Stream - ID ( 31 - bits ) | |X| Delta - Window - Size ( 31 - bits ) | parse_control_frame_window_update_v3_test() -> Delta - Window - Size DesiredControlFrame = #spdy_window_update{version=3, streamid=835, delta_size=999}, {ControlFrame, _Z} = espdy_parser:parse_frame(ControlFrameData, <<>>), ?assertEqual(DesiredControlFrame, ControlFrame). build_control_frame_window_update_v3_test() -> Frame = #spdy_window_update{version=3, streamid=835, delta_size=999}, ?assertEqual(Frame, build_and_parse_frame(3, Frame)). encode_name_value_header_v2_test() -> Headers = [{<<"method">>,<<"GET">>}, {<<"url">>,<<"/">>}, {<<"version">>,<<"HTTP/1.1">>}], Desired = <<120,187,223,162,81,178,98,96,102,96,203,5,230,195,252,20,6,102,119, 215,16,6,102,144,32,163,62,3,59,84,13,3,7,76,43,0,0,0,255,255>>, Packed = pack_headers(2, Headers), ?assertEqual(Desired, Packed). encode_name_value_header_v3_test() -> Headers = [{<<":method">>,<<"GET">>}, {<<":path">>,<<"/hello_world">>}, {<<":version">>,<<"HTTP/1.1">>}], Desired = <<120,187,227,198,167,194,2,37,58,80,122,180,66,164,90, 119,215,16,80,6,179,42,72,4,151,77,60,250,25,169,192, 2,50,190,60,191,40,7,156,153,173,176,164,93,0,0,0,0,255,255>>, Packed = pack_headers(3, Headers), ?assertEqual(Desired, Packed). parse_name_val_pairs_v2_test() -> Result = espdy_parser:parse_name_val_pairs(2, 1, RawHeaderData, []), ?assertEqual([{<<"method">>,<<"GET">>}], Result). parse_name_val_pairs_v2_multiple_values_test() -> Result = espdy_parser:parse_name_val_pairs(2, 1, RawHeaderData, []), ?assertEqual([{<<"x-forwarded-for">>,[<<"1.2.3.4">>, <<"5.6.7.8">>, <<"9.10.11.12">>]}], Result). parse_name_val_pairs_v2_invalid_header_name_test() -> Result = espdy_parser:parse_name_val_pairs(2, 1, RawHeaderData, []), ?assertEqual({error, stream_protocol_error}, Result). parse_name_val_pairs_v2_zero_length_name_test() -> Result = espdy_parser:parse_name_val_pairs(2, 1, RawHeaderData, []), ?assertEqual({error, stream_protocol_error}, Result). parse_name_val_pairs_v2_zero_length_value_test() -> Result = espdy_parser:parse_name_val_pairs(2, 1, RawHeaderData, []), ?assertEqual({error, stream_protocol_error}, Result). parse_name_val_pairs_v2_consecutive_nuls_test() -> Result = espdy_parser:parse_name_val_pairs(2, 1, RawHeaderData, []), ?assertEqual({error, stream_protocol_error}, Result). parse_name_val_pairs_v2_duplicate_header_names_test() -> Result = espdy_parser:parse_name_val_pairs(2, 2, RawHeaderData, []), ?assertEqual({error, stream_protocol_error}, Result). parse_name_val_pairs_v3_test() -> Result = espdy_parser:parse_name_val_pairs(3, 1, RawHeaderData, []), ?assertEqual([{<<":method">>,<<"GET">>}], Result). parse_name_val_pairs_v3_multiple_values_test() -> Result = espdy_parser:parse_name_val_pairs(3, 1, RawHeaderData, []), ?assertEqual([{<<"x-forwarded-for">>,[<<"1.2.3.4">>, <<"5.6.7.8">>, <<"9.10.11.12">>]}], Result). parse_name_val_pairs_v3_invalid_header_name_test() -> Result = espdy_parser:parse_name_val_pairs(3, 1, RawHeaderData, []), ?assertEqual({error, stream_protocol_error}, Result). parse_name_val_pairs_v3_zero_length_name_test() -> Result = espdy_parser:parse_name_val_pairs(3, 1, RawHeaderData, []), ?assertEqual({error, stream_protocol_error}, Result). parse_name_val_pairs_v3_zero_length_value_test() -> 0 - length header values are allowed in spdy/3 Result = espdy_parser:parse_name_val_pairs(3, 1, RawHeaderData, []), ?assertEqual([{<<"method">>,<<>>}], Result). parse_name_val_pairs_v3_consecutive_nuls_test() -> Result = espdy_parser:parse_name_val_pairs(3, 1, RawHeaderData, []), ?assertEqual({error, stream_protocol_error}, Result). parse_name_val_pairs_v3_duplicate_header_names_test() -> Result = espdy_parser:parse_name_val_pairs(3, 2, RawHeaderData, []), ?assertEqual({error, stream_protocol_error}, Result). build_and_parse_frame(Version, Frame) -> Zdef = new_zlib_context_deflate(Version), CFData = espdy_parser:build_frame(Frame, Zdef), Zinf = new_zlib_context_inflate(), {FrameParsed, _Z} = espdy_parser:parse_frame(CFData, Zinf), FrameParsed. pack_headers(Version, Headers) when Version =:= 2; Version =:= 3 -> Zdef = new_zlib_context_deflate(Version), espdy_parser:encode_name_value_header(Version, Headers, Zdef). new_zlib_context_deflate(V) -> Zdef = zlib:open(), ok = zlib:deflateInit(Zdef), case V of 2 -> zlib:deflateSetDictionary(Zdef, ?HEADERS_ZLIB_DICT); 3 -> zlib:deflateSetDictionary(Zdef, ?HEADERS_ZLIB_DICT_V3) end, Zdef. new_zlib_context_inflate() -> Zinf = zlib:open(), ok = zlib:inflateInit(Zinf), Zinf.
8959a793da562058d7030d7ae55be7bf69368092b40f7ca19939f4d9713b8118
music-suite/music-pitch
Tokawa.hs
module Music.Pitch.Tokawa where
null
https://raw.githubusercontent.com/music-suite/music-pitch/65541021ae9f5bdaad26a02e622c88d60f068f63/src/Music/Pitch/Tokawa.hs
haskell
module Music.Pitch.Tokawa where
25034d219cd62af7e016f98b03c949af4fec489eaceed8cff9bdbea890669a33
ghc/nofib
Activity.hs
module Activity (activityGraph,Activity(..)) where import GRIP import StdLib import PSlib import Graph import Parse activityGraph ordering selectpes statFile = show ( , ticks ) + + --show "DEBUG " ++ show (aggs) ++ initGraph "Processor Activity Graph" (pes,selectpes) (ticks*100,100) ("Time (ms)","% Activity") (map f ordering) ++ scale (my_fromInt dimX/my_fromInt 100) (my_fromInt dimY/my_fromInt (maxticks)) ++ concat (map2 plotCurve (map colour order) (outlinesTrace traces)) where f a = (colour a,display a,aggr a aggs) active = if selectpes==[] then length pes-1 else length selectpes maxticks = active*ticks (pes,ticks,orderedStats) = getParameters stats (traces,aggs) = (akkumulate (processAct (map extractor order)) nullstate. gatherAct (Act 0 0 0 0 0 0). map (scaleAct ticks). getAct selectpes) orderedStats order = reverse ordering stats = parseFile statFile processAct :: [Activities->Int] -> State -> Activities -> (Trace,State) processAct extractors (i,r,g,f,t) a@(Act n i' r' g' f' t') = (trace, (i'+i,r'+r,g'+g,f'+f,t+t')) where trace@(T _ (m:_)) = makeTrace extractors n a makeTrace fs n s = T n (f fs) where f [] = [] f ex@(e:es) = sum (pam ex s):f es type State = (Int,Int,Int,Int,Int) nullstate = (0,0,0,0,0) data Trace = T Int [Int] outlinesTrace :: [Trace] -> [[Point]] outlinesTrace [T n a] = map (\x->[Pt n x]) a outlinesTrace (T n a:more) = map2 (:) (map (\x->Pt n x) a) (outlinesTrace more) aggr IDLE (i,_,_,_,t) = printFloat (percentage i t) ++ "%" aggr REDN (_,r,_,_,t) = printFloat (percentage r t) ++ "%" aggr GC (_,_,g,_,t) = printFloat (percentage g t) ++ "%" aggr FLUSH (_,_,_,f,t) = printFloat (percentage f t) ++ "%" percentage x y = my_fromInt x * 100 / my_fromInt y gatherAct :: Activities -> [Activities] -> [Activities] gatherAct t [] = [t,(Act (numberAct t+1) 0 0 0 0 0)] gatherAct t l@(a:as) | numberAct t==numberAct a = gatherAct (addAct t a) as | otherwise = t:gatherAct (Act (n+1) 0 0 0 0 0) l where n=numberAct t pam [] _ = [] pam (f:fs) a = f a:pam fs a data Activity = REDN | IDLE | FLUSH | GC deriving (Eq) extractor REDN = reduction extractor IDLE = idle extractor GC = gc extractor FLUSH = flush colour REDN = 0 colour IDLE = 8 colour FLUSH = 5 colour GC = 2 instance Parse Activity where parseType ('R':string) = (REDN,string) parseType ('G':string) = (GC,string) parseType ('F':string) = (FLUSH,string) parseType ('I':string) = (IDLE,string) parseType (string) = error ("No such Activity : "++show string++"\n") display REDN = "Reduction" display GC = "Garbage Collection" display FLUSH = "Flush Read/Write" display IDLE = "Idle" addAct (Act _ a b c d t1) (Act n e f g h t2) = Act n (a+e) (b+f) (c+g) (d+h) (t1+t2)
null
https://raw.githubusercontent.com/ghc/nofib/f34b90b5a6ce46284693119a06d1133908b11856/real/gg/Activity.hs
haskell
show "DEBUG " ++ show (aggs) ++
module Activity (activityGraph,Activity(..)) where import GRIP import StdLib import PSlib import Graph import Parse activityGraph ordering selectpes statFile = show ( , ticks ) + + initGraph "Processor Activity Graph" (pes,selectpes) (ticks*100,100) ("Time (ms)","% Activity") (map f ordering) ++ scale (my_fromInt dimX/my_fromInt 100) (my_fromInt dimY/my_fromInt (maxticks)) ++ concat (map2 plotCurve (map colour order) (outlinesTrace traces)) where f a = (colour a,display a,aggr a aggs) active = if selectpes==[] then length pes-1 else length selectpes maxticks = active*ticks (pes,ticks,orderedStats) = getParameters stats (traces,aggs) = (akkumulate (processAct (map extractor order)) nullstate. gatherAct (Act 0 0 0 0 0 0). map (scaleAct ticks). getAct selectpes) orderedStats order = reverse ordering stats = parseFile statFile processAct :: [Activities->Int] -> State -> Activities -> (Trace,State) processAct extractors (i,r,g,f,t) a@(Act n i' r' g' f' t') = (trace, (i'+i,r'+r,g'+g,f'+f,t+t')) where trace@(T _ (m:_)) = makeTrace extractors n a makeTrace fs n s = T n (f fs) where f [] = [] f ex@(e:es) = sum (pam ex s):f es type State = (Int,Int,Int,Int,Int) nullstate = (0,0,0,0,0) data Trace = T Int [Int] outlinesTrace :: [Trace] -> [[Point]] outlinesTrace [T n a] = map (\x->[Pt n x]) a outlinesTrace (T n a:more) = map2 (:) (map (\x->Pt n x) a) (outlinesTrace more) aggr IDLE (i,_,_,_,t) = printFloat (percentage i t) ++ "%" aggr REDN (_,r,_,_,t) = printFloat (percentage r t) ++ "%" aggr GC (_,_,g,_,t) = printFloat (percentage g t) ++ "%" aggr FLUSH (_,_,_,f,t) = printFloat (percentage f t) ++ "%" percentage x y = my_fromInt x * 100 / my_fromInt y gatherAct :: Activities -> [Activities] -> [Activities] gatherAct t [] = [t,(Act (numberAct t+1) 0 0 0 0 0)] gatherAct t l@(a:as) | numberAct t==numberAct a = gatherAct (addAct t a) as | otherwise = t:gatherAct (Act (n+1) 0 0 0 0 0) l where n=numberAct t pam [] _ = [] pam (f:fs) a = f a:pam fs a data Activity = REDN | IDLE | FLUSH | GC deriving (Eq) extractor REDN = reduction extractor IDLE = idle extractor GC = gc extractor FLUSH = flush colour REDN = 0 colour IDLE = 8 colour FLUSH = 5 colour GC = 2 instance Parse Activity where parseType ('R':string) = (REDN,string) parseType ('G':string) = (GC,string) parseType ('F':string) = (FLUSH,string) parseType ('I':string) = (IDLE,string) parseType (string) = error ("No such Activity : "++show string++"\n") display REDN = "Reduction" display GC = "Garbage Collection" display FLUSH = "Flush Read/Write" display IDLE = "Idle" addAct (Act _ a b c d t1) (Act n e f g h t2) = Act n (a+e) (b+f) (c+g) (d+h) (t1+t2)
3d135242a8cc0dfc7e86e27a66f3b2556826000809f53c3448bcb521d10b5548
haskell/vector
Unboxed.hs
{-# LANGUAGE ConstraintKinds #-} module Tests.Vector.Unboxed (tests) where import Test.Tasty import qualified Data.Vector.Unboxed import Tests.Vector.Property testGeneralUnboxedVector :: forall a. (CommonContext a Data.Vector.Unboxed.Vector, Data.Vector.Unboxed.Unbox a, Ord a, Data a) => Data.Vector.Unboxed.Vector a -> [TestTree] testGeneralUnboxedVector dummy = concatMap ($ dummy) [ testSanity , testPolymorphicFunctions , testOrdFunctions , testTuplyFunctions , testMonoidFunctions , testDataFunctions ] testUnitUnboxedVector dummy = concatMap ($ dummy) [ testGeneralUnboxedVector ] testBoolUnboxedVector dummy = concatMap ($ dummy) [ testGeneralUnboxedVector , testBoolFunctions ] testNumericUnboxedVector :: forall a. ( CommonContext a Data.Vector.Unboxed.Vector , Data.Vector.Unboxed.Unbox a, Ord a, Num a, Enum a, Random a, Data a) => Data.Vector.Unboxed.Vector a -> [TestTree] testNumericUnboxedVector dummy = concatMap ($ dummy) [ testGeneralUnboxedVector , testNumFunctions , testEnumFunctions ] testTupleUnboxedVector :: forall a. ( CommonContext a Data.Vector.Unboxed.Vector , Data.Vector.Unboxed.Unbox a, Ord a, Data a) => Data.Vector.Unboxed.Vector a -> [TestTree] testTupleUnboxedVector dummy = concatMap ($ dummy) [ testGeneralUnboxedVector ] tests = [ testGroup "()" $ testUnitUnboxedVector (undefined :: Data.Vector.Unboxed.Vector ()) , testGroup "(Bool)" $ testBoolUnboxedVector (undefined :: Data.Vector.Unboxed.Vector Bool) , testGroup "(Int)" $ testNumericUnboxedVector (undefined :: Data.Vector.Unboxed.Vector Int) , testGroup "(Float)" $ testNumericUnboxedVector (undefined :: Data.Vector.Unboxed.Vector Float) , testGroup "(Double)" $ testNumericUnboxedVector (undefined :: Data.Vector.Unboxed.Vector Double) , testGroup "(Int,Bool)" $ testTupleUnboxedVector (undefined :: Data.Vector.Unboxed.Vector (Int, Bool)) , testGroup "(Int,Bool,Int)" $ testTupleUnboxedVector (undefined :: Data.Vector.Unboxed.Vector (Int, Bool, Int)) , testGroup "unstream" $ testUnstream (undefined :: Data.Vector.Unboxed.Vector Int) ]
null
https://raw.githubusercontent.com/haskell/vector/b592c22e713aa8a901d9e4387ee4522632bd7d10/vector/tests/Tests/Vector/Unboxed.hs
haskell
# LANGUAGE ConstraintKinds #
module Tests.Vector.Unboxed (tests) where import Test.Tasty import qualified Data.Vector.Unboxed import Tests.Vector.Property testGeneralUnboxedVector :: forall a. (CommonContext a Data.Vector.Unboxed.Vector, Data.Vector.Unboxed.Unbox a, Ord a, Data a) => Data.Vector.Unboxed.Vector a -> [TestTree] testGeneralUnboxedVector dummy = concatMap ($ dummy) [ testSanity , testPolymorphicFunctions , testOrdFunctions , testTuplyFunctions , testMonoidFunctions , testDataFunctions ] testUnitUnboxedVector dummy = concatMap ($ dummy) [ testGeneralUnboxedVector ] testBoolUnboxedVector dummy = concatMap ($ dummy) [ testGeneralUnboxedVector , testBoolFunctions ] testNumericUnboxedVector :: forall a. ( CommonContext a Data.Vector.Unboxed.Vector , Data.Vector.Unboxed.Unbox a, Ord a, Num a, Enum a, Random a, Data a) => Data.Vector.Unboxed.Vector a -> [TestTree] testNumericUnboxedVector dummy = concatMap ($ dummy) [ testGeneralUnboxedVector , testNumFunctions , testEnumFunctions ] testTupleUnboxedVector :: forall a. ( CommonContext a Data.Vector.Unboxed.Vector , Data.Vector.Unboxed.Unbox a, Ord a, Data a) => Data.Vector.Unboxed.Vector a -> [TestTree] testTupleUnboxedVector dummy = concatMap ($ dummy) [ testGeneralUnboxedVector ] tests = [ testGroup "()" $ testUnitUnboxedVector (undefined :: Data.Vector.Unboxed.Vector ()) , testGroup "(Bool)" $ testBoolUnboxedVector (undefined :: Data.Vector.Unboxed.Vector Bool) , testGroup "(Int)" $ testNumericUnboxedVector (undefined :: Data.Vector.Unboxed.Vector Int) , testGroup "(Float)" $ testNumericUnboxedVector (undefined :: Data.Vector.Unboxed.Vector Float) , testGroup "(Double)" $ testNumericUnboxedVector (undefined :: Data.Vector.Unboxed.Vector Double) , testGroup "(Int,Bool)" $ testTupleUnboxedVector (undefined :: Data.Vector.Unboxed.Vector (Int, Bool)) , testGroup "(Int,Bool,Int)" $ testTupleUnboxedVector (undefined :: Data.Vector.Unboxed.Vector (Int, Bool, Int)) , testGroup "unstream" $ testUnstream (undefined :: Data.Vector.Unboxed.Vector Int) ]
a94b0612450c1d2b8f98f885eb21345de6791d0272d1aa9437536c547cfe6386
jubnzv/moonsmith
context.mli
open Core_kernel (** Random code generation context. *) type t = { mutable ctx_datum_stmts: Ast.stmt list; (** Statements that defines a global data on the top-level. *) ctx_funcdef_stmts: Ast.stmt list; (** Functions and methods defined on the top-level. *) ctx_call_stmts: Ast.stmt list; (** Function calls defined on the top-level. *) ctx_result_stmts: Ast.stmt list; (** Statements that combine and print result data. *) mutable ctx_global_env: Ast.env; (** Global environment for the top-level. *) ctx_config : Config.t; (** User-defined configuration. *) mutable ctx_table_fields_map: (int, int list, Int.comparator_witness) Base.Map.t; (** Map that associates ids of OOP tables with ids of definitions of their fields. *) mutable ctx_func_def_map: (int, Ast.stmt ref, Int.comparator_witness) Base.Map.t; * Map that associates ids of FuncDefStmts with pointer to their AST nodes . ctx_seed: int; * Seed used to initialize PRG . } val mk_context : Config.t -> t (** Adds given expression to the global environment. *) val add_to_global_env : t -> Ast.expr -> unit (** Returns a list of available tables defined in [ctx.ctx_datum_stmts]. *) val get_datum_tables : t -> Ast.stmt list * Peeks random lhs of [ ctx.ctx_datum_stmts ] . val peek_random_datum_exn : t -> Ast.expr * Peeks random lhs of [ ctx.ctx_datum_stmts ] which has requested type . Returns None if there is no datums with such type . Returns None if there is no datums with such type. *) val peek_typed_datum : t -> Ast.ty -> Ast.expr option (** Same as [get_datum_tables], but also returns indexes in the [ctx.ctx_datum_stmts]. *) val get_datum_tables_i : t -> (int * Ast.expr) list (** Generates the unique index. *) val get_free_idx : unit -> int
null
https://raw.githubusercontent.com/jubnzv/moonsmith/2e5f76cb6e5a20a9a67e33791561c91eca3c2943/src/context.mli
ocaml
* Random code generation context. * Statements that defines a global data on the top-level. * Functions and methods defined on the top-level. * Function calls defined on the top-level. * Statements that combine and print result data. * Global environment for the top-level. * User-defined configuration. * Map that associates ids of OOP tables with ids of definitions of their fields. * Adds given expression to the global environment. * Returns a list of available tables defined in [ctx.ctx_datum_stmts]. * Same as [get_datum_tables], but also returns indexes in the [ctx.ctx_datum_stmts]. * Generates the unique index.
open Core_kernel type t = { mutable ctx_datum_stmts: Ast.stmt list; ctx_funcdef_stmts: Ast.stmt list; ctx_call_stmts: Ast.stmt list; ctx_result_stmts: Ast.stmt list; mutable ctx_global_env: Ast.env; ctx_config : Config.t; mutable ctx_table_fields_map: (int, int list, Int.comparator_witness) Base.Map.t; mutable ctx_func_def_map: (int, Ast.stmt ref, Int.comparator_witness) Base.Map.t; * Map that associates ids of FuncDefStmts with pointer to their AST nodes . ctx_seed: int; * Seed used to initialize PRG . } val mk_context : Config.t -> t val add_to_global_env : t -> Ast.expr -> unit val get_datum_tables : t -> Ast.stmt list * Peeks random lhs of [ ctx.ctx_datum_stmts ] . val peek_random_datum_exn : t -> Ast.expr * Peeks random lhs of [ ctx.ctx_datum_stmts ] which has requested type . Returns None if there is no datums with such type . Returns None if there is no datums with such type. *) val peek_typed_datum : t -> Ast.ty -> Ast.expr option val get_datum_tables_i : t -> (int * Ast.expr) list val get_free_idx : unit -> int
4f8346b928291fc32e04174241ca4e35bd819a3721bc31f964e23909e7b83bd2
ul/ad-libitum
sets-impl.scm
Implementation of general sets and bags for SRFI 113 ;;; A "sob" object is the representation of both sets and bags. ;;; This allows each set-* and bag-* procedure to be implemented ;;; using the same code, without having to deal in ugly indirections over the field accessors . There are three fields , " sob - multi ? " , ;;; "sob-hash-table", and "sob-comparator." ;;; The value of "sob-multi?" is #t for bags and #f for sets. ;;; "Sob-hash-table" maps the elements of the sob to the number of times the element appears , which is always 1 for a set , any positive value ;;; for a bag. "Sob-comparator" is the comparator for the elements of ;;; the set. ;;; Note that sob-* procedures do not do type checking or (typically) the ;;; copying required for supporting pure functional update. These things ;;; are done by the set-* and bag-* procedures, which are externally ;;; exposed (but trivial and mostly uncommented below). Shim to convert from SRFI 69 to the future " intermediate hash tables " SRFI . Unfortunately , hash - table - fold is incompatible between the two ;;; and so is not usable. ;; This will be just "make-hash-table" in future. (define (make-hash-table/comparator comparator) (make-hash-table (comparator-equality-predicate comparator) (modulizer (comparator-hash-function comparator)))) These two procedures adjust for the mismatch between the hash functions of SRFI 114 , which return a potentially unbounded non - negative integer , and the hash functions of SRFI 69 , which expect to be able to pass a second argument which is an upper bound . (define (modulizer hash-function) (case-lambda ((obj) (hash-function obj)) ((obj limit) (modulo (hash-function obj) limit)))) Simple renaming . Chicken 's implementation of SRFI 69 provides ;; hash-table-for-each as a non-standard extension, with the opposite order , so in the Chicken module we suppress importing it to muffle ;; the conflict warning. (define hash-table-contains? hash-table-exists?) (define (hash-table-for-each proc hash-table) (hash-table-walk hash-table proc)) ;;; Record definition and core typing/checking procedures (define-record-type sob (raw-make-sob hash-table comparator multi?) sob? (hash-table sob-hash-table) (comparator sob-comparator) (multi? sob-multi?)) (define (set? obj) (and (sob? obj) (not (sob-multi? obj)))) (define (bag? obj) (and (sob? obj) (sob-multi? obj))) (define (check-set obj) (if (not (set? obj)) (error "not a set" obj))) (define (check-bag obj) (if (not (bag? obj)) (error "not a bag" obj))) ;; These procedures verify that not only are their arguments all sets ;; or all bags as the case may be, but also share the same comparator. (define (check-all-sets list) (for-each (lambda (obj) (check-set obj)) list) (sob-check-comparators list)) (define (check-all-bags list) (for-each (lambda (obj) (check-bag obj)) list) (sob-check-comparators list)) (define (sob-check-comparators list) (if (not (null? list)) (for-each (lambda (sob) (check-same-comparator (car list) sob)) (cdr list)))) This procedure is used directly when there are exactly two arguments . (define (check-same-comparator a b) (if (not (eq? (sob-comparator a) (sob-comparator b))) (error "different comparators" a b))) ;; This procedure defends against inserting an element ;; into a sob that violates its constructor, since ;; typical hash-table implementations don't check for us. (define (check-element sob element) (comparator-check-type (sob-comparator sob) element)) ;;; Constructors Construct an arbitrary empty sob out of nothing . (define (make-sob comparator multi?) (raw-make-sob (make-hash-table/comparator comparator) comparator multi?)) ;; Copy a sob, sharing the constructor. (define (sob-copy sob) (raw-make-sob (hash-table-copy (sob-hash-table sob)) (sob-comparator sob) (sob-multi? sob))) (define (set-copy set) (check-set set) (sob-copy set)) (define (bag-copy bag) (check-bag bag) (sob-copy bag)) Construct an empty sob that shares the constructor of an existing sob . (define (sob-empty-copy sob) (make-sob (sob-comparator sob) (sob-multi? sob))) Construct a set or a bag and insert elements into it . These are the ;; simplest external constructors. (define (set comparator . elements) (let ((result (make-sob comparator #f))) (for-each (lambda (x) (sob-increment! result x 1)) elements) result)) (define (bag comparator . elements) (let ((result (make-sob comparator #t))) (for-each (lambda (x) (sob-increment! result x 1)) elements) result)) ;; The fundamental (as opposed to simplest) constructor: unfold the results of iterating a function as a set . In line with SRFI 1 , ;; we provide an opportunity to map the sequence of seeds through a ;; mapper function. (define (sob-unfold stop? mapper successor seed comparator multi?) (let ((result (make-sob comparator multi?))) (let loop ((seed seed)) (if (stop? seed) result (begin (sob-increment! result (mapper seed) 1) (loop (successor seed))))))) (define (set-unfold continue? mapper successor seed comparator) (sob-unfold continue? mapper successor seed comparator #f)) (define (bag-unfold continue? mapper successor seed comparator) (sob-unfold continue? mapper successor seed comparator #t)) ;;; Predicates ;; Just a wrapper of hash-table-contains?. (define (sob-contains? sob member) (hash-table-contains? (sob-hash-table sob) member)) (define (set-contains? set member) (check-set set) (sob-contains? set member)) (define (bag-contains? bag member) (check-bag bag) (sob-contains? bag member)) ;; A sob is empty if its size is 0. (define (sob-empty? sob) (= 0 (hash-table-size (sob-hash-table sob)))) (define (set-empty? set) (check-set set) (sob-empty? set)) (define (bag-empty? bag) (check-bag bag) (sob-empty? bag)) Two sobs are disjoint if , when looping through one , we ca n't find ;; any of its elements in the other. We have to try both ways: ;; sob-half-disjoint checks just one direction for simplicity. (define (sob-half-disjoint? a b) (let ((ha (sob-hash-table a)) (hb (sob-hash-table b))) (call/cc (lambda (return) (hash-table-for-each (lambda (key val) (if (hash-table-contains? hb key) (return #f))) ha) #t)))) (define (set-disjoint? a b) (check-set a) (check-set b) (check-same-comparator a b) (and (sob-half-disjoint? a b) (sob-half-disjoint? b a))) (define (bag-disjoint? a b) (check-bag a) (check-bag b) (check-same-comparator a b) (and (sob-half-disjoint? a b) (sob-half-disjoint? b a))) Accessors If two objects are indistinguishable by the comparator 's equality procedure , only one of them will be represented in the sob . ;; This procedure lets us find out which one it is; it will return ;; the value stored in the sob that is equal to the element. ;; Note that we have to search the whole hash table item by item. ;; The default is returned if there is no such element. (define (sob-member sob element default) (define (same? a b) (=? (sob-comparator sob) a b)) (call/cc (lambda (return) (hash-table-for-each (lambda (key val) (if (same? key element) (return key))) (sob-hash-table sob)) default))) (define (set-member set element default) (check-set set) (sob-member set element default)) (define (bag-member bag element default) (check-bag bag) (sob-member bag element default)) ;; Retrieve the comparator. (define (set-element-comparator set) (check-set set) (sob-comparator set)) (define (bag-element-comparator bag) (check-bag bag) (sob-comparator bag)) Updaters ( pure functional and linear update ) ;; The primitive operation for adding an element to a sob. ;; There are a few cases where we bypass this for efficiency. (define (sob-increment! sob element count) (check-element sob element) (hash-table-update!/default (sob-hash-table sob) element (if (sob-multi? sob) (lambda (value) (+ value count)) (lambda (value) 1)) 0)) ;; The primitive operation for removing an element from a sob. Note this procedure is incomplete : it allows the count of an element to drop below 1 . ;; Therefore, whenever it is used it is necessary to call sob-cleanup! ;; to fix things up. This is done because it is unsafe to remove an ;; object from a hash table while iterating through it. (define (sob-decrement! sob element count) (hash-table-update!/default (sob-hash-table sob) element (lambda (value) (- value count)) 0)) This is the cleanup procedure , which happens in two passes : it ;; iterates through the sob, deciding which elements to remove (those ;; with non-positive counts), and collecting them in a list. When the ;; iteration is done, it is safe to remove the elements using the list, ;; because we are no longer iterating over the hash table. It returns ;; its argument, because it is often tail-called at the end of some ;; procedure that wants to return the clean sob. (define (sob-cleanup! sob) (let ((ht (sob-hash-table sob))) (for-each (lambda (key) (hash-table-delete! ht key)) (nonpositive-keys ht)) sob)) (define (nonpositive-keys ht) (let ((result '())) (hash-table-for-each (lambda (key value) (when (<= value 0) (set! result (cons key result)))) ht) result)) ;; We expose these for bags but not sets. (define (bag-increment! bag element count) (check-bag bag) (sob-increment! bag element count) bag) (define (bag-decrement! bag element count) (check-bag bag) (sob-decrement! bag element count) (sob-cleanup! bag) bag) ;; The primitive operation to add elements from a list. We expose this two ways : with a list argument and with multiple arguments . (define (sob-adjoin-all! sob elements) (for-each (lambda (elem) (sob-increment! sob elem 1)) elements)) (define (set-adjoin! set . elements) (check-set set) (sob-adjoin-all! set elements) set) (define (bag-adjoin! bag . elements) (check-bag bag) (sob-adjoin-all! bag elements) bag) ;; These versions copy the set or bag before adjoining. (define (set-adjoin set . elements) (check-set set) (let ((result (sob-copy set))) (sob-adjoin-all! result elements) result)) (define (bag-adjoin bag . elements) (check-bag bag) (let ((result (sob-copy bag))) (sob-adjoin-all! result elements) result)) ;; Given an element which resides in a set, this makes sure that the ;; specified element is represented by the form given. Thus if a sob contains 2 and the equality predicate is = , then calling ( sob - replace ! sob 2.0 ) will replace the 2 with 2.0 . Does nothing ;; if there is no such element in the sob. (define (sob-replace! sob element) (let* ((comparator (sob-comparator sob)) (= (comparator-equality-predicate comparator)) (ht (sob-hash-table sob))) (comparator-check-type comparator element) (call/cc (lambda (return) (hash-table-for-each (lambda (key value) (when (= key element) (hash-table-delete! ht key) (hash-table-set! ht element value) (return sob))) ht) sob)))) (define (set-replace! set element) (check-set set) (sob-replace! set element) set) (define (bag-replace! bag element) (check-bag bag) (sob-replace! bag element) bag) Non - destructive versions that copy the set first . Yes , a little ;; bit inefficient because it copies the element to be replaced before ;; actually replacing it. (define (set-replace set element) (check-set set) (let ((result (sob-copy set))) (sob-replace! result element) result)) (define (bag-replace bag element) (check-bag bag) (let ((result (sob-copy bag))) (sob-replace! result element) result)) ;; The primitive operation to delete elemnets from a list. Like sob - adjoin - all ! , this is exposed two ways . It calls ;; sob-cleanup! itself, so its callers don't need to (though it is safe ;; to do so.) (define (sob-delete-all! sob elements) (for-each (lambda (element) (sob-decrement! sob element 1)) elements) (sob-cleanup! sob) sob) (define (set-delete! set . elements) (check-set set) (sob-delete-all! set elements)) (define (bag-delete! bag . elements) (check-bag bag) (sob-delete-all! bag elements)) (define (set-delete-all! set elements) (check-set set) (sob-delete-all! set elements)) (define (bag-delete-all! bag elements) (check-bag bag) (sob-delete-all! bag elements)) Non - destructive version copy first ; this is inefficient . (define (set-delete set . elements) (check-set set) (sob-delete-all! (sob-copy set) elements)) (define (bag-delete bag . elements) (check-bag bag) (sob-delete-all! (sob-copy bag) elements)) (define (set-delete-all set elements) (check-set set) (sob-delete-all! (sob-copy set) elements)) (define (bag-delete-all bag elements) (check-bag bag) (sob-delete-all! (sob-copy bag) elements)) ;; Flag used by sob-search! to represent a missing object. (define missing (string-copy "missing")) ;; Searches and then dispatches to user-defined procedures on failure ;; and success, which in turn should reinvoke a procedure to take some ;; action on the set (insert, ignore, replace, or remove). (define (sob-search! sob element failure success) (define (insert obj) (sob-increment! sob element 1) (values sob obj)) (define (ignore obj) (values sob obj)) (define (update new-elem obj) (sob-decrement! sob element 1) (sob-increment! sob new-elem 1) (values (sob-cleanup! sob) obj)) (define (remove obj) (sob-decrement! sob element 1) (values (sob-cleanup! sob) obj)) (let ((true-element (sob-member sob element missing))) (if (eq? true-element missing) (failure insert ignore) (success true-element update remove)))) (define (set-search! set element failure success) (check-set set) (sob-search! set element failure success)) (define (bag-search! bag element failure success) (check-bag bag) (sob-search! bag element failure success)) ;; Return the size of a sob. If it's a set, we can just use the ;; number of associations in the hash table, but if it's a bag, we ;; have to add up the counts. (define (sob-size sob) (if (sob-multi? sob) (let ((result 0)) (hash-table-for-each (lambda (elem count) (set! result (+ count result))) (sob-hash-table sob)) result) (hash-table-size (sob-hash-table sob)))) (define (set-size set) (check-set set) (sob-size set)) (define (bag-size bag) (check-bag bag) (sob-size bag)) ;; Search a sob to find something that matches a predicate. You don't ;; know which element you will get, so this is not as useful as finding ;; an element in a list or other ordered container. If it's not there, ;; call the failure thunk. (define (sob-find pred sob failure) (call/cc (lambda (return) (hash-table-for-each (lambda (key value) (if (pred key) (return key))) (sob-hash-table sob)) (failure)))) (define (set-find pred set failure) (check-set set) (sob-find pred set failure)) (define (bag-find pred bag failure) (check-bag bag) (sob-find pred bag failure)) ;; Count the number of elements in the sob that satisfy the predicate. ;; This is a special case of folding. (define (sob-count pred sob) (sob-fold (lambda (elem total) (if (pred elem) (+ total 1) total)) 0 sob)) (define (set-count pred set) (check-set set) (sob-count pred set)) (define (bag-count pred bag) (check-bag bag) (sob-count pred bag)) ;; Check if any of the elements in a sob satisfy a predicate. Breaks out ;; early (with call/cc) if a success is found. (define (sob-any? pred sob) (call/cc (lambda (return) (hash-table-for-each (lambda (elem value) (if (pred elem) (return #t))) (sob-hash-table sob)) #f))) (define (set-any? pred set) (check-set set) (sob-any? pred set)) (define (bag-any? pred bag) (check-bag bag) (sob-any? pred bag)) ;; Analogous to set-any?. Breaks out early if a failure is found. (define (sob-every? pred sob) (call/cc (lambda (return) (hash-table-for-each (lambda (elem value) (if (not (pred elem)) (return #f))) (sob-hash-table sob)) #t))) (define (set-every? pred set) (check-set set) (sob-every? pred set)) (define (bag-every? pred bag) (check-bag bag) (sob-every? pred bag)) ;;; Mapping and folding ;; A utility for iterating a command n times. This is used by sob-for-each ;; to execute a procedure over the repeated elements in a bag. Because ;; of the representation of sets, it works for them too. (define (do-n-times cmd n) (let loop ((n n)) (when (> n 0) (cmd) (loop (- n 1))))) ;; Basic iterator over a sob. (define (sob-for-each proc sob) (hash-table-for-each (lambda (key value) (do-n-times (lambda () (proc key)) value)) (sob-hash-table sob))) (define (set-for-each proc set) (check-set set) (sob-for-each proc set)) (define (bag-for-each proc bag) (check-bag bag) (sob-for-each proc bag)) ;; Fundamental mapping operator. We map over the associations directly, ;; because each instance of an element in a bag will be treated identically ;; anyway; we insert them all at once with sob-increment!. (define (sob-map comparator proc sob) (let ((result (make-sob comparator (sob-multi? sob)))) (hash-table-for-each (lambda (key value) (sob-increment! result (proc key) value)) (sob-hash-table sob)) result)) (define (set-map comparator proc set) (check-set set) (sob-map comparator proc set)) (define (bag-map comparator proc bag) (check-bag bag) (sob-map comparator proc bag)) ;; The fundamental deconstructor. Note that there are no left vs. right ;; folds because there is no order. Each element in a bag is fed into ;; the fold separately. (define (sob-fold proc nil sob) (let ((result nil)) (sob-for-each (lambda (elem) (set! result (proc elem result))) sob) result)) (define (set-fold proc nil set) (check-set set) (sob-fold proc nil set)) (define (bag-fold proc nil bag) (check-bag bag) (sob-fold proc nil bag)) ;; Process every element and copy the ones that satisfy the predicate. ;; Identical elements are processed all at once. This is used for both ;; filter and remove. (define (sob-filter pred sob) (let ((result (sob-empty-copy sob))) (hash-table-for-each (lambda (key value) (if (pred key) (sob-increment! result key value))) (sob-hash-table sob)) result)) (define (set-filter pred set) (check-set set) (sob-filter pred set)) (define (bag-filter pred bag) (check-bag bag) (sob-filter pred bag)) (define (set-remove pred set) (check-set set) (sob-filter (lambda (x) (not (pred x))) set)) (define (bag-remove pred bag) (check-bag bag) (sob-filter (lambda (x) (not (pred x))) bag)) ;; Process each element and remove those that don't satisfy the filter. ;; This does its own cleanup, and is used for both filter! and remove!. (define (sob-filter! pred sob) (hash-table-for-each (lambda (key value) (if (not (pred key)) (sob-decrement! sob key value))) (sob-hash-table sob)) (sob-cleanup! sob)) (define (set-filter! pred set) (check-set set) (sob-filter! pred set)) (define (bag-filter! pred bag) (check-bag bag) (sob-filter! pred bag)) (define (set-remove! pred set) (check-set set) (sob-filter! (lambda (x) (not (pred x))) set)) (define (bag-remove! pred bag) (check-bag bag) (sob-filter! (lambda (x) (not (pred x))) bag)) Create two sobs and copy the elements that satisfy the predicate into one of them , all others into the other . This is more efficient than ;; filtering and removing separately. (define (sob-partition pred sob) (let ((res1 (sob-empty-copy sob)) (res2 (sob-empty-copy sob))) (hash-table-for-each (lambda (key value) (if (pred key) (sob-increment! res1 key value) (sob-increment! res2 key value))) (sob-hash-table sob)) (values res1 res2))) (define (set-partition pred set) (check-set set) (sob-partition pred set)) (define (bag-partition pred bag) (check-bag bag) (sob-partition pred bag)) ;; Create a sob and iterate through the given sob. Anything that satisfies ;; the predicate is left alone; anything that doesn't is removed from the ;; given sob and added to the new sob. (define (sob-partition! pred sob) (let ((result (sob-empty-copy sob))) (hash-table-for-each (lambda (key value) (if (not (pred key)) (begin (sob-decrement! sob key value) (sob-increment! result key value)))) (sob-hash-table sob)) (values (sob-cleanup! sob) result))) (define (set-partition! pred set) (check-set set) (sob-partition! pred set)) (define (bag-partition! pred bag) (check-bag bag) (sob-partition! pred bag)) ;;; Copying and conversion ;;; Convert a sob to a list; a special case of sob-fold. (define (sob->list sob) (sob-fold (lambda (elem list) (cons elem list)) '() sob)) (define (set->list set) (check-set set) (sob->list set)) (define (bag->list bag) (check-bag bag) (sob->list bag)) ;; Convert a list to a sob. Probably could be done using unfold, but ;; since sobs are mutable anyway, it's just as easy to add the elements ;; by side effect. (define (list->sob! sob list) (for-each (lambda (elem) (sob-increment! sob elem 1)) list) sob) (define (list->set comparator list) (list->sob! (make-sob comparator #f) list)) (define (list->bag comparator list) (list->sob! (make-sob comparator #t) list)) (define (list->set! set list) (check-set set) (list->sob! set list)) (define (list->bag! bag list) (check-bag bag) (list->sob! bag list)) ;;; Subsets ;; All of these procedures follow the same pattern. The ;; sob<op>? procedures are case-lambdas that reduce the multi-argument case to the two - argument case . As usual , the set < op > ? and bag < op > ? procedures are trivial layers over the sob < op > ? procedure . ;; The dyadic-sob<op>? procedures are where it gets interesting, so see ;; the comments on them. (define sob=? (case-lambda ((sob) #t) ((sob1 sob2) (dyadic-sob=? sob1 sob2)) ((sob1 sob2 . sobs) (and (dyadic-sob=? sob1 sob2) (apply sob=? sob2 sobs))))) (define (set=? . sets) (check-all-sets sets) (apply sob=? sets)) (define (bag=? . bags) (check-all-bags bags) (apply sob=? bags)) ;; First we check that there are the same number of entries in the hashtables of the two sobs ; if that 's not true , they ca n't be equal . ;; Then we check that for each key, the values are the same (where being absent counts as a value of 0 ) . If any values are n't equal , ;; again they can't be equal. (define (dyadic-sob=? sob1 sob2) (call/cc (lambda (return) (let ((ht1 (sob-hash-table sob1)) (ht2 (sob-hash-table sob2))) (if (not (= (hash-table-size ht1) (hash-table-size ht2))) (return #f)) (hash-table-for-each (lambda (key value) (if (not (= value (hash-table-ref/default ht2 key 0))) (return #f))) ht1)) #t))) (define sob<=? (case-lambda ((sob) #t) ((sob1 sob2) (dyadic-sob<=? sob1 sob2)) ((sob1 sob2 . sobs) (and (dyadic-sob<=? sob1 sob2) (apply sob<=? sob2 sobs))))) (define (set<=? . sets) (check-all-sets sets) (apply sob<=? sets)) (define (bag<=? . bags) (check-all-bags bags) (apply sob<=? bags)) ;; This is analogous to dyadic-sob=?, except that we have to check ;; both sobs to make sure each value is <= in order to be sure ;; that we've traversed all the elements in either sob. (define (dyadic-sob<=? sob1 sob2) (call/cc (lambda (return) (let ((ht1 (sob-hash-table sob1)) (ht2 (sob-hash-table sob2))) (if (not (<= (hash-table-size ht1) (hash-table-size ht2))) (return #f)) (hash-table-for-each (lambda (key value) (if (not (<= value (hash-table-ref/default ht2 key 0))) (return #f))) ht1)) #t))) (define sob>? (case-lambda ((sob) #t) ((sob1 sob2) (dyadic-sob>? sob1 sob2)) ((sob1 sob2 . sobs) (and (dyadic-sob>? sob1 sob2) (apply sob>? sob2 sobs))))) (define (set>? . sets) (check-all-sets sets) (apply sob>? sets)) (define (bag>? . bags) (check-all-bags bags) (apply sob>? bags)) ;; > is the negation of <=. Note that this is only true at the dyadic ;; level; we can't just replace sob>? with a negation of sob<=?. (define (dyadic-sob>? sob1 sob2) (not (dyadic-sob<=? sob1 sob2))) (define sob<? (case-lambda ((sob) #t) ((sob1 sob2) (dyadic-sob<? sob1 sob2)) ((sob1 sob2 . sobs) (and (dyadic-sob<? sob1 sob2) (apply sob<? sob2 sobs))))) (define (set<? . sets) (check-all-sets sets) (apply sob<? sets)) (define (bag<? . bags) (check-all-bags bags) (apply sob<? bags)) ;; < is the inverse of >. Again, this is only true dyadically. (define (dyadic-sob<? sob1 sob2) (dyadic-sob>? sob2 sob1)) (define sob>=? (case-lambda ((sob) #t) ((sob1 sob2) (dyadic-sob>=? sob1 sob2)) ((sob1 sob2 . sobs) (and (dyadic-sob>=? sob1 sob2) (apply sob>=? sob2 sobs))))) (define (set>=? . sets) (check-all-sets sets) (apply sob>=? sets)) (define (bag>=? . bags) (check-all-bags bags) (apply sob>=? bags)) ;; Finally, >= is the negation of <. Good thing we have tail recursion. (define (dyadic-sob>=? sob1 sob2) (not (dyadic-sob<? sob1 sob2))) ;;; Set theory operations A trivial helper function which upper - bounds n by one if multi ? is false . (define (max-one n multi?) (if multi? n (if (> n 1) 1 n))) ;; The logic of union, intersection, difference, and sum is the same: the ;; sob-* and sob-*! procedures do the reduction to the dyadic-sob-*! ;; procedures. The difference is that the sob-* procedures allocate an empty copy of the first sob to accumulate the results in , whereas the sob- * ! procedures work directly in the first sob . ;; Note that there is no set-sum, as it is the same as set-union. (define (sob-union sob1 . sobs) (if (null? sobs) sob1 (let ((result (sob-empty-copy sob1))) (dyadic-sob-union! result sob1 (car sobs)) (for-each (lambda (sob) (dyadic-sob-union! result result sob)) (cdr sobs)) result))) ;; For union, we take the max of the counts of each element found ;; in either sob and put that in the result. On the pass through sob2 , we know that the intersection is already accounted for , ;; so we just copy over things that aren't in sob1. (define (dyadic-sob-union! result sob1 sob2) (let ((sob1-ht (sob-hash-table sob1)) (sob2-ht (sob-hash-table sob2)) (result-ht (sob-hash-table result))) (hash-table-for-each (lambda (key value1) (let ((value2 (hash-table-ref/default sob2-ht key 0))) (hash-table-set! result-ht key (max value1 value2)))) sob1-ht) (hash-table-for-each (lambda (key value2) (let ((value1 (hash-table-ref/default sob1-ht key 0))) (if (= value1 0) (hash-table-set! result-ht key value2)))) sob2-ht))) (define (set-union . sets) (check-all-sets sets) (apply sob-union sets)) (define (bag-union . bags) (check-all-bags bags) (apply sob-union bags)) (define (sob-union! sob1 . sobs) (for-each (lambda (sob) (dyadic-sob-union! sob1 sob1 sob)) sobs) sob1) (define (set-union! . sets) (check-all-sets sets) (apply sob-union! sets)) (define (bag-union! . bags) (check-all-bags bags) (apply sob-union! bags)) (define (sob-intersection sob1 . sobs) (if (null? sobs) sob1 (let ((result (sob-empty-copy sob1))) (dyadic-sob-intersection! result sob1 (car sobs)) (for-each (lambda (sob) (dyadic-sob-intersection! result result sob)) (cdr sobs)) (sob-cleanup! result)))) ;; For intersection, we compute the min of the counts of each element. ;; We only have to scan sob1. We clean up the result when we are ;; done, in case it is the same as sob1. (define (dyadic-sob-intersection! result sob1 sob2) (let ((sob1-ht (sob-hash-table sob1)) (sob2-ht (sob-hash-table sob2)) (result-ht (sob-hash-table result))) (hash-table-for-each (lambda (key value1) (let ((value2 (hash-table-ref/default sob2-ht key 0))) (hash-table-set! result-ht key (min value1 value2)))) sob1-ht))) (define (set-intersection . sets) (check-all-sets sets) (apply sob-intersection sets)) (define (bag-intersection . bags) (check-all-bags bags) (apply sob-intersection bags)) (define (sob-intersection! sob1 . sobs) (for-each (lambda (sob) (dyadic-sob-intersection! sob1 sob1 sob)) sobs) (sob-cleanup! sob1)) (define (set-intersection! . sets) (check-all-sets sets) (apply sob-intersection! sets)) (define (bag-intersection! . bags) (check-all-bags bags) (apply sob-intersection! bags)) (define (sob-difference sob1 . sobs) (if (null? sobs) sob1 (let ((result (sob-empty-copy sob1))) (dyadic-sob-difference! result sob1 (car sobs)) (for-each (lambda (sob) (dyadic-sob-difference! result result sob)) (cdr sobs)) (sob-cleanup! result)))) ;; For difference, we use (big surprise) the numeric difference, bounded by zero . We only need to scan sob1 , but we clean up the result in ;; case it is the same as sob1. (define (dyadic-sob-difference! result sob1 sob2) (let ((sob1-ht (sob-hash-table sob1)) (sob2-ht (sob-hash-table sob2)) (result-ht (sob-hash-table result))) (hash-table-for-each (lambda (key value1) (let ((value2 (hash-table-ref/default sob2-ht key 0))) (hash-table-set! result-ht key (- value1 value2)))) sob1-ht))) (define (set-difference . sets) (check-all-sets sets) (apply sob-difference sets)) (define (bag-difference . bags) (check-all-bags bags) (apply sob-difference bags)) (define (sob-difference! sob1 . sobs) (for-each (lambda (sob) (dyadic-sob-difference! sob1 sob1 sob)) sobs) (sob-cleanup! sob1)) (define (set-difference! . sets) (check-all-sets sets) (apply sob-difference! sets)) (define (bag-difference! . bags) (check-all-bags bags) (apply sob-difference! bags)) (define (sob-sum sob1 . sobs) (if (null? sobs) sob1 (let ((result (sob-empty-copy sob1))) (dyadic-sob-sum! result sob1 (car sobs)) (for-each (lambda (sob) (dyadic-sob-sum! result result sob)) (cdr sobs)) result))) ;; Sum is just like union, except that we take the sum rather than the max. (define (dyadic-sob-sum! result sob1 sob2) (let ((sob1-ht (sob-hash-table sob1)) (sob2-ht (sob-hash-table sob2)) (result-ht (sob-hash-table result))) (hash-table-for-each (lambda (key value1) (let ((value2 (hash-table-ref/default sob2-ht key 0))) (hash-table-set! result-ht key (+ value1 value2)))) sob1-ht) (hash-table-for-each (lambda (key value2) (let ((value1 (hash-table-ref/default sob1-ht key 0))) (if (= value1 0) (hash-table-set! result-ht key value2)))) sob2-ht))) ;; Sum is defined for bags only; for sets, it is the same as union. (define (bag-sum . bags) (check-all-bags bags) (apply sob-sum bags)) (define (sob-sum! sob1 . sobs) (for-each (lambda (sob) (dyadic-sob-sum! sob1 sob1 sob)) sobs) sob1) (define (bag-sum! . bags) (check-all-bags bags) (apply sob-sum! bags)) For xor exactly two arguments are required , so the above structures are ;; not necessary. This version accepts a result sob and computes the absolute difference between the counts in the first sob and the corresponding counts in the second . We start by copying the entries in the second sob but not the first into the first . Then we scan the first sob , computing the absolute difference of the values and writing them back into the first sob . It 's essential to scan the second sob first , as we are not going to damage it in the process . ( Hat tip : . ) (define (sob-xor! result sob1 sob2) (let ((sob1-ht (sob-hash-table sob1)) (sob2-ht (sob-hash-table sob2)) (result-ht (sob-hash-table result))) (hash-table-for-each (lambda (key value2) (let ((value1 (hash-table-ref/default sob1-ht key 0))) (if (= value1 0) (hash-table-set! result-ht key value2)))) sob2-ht) (hash-table-for-each (lambda (key value1) (let ((value2 (hash-table-ref/default sob2-ht key 0))) (hash-table-set! result-ht key (abs (- value1 value2))))) sob1-ht) (sob-cleanup! result))) (define (set-xor set1 set2) (check-set set1) (check-set set2) (check-same-comparator set1 set2) (sob-xor! (sob-empty-copy set1) set1 set2)) (define (bag-xor bag1 bag2) (check-bag bag1) (check-bag bag2) (check-same-comparator bag1 bag2) (sob-xor! (sob-empty-copy bag1) bag1 bag2)) (define (set-xor! set1 set2) (check-set set1) (check-set set2) (check-same-comparator set1 set2) (sob-xor! set1 set1 set2)) (define (bag-xor! bag1 bag2) (check-bag bag1) (check-bag bag2) (check-same-comparator bag1 bag2) (sob-xor! bag1 bag1 bag2)) ;;; A few bag-specific procedures (define (sob-product! n result sob) (let ((rht (sob-hash-table result))) (hash-table-for-each (lambda (elem count) (hash-table-set! rht elem (* count n))) (sob-hash-table sob)) result)) (define (valid-n n) (and (integer? n) (exact? n) (positive? n))) (define (bag-product n bag) (check-bag bag) (valid-n n) (sob-product! n (sob-empty-copy bag) bag)) (define (bag-product! n bag) (check-bag bag) (valid-n n) (sob-product! n bag bag)) (define (bag-unique-size bag) (check-bag bag) (hash-table-size (sob-hash-table bag))) (define (bag-element-count bag elem) (check-bag bag) (hash-table-ref/default (sob-hash-table bag) elem 0)) (define (bag-for-each-unique proc bag) (check-bag bag) (hash-table-for-each (lambda (key value) (proc key value)) (sob-hash-table bag))) (define (bag-fold-unique proc nil bag) (check-bag bag) (let ((result nil)) (hash-table-for-each (lambda (elem count) (set! result (proc elem count result))) (sob-hash-table bag)) result)) (define (bag->set bag) (check-bag bag) (let ((result (make-sob (sob-comparator bag) #f))) (hash-table-for-each (lambda (key value) (sob-increment! result key value)) (sob-hash-table bag)) result)) (define (set->bag set) (check-set set) (let ((result (make-sob (sob-comparator set) #t))) (hash-table-for-each (lambda (key value) (sob-increment! result key value)) (sob-hash-table set)) result)) (define (set->bag! bag set) (check-bag bag) (check-set set) (check-same-comparator set bag) (hash-table-for-each (lambda (key value) (sob-increment! bag key value)) (sob-hash-table set)) bag) (define (bag->alist bag) (check-bag bag) (bag-fold-unique (lambda (elem count list) (cons (cons elem count) list)) '() bag)) (define (alist->bag comparator alist) (let* ((result (bag comparator)) (ht (sob-hash-table result))) (for-each (lambda (assoc) (let ((element (car assoc))) (if (not (hash-table-contains? ht element)) (sob-increment! result element (cdr assoc))))) alist) result)) ;;; Comparators ;; Hash over sobs (define (sob-hash sob) (let* ((ht (sob-hash-table sob)) (hash (comparator-hash-function (sob-comparator sob)))) (sob-fold (lambda (element result) (+ (hash element) result)) 5381 sob))) ;; Set and bag comparator (define set-comparator (make-comparator set? set=? #f sob-hash)) (define bag-comparator (make-comparator bag? bag=? #f sob-hash)) ;;; Register above comparators for use by default-comparator (define init-comparators (begin (comparator-register-default! set-comparator) (comparator-register-default! bag-comparator))) ;;; Set/bag printer (for debugging) (define (sob-print sob port) (display (if (sob-multi? sob) "&bag[" "&set[") port) (sob-for-each (lambda (elem) (display " " port) (write elem port)) sob) (display " ]" port)) ;; Chicken-specific (cond-expand (chicken (define-record-printer sob sob-print)) (else))
null
https://raw.githubusercontent.com/ul/ad-libitum/882fa5680db6341367941c40f2fa5ca1f7c0c47a/srfi/s113/sets-impl.scm
scheme
A "sob" object is the representation of both sets and bags. This allows each set-* and bag-* procedure to be implemented using the same code, without having to deal in ugly indirections "sob-hash-table", and "sob-comparator." The value of "sob-multi?" is #t for bags and #f for sets. "Sob-hash-table" maps the elements of the sob to the number of times for a bag. "Sob-comparator" is the comparator for the elements of the set. Note that sob-* procedures do not do type checking or (typically) the copying required for supporting pure functional update. These things are done by the set-* and bag-* procedures, which are externally exposed (but trivial and mostly uncommented below). and so is not usable. This will be just "make-hash-table" in future. hash-table-for-each as a non-standard extension, with the opposite the conflict warning. Record definition and core typing/checking procedures These procedures verify that not only are their arguments all sets or all bags as the case may be, but also share the same comparator. This procedure defends against inserting an element into a sob that violates its constructor, since typical hash-table implementations don't check for us. Constructors Copy a sob, sharing the constructor. simplest external constructors. The fundamental (as opposed to simplest) constructor: unfold the we provide an opportunity to map the sequence of seeds through a mapper function. Predicates Just a wrapper of hash-table-contains?. A sob is empty if its size is 0. any of its elements in the other. We have to try both ways: sob-half-disjoint checks just one direction for simplicity. This procedure lets us find out which one it is; it will return the value stored in the sob that is equal to the element. Note that we have to search the whole hash table item by item. The default is returned if there is no such element. Retrieve the comparator. The primitive operation for adding an element to a sob. There are a few cases where we bypass this for efficiency. The primitive operation for removing an element from a sob. Note this Therefore, whenever it is used it is necessary to call sob-cleanup! to fix things up. This is done because it is unsafe to remove an object from a hash table while iterating through it. iterates through the sob, deciding which elements to remove (those with non-positive counts), and collecting them in a list. When the iteration is done, it is safe to remove the elements using the list, because we are no longer iterating over the hash table. It returns its argument, because it is often tail-called at the end of some procedure that wants to return the clean sob. We expose these for bags but not sets. The primitive operation to add elements from a list. We expose These versions copy the set or bag before adjoining. Given an element which resides in a set, this makes sure that the specified element is represented by the form given. Thus if a if there is no such element in the sob. bit inefficient because it copies the element to be replaced before actually replacing it. The primitive operation to delete elemnets from a list. sob-cleanup! itself, so its callers don't need to (though it is safe to do so.) this is inefficient . Flag used by sob-search! to represent a missing object. Searches and then dispatches to user-defined procedures on failure and success, which in turn should reinvoke a procedure to take some action on the set (insert, ignore, replace, or remove). Return the size of a sob. If it's a set, we can just use the number of associations in the hash table, but if it's a bag, we have to add up the counts. Search a sob to find something that matches a predicate. You don't know which element you will get, so this is not as useful as finding an element in a list or other ordered container. If it's not there, call the failure thunk. Count the number of elements in the sob that satisfy the predicate. This is a special case of folding. Check if any of the elements in a sob satisfy a predicate. Breaks out early (with call/cc) if a success is found. Analogous to set-any?. Breaks out early if a failure is found. Mapping and folding A utility for iterating a command n times. This is used by sob-for-each to execute a procedure over the repeated elements in a bag. Because of the representation of sets, it works for them too. Basic iterator over a sob. Fundamental mapping operator. We map over the associations directly, because each instance of an element in a bag will be treated identically anyway; we insert them all at once with sob-increment!. The fundamental deconstructor. Note that there are no left vs. right folds because there is no order. Each element in a bag is fed into the fold separately. Process every element and copy the ones that satisfy the predicate. Identical elements are processed all at once. This is used for both filter and remove. Process each element and remove those that don't satisfy the filter. This does its own cleanup, and is used for both filter! and remove!. filtering and removing separately. Create a sob and iterate through the given sob. Anything that satisfies the predicate is left alone; anything that doesn't is removed from the given sob and added to the new sob. Copying and conversion Convert a sob to a list; a special case of sob-fold. Convert a list to a sob. Probably could be done using unfold, but since sobs are mutable anyway, it's just as easy to add the elements by side effect. Subsets All of these procedures follow the same pattern. The sob<op>? procedures are case-lambdas that reduce the multi-argument The dyadic-sob<op>? procedures are where it gets interesting, so see the comments on them. First we check that there are the same number of entries in the if that 's not true , they ca n't be equal . Then we check that for each key, the values are the same (where again they can't be equal. This is analogous to dyadic-sob=?, except that we have to check both sobs to make sure each value is <= in order to be sure that we've traversed all the elements in either sob. > is the negation of <=. Note that this is only true at the dyadic level; we can't just replace sob>? with a negation of sob<=?. < is the inverse of >. Again, this is only true dyadically. Finally, >= is the negation of <. Good thing we have tail recursion. Set theory operations The logic of union, intersection, difference, and sum is the same: the sob-* and sob-*! procedures do the reduction to the dyadic-sob-*! procedures. The difference is that the sob-* procedures allocate Note that there is no set-sum, as it is the same as set-union. For union, we take the max of the counts of each element found in either sob and put that in the result. On the pass through so we just copy over things that aren't in sob1. For intersection, we compute the min of the counts of each element. We only have to scan sob1. We clean up the result when we are done, in case it is the same as sob1. For difference, we use (big surprise) the numeric difference, bounded case it is the same as sob1. Sum is just like union, except that we take the sum rather than the max. Sum is defined for bags only; for sets, it is the same as union. not necessary. This version accepts a result sob and computes the A few bag-specific procedures Comparators Hash over sobs Set and bag comparator Register above comparators for use by default-comparator Set/bag printer (for debugging) Chicken-specific
Implementation of general sets and bags for SRFI 113 over the field accessors . There are three fields , " sob - multi ? " , the element appears , which is always 1 for a set , any positive value Shim to convert from SRFI 69 to the future " intermediate hash tables " SRFI . Unfortunately , hash - table - fold is incompatible between the two (define (make-hash-table/comparator comparator) (make-hash-table (comparator-equality-predicate comparator) (modulizer (comparator-hash-function comparator)))) These two procedures adjust for the mismatch between the hash functions of SRFI 114 , which return a potentially unbounded non - negative integer , and the hash functions of SRFI 69 , which expect to be able to pass a second argument which is an upper bound . (define (modulizer hash-function) (case-lambda ((obj) (hash-function obj)) ((obj limit) (modulo (hash-function obj) limit)))) Simple renaming . Chicken 's implementation of SRFI 69 provides order , so in the Chicken module we suppress importing it to muffle (define hash-table-contains? hash-table-exists?) (define (hash-table-for-each proc hash-table) (hash-table-walk hash-table proc)) (define-record-type sob (raw-make-sob hash-table comparator multi?) sob? (hash-table sob-hash-table) (comparator sob-comparator) (multi? sob-multi?)) (define (set? obj) (and (sob? obj) (not (sob-multi? obj)))) (define (bag? obj) (and (sob? obj) (sob-multi? obj))) (define (check-set obj) (if (not (set? obj)) (error "not a set" obj))) (define (check-bag obj) (if (not (bag? obj)) (error "not a bag" obj))) (define (check-all-sets list) (for-each (lambda (obj) (check-set obj)) list) (sob-check-comparators list)) (define (check-all-bags list) (for-each (lambda (obj) (check-bag obj)) list) (sob-check-comparators list)) (define (sob-check-comparators list) (if (not (null? list)) (for-each (lambda (sob) (check-same-comparator (car list) sob)) (cdr list)))) This procedure is used directly when there are exactly two arguments . (define (check-same-comparator a b) (if (not (eq? (sob-comparator a) (sob-comparator b))) (error "different comparators" a b))) (define (check-element sob element) (comparator-check-type (sob-comparator sob) element)) Construct an arbitrary empty sob out of nothing . (define (make-sob comparator multi?) (raw-make-sob (make-hash-table/comparator comparator) comparator multi?)) (define (sob-copy sob) (raw-make-sob (hash-table-copy (sob-hash-table sob)) (sob-comparator sob) (sob-multi? sob))) (define (set-copy set) (check-set set) (sob-copy set)) (define (bag-copy bag) (check-bag bag) (sob-copy bag)) Construct an empty sob that shares the constructor of an existing sob . (define (sob-empty-copy sob) (make-sob (sob-comparator sob) (sob-multi? sob))) Construct a set or a bag and insert elements into it . These are the (define (set comparator . elements) (let ((result (make-sob comparator #f))) (for-each (lambda (x) (sob-increment! result x 1)) elements) result)) (define (bag comparator . elements) (let ((result (make-sob comparator #t))) (for-each (lambda (x) (sob-increment! result x 1)) elements) result)) results of iterating a function as a set . In line with SRFI 1 , (define (sob-unfold stop? mapper successor seed comparator multi?) (let ((result (make-sob comparator multi?))) (let loop ((seed seed)) (if (stop? seed) result (begin (sob-increment! result (mapper seed) 1) (loop (successor seed))))))) (define (set-unfold continue? mapper successor seed comparator) (sob-unfold continue? mapper successor seed comparator #f)) (define (bag-unfold continue? mapper successor seed comparator) (sob-unfold continue? mapper successor seed comparator #t)) (define (sob-contains? sob member) (hash-table-contains? (sob-hash-table sob) member)) (define (set-contains? set member) (check-set set) (sob-contains? set member)) (define (bag-contains? bag member) (check-bag bag) (sob-contains? bag member)) (define (sob-empty? sob) (= 0 (hash-table-size (sob-hash-table sob)))) (define (set-empty? set) (check-set set) (sob-empty? set)) (define (bag-empty? bag) (check-bag bag) (sob-empty? bag)) Two sobs are disjoint if , when looping through one , we ca n't find (define (sob-half-disjoint? a b) (let ((ha (sob-hash-table a)) (hb (sob-hash-table b))) (call/cc (lambda (return) (hash-table-for-each (lambda (key val) (if (hash-table-contains? hb key) (return #f))) ha) #t)))) (define (set-disjoint? a b) (check-set a) (check-set b) (check-same-comparator a b) (and (sob-half-disjoint? a b) (sob-half-disjoint? b a))) (define (bag-disjoint? a b) (check-bag a) (check-bag b) (check-same-comparator a b) (and (sob-half-disjoint? a b) (sob-half-disjoint? b a))) Accessors If two objects are indistinguishable by the comparator 's equality procedure , only one of them will be represented in the sob . (define (sob-member sob element default) (define (same? a b) (=? (sob-comparator sob) a b)) (call/cc (lambda (return) (hash-table-for-each (lambda (key val) (if (same? key element) (return key))) (sob-hash-table sob)) default))) (define (set-member set element default) (check-set set) (sob-member set element default)) (define (bag-member bag element default) (check-bag bag) (sob-member bag element default)) (define (set-element-comparator set) (check-set set) (sob-comparator set)) (define (bag-element-comparator bag) (check-bag bag) (sob-comparator bag)) Updaters ( pure functional and linear update ) (define (sob-increment! sob element count) (check-element sob element) (hash-table-update!/default (sob-hash-table sob) element (if (sob-multi? sob) (lambda (value) (+ value count)) (lambda (value) 1)) 0)) procedure is incomplete : it allows the count of an element to drop below 1 . (define (sob-decrement! sob element count) (hash-table-update!/default (sob-hash-table sob) element (lambda (value) (- value count)) 0)) This is the cleanup procedure , which happens in two passes : it (define (sob-cleanup! sob) (let ((ht (sob-hash-table sob))) (for-each (lambda (key) (hash-table-delete! ht key)) (nonpositive-keys ht)) sob)) (define (nonpositive-keys ht) (let ((result '())) (hash-table-for-each (lambda (key value) (when (<= value 0) (set! result (cons key result)))) ht) result)) (define (bag-increment! bag element count) (check-bag bag) (sob-increment! bag element count) bag) (define (bag-decrement! bag element count) (check-bag bag) (sob-decrement! bag element count) (sob-cleanup! bag) bag) this two ways : with a list argument and with multiple arguments . (define (sob-adjoin-all! sob elements) (for-each (lambda (elem) (sob-increment! sob elem 1)) elements)) (define (set-adjoin! set . elements) (check-set set) (sob-adjoin-all! set elements) set) (define (bag-adjoin! bag . elements) (check-bag bag) (sob-adjoin-all! bag elements) bag) (define (set-adjoin set . elements) (check-set set) (let ((result (sob-copy set))) (sob-adjoin-all! result elements) result)) (define (bag-adjoin bag . elements) (check-bag bag) (let ((result (sob-copy bag))) (sob-adjoin-all! result elements) result)) sob contains 2 and the equality predicate is = , then calling ( sob - replace ! sob 2.0 ) will replace the 2 with 2.0 . Does nothing (define (sob-replace! sob element) (let* ((comparator (sob-comparator sob)) (= (comparator-equality-predicate comparator)) (ht (sob-hash-table sob))) (comparator-check-type comparator element) (call/cc (lambda (return) (hash-table-for-each (lambda (key value) (when (= key element) (hash-table-delete! ht key) (hash-table-set! ht element value) (return sob))) ht) sob)))) (define (set-replace! set element) (check-set set) (sob-replace! set element) set) (define (bag-replace! bag element) (check-bag bag) (sob-replace! bag element) bag) Non - destructive versions that copy the set first . Yes , a little (define (set-replace set element) (check-set set) (let ((result (sob-copy set))) (sob-replace! result element) result)) (define (bag-replace bag element) (check-bag bag) (let ((result (sob-copy bag))) (sob-replace! result element) result)) Like sob - adjoin - all ! , this is exposed two ways . It calls (define (sob-delete-all! sob elements) (for-each (lambda (element) (sob-decrement! sob element 1)) elements) (sob-cleanup! sob) sob) (define (set-delete! set . elements) (check-set set) (sob-delete-all! set elements)) (define (bag-delete! bag . elements) (check-bag bag) (sob-delete-all! bag elements)) (define (set-delete-all! set elements) (check-set set) (sob-delete-all! set elements)) (define (bag-delete-all! bag elements) (check-bag bag) (sob-delete-all! bag elements)) (define (set-delete set . elements) (check-set set) (sob-delete-all! (sob-copy set) elements)) (define (bag-delete bag . elements) (check-bag bag) (sob-delete-all! (sob-copy bag) elements)) (define (set-delete-all set elements) (check-set set) (sob-delete-all! (sob-copy set) elements)) (define (bag-delete-all bag elements) (check-bag bag) (sob-delete-all! (sob-copy bag) elements)) (define missing (string-copy "missing")) (define (sob-search! sob element failure success) (define (insert obj) (sob-increment! sob element 1) (values sob obj)) (define (ignore obj) (values sob obj)) (define (update new-elem obj) (sob-decrement! sob element 1) (sob-increment! sob new-elem 1) (values (sob-cleanup! sob) obj)) (define (remove obj) (sob-decrement! sob element 1) (values (sob-cleanup! sob) obj)) (let ((true-element (sob-member sob element missing))) (if (eq? true-element missing) (failure insert ignore) (success true-element update remove)))) (define (set-search! set element failure success) (check-set set) (sob-search! set element failure success)) (define (bag-search! bag element failure success) (check-bag bag) (sob-search! bag element failure success)) (define (sob-size sob) (if (sob-multi? sob) (let ((result 0)) (hash-table-for-each (lambda (elem count) (set! result (+ count result))) (sob-hash-table sob)) result) (hash-table-size (sob-hash-table sob)))) (define (set-size set) (check-set set) (sob-size set)) (define (bag-size bag) (check-bag bag) (sob-size bag)) (define (sob-find pred sob failure) (call/cc (lambda (return) (hash-table-for-each (lambda (key value) (if (pred key) (return key))) (sob-hash-table sob)) (failure)))) (define (set-find pred set failure) (check-set set) (sob-find pred set failure)) (define (bag-find pred bag failure) (check-bag bag) (sob-find pred bag failure)) (define (sob-count pred sob) (sob-fold (lambda (elem total) (if (pred elem) (+ total 1) total)) 0 sob)) (define (set-count pred set) (check-set set) (sob-count pred set)) (define (bag-count pred bag) (check-bag bag) (sob-count pred bag)) (define (sob-any? pred sob) (call/cc (lambda (return) (hash-table-for-each (lambda (elem value) (if (pred elem) (return #t))) (sob-hash-table sob)) #f))) (define (set-any? pred set) (check-set set) (sob-any? pred set)) (define (bag-any? pred bag) (check-bag bag) (sob-any? pred bag)) (define (sob-every? pred sob) (call/cc (lambda (return) (hash-table-for-each (lambda (elem value) (if (not (pred elem)) (return #f))) (sob-hash-table sob)) #t))) (define (set-every? pred set) (check-set set) (sob-every? pred set)) (define (bag-every? pred bag) (check-bag bag) (sob-every? pred bag)) (define (do-n-times cmd n) (let loop ((n n)) (when (> n 0) (cmd) (loop (- n 1))))) (define (sob-for-each proc sob) (hash-table-for-each (lambda (key value) (do-n-times (lambda () (proc key)) value)) (sob-hash-table sob))) (define (set-for-each proc set) (check-set set) (sob-for-each proc set)) (define (bag-for-each proc bag) (check-bag bag) (sob-for-each proc bag)) (define (sob-map comparator proc sob) (let ((result (make-sob comparator (sob-multi? sob)))) (hash-table-for-each (lambda (key value) (sob-increment! result (proc key) value)) (sob-hash-table sob)) result)) (define (set-map comparator proc set) (check-set set) (sob-map comparator proc set)) (define (bag-map comparator proc bag) (check-bag bag) (sob-map comparator proc bag)) (define (sob-fold proc nil sob) (let ((result nil)) (sob-for-each (lambda (elem) (set! result (proc elem result))) sob) result)) (define (set-fold proc nil set) (check-set set) (sob-fold proc nil set)) (define (bag-fold proc nil bag) (check-bag bag) (sob-fold proc nil bag)) (define (sob-filter pred sob) (let ((result (sob-empty-copy sob))) (hash-table-for-each (lambda (key value) (if (pred key) (sob-increment! result key value))) (sob-hash-table sob)) result)) (define (set-filter pred set) (check-set set) (sob-filter pred set)) (define (bag-filter pred bag) (check-bag bag) (sob-filter pred bag)) (define (set-remove pred set) (check-set set) (sob-filter (lambda (x) (not (pred x))) set)) (define (bag-remove pred bag) (check-bag bag) (sob-filter (lambda (x) (not (pred x))) bag)) (define (sob-filter! pred sob) (hash-table-for-each (lambda (key value) (if (not (pred key)) (sob-decrement! sob key value))) (sob-hash-table sob)) (sob-cleanup! sob)) (define (set-filter! pred set) (check-set set) (sob-filter! pred set)) (define (bag-filter! pred bag) (check-bag bag) (sob-filter! pred bag)) (define (set-remove! pred set) (check-set set) (sob-filter! (lambda (x) (not (pred x))) set)) (define (bag-remove! pred bag) (check-bag bag) (sob-filter! (lambda (x) (not (pred x))) bag)) Create two sobs and copy the elements that satisfy the predicate into one of them , all others into the other . This is more efficient than (define (sob-partition pred sob) (let ((res1 (sob-empty-copy sob)) (res2 (sob-empty-copy sob))) (hash-table-for-each (lambda (key value) (if (pred key) (sob-increment! res1 key value) (sob-increment! res2 key value))) (sob-hash-table sob)) (values res1 res2))) (define (set-partition pred set) (check-set set) (sob-partition pred set)) (define (bag-partition pred bag) (check-bag bag) (sob-partition pred bag)) (define (sob-partition! pred sob) (let ((result (sob-empty-copy sob))) (hash-table-for-each (lambda (key value) (if (not (pred key)) (begin (sob-decrement! sob key value) (sob-increment! result key value)))) (sob-hash-table sob)) (values (sob-cleanup! sob) result))) (define (set-partition! pred set) (check-set set) (sob-partition! pred set)) (define (bag-partition! pred bag) (check-bag bag) (sob-partition! pred bag)) (define (sob->list sob) (sob-fold (lambda (elem list) (cons elem list)) '() sob)) (define (set->list set) (check-set set) (sob->list set)) (define (bag->list bag) (check-bag bag) (sob->list bag)) (define (list->sob! sob list) (for-each (lambda (elem) (sob-increment! sob elem 1)) list) sob) (define (list->set comparator list) (list->sob! (make-sob comparator #f) list)) (define (list->bag comparator list) (list->sob! (make-sob comparator #t) list)) (define (list->set! set list) (check-set set) (list->sob! set list)) (define (list->bag! bag list) (check-bag bag) (list->sob! bag list)) case to the two - argument case . As usual , the set < op > ? and bag < op > ? procedures are trivial layers over the sob < op > ? procedure . (define sob=? (case-lambda ((sob) #t) ((sob1 sob2) (dyadic-sob=? sob1 sob2)) ((sob1 sob2 . sobs) (and (dyadic-sob=? sob1 sob2) (apply sob=? sob2 sobs))))) (define (set=? . sets) (check-all-sets sets) (apply sob=? sets)) (define (bag=? . bags) (check-all-bags bags) (apply sob=? bags)) being absent counts as a value of 0 ) . If any values are n't equal , (define (dyadic-sob=? sob1 sob2) (call/cc (lambda (return) (let ((ht1 (sob-hash-table sob1)) (ht2 (sob-hash-table sob2))) (if (not (= (hash-table-size ht1) (hash-table-size ht2))) (return #f)) (hash-table-for-each (lambda (key value) (if (not (= value (hash-table-ref/default ht2 key 0))) (return #f))) ht1)) #t))) (define sob<=? (case-lambda ((sob) #t) ((sob1 sob2) (dyadic-sob<=? sob1 sob2)) ((sob1 sob2 . sobs) (and (dyadic-sob<=? sob1 sob2) (apply sob<=? sob2 sobs))))) (define (set<=? . sets) (check-all-sets sets) (apply sob<=? sets)) (define (bag<=? . bags) (check-all-bags bags) (apply sob<=? bags)) (define (dyadic-sob<=? sob1 sob2) (call/cc (lambda (return) (let ((ht1 (sob-hash-table sob1)) (ht2 (sob-hash-table sob2))) (if (not (<= (hash-table-size ht1) (hash-table-size ht2))) (return #f)) (hash-table-for-each (lambda (key value) (if (not (<= value (hash-table-ref/default ht2 key 0))) (return #f))) ht1)) #t))) (define sob>? (case-lambda ((sob) #t) ((sob1 sob2) (dyadic-sob>? sob1 sob2)) ((sob1 sob2 . sobs) (and (dyadic-sob>? sob1 sob2) (apply sob>? sob2 sobs))))) (define (set>? . sets) (check-all-sets sets) (apply sob>? sets)) (define (bag>? . bags) (check-all-bags bags) (apply sob>? bags)) (define (dyadic-sob>? sob1 sob2) (not (dyadic-sob<=? sob1 sob2))) (define sob<? (case-lambda ((sob) #t) ((sob1 sob2) (dyadic-sob<? sob1 sob2)) ((sob1 sob2 . sobs) (and (dyadic-sob<? sob1 sob2) (apply sob<? sob2 sobs))))) (define (set<? . sets) (check-all-sets sets) (apply sob<? sets)) (define (bag<? . bags) (check-all-bags bags) (apply sob<? bags)) (define (dyadic-sob<? sob1 sob2) (dyadic-sob>? sob2 sob1)) (define sob>=? (case-lambda ((sob) #t) ((sob1 sob2) (dyadic-sob>=? sob1 sob2)) ((sob1 sob2 . sobs) (and (dyadic-sob>=? sob1 sob2) (apply sob>=? sob2 sobs))))) (define (set>=? . sets) (check-all-sets sets) (apply sob>=? sets)) (define (bag>=? . bags) (check-all-bags bags) (apply sob>=? bags)) (define (dyadic-sob>=? sob1 sob2) (not (dyadic-sob<? sob1 sob2))) A trivial helper function which upper - bounds n by one if multi ? is false . (define (max-one n multi?) (if multi? n (if (> n 1) 1 n))) an empty copy of the first sob to accumulate the results in , whereas the sob- * ! procedures work directly in the first sob . (define (sob-union sob1 . sobs) (if (null? sobs) sob1 (let ((result (sob-empty-copy sob1))) (dyadic-sob-union! result sob1 (car sobs)) (for-each (lambda (sob) (dyadic-sob-union! result result sob)) (cdr sobs)) result))) sob2 , we know that the intersection is already accounted for , (define (dyadic-sob-union! result sob1 sob2) (let ((sob1-ht (sob-hash-table sob1)) (sob2-ht (sob-hash-table sob2)) (result-ht (sob-hash-table result))) (hash-table-for-each (lambda (key value1) (let ((value2 (hash-table-ref/default sob2-ht key 0))) (hash-table-set! result-ht key (max value1 value2)))) sob1-ht) (hash-table-for-each (lambda (key value2) (let ((value1 (hash-table-ref/default sob1-ht key 0))) (if (= value1 0) (hash-table-set! result-ht key value2)))) sob2-ht))) (define (set-union . sets) (check-all-sets sets) (apply sob-union sets)) (define (bag-union . bags) (check-all-bags bags) (apply sob-union bags)) (define (sob-union! sob1 . sobs) (for-each (lambda (sob) (dyadic-sob-union! sob1 sob1 sob)) sobs) sob1) (define (set-union! . sets) (check-all-sets sets) (apply sob-union! sets)) (define (bag-union! . bags) (check-all-bags bags) (apply sob-union! bags)) (define (sob-intersection sob1 . sobs) (if (null? sobs) sob1 (let ((result (sob-empty-copy sob1))) (dyadic-sob-intersection! result sob1 (car sobs)) (for-each (lambda (sob) (dyadic-sob-intersection! result result sob)) (cdr sobs)) (sob-cleanup! result)))) (define (dyadic-sob-intersection! result sob1 sob2) (let ((sob1-ht (sob-hash-table sob1)) (sob2-ht (sob-hash-table sob2)) (result-ht (sob-hash-table result))) (hash-table-for-each (lambda (key value1) (let ((value2 (hash-table-ref/default sob2-ht key 0))) (hash-table-set! result-ht key (min value1 value2)))) sob1-ht))) (define (set-intersection . sets) (check-all-sets sets) (apply sob-intersection sets)) (define (bag-intersection . bags) (check-all-bags bags) (apply sob-intersection bags)) (define (sob-intersection! sob1 . sobs) (for-each (lambda (sob) (dyadic-sob-intersection! sob1 sob1 sob)) sobs) (sob-cleanup! sob1)) (define (set-intersection! . sets) (check-all-sets sets) (apply sob-intersection! sets)) (define (bag-intersection! . bags) (check-all-bags bags) (apply sob-intersection! bags)) (define (sob-difference sob1 . sobs) (if (null? sobs) sob1 (let ((result (sob-empty-copy sob1))) (dyadic-sob-difference! result sob1 (car sobs)) (for-each (lambda (sob) (dyadic-sob-difference! result result sob)) (cdr sobs)) (sob-cleanup! result)))) by zero . We only need to scan sob1 , but we clean up the result in (define (dyadic-sob-difference! result sob1 sob2) (let ((sob1-ht (sob-hash-table sob1)) (sob2-ht (sob-hash-table sob2)) (result-ht (sob-hash-table result))) (hash-table-for-each (lambda (key value1) (let ((value2 (hash-table-ref/default sob2-ht key 0))) (hash-table-set! result-ht key (- value1 value2)))) sob1-ht))) (define (set-difference . sets) (check-all-sets sets) (apply sob-difference sets)) (define (bag-difference . bags) (check-all-bags bags) (apply sob-difference bags)) (define (sob-difference! sob1 . sobs) (for-each (lambda (sob) (dyadic-sob-difference! sob1 sob1 sob)) sobs) (sob-cleanup! sob1)) (define (set-difference! . sets) (check-all-sets sets) (apply sob-difference! sets)) (define (bag-difference! . bags) (check-all-bags bags) (apply sob-difference! bags)) (define (sob-sum sob1 . sobs) (if (null? sobs) sob1 (let ((result (sob-empty-copy sob1))) (dyadic-sob-sum! result sob1 (car sobs)) (for-each (lambda (sob) (dyadic-sob-sum! result result sob)) (cdr sobs)) result))) (define (dyadic-sob-sum! result sob1 sob2) (let ((sob1-ht (sob-hash-table sob1)) (sob2-ht (sob-hash-table sob2)) (result-ht (sob-hash-table result))) (hash-table-for-each (lambda (key value1) (let ((value2 (hash-table-ref/default sob2-ht key 0))) (hash-table-set! result-ht key (+ value1 value2)))) sob1-ht) (hash-table-for-each (lambda (key value2) (let ((value1 (hash-table-ref/default sob1-ht key 0))) (if (= value1 0) (hash-table-set! result-ht key value2)))) sob2-ht))) (define (bag-sum . bags) (check-all-bags bags) (apply sob-sum bags)) (define (sob-sum! sob1 . sobs) (for-each (lambda (sob) (dyadic-sob-sum! sob1 sob1 sob)) sobs) sob1) (define (bag-sum! . bags) (check-all-bags bags) (apply sob-sum! bags)) For xor exactly two arguments are required , so the above structures are absolute difference between the counts in the first sob and the corresponding counts in the second . We start by copying the entries in the second sob but not the first into the first . Then we scan the first sob , computing the absolute difference of the values and writing them back into the first sob . It 's essential to scan the second sob first , as we are not going to damage it in the process . ( Hat tip : . ) (define (sob-xor! result sob1 sob2) (let ((sob1-ht (sob-hash-table sob1)) (sob2-ht (sob-hash-table sob2)) (result-ht (sob-hash-table result))) (hash-table-for-each (lambda (key value2) (let ((value1 (hash-table-ref/default sob1-ht key 0))) (if (= value1 0) (hash-table-set! result-ht key value2)))) sob2-ht) (hash-table-for-each (lambda (key value1) (let ((value2 (hash-table-ref/default sob2-ht key 0))) (hash-table-set! result-ht key (abs (- value1 value2))))) sob1-ht) (sob-cleanup! result))) (define (set-xor set1 set2) (check-set set1) (check-set set2) (check-same-comparator set1 set2) (sob-xor! (sob-empty-copy set1) set1 set2)) (define (bag-xor bag1 bag2) (check-bag bag1) (check-bag bag2) (check-same-comparator bag1 bag2) (sob-xor! (sob-empty-copy bag1) bag1 bag2)) (define (set-xor! set1 set2) (check-set set1) (check-set set2) (check-same-comparator set1 set2) (sob-xor! set1 set1 set2)) (define (bag-xor! bag1 bag2) (check-bag bag1) (check-bag bag2) (check-same-comparator bag1 bag2) (sob-xor! bag1 bag1 bag2)) (define (sob-product! n result sob) (let ((rht (sob-hash-table result))) (hash-table-for-each (lambda (elem count) (hash-table-set! rht elem (* count n))) (sob-hash-table sob)) result)) (define (valid-n n) (and (integer? n) (exact? n) (positive? n))) (define (bag-product n bag) (check-bag bag) (valid-n n) (sob-product! n (sob-empty-copy bag) bag)) (define (bag-product! n bag) (check-bag bag) (valid-n n) (sob-product! n bag bag)) (define (bag-unique-size bag) (check-bag bag) (hash-table-size (sob-hash-table bag))) (define (bag-element-count bag elem) (check-bag bag) (hash-table-ref/default (sob-hash-table bag) elem 0)) (define (bag-for-each-unique proc bag) (check-bag bag) (hash-table-for-each (lambda (key value) (proc key value)) (sob-hash-table bag))) (define (bag-fold-unique proc nil bag) (check-bag bag) (let ((result nil)) (hash-table-for-each (lambda (elem count) (set! result (proc elem count result))) (sob-hash-table bag)) result)) (define (bag->set bag) (check-bag bag) (let ((result (make-sob (sob-comparator bag) #f))) (hash-table-for-each (lambda (key value) (sob-increment! result key value)) (sob-hash-table bag)) result)) (define (set->bag set) (check-set set) (let ((result (make-sob (sob-comparator set) #t))) (hash-table-for-each (lambda (key value) (sob-increment! result key value)) (sob-hash-table set)) result)) (define (set->bag! bag set) (check-bag bag) (check-set set) (check-same-comparator set bag) (hash-table-for-each (lambda (key value) (sob-increment! bag key value)) (sob-hash-table set)) bag) (define (bag->alist bag) (check-bag bag) (bag-fold-unique (lambda (elem count list) (cons (cons elem count) list)) '() bag)) (define (alist->bag comparator alist) (let* ((result (bag comparator)) (ht (sob-hash-table result))) (for-each (lambda (assoc) (let ((element (car assoc))) (if (not (hash-table-contains? ht element)) (sob-increment! result element (cdr assoc))))) alist) result)) (define (sob-hash sob) (let* ((ht (sob-hash-table sob)) (hash (comparator-hash-function (sob-comparator sob)))) (sob-fold (lambda (element result) (+ (hash element) result)) 5381 sob))) (define set-comparator (make-comparator set? set=? #f sob-hash)) (define bag-comparator (make-comparator bag? bag=? #f sob-hash)) (define init-comparators (begin (comparator-register-default! set-comparator) (comparator-register-default! bag-comparator))) (define (sob-print sob port) (display (if (sob-multi? sob) "&bag[" "&set[") port) (sob-for-each (lambda (elem) (display " " port) (write elem port)) sob) (display " ]" port)) (cond-expand (chicken (define-record-printer sob sob-print)) (else))
1a229ff72579bd646703815787452e8767c3e052584f222a83c084584b58515b
haskell-suite/base
Ix.hs
# LANGUAGE Trustworthy # # LANGUAGE CPP # ----------------------------------------------------------------------------- -- | -- Module : Data.Ix Copyright : ( c ) The University of Glasgow 2001 -- License : BSD-style (see the file libraries/base/LICENSE) -- -- Maintainer : -- Stability : stable -- Portability : portable -- -- The 'Ix' class is used to map a contiguous subrange of values in -- type onto integers. It is used primarily for array indexing -- (see the array package). -- ----------------------------------------------------------------------------- module Data.Ix ( -- * The 'Ix' class Ix ( range , index , inRange , rangeSize ) -- Ix instances: -- -- Ix Char Ix Int Ix Integer Ix Bool -- Ix Ordering -- Ix () -- (Ix a, Ix b) => Ix (a, b) -- ... -- * Deriving Instances of 'Ix' -- | Derived instance declarations for the class 'Ix' are only possible -- for enumerations (i.e. datatypes having only nullary constructors) -- and single-constructor datatypes, including arbitrarily large tuples, -- whose constituent types are instances of 'Ix'. -- -- * For an enumeration, the nullary constructors are assumed to be -- numbered left-to-right with the indices being 0 to n-1 inclusive. This is the same numbering defined by the ' ' class . For example , given -- the datatype: -- -- > data Colour = Red | Orange | Yellow | Green | Blue | Indigo | Violet -- -- we would have: -- > range ( Yellow , Blue ) = = [ Yellow , Green , Blue ] > index ( Yellow , Blue ) Green = = 1 > inRange ( Yellow , Blue ) Red = = False -- -- * For single-constructor datatypes, the derived instance declarations are as shown for tuples in Figure 1 -- <#prelude-index>. ) where import Prelude #ifdef __GLASGOW_HASKELL__ import GHC.Arr #endif #ifdef __HUGS__ import Hugs.Prelude( Ix(..) ) #endif
null
https://raw.githubusercontent.com/haskell-suite/base/1ee14681910c76d0a5a436c33ecf3289443e65ed/Data/Ix.hs
haskell
--------------------------------------------------------------------------- | Module : Data.Ix License : BSD-style (see the file libraries/base/LICENSE) Maintainer : Stability : stable Portability : portable The 'Ix' class is used to map a contiguous subrange of values in type onto integers. It is used primarily for array indexing (see the array package). --------------------------------------------------------------------------- * The 'Ix' class Ix instances: Ix Char Ix Ordering Ix () (Ix a, Ix b) => Ix (a, b) ... * Deriving Instances of 'Ix' | Derived instance declarations for the class 'Ix' are only possible for enumerations (i.e. datatypes having only nullary constructors) and single-constructor datatypes, including arbitrarily large tuples, whose constituent types are instances of 'Ix'. * For an enumeration, the nullary constructors are assumed to be numbered left-to-right with the indices being 0 to n-1 inclusive. This the datatype: > data Colour = Red | Orange | Yellow | Green | Blue | Indigo | Violet we would have: * For single-constructor datatypes, the derived instance declarations <#prelude-index>.
# LANGUAGE Trustworthy # # LANGUAGE CPP # Copyright : ( c ) The University of Glasgow 2001 module Data.Ix ( Ix ( range , index , inRange , rangeSize ) Ix Int Ix Integer Ix Bool is the same numbering defined by the ' ' class . For example , given > range ( Yellow , Blue ) = = [ Yellow , Green , Blue ] > index ( Yellow , Blue ) Green = = 1 > inRange ( Yellow , Blue ) Red = = False are as shown for tuples in Figure 1 ) where import Prelude #ifdef __GLASGOW_HASKELL__ import GHC.Arr #endif #ifdef __HUGS__ import Hugs.Prelude( Ix(..) ) #endif
7b53b0aa6bee16e02086976bef0515240c9409a925f62c8c16e3030f37608483
VincentToups/racket-lib
burse.rkt
#lang racket (require racket/dict) (define denominations '((fifties . 50) (twenties . 20) (tens . 10) (fives . 5) (ones . 1) (quarters . 0.25) (dimes . 0.10) (nickels . 0.05) (pennies . 0.01))) (define the-empty-burse '((fifties . 0) (twenties . 0) (tens . 0) (fives . 0) (ones . 0) (quarters . 0) (dimes . 0) (nickels . 0) (pennies . 0))) (define (pair-first p) (car p)) (define (pair-second p) (cdr p)) (define (burse-amount burse denominations) (let loop ((amount 0) (burse burse)) (if (empty? burse) amount (let* ((denom (pair-first (first burse))) (count (pair-second (first burse))) (denom-amount (dict-ref denominations denom))) (loop (+ amount (* count denom-amount)) (rest burse)))))) (define (increment-count burse denom) (let ((n (dict-ref burse denom))) (dict-set burse denom (+ n 1)))) (define (make-payment amount denominations initial-burse) (display (format "amount ~a~n" amount)) (cond ((or (= 0 amount) (< amount 0.01)) initial-burse) ((empty? denominations) (error "Insufficient denominations to make exact payment.")) (#t (let ((current-denomination (pair-first (first denominations))) (current-amount (pair-second (first denominations)))) (if (>= amount current-amount) (make-payment (- amount current-amount) denominations (increment-count initial-burse current-denomination)) (make-payment amount (rest denominations) initial-burse))))))
null
https://raw.githubusercontent.com/VincentToups/racket-lib/d8aed0959fd148615b000ceecd7b8a6128cfcfa8/pure-lands/chapter-01/burse.rkt
racket
#lang racket (require racket/dict) (define denominations '((fifties . 50) (twenties . 20) (tens . 10) (fives . 5) (ones . 1) (quarters . 0.25) (dimes . 0.10) (nickels . 0.05) (pennies . 0.01))) (define the-empty-burse '((fifties . 0) (twenties . 0) (tens . 0) (fives . 0) (ones . 0) (quarters . 0) (dimes . 0) (nickels . 0) (pennies . 0))) (define (pair-first p) (car p)) (define (pair-second p) (cdr p)) (define (burse-amount burse denominations) (let loop ((amount 0) (burse burse)) (if (empty? burse) amount (let* ((denom (pair-first (first burse))) (count (pair-second (first burse))) (denom-amount (dict-ref denominations denom))) (loop (+ amount (* count denom-amount)) (rest burse)))))) (define (increment-count burse denom) (let ((n (dict-ref burse denom))) (dict-set burse denom (+ n 1)))) (define (make-payment amount denominations initial-burse) (display (format "amount ~a~n" amount)) (cond ((or (= 0 amount) (< amount 0.01)) initial-burse) ((empty? denominations) (error "Insufficient denominations to make exact payment.")) (#t (let ((current-denomination (pair-first (first denominations))) (current-amount (pair-second (first denominations)))) (if (>= amount current-amount) (make-payment (- amount current-amount) denominations (increment-count initial-burse current-denomination)) (make-payment amount (rest denominations) initial-burse))))))
1ac22a4116b461b895e36d2e1743eda127da1aa602be701ab200d354a835ddcc
BinaryAnalysisPlatform/bap
bap_int_conversions.ml
open Core_kernel[@@warning "-D"] open Or_error let to_int conv sexp v = match conv v with | Some v -> Ok v | None -> error "doesn't fit into int" v sexp let int_of_int64 = to_int Int64.to_int Int64.sexp_of_t let int_of_int32 = to_int Int32.to_int Int32.sexp_of_t let int_of_nativeint = to_int Nativeint.to_int Nativeint.sexp_of_t let int_of_word = Bap_bitvector.to_int
null
https://raw.githubusercontent.com/BinaryAnalysisPlatform/bap/253afc171bbfd0fe1b34f6442795dbf4b1798348/lib/bap_types/bap_int_conversions.ml
ocaml
open Core_kernel[@@warning "-D"] open Or_error let to_int conv sexp v = match conv v with | Some v -> Ok v | None -> error "doesn't fit into int" v sexp let int_of_int64 = to_int Int64.to_int Int64.sexp_of_t let int_of_int32 = to_int Int32.to_int Int32.sexp_of_t let int_of_nativeint = to_int Nativeint.to_int Nativeint.sexp_of_t let int_of_word = Bap_bitvector.to_int
2e47594a4e847d5aeb456053ae15aed105641dd941c2dcc8a38c553b6476539e
input-output-hk/cardano-sl
NodeInfo.hs
module Pos.Infra.Reporting.NodeInfo ( extendWithNodeInfo , getNodeInfo , extendRTDesc ) where import Universum import Data.Bits (Bits (..)) import Formatting (sformat, stext, (%)) import Network.Info (IPv4 (..), getNetworkInterfaces, ipv4) import Serokell.Util.Text (listBuilderJSON) import Pos.Infra.Diffusion.Types (Diffusion (..)) -- The cardano-report-server has been switched off and removing code that -- depends on it makes building other projects like cardano-byron-proxy -- easier. We leave the API here, but turn all operations into a NO-OP. extendWithNodeInfo :: MonadIO m => Diffusion m -> reportType -> m reportType extendWithNodeInfo _oq rt = pure rt -- | Uses a 'Diffusion' to get a text representation of the current network -- state as seen by this node. Also includes this node's external IP addresses. -- FIXME whether to include IP addresses should be decided by the diffusion. getNodeInfo :: MonadIO m => Diffusion m -> m Text getNodeInfo diffusion = do statusText <- formatStatus diffusion sformat (ips :: [Text]) <- map show . filter ipExternal . map ipv4 <$> liftIO getNetworkInterfaces pure $ sformat outputF (pretty $ listBuilderJSON ips) statusText where ipExternal (IPv4 w) = the last is 127.0.0.1 outputF = ("{ nodeIps: '"%stext%"', peers: '"%stext%"' }") checks if ipv4 is from local range ipv4Local :: Word32 -> Bool ipv4Local w = or [b1 == 10, b1 == 172 && b2 >= 16 && b2 <= 31, b1 == 192 && b2 == 168] where b1 = w .&. 0xff b2 = (w `shiftR` 8) .&. 0xff extendRTDesc :: Text -> reportType -> reportType extendRTDesc _ x = x
null
https://raw.githubusercontent.com/input-output-hk/cardano-sl/1499214d93767b703b9599369a431e67d83f10a2/infra/src/Pos/Infra/Reporting/NodeInfo.hs
haskell
The cardano-report-server has been switched off and removing code that depends on it makes building other projects like cardano-byron-proxy easier. We leave the API here, but turn all operations into a NO-OP. | Uses a 'Diffusion' to get a text representation of the current network state as seen by this node. Also includes this node's external IP addresses. FIXME whether to include IP addresses should be decided by the diffusion.
module Pos.Infra.Reporting.NodeInfo ( extendWithNodeInfo , getNodeInfo , extendRTDesc ) where import Universum import Data.Bits (Bits (..)) import Formatting (sformat, stext, (%)) import Network.Info (IPv4 (..), getNetworkInterfaces, ipv4) import Serokell.Util.Text (listBuilderJSON) import Pos.Infra.Diffusion.Types (Diffusion (..)) extendWithNodeInfo :: MonadIO m => Diffusion m -> reportType -> m reportType extendWithNodeInfo _oq rt = pure rt getNodeInfo :: MonadIO m => Diffusion m -> m Text getNodeInfo diffusion = do statusText <- formatStatus diffusion sformat (ips :: [Text]) <- map show . filter ipExternal . map ipv4 <$> liftIO getNetworkInterfaces pure $ sformat outputF (pretty $ listBuilderJSON ips) statusText where ipExternal (IPv4 w) = the last is 127.0.0.1 outputF = ("{ nodeIps: '"%stext%"', peers: '"%stext%"' }") checks if ipv4 is from local range ipv4Local :: Word32 -> Bool ipv4Local w = or [b1 == 10, b1 == 172 && b2 >= 16 && b2 <= 31, b1 == 192 && b2 == 168] where b1 = w .&. 0xff b2 = (w `shiftR` 8) .&. 0xff extendRTDesc :: Text -> reportType -> reportType extendRTDesc _ x = x
dfffc312951634c8f84dbc0dc8a8eb68864d4874cb61c16cadf303c8eb61c502
vascokk/rivus_cep
event1.erl
-module(event1). -behaviour(event_behaviour). -export([get_param_by_name/2, get_param_names/0]). get_param_by_name(Event, ParamName) -> case ParamName of name -> element(1, Event); eventparam1 -> element(2, Event); eventparam2 -> element(3, Event); eventparam3 -> element(4, Event); eventparam4 -> element(5, Event) end. get_param_names() -> [eventparam1, eventparam2, eventparam3, eventparam4].
null
https://raw.githubusercontent.com/vascokk/rivus_cep/e9fe6ed79201d852065f7fb2a24a880414031d27/test/event1.erl
erlang
-module(event1). -behaviour(event_behaviour). -export([get_param_by_name/2, get_param_names/0]). get_param_by_name(Event, ParamName) -> case ParamName of name -> element(1, Event); eventparam1 -> element(2, Event); eventparam2 -> element(3, Event); eventparam3 -> element(4, Event); eventparam4 -> element(5, Event) end. get_param_names() -> [eventparam1, eventparam2, eventparam3, eventparam4].
3f3ee5e7db78173d61cd87a1bc6e5e1fe9a356a9c3ad267e63e1ded6cc1bcb2d
michalkonecny/aern2
CachedUnsafe.hs
# LANGUAGE CPP # -- #define DEBUG | Module : AERN2.QA.Strategy . CachedUnsafe Description : QA net plain evaluation with unsafe IO caching Copyright : ( c ) : : Stability : experimental Portability : portable QA net plain evaluation with unsafe IO caching Module : AERN2.QA.Strategy.CachedUnsafe Description : QA net plain evaluation with unsafe IO caching Copyright : (c) Michal Konecny License : BSD3 Maintainer : Stability : experimental Portability : portable QA net plain evaluation with unsafe IO caching -} module AERN2.QA.Strategy.CachedUnsafe ( qaUnsafeCachingMV ) where #ifdef DEBUG import Debug.Trace (trace) #define maybeTrace trace #define maybeTraceIO putStrLn #else #define maybeTrace (\ (_ :: String) t -> t) #define maybeTraceIO (\ (_ :: String)-> return ()) #endif import MixedTypesNumPrelude import qualified Prelude as P -- import Text.Printf import System.IO.Unsafe (unsafePerformIO) import Control.Concurrent.MVar import AERN2.QA.Protocol | Normal Haskell functions are a trivial instance where registration has no effect . Normal Haskell functions are a trivial QAArrow instance where registration has no effect. -} instance QAArrow (->) where type QAId (->) = () qaRegister _ = id newQA name sources p sampleQ makeQ = addUnsafeMemoisation $ defaultNewQA name sources p sampleQ makeQ qaMakeQueryGetPromiseA src (qa,q) = qaMakeQueryGetPromise qa (qaId qa, src) q qaFulfilPromiseA promise = promise () {-| A global variable controlling whether unsafe caching is used in QA objects in the (->) arrow -} qaUnsafeCachingMV :: MVar Bool qaUnsafeCachingMV = unsafePerformIO (newMVar True) | Add caching to pure ( - > ) QA objects via unsafe memoization , inspired by -0.2.3/docs/src/Data-Number-IReal-UnsafeMemo.html#unsafeMemo , which , in turn , is inspired by uglymemo . Add caching to pure (->) QA objects via unsafe memoization, inspired by -0.2.3/docs/src/Data-Number-IReal-UnsafeMemo.html#unsafeMemo, which, in turn, is inspired by Lennart Augustsson's uglymemo. -} addUnsafeMemoisation :: (QAProtocolCacheable p) => QA (->) p -> QA (->) p addUnsafeMemoisation qa = qa { qaMakeQueryGetPromise = \ _src -> unsafeMemo } where unsafeMemo = (unsafePerformIO .) . unsafePerformIO memoIO p = qaProtocol qa -- name = qaName qa memoIO = do putStrLn $ " starting for " + + name cacheVar <- newMVar $ newQACache p return $ useMVar cacheVar where useMVar cacheVar q () = do shouldCache <- readMVar qaUnsafeCachingMV if not shouldCache then return $ qaMakeQueryGetPromise qa (Nothing, Nothing) q () else do putStrLn $ " : q = " + + ( show q ) cache <- readMVar cacheVar putStrLn $ " : got cache " case lookupQACache p cache q of (Just a, _logMsg) -> do putStrLn $ printf " % s : using cache : ? % s - > ! % s " name ( show q ) ( show a ) return a _ -> do let a = qaMakeQueryGetPromise qa (Nothing, Nothing) q () modifyMVar_ cacheVar (const (return (updateQACache p q a cache))) putStrLn $ printf " s : updated cache : ? % s - > ! % s " name ( show q ) ( show a ) cache' <- readMVar cacheVar case lookupQACache p cache' q of (Just a', _) -> return a' this arranges that any size reductions specified in lookupQACache are applied even when the cache was not used _ -> return a
null
https://raw.githubusercontent.com/michalkonecny/aern2/7ab41113ca8f73dca70d887d190ddab3b43ef084/aern2-net/src/AERN2/QA/Strategy/CachedUnsafe.hs
haskell
#define DEBUG import Text.Printf | A global variable controlling whether unsafe caching is used in QA objects in the (->) arrow name = qaName qa
# LANGUAGE CPP # | Module : AERN2.QA.Strategy . CachedUnsafe Description : QA net plain evaluation with unsafe IO caching Copyright : ( c ) : : Stability : experimental Portability : portable QA net plain evaluation with unsafe IO caching Module : AERN2.QA.Strategy.CachedUnsafe Description : QA net plain evaluation with unsafe IO caching Copyright : (c) Michal Konecny License : BSD3 Maintainer : Stability : experimental Portability : portable QA net plain evaluation with unsafe IO caching -} module AERN2.QA.Strategy.CachedUnsafe ( qaUnsafeCachingMV ) where #ifdef DEBUG import Debug.Trace (trace) #define maybeTrace trace #define maybeTraceIO putStrLn #else #define maybeTrace (\ (_ :: String) t -> t) #define maybeTraceIO (\ (_ :: String)-> return ()) #endif import MixedTypesNumPrelude import qualified Prelude as P import System.IO.Unsafe (unsafePerformIO) import Control.Concurrent.MVar import AERN2.QA.Protocol | Normal Haskell functions are a trivial instance where registration has no effect . Normal Haskell functions are a trivial QAArrow instance where registration has no effect. -} instance QAArrow (->) where type QAId (->) = () qaRegister _ = id newQA name sources p sampleQ makeQ = addUnsafeMemoisation $ defaultNewQA name sources p sampleQ makeQ qaMakeQueryGetPromiseA src (qa,q) = qaMakeQueryGetPromise qa (qaId qa, src) q qaFulfilPromiseA promise = promise () qaUnsafeCachingMV :: MVar Bool qaUnsafeCachingMV = unsafePerformIO (newMVar True) | Add caching to pure ( - > ) QA objects via unsafe memoization , inspired by -0.2.3/docs/src/Data-Number-IReal-UnsafeMemo.html#unsafeMemo , which , in turn , is inspired by uglymemo . Add caching to pure (->) QA objects via unsafe memoization, inspired by -0.2.3/docs/src/Data-Number-IReal-UnsafeMemo.html#unsafeMemo, which, in turn, is inspired by Lennart Augustsson's uglymemo. -} addUnsafeMemoisation :: (QAProtocolCacheable p) => QA (->) p -> QA (->) p addUnsafeMemoisation qa = qa { qaMakeQueryGetPromise = \ _src -> unsafeMemo } where unsafeMemo = (unsafePerformIO .) . unsafePerformIO memoIO p = qaProtocol qa memoIO = do putStrLn $ " starting for " + + name cacheVar <- newMVar $ newQACache p return $ useMVar cacheVar where useMVar cacheVar q () = do shouldCache <- readMVar qaUnsafeCachingMV if not shouldCache then return $ qaMakeQueryGetPromise qa (Nothing, Nothing) q () else do putStrLn $ " : q = " + + ( show q ) cache <- readMVar cacheVar putStrLn $ " : got cache " case lookupQACache p cache q of (Just a, _logMsg) -> do putStrLn $ printf " % s : using cache : ? % s - > ! % s " name ( show q ) ( show a ) return a _ -> do let a = qaMakeQueryGetPromise qa (Nothing, Nothing) q () modifyMVar_ cacheVar (const (return (updateQACache p q a cache))) putStrLn $ printf " s : updated cache : ? % s - > ! % s " name ( show q ) ( show a ) cache' <- readMVar cacheVar case lookupQACache p cache' q of (Just a', _) -> return a' this arranges that any size reductions specified in lookupQACache are applied even when the cache was not used _ -> return a
68027f1bcda3b88106d47b28ea6a0d4d17b4edf0f7dd0eafbac95efff25f97aa
batsh-dev-team/Batsh
winbat_format.ml
open Core_kernel open Winbat_ast let escape (str : string) : string = let buffer = Buffer.create (String.length str) in let exclamation = match String.index str '!' with | None -> false | Some _ -> true in String.iter str ~f:(fun ch -> let escaped = match ch with | '%' -> "%%" | '^' -> if exclamation then "^^^^" else "^^" | '&' -> "^&" | '<' -> "^<" | '>' -> "^>" | '\'' -> "^'" | '"' -> "^\"" | '`' -> "^`" | ',' -> "^," | ';' -> "^;" | '=' -> "^=" | '(' -> "^(" | ')' -> "^)" | '!' -> "^^!" | '\n' -> "^\n\n" | _ -> String.of_char ch in Buffer.add_string buffer escaped ); Buffer.contents buffer let rec print_leftvalue (buf : Buffer.t) (lvalue : leftvalue) ~(bare : bool) = match lvalue with | `Identifier ident -> if bare || (Char.equal (String.get ident 0) '%') then bprintf buf "%s" ident else bprintf buf "!%s!" ident | `ListAccess (lvalue, index) -> if bare then bprintf buf "%a_%a" (print_leftvalue ~bare: true) lvalue (print_varint ~bare: true) index else bprintf buf "!%a_%a!" (print_leftvalue ~bare: true) lvalue (print_varint ~bare: true) index and print_varint (buf : Buffer.t) (index : varint) ~(bare : bool) = match index with | `Var lvalue -> (print_leftvalue ~bare) buf lvalue | `Int num -> bprintf buf "%d" num let rec print_arith buf (arith : arithmetic) = match arith with | `Var lvalue -> print_leftvalue buf lvalue ~bare: false | `Int num -> bprintf buf "%d" num | `ArithUnary (operator, arith) -> bprintf buf "%s^(%a^)" operator print_arith arith | `ArithBinary (operator, left, right) -> ( let operator = if String.equal operator "%" then "%%" else operator in bprintf buf "^(%a %s %a^)" print_arith left operator print_arith right ) let print_varstring buf (var : varstring) = match var with | `Var lvalue -> print_leftvalue buf lvalue ~bare: false | `Str str -> Buffer.add_string buf (escape str) | `Rawstr str -> Buffer.add_string buf str let print_varstrings buf (vars : varstrings) = List.iter vars ~f: (print_varstring buf) let print_parameters buf (params : parameters) = let comsume = ref false in List.iter params ~f: (fun vars -> match vars with | [] -> comsume := true | _ -> if !comsume then comsume := false else Buffer.add_char buf ' '; print_varstrings buf vars ) let print_comparison buf (condition : comparison) = match condition with | `TestCompare (operator, expr) -> bprintf buf "%s %a" operator print_varstrings expr | `UniCompare (operator, expr) -> ( let sign = match operator with | "" -> "EQU" | "!" -> "NEQ" | _ -> failwith ("Unknown operator: " ^ operator) in bprintf buf "%a %s 1" print_varstrings expr sign ) | `StrCompare (operator, left, right) -> ( let sign = match operator with | "==" | "===" -> "EQU" | "!=" | "!==" -> "NEQ" | ">" -> "GTR" | "<" -> "LSS" | ">=" -> "GEQ" | "<=" -> "LEQ" | _ -> failwith ("Unknown operator: " ^ operator) in bprintf buf "%a %s %a" print_varstrings left sign print_varstrings right ) let rec print_statement buf (stmt: statement) ~(indent: int) = Formatutil.print_indent buf indent; match stmt with | `Comment comment -> let len = String.length comment in bprintf buf "rem%s%s" ( if len = 0 || (len > 0 && Char.equal (String.get comment 0) ' ') then "" else " " ) comment | `Raw str -> Buffer.add_string buf str | `Label lbl -> bprintf buf ":%s" lbl | `Goto lbl -> bprintf buf "goto %s" lbl | `Assignment (lvalue, vars) -> bprintf buf "set %a=%a" (print_leftvalue ~bare: true) lvalue print_varstrings vars | `ArithAssign (lvalue, arith) -> bprintf buf "set /a %a=%a" (print_leftvalue ~bare: true) lvalue print_arith arith | `Call (name, params) -> bprintf buf "%a%a" print_varstrings name print_parameters params | `Output (lvalue, name, params) -> bprintf buf "for /f \"delims=\" %%%%i in ('%a%a') do set %a=%%%%i" print_varstrings name print_parameters params (print_leftvalue ~bare: true) lvalue | `If (condition, stmts) -> bprintf buf "if %a (\n%a\n%a)" print_comparison condition (print_statements ~indent: (indent + 2)) stmts Formatutil.print_indent indent | `IfElse (condition, then_stmts, else_stmts) -> bprintf buf "if %a (\n%a\n%a) else (\n%a\n%a)" print_comparison condition (print_statements ~indent: (indent + 2)) then_stmts Formatutil.print_indent indent (print_statements ~indent: (indent + 2)) else_stmts Formatutil.print_indent indent | `Empty -> () and print_statements: Buffer.t -> statements -> indent:int -> unit = Formatutil.print_statements ~f: print_statement let print (buf: Buffer.t) (program: t) :unit = print_statements buf program ~indent: 0
null
https://raw.githubusercontent.com/batsh-dev-team/Batsh/5c8ae421e0eea5dcb3da01643152ad96af941f07/lib/winbat_format.ml
ocaml
open Core_kernel open Winbat_ast let escape (str : string) : string = let buffer = Buffer.create (String.length str) in let exclamation = match String.index str '!' with | None -> false | Some _ -> true in String.iter str ~f:(fun ch -> let escaped = match ch with | '%' -> "%%" | '^' -> if exclamation then "^^^^" else "^^" | '&' -> "^&" | '<' -> "^<" | '>' -> "^>" | '\'' -> "^'" | '"' -> "^\"" | '`' -> "^`" | ',' -> "^," | ';' -> "^;" | '=' -> "^=" | '(' -> "^(" | ')' -> "^)" | '!' -> "^^!" | '\n' -> "^\n\n" | _ -> String.of_char ch in Buffer.add_string buffer escaped ); Buffer.contents buffer let rec print_leftvalue (buf : Buffer.t) (lvalue : leftvalue) ~(bare : bool) = match lvalue with | `Identifier ident -> if bare || (Char.equal (String.get ident 0) '%') then bprintf buf "%s" ident else bprintf buf "!%s!" ident | `ListAccess (lvalue, index) -> if bare then bprintf buf "%a_%a" (print_leftvalue ~bare: true) lvalue (print_varint ~bare: true) index else bprintf buf "!%a_%a!" (print_leftvalue ~bare: true) lvalue (print_varint ~bare: true) index and print_varint (buf : Buffer.t) (index : varint) ~(bare : bool) = match index with | `Var lvalue -> (print_leftvalue ~bare) buf lvalue | `Int num -> bprintf buf "%d" num let rec print_arith buf (arith : arithmetic) = match arith with | `Var lvalue -> print_leftvalue buf lvalue ~bare: false | `Int num -> bprintf buf "%d" num | `ArithUnary (operator, arith) -> bprintf buf "%s^(%a^)" operator print_arith arith | `ArithBinary (operator, left, right) -> ( let operator = if String.equal operator "%" then "%%" else operator in bprintf buf "^(%a %s %a^)" print_arith left operator print_arith right ) let print_varstring buf (var : varstring) = match var with | `Var lvalue -> print_leftvalue buf lvalue ~bare: false | `Str str -> Buffer.add_string buf (escape str) | `Rawstr str -> Buffer.add_string buf str let print_varstrings buf (vars : varstrings) = List.iter vars ~f: (print_varstring buf) let print_parameters buf (params : parameters) = let comsume = ref false in List.iter params ~f: (fun vars -> match vars with | [] -> comsume := true | _ -> if !comsume then comsume := false else Buffer.add_char buf ' '; print_varstrings buf vars ) let print_comparison buf (condition : comparison) = match condition with | `TestCompare (operator, expr) -> bprintf buf "%s %a" operator print_varstrings expr | `UniCompare (operator, expr) -> ( let sign = match operator with | "" -> "EQU" | "!" -> "NEQ" | _ -> failwith ("Unknown operator: " ^ operator) in bprintf buf "%a %s 1" print_varstrings expr sign ) | `StrCompare (operator, left, right) -> ( let sign = match operator with | "==" | "===" -> "EQU" | "!=" | "!==" -> "NEQ" | ">" -> "GTR" | "<" -> "LSS" | ">=" -> "GEQ" | "<=" -> "LEQ" | _ -> failwith ("Unknown operator: " ^ operator) in bprintf buf "%a %s %a" print_varstrings left sign print_varstrings right ) let rec print_statement buf (stmt: statement) ~(indent: int) = Formatutil.print_indent buf indent; match stmt with | `Comment comment -> let len = String.length comment in bprintf buf "rem%s%s" ( if len = 0 || (len > 0 && Char.equal (String.get comment 0) ' ') then "" else " " ) comment | `Raw str -> Buffer.add_string buf str | `Label lbl -> bprintf buf ":%s" lbl | `Goto lbl -> bprintf buf "goto %s" lbl | `Assignment (lvalue, vars) -> bprintf buf "set %a=%a" (print_leftvalue ~bare: true) lvalue print_varstrings vars | `ArithAssign (lvalue, arith) -> bprintf buf "set /a %a=%a" (print_leftvalue ~bare: true) lvalue print_arith arith | `Call (name, params) -> bprintf buf "%a%a" print_varstrings name print_parameters params | `Output (lvalue, name, params) -> bprintf buf "for /f \"delims=\" %%%%i in ('%a%a') do set %a=%%%%i" print_varstrings name print_parameters params (print_leftvalue ~bare: true) lvalue | `If (condition, stmts) -> bprintf buf "if %a (\n%a\n%a)" print_comparison condition (print_statements ~indent: (indent + 2)) stmts Formatutil.print_indent indent | `IfElse (condition, then_stmts, else_stmts) -> bprintf buf "if %a (\n%a\n%a) else (\n%a\n%a)" print_comparison condition (print_statements ~indent: (indent + 2)) then_stmts Formatutil.print_indent indent (print_statements ~indent: (indent + 2)) else_stmts Formatutil.print_indent indent | `Empty -> () and print_statements: Buffer.t -> statements -> indent:int -> unit = Formatutil.print_statements ~f: print_statement let print (buf: Buffer.t) (program: t) :unit = print_statements buf program ~indent: 0
dfd5a9f106385644595ad2acd308d1209a986daa569ff267b3d5ea590b453028
theodormoroianu/SecondYearCourses
LambdaChurch_20210415164404.hs
module LambdaChurch where import Data.Char (isLetter) import Data.List ( nub ) class ShowNice a where showNice :: a -> String class ReadNice a where readNice :: String -> (a, String) data Variable = Variable { name :: String , count :: Int } deriving (Show, Eq, Ord) var :: String -> Variable var x = Variable x 0 instance ShowNice Variable where showNice (Variable x 0) = x showNice (Variable x cnt) = x <> "_" <> show cnt instance ReadNice Variable where readNice s | null x = error $ "expected variable but found " <> s | otherwise = (var x, s') where (x, s') = span isLetter s freshVariable :: Variable -> [Variable] -> Variable freshVariable var vars = Variable x (cnt + 1) where x = name var varsWithName = filter ((== x) . name) vars Variable _ cnt = maximum (var : varsWithName) data Term = V Variable | App Term Term | Lam Variable Term deriving (Show) -- alpha-equivalence aEq :: Term -> Term -> Bool aEq (V x) (V x') = x == x' aEq (App t1 t2) (App t1' t2') = aEq t1 t1' && aEq t2 t2' aEq (Lam x t) (Lam x' t') | x == x' = aEq t t' | otherwise = aEq (subst (V y) x t) (subst (V y) x' t') where fvT = freeVars t fvT' = freeVars t' allFV = nub ([x, x'] ++ fvT ++ fvT') y = freshVariable x allFV aEq _ _ = False v :: String -> Term v x = V (var x) lam :: String -> Term -> Term lam x = Lam (var x) lams :: [String] -> Term -> Term lams xs t = foldr lam t xs ($$) :: Term -> Term -> Term ($$) = App infixl 9 $$ instance ShowNice Term where showNice (V var) = showNice var showNice (App t1 t2) = "(" <> showNice t1 <> " " <> showNice t2 <> ")" showNice (Lam var t) = "(" <> "\\" <> showNice var <> "." <> showNice t <> ")" instance ReadNice Term where readNice [] = error "Nothing to read" readNice ('(' : '\\' : s) = (Lam var t, s'') where (var, '.' : s') = readNice s (t, ')' : s'') = readNice s' readNice ('(' : s) = (App t1 t2, s'') where (t1, ' ' : s') = readNice s (t2, ')' : s'') = readNice s' readNice s = (V var, s') where (var, s') = readNice s freeVars :: Term -> [Variable] freeVars (V var) = [var] freeVars (App t1 t2) = nub $ freeVars t1 ++ freeVars t2 freeVars (Lam var t) = filter (/= var) (freeVars t) -- subst u x t defines [u/x]t, i.e., substituting u for x in t for example [ 3 / x](x + x ) = = 3 + 3 -- This substitution avoids variable captures so it is safe to be used when -- reducing terms with free variables (e.g., if evaluating inside lambda abstractions) subst :: Term -- ^ substitution term -> Variable -- ^ variable to be substitutes -> Term -- ^ term in which the substitution occurs -> Term subst u x (V y) | x == y = u | otherwise = V y subst u x (App t1 t2) = App (subst u x t1) (subst u x t2) subst u x (Lam y t) | x == y = Lam y t | y `notElem` fvU = Lam y (subst u x t) | x `notElem` fvT = Lam y t | otherwise = Lam y' (subst u x (subst (V y') y t)) where fvT = freeVars t fvU = freeVars u allFV = nub ([x] ++ fvU ++ fvT) y' = freshVariable y allFV -- Normal order reduction -- - like call by name -- - but also reduce under lambda abstractions if no application is possible -- - guarantees reaching a normal form if it exists normalReduceStep :: Term -> Maybe Term normalReduceStep (App (Lam v t) t2) = Just $ subst t2 v t normalReduceStep (App t1 t2) | Just t1' <- normalReduceStep t1 = Just $ App t1' t2 | Just t2' <- normalReduceStep t2 = Just $ App t1 t2' normalReduceStep (Lam x t) | Just t' <- normalReduceStep t = Just $ Lam x t' normalReduceStep _ = Nothing normalReduce :: Term -> Term normalReduce t | Just t' <- normalReduceStep t = normalReduce t' | otherwise = t reduce :: Term -> Term reduce = normalReduce -- alpha-beta equivalence (for strongly normalizing terms) is obtained by -- fully evaluating the terms using beta-reduction, then checking their -- alpha-equivalence. abEq :: Term -> Term -> Bool abEq t1 t2 = aEq (reduce t1) (reduce t2) evaluate :: String -> String evaluate s = showNice (reduce t) where (t, "") = readNice s -- Church Encodings in Lambda churchTrue :: Term churchTrue = lams ["t", "f"] (v "t") churchFalse :: Term churchFalse = lams ["t", "f"] (v "f") churchIf :: Term churchIf = lams ["c", "then", "else"] (v "c" $$ v "then" $$ v "else") churchNot :: Term churchNot = lam "b" (v "b" $$ churchFalse $$ churchTrue) churchAnd :: Term churchAnd = lams ["b1", "b2"] (v "b1" $$ v "b2" $$ churchFalse) churchOr :: Term churchOr = lams ["b1", "b2"] (v "b1" $$ churchTrue $$ v "b2") church0 :: Term church0 = lams ["s", "z"] (v "z") -- note that it's the same as churchFalse church1 :: Term church1 = lams ["s", "z"] (v "s" $$ v "z") church2 :: Term church2 = lams ["s", "z"] (v "s" $$ (v "s" $$ v "z")) churchS :: Term churchS = lams ["t","s","z"] (v "s" $$ (v "t" $$ v "s" $$ v "z")) churchNat :: Integer -> Term churchNat n = lams ["s", "z"] (iterate' n (v "s" $$) (v "z")) churchPlus :: Term churchPlus = lams ["n", "m", "s", "z"] (v "n" $$ v "s" $$ (v "m" $$ v "s" $$ v "z")) churchPlus' :: Term churchPlus' = lams ["n", "m"] (v "n" $$ churchS $$ v "m") churchMul :: Term churchMul = lams ["n", "m", "s"] (v "n" $$ (v "m" $$ v "s")) churchMul' :: Term churchMul' = lams ["n", "m"] (v "n" $$ (churchPlus' $$ v "m") $$ church0) churchPow :: Term churchPow = lams ["m", "n"] (v "n" $$ v "m") churchPow' :: Term churchPow' = lams ["m", "n"] (v "n" $$ (churchMul' $$ v "m") $$ church1) churchIs0 :: Term churchIs0 = lam "n" (v "n" $$ (churchAnd $$ churchFalse) $$ churchTrue) churchS' :: Term churchS' = lam "n" (v "n" $$ churchS $$ church1) churchS'Rev0 :: Term churchS'Rev0 = lams ["s","z"] church0 churchPred :: Term churchPred = lam "n" (churchIf $$ (churchIs0 $$ v "n") $$ church0 $$ (v "n" $$ churchS' $$ churchS'Rev0)) churchSub :: Term churchSub = lams ["m", "n"] (v "n" $$ churchPred $$ v "m") churchLte :: Term churchLte = lams ["m", "n"] (churchIs0 $$ (churchSub $$ v "m" $$ v "n")) churchGte :: Term churchGte = lams ["m", "n"] (churchLte $$ v "n" $$ v "m") churchLt :: Term churchLt = lams ["m", "n"] (churchNot $$ (churchGte $$ v "m" $$ v "n")) churchGt :: Term churchGt = lams ["m", "n"] (churchLt $$ v "n" $$ v "m") churchEq :: Term churchEq = lams ["m", "n"] (churchAnd $$ (churchLte $$ v "m" $$ v "n") $$ (churchLte $$ v "n" $$ v "m")) churchPair :: Term churchPair = lams ["f", "s", "action"] (v "action" $$ v "f" $$ v "s") churchFst :: Term churchFst = lam "pair" (v "pair" $$ churchTrue) churchSnd :: Term churchSnd = lam "pair" (v "pair" $$ churchFalse) churchPred' :: Term churchPred' = lam "n" (churchFst $$ (v "n" $$ lam "p" (lam "x" (churchPair $$ v "x" $$ (churchS $$ v "x")) $$ (churchSnd $$ v "p")) $$ (churchPair $$ church0 $$ church0) )) cPred :: CNat -> CNat cPred = \n -> cFst $ cFor n (\p -> (\x -> cPair x (cS x)) (cSnd p)) (cPair 0 0) churchFactorial :: Term churchFactorial = lam "n" (churchSnd $$ (v "n" $$ lam "p" (churchPair $$ (churchS $$ (churchFst $$ v "p")) $$ (churchMul $$ (churchFst $$ v "p") $$ (churchSnd $$ v "p")) ) $$ (churchPair $$ church1 $$ church1) )) churchFibonacci :: Term churchFibonacci = lam "n" (churchFst $$ (v "n" $$ lam "p" (churchPair $$ (churchSnd $$ v "p") $$ (churchPlus $$ (churchFst $$ v "p") $$ (churchSnd $$ v "p")) ) $$ (churchPair $$ church0 $$ church1) )) cFibonacci :: CNat -> CNat cFibonacci = \n -> cFst $ cFor n (\p -> cPair (cSnd p) (cFst p + cSnd p)) (cPair 0 1) churchDivMod :: Term churchDivMod = lams ["m", "n"] (v "m" $$ lam "pair" (churchIf $$ (churchLte $$ v "n" $$ (churchSnd $$ v "pair")) $$ (churchPair $$ (churchS $$ (churchFst $$ v "pair")) $$ (churchSub $$ (churchSnd $$ v "pair") $$ v "n" ) ) $$ v "pair" ) $$ (churchPair $$ church0 $$ v "m") ) cDivMod :: CNat -> CNat -> CPair CNat CNat cDivMod = \m n -> cFor m (\p -> cIf (n <=: cSnd p) (cPair (cS (cFst p)) (cSnd p - n)) p) (cPair 0 m) newtype CList a = CList { cFoldR :: forall b. (a -> b -> b) -> b -> b } instance Foldable CList where foldr agg init xs = cFoldR xs agg init churchNil :: Term churchNil = lams ["agg", "init"] (v "init") cNil :: CList a cNil = CList $ \agg init -> init churchCons :: Term churchCons = lams ["x","l","agg", "init"] (v "agg" $$ v "x" $$ (v "l" $$ v "agg" $$ v "init") ) (.:) :: a -> CList a -> CList a (.:) = \x xs -> CList $ \agg init -> agg x (cFoldR xs agg init) churchList :: [Term] -> Term churchList = foldr (\x l -> churchCons $$ x $$ l) churchNil cList :: [a] -> CList a cList = foldr (.:) cNil churchNatList :: [Integer] -> Term churchNatList = churchList . map churchNat cNatList :: [Integer] -> CList CNat cNatList = cList . map cNat churchSum :: Term churchSum = lam "l" (v "l" $$ churchPlus $$ church0) cSum :: CList CNat -> CNat since CList is an instance of Foldable ; otherwise : \l - > cFoldR l ( + ) 0 churchIsNil :: Term churchIsNil = lam "l" (v "l" $$ lams ["x", "a"] churchFalse $$ churchTrue) cIsNil :: CList a -> CBool cIsNil = \l -> cFoldR l (\_ _ -> cFalse) cTrue churchHead :: Term churchHead = lams ["l", "default"] (v "l" $$ lams ["x", "a"] (v "x") $$ v "default") cHead :: CList a -> a -> a cHead = \l d -> cFoldR l (\x _ -> x) d churchTail :: Term churchTail = lam "l" (churchFst $$ (v "l" $$ lams ["x","p"] (lam "t" (churchPair $$ v "t" $$ (churchCons $$ v "x" $$ v "t")) $$ (churchSnd $$ v "p")) $$ (churchPair $$ churchNil $$ churchNil) )) cTail :: CList a -> CList a cTail = \l -> cFst $ cFoldR l (\x p -> (\t -> cPair t (x .: t)) (cSnd p)) (cPair cNil cNil) cLength :: CList a -> CNat cLength = \l -> cFoldR l (\_ n -> cS n) 0 fix :: Term fix = lam "f" (lam "x" (v "f" $$ (v "x" $$ v "x")) $$ lam "x" (v "f" $$ (v "x" $$ v "x"))) divmod :: (Enum a, Num a, Ord b, Num b) => b -> b -> (a, b) divmod m n = divmod' (0, 0) where divmod' (x, y) | x' <= m = divmod' (x', succ y) | otherwise = (y, m - x) where x' = x + n divmod' m n = if n == 0 then (0, m) else Function.fix (\f p -> (\x' -> if x' > 0 then f ((,) (succ (fst p)) x') else if (<=) n (snd p) then ((,) (succ (fst p)) 0) else p) ((-) (snd p) n)) (0, m) churchDivMod' :: Term churchDivMod' = lams ["m", "n"] (churchIs0 $$ v "n" $$ (churchPair $$ church0 $$ v "m") $$ (fix $$ lams ["f", "p"] (lam "x" (churchIs0 $$ v "x" $$ (churchLte $$ v "n" $$ (churchSnd $$ v "p") $$ (churchPair $$ (churchS $$ (churchFst $$ v "p")) $$ church0) $$ v "p" ) $$ (v "f" $$ (churchPair $$ (churchS $$ (churchFst $$ v "p")) $$ v "x")) ) $$ (churchSub $$ (churchSnd $$ v "p") $$ v "n") ) $$ (churchPair $$ church0 $$ v "m") ) ) churchSudan :: Term churchSudan = fix $$ lam "f" (lams ["n", "x", "y"] (churchIs0 $$ v "n" $$ (churchPlus $$ v "x" $$ v "y") $$ (churchIs0 $$ v "y" $$ v "x" $$ (lam "fnpy" (v "f" $$ (churchPred $$ v "n") $$ v "fnpy" $$ (churchPlus $$ v "fnpy" $$ v "y") ) $$ (v "f" $$ v "n" $$ v "x" $$ (churchPred $$ v "y")) ) ) )) churchAckermann :: Term churchAckermann = fix $$ lam "A" (lams ["m", "n"] (churchIs0 $$ v "m" $$ (churchS $$ v "n") $$ (churchIs0 $$ v "n" $$ (v "A" $$ (churchPred $$ v "m") $$ church1) $$ (v "A" $$ (churchPred $$ v "m") $$ (v "A" $$ v "m" $$ (churchPred $$ v "n"))) ) ) )
null
https://raw.githubusercontent.com/theodormoroianu/SecondYearCourses/5e359e6a7cf588a527d27209bf53b4ce6b8d5e83/FLP/Laboratoare/Lab%209/.history/LambdaChurch_20210415164404.hs
haskell
alpha-equivalence subst u x t defines [u/x]t, i.e., substituting u for x in t This substitution avoids variable captures so it is safe to be used when reducing terms with free variables (e.g., if evaluating inside lambda abstractions) ^ substitution term ^ variable to be substitutes ^ term in which the substitution occurs Normal order reduction - like call by name - but also reduce under lambda abstractions if no application is possible - guarantees reaching a normal form if it exists alpha-beta equivalence (for strongly normalizing terms) is obtained by fully evaluating the terms using beta-reduction, then checking their alpha-equivalence. Church Encodings in Lambda note that it's the same as churchFalse
module LambdaChurch where import Data.Char (isLetter) import Data.List ( nub ) class ShowNice a where showNice :: a -> String class ReadNice a where readNice :: String -> (a, String) data Variable = Variable { name :: String , count :: Int } deriving (Show, Eq, Ord) var :: String -> Variable var x = Variable x 0 instance ShowNice Variable where showNice (Variable x 0) = x showNice (Variable x cnt) = x <> "_" <> show cnt instance ReadNice Variable where readNice s | null x = error $ "expected variable but found " <> s | otherwise = (var x, s') where (x, s') = span isLetter s freshVariable :: Variable -> [Variable] -> Variable freshVariable var vars = Variable x (cnt + 1) where x = name var varsWithName = filter ((== x) . name) vars Variable _ cnt = maximum (var : varsWithName) data Term = V Variable | App Term Term | Lam Variable Term deriving (Show) aEq :: Term -> Term -> Bool aEq (V x) (V x') = x == x' aEq (App t1 t2) (App t1' t2') = aEq t1 t1' && aEq t2 t2' aEq (Lam x t) (Lam x' t') | x == x' = aEq t t' | otherwise = aEq (subst (V y) x t) (subst (V y) x' t') where fvT = freeVars t fvT' = freeVars t' allFV = nub ([x, x'] ++ fvT ++ fvT') y = freshVariable x allFV aEq _ _ = False v :: String -> Term v x = V (var x) lam :: String -> Term -> Term lam x = Lam (var x) lams :: [String] -> Term -> Term lams xs t = foldr lam t xs ($$) :: Term -> Term -> Term ($$) = App infixl 9 $$ instance ShowNice Term where showNice (V var) = showNice var showNice (App t1 t2) = "(" <> showNice t1 <> " " <> showNice t2 <> ")" showNice (Lam var t) = "(" <> "\\" <> showNice var <> "." <> showNice t <> ")" instance ReadNice Term where readNice [] = error "Nothing to read" readNice ('(' : '\\' : s) = (Lam var t, s'') where (var, '.' : s') = readNice s (t, ')' : s'') = readNice s' readNice ('(' : s) = (App t1 t2, s'') where (t1, ' ' : s') = readNice s (t2, ')' : s'') = readNice s' readNice s = (V var, s') where (var, s') = readNice s freeVars :: Term -> [Variable] freeVars (V var) = [var] freeVars (App t1 t2) = nub $ freeVars t1 ++ freeVars t2 freeVars (Lam var t) = filter (/= var) (freeVars t) for example [ 3 / x](x + x ) = = 3 + 3 subst -> Term subst u x (V y) | x == y = u | otherwise = V y subst u x (App t1 t2) = App (subst u x t1) (subst u x t2) subst u x (Lam y t) | x == y = Lam y t | y `notElem` fvU = Lam y (subst u x t) | x `notElem` fvT = Lam y t | otherwise = Lam y' (subst u x (subst (V y') y t)) where fvT = freeVars t fvU = freeVars u allFV = nub ([x] ++ fvU ++ fvT) y' = freshVariable y allFV normalReduceStep :: Term -> Maybe Term normalReduceStep (App (Lam v t) t2) = Just $ subst t2 v t normalReduceStep (App t1 t2) | Just t1' <- normalReduceStep t1 = Just $ App t1' t2 | Just t2' <- normalReduceStep t2 = Just $ App t1 t2' normalReduceStep (Lam x t) | Just t' <- normalReduceStep t = Just $ Lam x t' normalReduceStep _ = Nothing normalReduce :: Term -> Term normalReduce t | Just t' <- normalReduceStep t = normalReduce t' | otherwise = t reduce :: Term -> Term reduce = normalReduce abEq :: Term -> Term -> Bool abEq t1 t2 = aEq (reduce t1) (reduce t2) evaluate :: String -> String evaluate s = showNice (reduce t) where (t, "") = readNice s churchTrue :: Term churchTrue = lams ["t", "f"] (v "t") churchFalse :: Term churchFalse = lams ["t", "f"] (v "f") churchIf :: Term churchIf = lams ["c", "then", "else"] (v "c" $$ v "then" $$ v "else") churchNot :: Term churchNot = lam "b" (v "b" $$ churchFalse $$ churchTrue) churchAnd :: Term churchAnd = lams ["b1", "b2"] (v "b1" $$ v "b2" $$ churchFalse) churchOr :: Term churchOr = lams ["b1", "b2"] (v "b1" $$ churchTrue $$ v "b2") church0 :: Term church1 :: Term church1 = lams ["s", "z"] (v "s" $$ v "z") church2 :: Term church2 = lams ["s", "z"] (v "s" $$ (v "s" $$ v "z")) churchS :: Term churchS = lams ["t","s","z"] (v "s" $$ (v "t" $$ v "s" $$ v "z")) churchNat :: Integer -> Term churchNat n = lams ["s", "z"] (iterate' n (v "s" $$) (v "z")) churchPlus :: Term churchPlus = lams ["n", "m", "s", "z"] (v "n" $$ v "s" $$ (v "m" $$ v "s" $$ v "z")) churchPlus' :: Term churchPlus' = lams ["n", "m"] (v "n" $$ churchS $$ v "m") churchMul :: Term churchMul = lams ["n", "m", "s"] (v "n" $$ (v "m" $$ v "s")) churchMul' :: Term churchMul' = lams ["n", "m"] (v "n" $$ (churchPlus' $$ v "m") $$ church0) churchPow :: Term churchPow = lams ["m", "n"] (v "n" $$ v "m") churchPow' :: Term churchPow' = lams ["m", "n"] (v "n" $$ (churchMul' $$ v "m") $$ church1) churchIs0 :: Term churchIs0 = lam "n" (v "n" $$ (churchAnd $$ churchFalse) $$ churchTrue) churchS' :: Term churchS' = lam "n" (v "n" $$ churchS $$ church1) churchS'Rev0 :: Term churchS'Rev0 = lams ["s","z"] church0 churchPred :: Term churchPred = lam "n" (churchIf $$ (churchIs0 $$ v "n") $$ church0 $$ (v "n" $$ churchS' $$ churchS'Rev0)) churchSub :: Term churchSub = lams ["m", "n"] (v "n" $$ churchPred $$ v "m") churchLte :: Term churchLte = lams ["m", "n"] (churchIs0 $$ (churchSub $$ v "m" $$ v "n")) churchGte :: Term churchGte = lams ["m", "n"] (churchLte $$ v "n" $$ v "m") churchLt :: Term churchLt = lams ["m", "n"] (churchNot $$ (churchGte $$ v "m" $$ v "n")) churchGt :: Term churchGt = lams ["m", "n"] (churchLt $$ v "n" $$ v "m") churchEq :: Term churchEq = lams ["m", "n"] (churchAnd $$ (churchLte $$ v "m" $$ v "n") $$ (churchLte $$ v "n" $$ v "m")) churchPair :: Term churchPair = lams ["f", "s", "action"] (v "action" $$ v "f" $$ v "s") churchFst :: Term churchFst = lam "pair" (v "pair" $$ churchTrue) churchSnd :: Term churchSnd = lam "pair" (v "pair" $$ churchFalse) churchPred' :: Term churchPred' = lam "n" (churchFst $$ (v "n" $$ lam "p" (lam "x" (churchPair $$ v "x" $$ (churchS $$ v "x")) $$ (churchSnd $$ v "p")) $$ (churchPair $$ church0 $$ church0) )) cPred :: CNat -> CNat cPred = \n -> cFst $ cFor n (\p -> (\x -> cPair x (cS x)) (cSnd p)) (cPair 0 0) churchFactorial :: Term churchFactorial = lam "n" (churchSnd $$ (v "n" $$ lam "p" (churchPair $$ (churchS $$ (churchFst $$ v "p")) $$ (churchMul $$ (churchFst $$ v "p") $$ (churchSnd $$ v "p")) ) $$ (churchPair $$ church1 $$ church1) )) churchFibonacci :: Term churchFibonacci = lam "n" (churchFst $$ (v "n" $$ lam "p" (churchPair $$ (churchSnd $$ v "p") $$ (churchPlus $$ (churchFst $$ v "p") $$ (churchSnd $$ v "p")) ) $$ (churchPair $$ church0 $$ church1) )) cFibonacci :: CNat -> CNat cFibonacci = \n -> cFst $ cFor n (\p -> cPair (cSnd p) (cFst p + cSnd p)) (cPair 0 1) churchDivMod :: Term churchDivMod = lams ["m", "n"] (v "m" $$ lam "pair" (churchIf $$ (churchLte $$ v "n" $$ (churchSnd $$ v "pair")) $$ (churchPair $$ (churchS $$ (churchFst $$ v "pair")) $$ (churchSub $$ (churchSnd $$ v "pair") $$ v "n" ) ) $$ v "pair" ) $$ (churchPair $$ church0 $$ v "m") ) cDivMod :: CNat -> CNat -> CPair CNat CNat cDivMod = \m n -> cFor m (\p -> cIf (n <=: cSnd p) (cPair (cS (cFst p)) (cSnd p - n)) p) (cPair 0 m) newtype CList a = CList { cFoldR :: forall b. (a -> b -> b) -> b -> b } instance Foldable CList where foldr agg init xs = cFoldR xs agg init churchNil :: Term churchNil = lams ["agg", "init"] (v "init") cNil :: CList a cNil = CList $ \agg init -> init churchCons :: Term churchCons = lams ["x","l","agg", "init"] (v "agg" $$ v "x" $$ (v "l" $$ v "agg" $$ v "init") ) (.:) :: a -> CList a -> CList a (.:) = \x xs -> CList $ \agg init -> agg x (cFoldR xs agg init) churchList :: [Term] -> Term churchList = foldr (\x l -> churchCons $$ x $$ l) churchNil cList :: [a] -> CList a cList = foldr (.:) cNil churchNatList :: [Integer] -> Term churchNatList = churchList . map churchNat cNatList :: [Integer] -> CList CNat cNatList = cList . map cNat churchSum :: Term churchSum = lam "l" (v "l" $$ churchPlus $$ church0) cSum :: CList CNat -> CNat since CList is an instance of Foldable ; otherwise : \l - > cFoldR l ( + ) 0 churchIsNil :: Term churchIsNil = lam "l" (v "l" $$ lams ["x", "a"] churchFalse $$ churchTrue) cIsNil :: CList a -> CBool cIsNil = \l -> cFoldR l (\_ _ -> cFalse) cTrue churchHead :: Term churchHead = lams ["l", "default"] (v "l" $$ lams ["x", "a"] (v "x") $$ v "default") cHead :: CList a -> a -> a cHead = \l d -> cFoldR l (\x _ -> x) d churchTail :: Term churchTail = lam "l" (churchFst $$ (v "l" $$ lams ["x","p"] (lam "t" (churchPair $$ v "t" $$ (churchCons $$ v "x" $$ v "t")) $$ (churchSnd $$ v "p")) $$ (churchPair $$ churchNil $$ churchNil) )) cTail :: CList a -> CList a cTail = \l -> cFst $ cFoldR l (\x p -> (\t -> cPair t (x .: t)) (cSnd p)) (cPair cNil cNil) cLength :: CList a -> CNat cLength = \l -> cFoldR l (\_ n -> cS n) 0 fix :: Term fix = lam "f" (lam "x" (v "f" $$ (v "x" $$ v "x")) $$ lam "x" (v "f" $$ (v "x" $$ v "x"))) divmod :: (Enum a, Num a, Ord b, Num b) => b -> b -> (a, b) divmod m n = divmod' (0, 0) where divmod' (x, y) | x' <= m = divmod' (x', succ y) | otherwise = (y, m - x) where x' = x + n divmod' m n = if n == 0 then (0, m) else Function.fix (\f p -> (\x' -> if x' > 0 then f ((,) (succ (fst p)) x') else if (<=) n (snd p) then ((,) (succ (fst p)) 0) else p) ((-) (snd p) n)) (0, m) churchDivMod' :: Term churchDivMod' = lams ["m", "n"] (churchIs0 $$ v "n" $$ (churchPair $$ church0 $$ v "m") $$ (fix $$ lams ["f", "p"] (lam "x" (churchIs0 $$ v "x" $$ (churchLte $$ v "n" $$ (churchSnd $$ v "p") $$ (churchPair $$ (churchS $$ (churchFst $$ v "p")) $$ church0) $$ v "p" ) $$ (v "f" $$ (churchPair $$ (churchS $$ (churchFst $$ v "p")) $$ v "x")) ) $$ (churchSub $$ (churchSnd $$ v "p") $$ v "n") ) $$ (churchPair $$ church0 $$ v "m") ) ) churchSudan :: Term churchSudan = fix $$ lam "f" (lams ["n", "x", "y"] (churchIs0 $$ v "n" $$ (churchPlus $$ v "x" $$ v "y") $$ (churchIs0 $$ v "y" $$ v "x" $$ (lam "fnpy" (v "f" $$ (churchPred $$ v "n") $$ v "fnpy" $$ (churchPlus $$ v "fnpy" $$ v "y") ) $$ (v "f" $$ v "n" $$ v "x" $$ (churchPred $$ v "y")) ) ) )) churchAckermann :: Term churchAckermann = fix $$ lam "A" (lams ["m", "n"] (churchIs0 $$ v "m" $$ (churchS $$ v "n") $$ (churchIs0 $$ v "n" $$ (v "A" $$ (churchPred $$ v "m") $$ church1) $$ (v "A" $$ (churchPred $$ v "m") $$ (v "A" $$ v "m" $$ (churchPred $$ v "n"))) ) ) )
c13d2c7c56e1dafff5943b895d146c8ccbe5f378ef8a46f697b4949bd131d985
ott-lang/ott
main.ml
(**************************************************************************) (* Ott *) (* *) , Computer Laboratory , University of Cambridge , project , INRIA Rocquencourt (* *) Copyright 2005 - 2010 (* *) (* Redistribution and use in source and binary forms, with or without *) (* modification, are permitted provided that the following conditions *) (* are met: *) 1 . Redistributions of source code must retain the above copyright (* notice, this list of conditions and the following disclaimer. *) 2 . Redistributions in binary form must reproduce the above copyright (* notice, this list of conditions and the following disclaimer in the *) (* documentation and/or other materials provided with the distribution. *) 3 . The names of the authors may not be used to endorse or promote (* products derived from this software without specific prior written *) (* permission. *) (* *) THIS SOFTWARE IS PROVIDED BY THE AUTHORS ` ` AS IS '' AND ANY EXPRESS (* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED *) (* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE *) ARE DISCLAIMED . IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL (* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE *) (* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS *) INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER (* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR *) (* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN *) (* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *) (**************************************************************************) open Location open Types (* command-line options *) let colour = ref true let file_arguments = ref ([]:(file_argument*string) list) let i_arguments = ref false let dot_filename_opt = ref (None : string option) let alltt_filename_opt = ref (None : string option) let write_systemdefn_filename_opt = ref (None : string option) let read_systemdefn_filename_opt = ref (None : string option) let tex_name_prefix = ref "ott" let tex_filter_filenames = ref ([] : (string * string) list) let tex_filter_filename_srcs = ref ([] : string list) let tex_filter_filename_dsts = ref ([] : string list) let isa_filter_filenames = ref ([] : (string * string) list) let isa_filter_filename_srcs = ref ([] : string list) let isa_filter_filename_dsts = ref ([] : string list) let hol_filter_filenames = ref ([] : (string * string) list) let hol_filter_filename_srcs = ref ([] : string list) let hol_filter_filename_dsts = ref ([] : string list) let lem_filter_filenames = ref ([] : (string * string) list) let lem_filter_filename_srcs = ref ([] : string list) let lem_filter_filename_dsts = ref ([] : string list) let coq_filter_filenames = ref ([] : (string * string) list) let coq_filter_filename_srcs = ref ([] : string list) let coq_filter_filename_dsts = ref ([] : string list) let twf_filter_filenames = ref ([] : (string * string) list) let twf_filter_filename_srcs = ref ([] : string list) let twf_filter_filename_dsts = ref ([] : string list) let caml_filter_filenames = ref ([] : (string * string) list) let caml_filter_filename_srcs = ref ([] : string list) let caml_filter_filename_dsts = ref ([] : string list) let caml_pp_filename = ref (None : string option) let lift_cons_prefixes = ref false let test_parse_list = ref ([] : string list) let sort = ref true let quotient_rules = ref true let generate_aux_rules = ref true let showraw = ref false let tex_show_meta = ref true let tex_show_categories = ref false let tex_suppressed_categories = ref ([]:string list) let tex_suppressed_ntrs = ref ([]:string list) let tex_colour = ref true let tex_wrap = ref true let process_defns = ref true let signal_parse_errors = ref false let ascii_ugly = ref false let show_sort = ref false let show_deps = ref false let show_defns = ref false let isa_syntax = ref false let isa_primrec = ref true let isa_inductive = ref true let isa_generate_lemmas = ref true let coq_avoid = ref 1 let coq_expand_lists = ref false let coq_lngen = ref false let coq_names_in_rules = ref true let coq_use_filter_fn = ref false let merge_fragments = ref false let picky_multiple_parses = ref false let caml_include_terminals = ref false let options = Arg.align [ (* main output stages *) ( "-i", Arg.String (fun s -> i_arguments := true; file_arguments := (In,s) ::(!file_arguments)), "<filename> Input file (can be used multiple times)" ); ( "-o", Arg.String (fun s -> file_arguments := (Out,s) ::(!file_arguments)), "<filename> Output file (can be used multiple times)" ); ( "-writesys", Arg.String (fun s -> match !write_systemdefn_filename_opt with | None -> write_systemdefn_filename_opt := Some s | Some _ -> Auxl.error None "\nError: multiple -writesys <filename> not suppported\n"), "<filename> Output system definition" ); ( "-readsys", Arg.String (fun s -> match !read_systemdefn_filename_opt with | None -> read_systemdefn_filename_opt := Some s | Some _ -> Auxl.error None "\nError: multiple -readsys <filename> not suppported\n"), "<filename> Input system definition" ); (* filter filenames *) ( "-tex_filter", Arg.Tuple[Arg.String (fun s -> tex_filter_filename_srcs := s :: !tex_filter_filename_srcs); Arg.String (fun s -> tex_filter_filename_dsts := s :: !tex_filter_filename_dsts)], "<src><dst> Files to TeX filter" ); ( "-coq_filter", Arg.Tuple[Arg.String (fun s -> coq_filter_filename_srcs := s :: !coq_filter_filename_srcs); Arg.String (fun s -> coq_filter_filename_dsts := s :: !coq_filter_filename_dsts)], "<src><dst> Files to Coq filter" ); ( "-hol_filter", Arg.Tuple[Arg.String (fun s -> hol_filter_filename_srcs := s :: !hol_filter_filename_srcs); Arg.String (fun s -> hol_filter_filename_dsts := s :: !hol_filter_filename_dsts)], "<src><dst> Files to HOL filter" ); ( "-lem_filter", Arg.Tuple[Arg.String (fun s -> lem_filter_filename_srcs := s :: !lem_filter_filename_srcs); Arg.String (fun s -> lem_filter_filename_dsts := s :: !lem_filter_filename_dsts)], "<src><dst> Files to HOL filter" ); ( "-isa_filter", Arg.Tuple[Arg.String (fun s -> isa_filter_filename_srcs := s :: !isa_filter_filename_srcs); Arg.String (fun s -> isa_filter_filename_dsts := s :: !isa_filter_filename_dsts)], "<src><dst> Files to Isabelle filter" ); (* ( "-twelf_filter", *) Arg . Tuple[Arg . String ( fun s - > twf_filter_filename_srcs : = s : : ! twf_filter_filename_srcs ) ; (* Arg.String (fun s -> twf_filter_filename_dsts := s :: !twf_filter_filename_dsts)], *) " < src><dst > Files to Twelf filter " ) ; ( "-ocaml_filter", Arg.Tuple[Arg.String (fun s -> caml_filter_filename_srcs := s :: !caml_filter_filename_srcs); Arg.String (fun s -> caml_filter_filename_dsts := s :: !caml_filter_filename_dsts)], "<src><dst> Files to OCaml filter" ); ( "-merge", Arg.Bool (fun b -> merge_fragments := b), "<"^string_of_bool !merge_fragments ^"> merge grammar and definition rules" ); ( "-parse", Arg.String (fun s -> test_parse_list := !test_parse_list @ [s]), "<string> Test parse symterm,eg \":nontermroot: term\"" ); (* general behaviour *) ( "-fast_parse", Arg.Bool (fun b -> New_term_parser.fast_parse := b), "<"^string_of_bool !New_term_parser.fast_parse^"> do not parse :rulename: pseudoterminals" ); ( "-signal_parse_errors", Arg.Bool (fun b -> signal_parse_errors := b), "<"^string_of_bool !signal_parse_errors^"> return >0 if there are bad defns" ); ( "-picky_multiple_parses", Arg.Bool (fun b -> picky_multiple_parses := b), "<"^string_of_bool !picky_multiple_parses^"> Picky about multiple parses" ); ( "-quotient_rules", Arg.Bool (fun b -> quotient_rules := b), "<"^string_of_bool !quotient_rules^"> Quotient rules, as per {{ quotient-with ntr }} homs" ); ( "-generate_aux_rules", Arg.Bool (fun b -> generate_aux_rules := b), "<"^string_of_bool !generate_aux_rules^"> Generate auxiliary rules or constructor arguments from {{ aux ... }} homs" ); ( "-aux_style_rules", Arg.Bool (fun b -> Global_option.aux_style_rules := b), "<"^string_of_bool !Global_option.aux_style_rules^"> Auxiliary rules (true) vs constructor arguments (false)" ); ( "-output_source_locations", Arg.Int (fun i -> Global_option.output_source_locations := i), "<"^string_of_int !Global_option.output_source_locations^"> Include source location info in output (0=none, 1=drules, 2=grammar+drules)" ); (* options for ascii output *) ( "-colour", Arg.Bool (fun b -> Auxl.colour := b; colour := b), "<"^string_of_bool !colour ^"> Use (vt220) colour for ASCII pretty print" ); ( "-show_sort", Arg.Bool (fun b -> show_sort := b), "<"^string_of_bool !show_sort ^"> Show ASCII pretty print of syntax" ); ( "-show_defns", Arg.Bool (fun b -> show_defns := b), "<"^string_of_bool !show_defns ^"> Show ASCII pretty print defns" ); (* this doesn't seem to work anymore *) (* ( "-lift_cons_prefixes", *) Arg . ( fun b - > lift_cons_prefixes : = b ) , (* "<"^string_of_bool !lift_cons_prefixes^"> Lift constructor prefixes back to rules in ASCII pretty prints" ); *) (* options for tex output *) ( "-tex_show_meta", Arg.Bool (fun b -> tex_show_meta := b), "<"^string_of_bool !tex_show_meta^"> Include meta prods and rules in TeX output" ); ( "-tex_show_categories", Arg.Bool (fun b -> tex_show_categories := b), "<"^string_of_bool !tex_show_categories^"> Signal production flags in TeX output" ); ( "-tex_suppress_category", Arg.String (fun s -> tex_suppressed_categories := s :: !tex_suppressed_categories), "<["^ String.concat "," !tex_suppressed_categories^"]> Suppress productions and rules with this category in TeX output" ); ( "-tex_suppress_ntr", Arg.String (fun s -> tex_suppressed_ntrs := s :: !tex_suppressed_ntrs), "<["^ String.concat "," !tex_suppressed_ntrs^"]> Suppress nonterminal root in TeX output" ); ( "-tex_colour", Arg.Bool (fun b -> tex_colour := b), "<"^string_of_bool !tex_colour^"> Colour parse errors in TeX output" ); ( "-tex_wrap", Arg.Bool (fun b -> tex_wrap := b), "<"^string_of_bool !tex_wrap ^"> Wrap TeX output in document pre/postamble" ); ( "-tex_name_prefix", Arg.String (fun s -> tex_name_prefix := s), "<string> Prefix for tex commands (default \""^ !tex_name_prefix^"\")" ); (* options for isa output *) ( "-isabelle_primrec", Arg.Bool (fun b -> isa_primrec := b), "<"^string_of_bool !isa_primrec ^"> Use \"primrec\" instead of \"fun\"\n for functions" ); ( "-isabelle_inductive", Arg.Bool (fun b -> isa_inductive := b), "<"^string_of_bool !isa_inductive ^"> Use \"inductive\" instead of \"inductive_set\"\n for relations" ); ( "-isa_syntax", Arg.Bool (fun b -> isa_syntax := b), "<"^string_of_bool !isa_syntax ^"> Use fancy syntax in Isabelle output" ); ( "-isa_generate_lemmas", Arg.Bool (fun b -> isa_generate_lemmas := b), "<"^string_of_bool !isa_syntax ^"> Lemmas for collapsed functions in Isabelle" ); (* options for coq output *) ( "-coq_avoid", Arg.Int (fun i -> coq_avoid := i), "<"^string_of_int !coq_avoid^"> coq type-name avoidance\n (0=nothing, 1=avoid, 2=secondaryify)" ); ( "-coq_expand_list_types", Arg.Bool (fun b -> coq_expand_lists := b), "<"^string_of_bool !coq_expand_lists^"> Expand list types in Coq output" ); ( "-coq_lngen", Arg.Bool (fun b -> coq_lngen := b), "<"^string_of_bool !coq_lngen^"> lngen compatibility" ); ( "-coq_names_in_rules", Arg.Bool (fun b -> coq_names_in_rules := b), "<"^string_of_bool !coq_names_in_rules^"> Copy user names in rule definitions" ); ( "-coq_use_filter_fn", Arg.Bool (fun b -> coq_use_filter_fn := b), "<"^string_of_bool !coq_use_filter_fn^"> Use list_filter instead of list_minus2 in substitutions" ); (* options for OCaml output *) ( "-ocaml_include_terminals", Arg.Bool (fun b -> caml_include_terminals := b), "<"^string_of_bool !caml_include_terminals^"> Include terminals in OCaml output (experimental!)" ); ( "-ocaml_pp", Arg.String (fun s -> caml_pp_filename := Some s), " <target.ml filename> generate OCaml AST pretty printer files (experimental!) (also included in .mly target)" ); ( "-ocaml_pp_ast_module", Arg.String (fun s -> Global_option.caml_pp_ast_module := Some s), " override default OCaml module name for AST module (experimental!)" ); ( "-ocaml_pp_json", Arg.Bool (fun b -> Global_option.caml_pp_json := b), "<"^string_of_bool !Global_option.caml_pp_json^"> Include JSON output in pretty printer (experimental)"); (* options for debugging *) ( "-pp_grammar", Arg.Set Global_option.do_pp_grammar, " (debug) print term grammar" ); ( "-dot", Arg.String (fun s -> dot_filename_opt := Some s), "<filename> (debug) dot graph of syntax dependencies" ); ( "-alltt", Arg.String (fun s -> alltt_filename_opt := Some s), "<filename> (debug) alltt output of single source file" ); ( "-sort", Arg.Bool (fun b -> sort := b), "<"^string_of_bool !sort^"> (debug) do topological sort" ); ( "-process_defns", Arg.Bool (fun b -> process_defns := b), "<"^string_of_bool !process_defns^"> (debug) process inductive reln definitions" ); ( "-showraw", Arg.Bool (fun b -> showraw := b), "<"^string_of_bool !showraw ^"> (debug) show raw grammar"); ( "-ugly", Arg.Bool (fun b -> ascii_ugly := b), "<"^string_of_bool !ascii_ugly^"> (debug) use ugly ASCII output" ); ( "-no_rbcatn", Arg.Bool (fun b -> Substs_pp.no_rbcatn := b), "<"^string_of_bool !Substs_pp.no_rbcatn^"> (debug) remove relevant bind clauses" ); ( "-lem_debug", Arg.Bool (fun b -> Types.lem_debug := b), " (debug) print lem debug locations" ); ] let usage_msg = ("\n" ^ "usage: ott <options> <filename1> .. <filenamen> \n" ^ " (use \"OCAMLRUNPARAM=p ott ...\" to show the ocamlyacc trace)\n" ^ " (ott <options> <filename1> .. <filenamen> is equivalent to\n ott -i <filename1> .. -i <filenamen> <options>)\n") let _ = print_string ("Ott version "^Version.n^" distribution of "^Version.d^"\n") let _ = let extra_arguments = ref [] in Arg.parse options (fun s -> if !i_arguments then Auxl.exit_with None "must either use -i <filename> or specify all input filenames at the end of the command line" else extra_arguments := (In,s) ::(!extra_arguments)) usage_msg; file_arguments := !file_arguments @ !extra_arguments let _ = tex_filter_filenames := List.combine (!tex_filter_filename_srcs) (!tex_filter_filename_dsts) let _ = hol_filter_filenames := List.combine (!hol_filter_filename_srcs) (!hol_filter_filename_dsts) let _ = lem_filter_filenames := List.combine (!lem_filter_filename_srcs) (!lem_filter_filename_dsts) let _ = isa_filter_filenames := List.combine (!isa_filter_filename_srcs) (!isa_filter_filename_dsts) let _ = coq_filter_filenames := List.combine (!coq_filter_filename_srcs) (!coq_filter_filename_dsts) let _ = twf_filter_filenames := List.combine (!twf_filter_filename_srcs) (!twf_filter_filename_dsts) let _ = caml_filter_filenames := List.combine (!caml_filter_filename_srcs) (!caml_filter_filename_dsts) let types_of_extensions = [ "ott","ott"; "tex","tex"; "v", "coq"; "thy","isa"; "sml","hol"; "lem","lem"; "twf","twf"; "ml", "ocaml"; "mll", "lex"; "mly", "menhir"] let extension_of_type t = List.assoc t (List.map (function (a,b)->(b,a)) types_of_extensions) let file_type name = try Some (List.assoc (let start = 1+String.length (Filename.chop_extension name) in String.sub name start (String.length name - start) ) types_of_extensions) with _ -> None let non_tex_output_types = ["coq"; "isa"; "hol"; "lem"; "twf"; "ocaml"] let output_types = "tex" :: "lex" :: "menhir" :: non_tex_output_types let input_types = "ott" :: output_types let classify_file_argument arg = match arg with | (In,name) -> (match file_type name with | Some e when (List.mem e input_types) -> (In,e,name) | _ -> Auxl.error None ("\nError: unrecognised extension of input file \""^name ^ "\" (must be one of " ^ String.concat "," (List.map extension_of_type input_types) ^")\n")) | (Out,name) -> (match file_type name with | Some e when (List.mem e output_types) -> (Out,e,name) | _ -> Auxl.error None ("\nError: unrecognised extension of output file \""^name ^ "\" (must be one of "^String.concat "," (List.map extension_of_type output_types) ^")\n")) (* all_file_arguments collects together a list of *) (* *) (* (In,filetype,filename) *) (* (Out,filetype,filename) *) (* *) values , containing first all the ott source files from the end of (* the command line, if any, then all the explicit -in and -out arguments, *) (* and finally any -tex/-coq/-hol/-isabelle/-lem/-ocaml arguments *) let all_file_arguments = List.map classify_file_argument (List.rev (!file_arguments)) (* collect the proof assistant targets *) let targets_in ts = List.filter (function t -> List.mem t ts) (Auxl.remove_duplicates (Auxl.option_map (function x -> match x with | (Out,t,_) -> Some t | _ -> None) all_file_arguments)) let targets_non_tex = targets_in non_tex_output_types let targets = targets_in output_types let targets_for_non_picky = targets_in [(*"lex";"ocaml";*)"hol";"lem";"isa";"twf";"coq";"tex"] (* collect the source filenames *) let source_filenames = Auxl.option_map (function x -> match x with | In,t,n -> Some (t,n) | Out,_,_ -> None) all_file_arguments let _ = if false then print_string ("source_filenames = "^String.concat ", " (List.map (function (t,n) -> n^":"^t) source_filenames)^"\n") (* pp modes, used both for main output and for filtered files *) let m_ascii = Ascii { ppa_colour = !colour; ppa_lift_cons_prefixes = false; ppa_ugly= !ascii_ugly; ppa_show_deps = !show_deps; ppa_show_defns = !show_defns } let m_tex = Tex {ppt_colour= !tex_colour; ppt_show_meta= !tex_show_meta; ppt_show_categories= !tex_show_categories; ppt_suppressed_categories= !tex_suppressed_categories; ppt_suppressed_ntrs= !tex_suppressed_ntrs; ppt_wrap= !tex_wrap; ppt_name_prefix= !tex_name_prefix } let m_isa = Isa { ppi_isa_primrec = !isa_primrec; ppi_isa_inductive = !isa_inductive; isa_library = ref ("",[]); ppi_fancy_syntax = !isa_syntax; ppi_generate_lemmas = !isa_generate_lemmas } let m_hol = Hol { hol_library = ref ("",[]); } let m_lem = Lem { lem_library = ref ("",[]); } let m_twf = Twf { twf_current_defn = ref ""; twf_library = ref ("",[]) } let m_coq = Coq { coq_expand_lists = !coq_expand_lists; coq_quantified_vars_from_de = ref []; coq_non_local_hyp_defn = ref ""; coq_non_local_hyp_defn_vars = ref []; coq_list_types = ref []; coq_list_aux_funcs = Some (ref ""); coq_list_aux_defns = { defined = ref []; newly_defined = ref [] }; coq_library = ref ("",[]); coq_locally_nameless = ref false; coq_lngen = !coq_lngen; coq_use_filter_fn = !coq_use_filter_fn; coq_names_in_rules = !coq_names_in_rules } let oo = { ppo_include_terminals = !caml_include_terminals; caml_library = ref ("",[]) } let m_caml = Caml oo (* collect the target ocaml filenames *) let target_ocaml_ast_module = if List.exists (function x -> match x with | Out,"menhir",n -> true | _,_,_ -> false) all_file_arguments then let target_ocaml_filenames = Auxl.option_map (function x -> match x with | Out,"ocaml",n -> Some n | _,_,_ -> None) all_file_arguments in match target_ocaml_filenames with | [n] -> String.capitalize_ascii (Filename.chop_extension n) | _ -> Auxl.error None "\n if there is a menhir output file, there must be exactly one ocaml output file" else "" let target_ocaml_parser_module = if List.exists (function x -> match x with | Out,"lex",n -> true | _,_,_ -> false) all_file_arguments then let target_menhir_filenames = Auxl.option_map (function x -> match x with | Out,"menhir",n -> Some n | _,_,_ -> None) all_file_arguments in match target_menhir_filenames with | [n] -> String.capitalize_ascii (Filename.chop_extension n) | _ -> Auxl.error None "\n if there is an ocamllex output file, there must be exactly one menhir output file" else "" let yo = { ppm_show_meta= false; (*!tex_show_meta;*) ppm_suppressed_categories= !tex_suppressed_categories; ppm_suppressed_ntrs= !tex_suppressed_ntrs; ppm_caml_opts = oo; ppm_caml_ast_module = target_ocaml_ast_module; ppm_caml_parser_module = target_ocaml_parser_module; } let m_menhir = Menhir yo let m_lex = Lex yo let reset_m_coq m = match m with | Coq co -> co.coq_non_local_hyp_defn := ""; co.coq_non_local_hyp_defn_vars := []; co.coq_list_types := []; Auxl.the (co.coq_list_aux_funcs) := ""; co.coq_list_aux_defns.defined := []; co.coq_list_aux_defns.newly_defined := []; co.coq_library := ("",[]); co.coq_locally_nameless := false | _ -> Auxl.errorm m "reset_m_coq" let m_caml = Caml { ppo_include_terminals = !caml_include_terminals; caml_library = ref ("",[]) } finally compute the set of modes used in this run of -- used when non - picky about multiple parses when non-picky about multiple parses *) here we used also to record the suffix - stripped filenames for hol and isa , for the non - picky checking , but now we feed dummy filenames into the m _ ... functions and isa, for the non-picky checking, but now we feed dummy filenames into the m_... functions *) let _ = Global_option.is_picky := ( !picky_multiple_parses, List.map (function t -> List.assoc t [(* "ocaml",m_caml; *) "hol",m_hol; "lem",m_lem; "isa",m_isa; "twf",m_twf; "coq",m_coq ; "tex",m_tex ]) targets_for_non_picky) (* process *) let process source_filenames = let sources = String.concat " " (List.map snd source_filenames) in (match !alltt_filename_opt,source_filenames with | None,_ -> () | Some alltt_filename,([] | _::_::_) -> Auxl.error None ("\nUsage: -alltt option can only be used with exactly one source file at a time\n"); | Some alltt_filename,[(source_filetype,source_filename)] -> let c = open_in source_filename in let c' = open_out alltt_filename in output_string c' "\\begin{alltt}\n"; let lexbuf = Lexing.from_channel c in let lexer = Grammar_lexer.my_lexer false Grammar_lexer.metalang in let rec process_input () = try let t = lexer lexbuf in match t with | Grammar_parser.EOF -> () | _ -> print_string (Grammar_lexer.de_lex_ascii t); flush stdout; output_string c' (Grammar_lexer.de_lex_tex t); flush c'; process_input () with My_parse_error (loc, s)-> Auxl.error loc (s) in process_input (); output_string c' "\\end{alltt}\n"; let _ = close_in c in let _ = close_out c' in ()); let parse_file (filetype,filename) = match filetype with | "ott" -> let c = open_in filename in let lexbuf = Lexing.from_channel c in if < > 1 then lexbuf.Lexing.lex_curr_p <- { lexbuf.Lexing.lex_curr_p with Lexing.pos_fname = filename}; let ris = (try Grammar_parser.main (Grammar_lexer.my_lexer true Grammar_lexer.metalang) lexbuf with My_parse_error (loc,s)-> (* Auxl.error ("\n"^s^" in file: "^filter_filename^"\n") in*) Auxl.error loc ("\n"^s^"\n")) in let _ = close_in c in ris | _ -> let s = Auxl.string_of_filename filename in let loc = Location.loc_of_filename filename (String.length s) in [Raw_item_embed [ (loc,filetype, [Embed_string(loc,s)])]] in let document = List.map parse_file source_filenames in if !showraw then ( let s = (String.concat "\n" (List.map (fun document_part -> String.concat "" (List.map Grammar_pp.pp_raw_item document_part)) document)) in let fd = open_out " test2.txt " in (* output_string fd s ; *) (* close_out fd; *) print_string s); (* if we're generating a parser, then construct the quotiented and unquotiented syntax, otherwise just generate the one asked for on the command line *) the unquotiented syntax , which is the one we 'll generate menhir rules from , should be without generated aux rules . rules from, should be without generated aux rules. *) (* the quotiented syntax, used to generate the OCaml types, should be with generated aux rules *) the quotiented un - auxed syntax , used to generate the pp functions , should be without the generated aux rules let f quotient generate_aux = try Grammar_typecheck.check_and_disambiguate m_tex quotient generate_aux targets_non_tex (List.map snd source_filenames) (!merge_fragments) document with | Typecheck_error (loc,s1,s2) -> Auxl.error (Some loc) ("(in checking and disambiguating "^(if quotient then "quotiented " else "") ^ "syntax)\n"^s1 ^ (if s2<>"" then " ("^s2^")" else "") ^ "\n") in let ((xd,structure,rdcs),xd_unquotiented,xd_quotiented_unaux) = if List.mem "menhir" targets (*|| !caml_pp_filename <> None*) then (f true !generate_aux_rules, (match f false false with (xd,_,_)-> xd), (match f !generate_aux_rules false with (xd,_,_)-> xd)) else match f !quotient_rules !generate_aux_rules with two dummies , unused in if !show_sort then ( print_endline "********** AFTER CHECK, DISAMBIGUATE AND SORT *********************\n"; print_endline (Grammar_pp.pp_syntaxdefn m_ascii xd)); FZ sorting is now performed while checking and disambiguate (* let xd = *) (* try *) (* Grammar_typecheck.sort_syntaxdefn xd structure targets *) (* with *) | Grammar_typecheck . Typecheck_error ( s,_)- > Auxl.error ( " \nError sorting the grammar:\n"^s^"\n " ) (* in *) if ! show_post_sort then ( (* print_endline "********** AFTER SORTING *********************\n"; *) (* print_endline (Grammar_pp.pp_syntaxdefn m_ascii xd)); *) (* make parser for symbolic terms *) let lookup = Term_parser.make_parser xd in begin try Grammar_typecheck.check_with_parser lookup xd with | Typecheck_error (loc,s1,s2) -> Auxl.error (Some loc) ("(in checking syntax)\n"^s1 ^ (if s2<>"" then " ("^s2^")\n" else "\n")) end; let sd = if !process_defns then (if !show_defns then (print_endline "********** PROCESSING DEFINITIONS *****************\n"; flush stdout); try let dcs = Defns.process_raw_defnclasss m_ascii xd lookup rdcs in let sd = { syntax = xd; relations = dcs; structure = structure; sources = sources} in sd with | Defns.Rule_parse_error (loc,s) -> Auxl.error (Some loc) ("\nError in processing definitions:\n"^s^"\n") | Bounds.Bounds (loc,s) | Typecheck_error (loc,s,_)-> Auxl.error (Some loc) ("\nError in processing definitions:\n"^s^"\n") ) else (print_endline "********** NOT PROCESSING DEFINITIONS *************\n"; flush stdout; let sd = { syntax = xd; relations = []; structure = structure; sources = sources} in sd) in let sd_unquotiented = { syntax = xd_unquotiented; relations = []; structure = structure; sources = sources} in let sd_quotiented_unaux = { syntax = xd_quotiented_unaux; relations = []; structure = structure; sources = sources} in sd,lookup,sd_unquotiented,sd_quotiented_unaux let read_systemdefn read_systemdefn_filename = let fd = open_in_bin read_systemdefn_filename in let sd,lookup ,sd_unquotiented, sd_quotiented_unaux = try Marshal.from_channel fd with Failure s -> Auxl.error None ("Cannot read dumped systemdefn\n " ^ s ^"\n") in close_in fd; sd,lookup,sd_unquotiented,sd_quotiented_unaux let output_stage (sd,lookup,sd_unquotiented,sd_quotiented_unaux) = * output of systemdefn ( match !write_systemdefn_filename_opt with | None -> () | Some s -> let fd = open_out_bin s in Marshal.to_channel fd (sd,lookup,sd_unquotiented) [Marshal.Closures]; close_out fd; print_string ("system definition in file: " ^ s ^ "\n") ); (** dot output of dependencies *) ( match !dot_filename_opt with | None -> () | Some s -> let fd = open_out s in output_string fd (Grammar_pp.pp_dot_dep_graph pp_ascii_opts_default sd.syntax); close_out fd; print_string ("dot version in file: " ^ s ^ "\n") ); (* for each target, compute the o/is informations *) let output_details = (* for each -o target *) (* collect the output file names, and for each output file name, collect the -i it depends on *) let sources_per_target = List.map (fun t -> (t, Auxl.option_map (fun (d,ft,fn) -> match d with | In -> Some (d,ft,fn) | Out -> if String.compare ft t = 0 then Some (d,ft,fn) else None) all_file_arguments)) targets in let rec compute_output ib a = match a with | [] -> [] | (In,ft,fn)::xs -> compute_output (fn::ib) xs | (Out,ft,fn)::xs -> ( if ib = [] then Auxl.warning None ("warning: no input files for the output file: "^fn^".\n"); (fn,ib)::(compute_output [] xs)) in List.map (fun (t,fs) -> t, compute_output [] fs) sources_per_target in (** target outputs *) List.iter (fun (t,fi) -> match t with | "tex" -> System_pp.pp_systemdefn_core_tex m_tex sd lookup fi | "coq" -> let sd = ( match !coq_avoid with | 0 -> sd | 1 -> Auxl.avoid_primaries_systemdefn false sd | 2 -> Auxl.avoid_primaries_systemdefn true sd | _ -> Auxl.error None "coq type-name avoidance must be in {0,1,2}" ) in System_pp.pp_systemdefn_core_io m_coq sd lookup fi !merge_fragments | "isa" -> System_pp.pp_systemdefn_core_io m_isa sd lookup fi !merge_fragments | "hol" -> System_pp.pp_systemdefn_core_io m_hol sd lookup fi !merge_fragments | "lem" -> System_pp.pp_systemdefn_core_io m_lem sd lookup fi !merge_fragments | "twf" -> System_pp.pp_systemdefn_core_io m_twf sd lookup fi !merge_fragments | "ocaml" -> System_pp.pp_systemdefn_core_io m_caml (Auxl.caml_rename sd) lookup fi !merge_fragments | "lex" -> Lex_menhir_pp.pp_lex_systemdefn m_lex (Auxl.caml_rename sd) fi | "menhir" -> let sd_quotiented = Auxl.caml_rename sd in let sd_unquotiented = Auxl.caml_rename sd_unquotiented in let xd_quotiented = sd.syntax in let xd_unquotiented = sd_unquotiented.syntax in let xd_quotiented_unaux = sd_quotiented_unaux.syntax in (Lex_menhir_pp.pp_menhir_syntaxdefn m_menhir sd.sources xd_quotiented xd_unquotiented lookup !generate_aux_rules fi; Lex_menhir_pp.pp_pp_syntaxdefn m_menhir sd.sources xd_quotiented xd_unquotiented xd_quotiented_unaux !generate_aux_rules true fi "") | _ -> Auxl.int_error("unknown target "^t)) output_details; (** experimental ocaml pp output, in isolation (it's also included in the .mly output *) begin match !caml_pp_filename with | None -> () | Some filename -> let sd_quotiented = Auxl.caml_rename sd in let sd_unquotiented = Auxl.caml_rename sd_unquotiented in let xd_quotiented = sd.syntax in let xd_unquotiented = sd_unquotiented.syntax in let xd_quotiented_unaux = sd_quotiented_unaux.syntax in ( Lex_menhir_pp.pp_menhir_syntaxdefn m_menhir sd.sources xd_quotiented xd_unquotiented lookup ! generate_aux_rules fi ; Lex_menhir_pp.pp_pp_syntaxdefn m_menhir sd.sources xd_quotiented xd_unquotiented xd_quotiented_unaux (!generate_aux_rules && not !Global_option.aux_style_rules) false [] filename end; (** command-line test parse *) (match !test_parse_list with [] -> ()|_ -> print_string "\n"); (List.iter (function s -> print_string ("test parse: string \""^s^"\"\n"); let r = Str.regexp (Str.quote ":" ^ "\\(" ^ Term_parser.ident_string ^"\\)"^ Str.quote ":" ^ "\\(.*\\)") in if (Str.string_match r s 0 && Str.match_end () = String.length s) then let ntr = Str.matched_group 1 s in let term = Str.matched_group 4 s in let (ntr, concrete) = if Str.string_match (Str.regexp "concrete_") ntr 0 then (Str.string_after ntr 9, true) else (ntr, false) in print_string ("test parse: "^ntr^" \""^term^"\"\n"); Term_parser.test_parse m_ascii sd.syntax ntr concrete term; print_string "\n" else print_string ("test parse: string "^s ^" not of the required :ntr:term form\n")) !test_parse_list); (** filtering other files *) let filter m (src_filename,dst_filename) = let fd_src = open_in src_filename in let fd_dst = open_out dst_filename in let lexbuf = Lexing.from_channel fd_src in lexbuf.Lexing.lex_curr_p <- { lexbuf.Lexing.lex_curr_p with Lexing.pos_fname = src_filename}; let unfiltered_document = try Grammar_parser.unfiltered_spec_el_list (Grammar_lexer.my_lexer true Grammar_lexer.filter) lexbuf with | Parsing.Parse_error -> Auxl.error None ("unfiltered document "^src_filename^" cannot be parsed\n") | My_parse_error (loc,s) -> Auxl.error loc s in Embed_pp.pp_embed_spec fd_dst m sd.syntax lookup (Auxl.collapse_embed_spec_el_list unfiltered_document); let _ = close_in fd_src in let _ = close_out fd_dst in () in (List.iter (filter m_tex) (!tex_filter_filenames)); (List.iter (filter m_coq) (!coq_filter_filenames)); (List.iter (filter m_isa) (!isa_filter_filenames)); (List.iter (filter m_hol) (!hol_filter_filenames)); (List.iter (filter m_lem) (!lem_filter_filenames)); (List.iter (filter m_twf) (!twf_filter_filenames)); (List.iter (filter m_caml) (!caml_filter_filenames)); let xd , targets document in if !process_defns then begin let bad, msg = Defns.pp_counts sd in print_string msg; if bad && !signal_parse_errors then exit 1 end; () set GC parameters to reasonable values let _ = Gc.set { (Gc.get()) with 8/16 MB in 32/64bit machines 40/80 MB in 32/64bit machines let _ = try ( match source_filenames, !read_systemdefn_filename_opt with | (_::_),None -> let (sd,lookup,sd_unquotiented,sd_quotiented_unaux) = process source_filenames in output_stage (sd,lookup,sd_unquotiented,sd_quotiented_unaux) | [], Some s -> let (sd,lookup,sd_unquotiented,sd_quotiented_unaux) = read_systemdefn s in output_stage (sd,lookup,sd_unquotiented,sd_quotiented_unaux) | [],None -> Arg.usage options usage_msg; Auxl.error None "\nError: must specify either some source filenames or a readsys option\n" | (_::_),Some _ -> Auxl.error None "\nError: must not specify both source filenames and a readsys option\n" ) with | Auxl.Located_Failure (l, s) -> Auxl.exit_with l s
null
https://raw.githubusercontent.com/ott-lang/ott/bd89321aeb74a1d35e9e6462486855fedd9e6064/src/main.ml
ocaml
************************************************************************ Ott Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: notice, this list of conditions and the following disclaimer. notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. products derived from this software without specific prior written permission. OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ************************************************************************ command-line options main output stages filter filenames ( "-twelf_filter", Arg.String (fun s -> twf_filter_filename_dsts := s :: !twf_filter_filename_dsts)], general behaviour options for ascii output this doesn't seem to work anymore ( "-lift_cons_prefixes", "<"^string_of_bool !lift_cons_prefixes^"> Lift constructor prefixes back to rules in ASCII pretty prints" ); options for tex output options for isa output options for coq output options for OCaml output options for debugging all_file_arguments collects together a list of (In,filetype,filename) (Out,filetype,filename) the command line, if any, then all the explicit -in and -out arguments, and finally any -tex/-coq/-hol/-isabelle/-lem/-ocaml arguments collect the proof assistant targets "lex";"ocaml"; collect the source filenames pp modes, used both for main output and for filtered files collect the target ocaml filenames !tex_show_meta; "ocaml",m_caml; process Auxl.error ("\n"^s^" in file: "^filter_filename^"\n") in output_string fd s ; close_out fd; if we're generating a parser, then construct the quotiented and unquotiented syntax, otherwise just generate the one asked for on the command line the quotiented syntax, used to generate the OCaml types, should be with generated aux rules || !caml_pp_filename <> None let xd = try Grammar_typecheck.sort_syntaxdefn xd structure targets with in print_endline "********** AFTER SORTING *********************\n"; print_endline (Grammar_pp.pp_syntaxdefn m_ascii xd)); make parser for symbolic terms * dot output of dependencies for each target, compute the o/is informations for each -o target collect the output file names, and for each output file name, collect the -i it depends on * target outputs * experimental ocaml pp output, in isolation (it's also included in the .mly output * command-line test parse * filtering other files
, Computer Laboratory , University of Cambridge , project , INRIA Rocquencourt Copyright 2005 - 2010 1 . Redistributions of source code must retain the above copyright 2 . Redistributions in binary form must reproduce the above copyright 3 . The names of the authors may not be used to endorse or promote THIS SOFTWARE IS PROVIDED BY THE AUTHORS ` ` AS IS '' AND ANY EXPRESS ARE DISCLAIMED . IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER open Location open Types let colour = ref true let file_arguments = ref ([]:(file_argument*string) list) let i_arguments = ref false let dot_filename_opt = ref (None : string option) let alltt_filename_opt = ref (None : string option) let write_systemdefn_filename_opt = ref (None : string option) let read_systemdefn_filename_opt = ref (None : string option) let tex_name_prefix = ref "ott" let tex_filter_filenames = ref ([] : (string * string) list) let tex_filter_filename_srcs = ref ([] : string list) let tex_filter_filename_dsts = ref ([] : string list) let isa_filter_filenames = ref ([] : (string * string) list) let isa_filter_filename_srcs = ref ([] : string list) let isa_filter_filename_dsts = ref ([] : string list) let hol_filter_filenames = ref ([] : (string * string) list) let hol_filter_filename_srcs = ref ([] : string list) let hol_filter_filename_dsts = ref ([] : string list) let lem_filter_filenames = ref ([] : (string * string) list) let lem_filter_filename_srcs = ref ([] : string list) let lem_filter_filename_dsts = ref ([] : string list) let coq_filter_filenames = ref ([] : (string * string) list) let coq_filter_filename_srcs = ref ([] : string list) let coq_filter_filename_dsts = ref ([] : string list) let twf_filter_filenames = ref ([] : (string * string) list) let twf_filter_filename_srcs = ref ([] : string list) let twf_filter_filename_dsts = ref ([] : string list) let caml_filter_filenames = ref ([] : (string * string) list) let caml_filter_filename_srcs = ref ([] : string list) let caml_filter_filename_dsts = ref ([] : string list) let caml_pp_filename = ref (None : string option) let lift_cons_prefixes = ref false let test_parse_list = ref ([] : string list) let sort = ref true let quotient_rules = ref true let generate_aux_rules = ref true let showraw = ref false let tex_show_meta = ref true let tex_show_categories = ref false let tex_suppressed_categories = ref ([]:string list) let tex_suppressed_ntrs = ref ([]:string list) let tex_colour = ref true let tex_wrap = ref true let process_defns = ref true let signal_parse_errors = ref false let ascii_ugly = ref false let show_sort = ref false let show_deps = ref false let show_defns = ref false let isa_syntax = ref false let isa_primrec = ref true let isa_inductive = ref true let isa_generate_lemmas = ref true let coq_avoid = ref 1 let coq_expand_lists = ref false let coq_lngen = ref false let coq_names_in_rules = ref true let coq_use_filter_fn = ref false let merge_fragments = ref false let picky_multiple_parses = ref false let caml_include_terminals = ref false let options = Arg.align [ ( "-i", Arg.String (fun s -> i_arguments := true; file_arguments := (In,s) ::(!file_arguments)), "<filename> Input file (can be used multiple times)" ); ( "-o", Arg.String (fun s -> file_arguments := (Out,s) ::(!file_arguments)), "<filename> Output file (can be used multiple times)" ); ( "-writesys", Arg.String (fun s -> match !write_systemdefn_filename_opt with | None -> write_systemdefn_filename_opt := Some s | Some _ -> Auxl.error None "\nError: multiple -writesys <filename> not suppported\n"), "<filename> Output system definition" ); ( "-readsys", Arg.String (fun s -> match !read_systemdefn_filename_opt with | None -> read_systemdefn_filename_opt := Some s | Some _ -> Auxl.error None "\nError: multiple -readsys <filename> not suppported\n"), "<filename> Input system definition" ); ( "-tex_filter", Arg.Tuple[Arg.String (fun s -> tex_filter_filename_srcs := s :: !tex_filter_filename_srcs); Arg.String (fun s -> tex_filter_filename_dsts := s :: !tex_filter_filename_dsts)], "<src><dst> Files to TeX filter" ); ( "-coq_filter", Arg.Tuple[Arg.String (fun s -> coq_filter_filename_srcs := s :: !coq_filter_filename_srcs); Arg.String (fun s -> coq_filter_filename_dsts := s :: !coq_filter_filename_dsts)], "<src><dst> Files to Coq filter" ); ( "-hol_filter", Arg.Tuple[Arg.String (fun s -> hol_filter_filename_srcs := s :: !hol_filter_filename_srcs); Arg.String (fun s -> hol_filter_filename_dsts := s :: !hol_filter_filename_dsts)], "<src><dst> Files to HOL filter" ); ( "-lem_filter", Arg.Tuple[Arg.String (fun s -> lem_filter_filename_srcs := s :: !lem_filter_filename_srcs); Arg.String (fun s -> lem_filter_filename_dsts := s :: !lem_filter_filename_dsts)], "<src><dst> Files to HOL filter" ); ( "-isa_filter", Arg.Tuple[Arg.String (fun s -> isa_filter_filename_srcs := s :: !isa_filter_filename_srcs); Arg.String (fun s -> isa_filter_filename_dsts := s :: !isa_filter_filename_dsts)], "<src><dst> Files to Isabelle filter" ); Arg . Tuple[Arg . String ( fun s - > twf_filter_filename_srcs : = s : : ! twf_filter_filename_srcs ) ; " < src><dst > Files to Twelf filter " ) ; ( "-ocaml_filter", Arg.Tuple[Arg.String (fun s -> caml_filter_filename_srcs := s :: !caml_filter_filename_srcs); Arg.String (fun s -> caml_filter_filename_dsts := s :: !caml_filter_filename_dsts)], "<src><dst> Files to OCaml filter" ); ( "-merge", Arg.Bool (fun b -> merge_fragments := b), "<"^string_of_bool !merge_fragments ^"> merge grammar and definition rules" ); ( "-parse", Arg.String (fun s -> test_parse_list := !test_parse_list @ [s]), "<string> Test parse symterm,eg \":nontermroot: term\"" ); ( "-fast_parse", Arg.Bool (fun b -> New_term_parser.fast_parse := b), "<"^string_of_bool !New_term_parser.fast_parse^"> do not parse :rulename: pseudoterminals" ); ( "-signal_parse_errors", Arg.Bool (fun b -> signal_parse_errors := b), "<"^string_of_bool !signal_parse_errors^"> return >0 if there are bad defns" ); ( "-picky_multiple_parses", Arg.Bool (fun b -> picky_multiple_parses := b), "<"^string_of_bool !picky_multiple_parses^"> Picky about multiple parses" ); ( "-quotient_rules", Arg.Bool (fun b -> quotient_rules := b), "<"^string_of_bool !quotient_rules^"> Quotient rules, as per {{ quotient-with ntr }} homs" ); ( "-generate_aux_rules", Arg.Bool (fun b -> generate_aux_rules := b), "<"^string_of_bool !generate_aux_rules^"> Generate auxiliary rules or constructor arguments from {{ aux ... }} homs" ); ( "-aux_style_rules", Arg.Bool (fun b -> Global_option.aux_style_rules := b), "<"^string_of_bool !Global_option.aux_style_rules^"> Auxiliary rules (true) vs constructor arguments (false)" ); ( "-output_source_locations", Arg.Int (fun i -> Global_option.output_source_locations := i), "<"^string_of_int !Global_option.output_source_locations^"> Include source location info in output (0=none, 1=drules, 2=grammar+drules)" ); ( "-colour", Arg.Bool (fun b -> Auxl.colour := b; colour := b), "<"^string_of_bool !colour ^"> Use (vt220) colour for ASCII pretty print" ); ( "-show_sort", Arg.Bool (fun b -> show_sort := b), "<"^string_of_bool !show_sort ^"> Show ASCII pretty print of syntax" ); ( "-show_defns", Arg.Bool (fun b -> show_defns := b), "<"^string_of_bool !show_defns ^"> Show ASCII pretty print defns" ); Arg . ( fun b - > lift_cons_prefixes : = b ) , ( "-tex_show_meta", Arg.Bool (fun b -> tex_show_meta := b), "<"^string_of_bool !tex_show_meta^"> Include meta prods and rules in TeX output" ); ( "-tex_show_categories", Arg.Bool (fun b -> tex_show_categories := b), "<"^string_of_bool !tex_show_categories^"> Signal production flags in TeX output" ); ( "-tex_suppress_category", Arg.String (fun s -> tex_suppressed_categories := s :: !tex_suppressed_categories), "<["^ String.concat "," !tex_suppressed_categories^"]> Suppress productions and rules with this category in TeX output" ); ( "-tex_suppress_ntr", Arg.String (fun s -> tex_suppressed_ntrs := s :: !tex_suppressed_ntrs), "<["^ String.concat "," !tex_suppressed_ntrs^"]> Suppress nonterminal root in TeX output" ); ( "-tex_colour", Arg.Bool (fun b -> tex_colour := b), "<"^string_of_bool !tex_colour^"> Colour parse errors in TeX output" ); ( "-tex_wrap", Arg.Bool (fun b -> tex_wrap := b), "<"^string_of_bool !tex_wrap ^"> Wrap TeX output in document pre/postamble" ); ( "-tex_name_prefix", Arg.String (fun s -> tex_name_prefix := s), "<string> Prefix for tex commands (default \""^ !tex_name_prefix^"\")" ); ( "-isabelle_primrec", Arg.Bool (fun b -> isa_primrec := b), "<"^string_of_bool !isa_primrec ^"> Use \"primrec\" instead of \"fun\"\n for functions" ); ( "-isabelle_inductive", Arg.Bool (fun b -> isa_inductive := b), "<"^string_of_bool !isa_inductive ^"> Use \"inductive\" instead of \"inductive_set\"\n for relations" ); ( "-isa_syntax", Arg.Bool (fun b -> isa_syntax := b), "<"^string_of_bool !isa_syntax ^"> Use fancy syntax in Isabelle output" ); ( "-isa_generate_lemmas", Arg.Bool (fun b -> isa_generate_lemmas := b), "<"^string_of_bool !isa_syntax ^"> Lemmas for collapsed functions in Isabelle" ); ( "-coq_avoid", Arg.Int (fun i -> coq_avoid := i), "<"^string_of_int !coq_avoid^"> coq type-name avoidance\n (0=nothing, 1=avoid, 2=secondaryify)" ); ( "-coq_expand_list_types", Arg.Bool (fun b -> coq_expand_lists := b), "<"^string_of_bool !coq_expand_lists^"> Expand list types in Coq output" ); ( "-coq_lngen", Arg.Bool (fun b -> coq_lngen := b), "<"^string_of_bool !coq_lngen^"> lngen compatibility" ); ( "-coq_names_in_rules", Arg.Bool (fun b -> coq_names_in_rules := b), "<"^string_of_bool !coq_names_in_rules^"> Copy user names in rule definitions" ); ( "-coq_use_filter_fn", Arg.Bool (fun b -> coq_use_filter_fn := b), "<"^string_of_bool !coq_use_filter_fn^"> Use list_filter instead of list_minus2 in substitutions" ); ( "-ocaml_include_terminals", Arg.Bool (fun b -> caml_include_terminals := b), "<"^string_of_bool !caml_include_terminals^"> Include terminals in OCaml output (experimental!)" ); ( "-ocaml_pp", Arg.String (fun s -> caml_pp_filename := Some s), " <target.ml filename> generate OCaml AST pretty printer files (experimental!) (also included in .mly target)" ); ( "-ocaml_pp_ast_module", Arg.String (fun s -> Global_option.caml_pp_ast_module := Some s), " override default OCaml module name for AST module (experimental!)" ); ( "-ocaml_pp_json", Arg.Bool (fun b -> Global_option.caml_pp_json := b), "<"^string_of_bool !Global_option.caml_pp_json^"> Include JSON output in pretty printer (experimental)"); ( "-pp_grammar", Arg.Set Global_option.do_pp_grammar, " (debug) print term grammar" ); ( "-dot", Arg.String (fun s -> dot_filename_opt := Some s), "<filename> (debug) dot graph of syntax dependencies" ); ( "-alltt", Arg.String (fun s -> alltt_filename_opt := Some s), "<filename> (debug) alltt output of single source file" ); ( "-sort", Arg.Bool (fun b -> sort := b), "<"^string_of_bool !sort^"> (debug) do topological sort" ); ( "-process_defns", Arg.Bool (fun b -> process_defns := b), "<"^string_of_bool !process_defns^"> (debug) process inductive reln definitions" ); ( "-showraw", Arg.Bool (fun b -> showraw := b), "<"^string_of_bool !showraw ^"> (debug) show raw grammar"); ( "-ugly", Arg.Bool (fun b -> ascii_ugly := b), "<"^string_of_bool !ascii_ugly^"> (debug) use ugly ASCII output" ); ( "-no_rbcatn", Arg.Bool (fun b -> Substs_pp.no_rbcatn := b), "<"^string_of_bool !Substs_pp.no_rbcatn^"> (debug) remove relevant bind clauses" ); ( "-lem_debug", Arg.Bool (fun b -> Types.lem_debug := b), " (debug) print lem debug locations" ); ] let usage_msg = ("\n" ^ "usage: ott <options> <filename1> .. <filenamen> \n" ^ " (use \"OCAMLRUNPARAM=p ott ...\" to show the ocamlyacc trace)\n" ^ " (ott <options> <filename1> .. <filenamen> is equivalent to\n ott -i <filename1> .. -i <filenamen> <options>)\n") let _ = print_string ("Ott version "^Version.n^" distribution of "^Version.d^"\n") let _ = let extra_arguments = ref [] in Arg.parse options (fun s -> if !i_arguments then Auxl.exit_with None "must either use -i <filename> or specify all input filenames at the end of the command line" else extra_arguments := (In,s) ::(!extra_arguments)) usage_msg; file_arguments := !file_arguments @ !extra_arguments let _ = tex_filter_filenames := List.combine (!tex_filter_filename_srcs) (!tex_filter_filename_dsts) let _ = hol_filter_filenames := List.combine (!hol_filter_filename_srcs) (!hol_filter_filename_dsts) let _ = lem_filter_filenames := List.combine (!lem_filter_filename_srcs) (!lem_filter_filename_dsts) let _ = isa_filter_filenames := List.combine (!isa_filter_filename_srcs) (!isa_filter_filename_dsts) let _ = coq_filter_filenames := List.combine (!coq_filter_filename_srcs) (!coq_filter_filename_dsts) let _ = twf_filter_filenames := List.combine (!twf_filter_filename_srcs) (!twf_filter_filename_dsts) let _ = caml_filter_filenames := List.combine (!caml_filter_filename_srcs) (!caml_filter_filename_dsts) let types_of_extensions = [ "ott","ott"; "tex","tex"; "v", "coq"; "thy","isa"; "sml","hol"; "lem","lem"; "twf","twf"; "ml", "ocaml"; "mll", "lex"; "mly", "menhir"] let extension_of_type t = List.assoc t (List.map (function (a,b)->(b,a)) types_of_extensions) let file_type name = try Some (List.assoc (let start = 1+String.length (Filename.chop_extension name) in String.sub name start (String.length name - start) ) types_of_extensions) with _ -> None let non_tex_output_types = ["coq"; "isa"; "hol"; "lem"; "twf"; "ocaml"] let output_types = "tex" :: "lex" :: "menhir" :: non_tex_output_types let input_types = "ott" :: output_types let classify_file_argument arg = match arg with | (In,name) -> (match file_type name with | Some e when (List.mem e input_types) -> (In,e,name) | _ -> Auxl.error None ("\nError: unrecognised extension of input file \""^name ^ "\" (must be one of " ^ String.concat "," (List.map extension_of_type input_types) ^")\n")) | (Out,name) -> (match file_type name with | Some e when (List.mem e output_types) -> (Out,e,name) | _ -> Auxl.error None ("\nError: unrecognised extension of output file \""^name ^ "\" (must be one of "^String.concat "," (List.map extension_of_type output_types) ^")\n")) values , containing first all the ott source files from the end of let all_file_arguments = List.map classify_file_argument (List.rev (!file_arguments)) let targets_in ts = List.filter (function t -> List.mem t ts) (Auxl.remove_duplicates (Auxl.option_map (function x -> match x with | (Out,t,_) -> Some t | _ -> None) all_file_arguments)) let targets_non_tex = targets_in non_tex_output_types let targets = targets_in output_types let source_filenames = Auxl.option_map (function x -> match x with | In,t,n -> Some (t,n) | Out,_,_ -> None) all_file_arguments let _ = if false then print_string ("source_filenames = "^String.concat ", " (List.map (function (t,n) -> n^":"^t) source_filenames)^"\n") let m_ascii = Ascii { ppa_colour = !colour; ppa_lift_cons_prefixes = false; ppa_ugly= !ascii_ugly; ppa_show_deps = !show_deps; ppa_show_defns = !show_defns } let m_tex = Tex {ppt_colour= !tex_colour; ppt_show_meta= !tex_show_meta; ppt_show_categories= !tex_show_categories; ppt_suppressed_categories= !tex_suppressed_categories; ppt_suppressed_ntrs= !tex_suppressed_ntrs; ppt_wrap= !tex_wrap; ppt_name_prefix= !tex_name_prefix } let m_isa = Isa { ppi_isa_primrec = !isa_primrec; ppi_isa_inductive = !isa_inductive; isa_library = ref ("",[]); ppi_fancy_syntax = !isa_syntax; ppi_generate_lemmas = !isa_generate_lemmas } let m_hol = Hol { hol_library = ref ("",[]); } let m_lem = Lem { lem_library = ref ("",[]); } let m_twf = Twf { twf_current_defn = ref ""; twf_library = ref ("",[]) } let m_coq = Coq { coq_expand_lists = !coq_expand_lists; coq_quantified_vars_from_de = ref []; coq_non_local_hyp_defn = ref ""; coq_non_local_hyp_defn_vars = ref []; coq_list_types = ref []; coq_list_aux_funcs = Some (ref ""); coq_list_aux_defns = { defined = ref []; newly_defined = ref [] }; coq_library = ref ("",[]); coq_locally_nameless = ref false; coq_lngen = !coq_lngen; coq_use_filter_fn = !coq_use_filter_fn; coq_names_in_rules = !coq_names_in_rules } let oo = { ppo_include_terminals = !caml_include_terminals; caml_library = ref ("",[]) } let m_caml = Caml oo let target_ocaml_ast_module = if List.exists (function x -> match x with | Out,"menhir",n -> true | _,_,_ -> false) all_file_arguments then let target_ocaml_filenames = Auxl.option_map (function x -> match x with | Out,"ocaml",n -> Some n | _,_,_ -> None) all_file_arguments in match target_ocaml_filenames with | [n] -> String.capitalize_ascii (Filename.chop_extension n) | _ -> Auxl.error None "\n if there is a menhir output file, there must be exactly one ocaml output file" else "" let target_ocaml_parser_module = if List.exists (function x -> match x with | Out,"lex",n -> true | _,_,_ -> false) all_file_arguments then let target_menhir_filenames = Auxl.option_map (function x -> match x with | Out,"menhir",n -> Some n | _,_,_ -> None) all_file_arguments in match target_menhir_filenames with | [n] -> String.capitalize_ascii (Filename.chop_extension n) | _ -> Auxl.error None "\n if there is an ocamllex output file, there must be exactly one menhir output file" else "" let yo = { ppm_suppressed_categories= !tex_suppressed_categories; ppm_suppressed_ntrs= !tex_suppressed_ntrs; ppm_caml_opts = oo; ppm_caml_ast_module = target_ocaml_ast_module; ppm_caml_parser_module = target_ocaml_parser_module; } let m_menhir = Menhir yo let m_lex = Lex yo let reset_m_coq m = match m with | Coq co -> co.coq_non_local_hyp_defn := ""; co.coq_non_local_hyp_defn_vars := []; co.coq_list_types := []; Auxl.the (co.coq_list_aux_funcs) := ""; co.coq_list_aux_defns.defined := []; co.coq_list_aux_defns.newly_defined := []; co.coq_library := ("",[]); co.coq_locally_nameless := false | _ -> Auxl.errorm m "reset_m_coq" let m_caml = Caml { ppo_include_terminals = !caml_include_terminals; caml_library = ref ("",[]) } finally compute the set of modes used in this run of -- used when non - picky about multiple parses when non-picky about multiple parses *) here we used also to record the suffix - stripped filenames for hol and isa , for the non - picky checking , but now we feed dummy filenames into the m _ ... functions and isa, for the non-picky checking, but now we feed dummy filenames into the m_... functions *) let _ = Global_option.is_picky := ( !picky_multiple_parses, List.map (function t -> List.assoc t "hol",m_hol; "lem",m_lem; "isa",m_isa; "twf",m_twf; "coq",m_coq ; "tex",m_tex ]) targets_for_non_picky) let process source_filenames = let sources = String.concat " " (List.map snd source_filenames) in (match !alltt_filename_opt,source_filenames with | None,_ -> () | Some alltt_filename,([] | _::_::_) -> Auxl.error None ("\nUsage: -alltt option can only be used with exactly one source file at a time\n"); | Some alltt_filename,[(source_filetype,source_filename)] -> let c = open_in source_filename in let c' = open_out alltt_filename in output_string c' "\\begin{alltt}\n"; let lexbuf = Lexing.from_channel c in let lexer = Grammar_lexer.my_lexer false Grammar_lexer.metalang in let rec process_input () = try let t = lexer lexbuf in match t with | Grammar_parser.EOF -> () | _ -> print_string (Grammar_lexer.de_lex_ascii t); flush stdout; output_string c' (Grammar_lexer.de_lex_tex t); flush c'; process_input () with My_parse_error (loc, s)-> Auxl.error loc (s) in process_input (); output_string c' "\\end{alltt}\n"; let _ = close_in c in let _ = close_out c' in ()); let parse_file (filetype,filename) = match filetype with | "ott" -> let c = open_in filename in let lexbuf = Lexing.from_channel c in if < > 1 then lexbuf.Lexing.lex_curr_p <- { lexbuf.Lexing.lex_curr_p with Lexing.pos_fname = filename}; let ris = (try Grammar_parser.main (Grammar_lexer.my_lexer true Grammar_lexer.metalang) lexbuf with My_parse_error (loc,s)-> Auxl.error loc ("\n"^s^"\n")) in let _ = close_in c in ris | _ -> let s = Auxl.string_of_filename filename in let loc = Location.loc_of_filename filename (String.length s) in [Raw_item_embed [ (loc,filetype, [Embed_string(loc,s)])]] in let document = List.map parse_file source_filenames in if !showraw then ( let s = (String.concat "\n" (List.map (fun document_part -> String.concat "" (List.map Grammar_pp.pp_raw_item document_part)) document)) in let fd = open_out " test2.txt " in print_string s); the unquotiented syntax , which is the one we 'll generate menhir rules from , should be without generated aux rules . rules from, should be without generated aux rules. *) the quotiented un - auxed syntax , used to generate the pp functions , should be without the generated aux rules let f quotient generate_aux = try Grammar_typecheck.check_and_disambiguate m_tex quotient generate_aux targets_non_tex (List.map snd source_filenames) (!merge_fragments) document with | Typecheck_error (loc,s1,s2) -> Auxl.error (Some loc) ("(in checking and disambiguating "^(if quotient then "quotiented " else "") ^ "syntax)\n"^s1 ^ (if s2<>"" then " ("^s2^")" else "") ^ "\n") in let ((xd,structure,rdcs),xd_unquotiented,xd_quotiented_unaux) = (f true !generate_aux_rules, (match f false false with (xd,_,_)-> xd), (match f !generate_aux_rules false with (xd,_,_)-> xd)) else match f !quotient_rules !generate_aux_rules with two dummies , unused in if !show_sort then ( print_endline "********** AFTER CHECK, DISAMBIGUATE AND SORT *********************\n"; print_endline (Grammar_pp.pp_syntaxdefn m_ascii xd)); FZ sorting is now performed while checking and disambiguate | Grammar_typecheck . Typecheck_error ( s,_)- > Auxl.error ( " \nError sorting the grammar:\n"^s^"\n " ) if ! show_post_sort then ( let lookup = Term_parser.make_parser xd in begin try Grammar_typecheck.check_with_parser lookup xd with | Typecheck_error (loc,s1,s2) -> Auxl.error (Some loc) ("(in checking syntax)\n"^s1 ^ (if s2<>"" then " ("^s2^")\n" else "\n")) end; let sd = if !process_defns then (if !show_defns then (print_endline "********** PROCESSING DEFINITIONS *****************\n"; flush stdout); try let dcs = Defns.process_raw_defnclasss m_ascii xd lookup rdcs in let sd = { syntax = xd; relations = dcs; structure = structure; sources = sources} in sd with | Defns.Rule_parse_error (loc,s) -> Auxl.error (Some loc) ("\nError in processing definitions:\n"^s^"\n") | Bounds.Bounds (loc,s) | Typecheck_error (loc,s,_)-> Auxl.error (Some loc) ("\nError in processing definitions:\n"^s^"\n") ) else (print_endline "********** NOT PROCESSING DEFINITIONS *************\n"; flush stdout; let sd = { syntax = xd; relations = []; structure = structure; sources = sources} in sd) in let sd_unquotiented = { syntax = xd_unquotiented; relations = []; structure = structure; sources = sources} in let sd_quotiented_unaux = { syntax = xd_quotiented_unaux; relations = []; structure = structure; sources = sources} in sd,lookup,sd_unquotiented,sd_quotiented_unaux let read_systemdefn read_systemdefn_filename = let fd = open_in_bin read_systemdefn_filename in let sd,lookup ,sd_unquotiented, sd_quotiented_unaux = try Marshal.from_channel fd with Failure s -> Auxl.error None ("Cannot read dumped systemdefn\n " ^ s ^"\n") in close_in fd; sd,lookup,sd_unquotiented,sd_quotiented_unaux let output_stage (sd,lookup,sd_unquotiented,sd_quotiented_unaux) = * output of systemdefn ( match !write_systemdefn_filename_opt with | None -> () | Some s -> let fd = open_out_bin s in Marshal.to_channel fd (sd,lookup,sd_unquotiented) [Marshal.Closures]; close_out fd; print_string ("system definition in file: " ^ s ^ "\n") ); ( match !dot_filename_opt with | None -> () | Some s -> let fd = open_out s in output_string fd (Grammar_pp.pp_dot_dep_graph pp_ascii_opts_default sd.syntax); close_out fd; print_string ("dot version in file: " ^ s ^ "\n") ); let output_details = let sources_per_target = List.map (fun t -> (t, Auxl.option_map (fun (d,ft,fn) -> match d with | In -> Some (d,ft,fn) | Out -> if String.compare ft t = 0 then Some (d,ft,fn) else None) all_file_arguments)) targets in let rec compute_output ib a = match a with | [] -> [] | (In,ft,fn)::xs -> compute_output (fn::ib) xs | (Out,ft,fn)::xs -> ( if ib = [] then Auxl.warning None ("warning: no input files for the output file: "^fn^".\n"); (fn,ib)::(compute_output [] xs)) in List.map (fun (t,fs) -> t, compute_output [] fs) sources_per_target in List.iter (fun (t,fi) -> match t with | "tex" -> System_pp.pp_systemdefn_core_tex m_tex sd lookup fi | "coq" -> let sd = ( match !coq_avoid with | 0 -> sd | 1 -> Auxl.avoid_primaries_systemdefn false sd | 2 -> Auxl.avoid_primaries_systemdefn true sd | _ -> Auxl.error None "coq type-name avoidance must be in {0,1,2}" ) in System_pp.pp_systemdefn_core_io m_coq sd lookup fi !merge_fragments | "isa" -> System_pp.pp_systemdefn_core_io m_isa sd lookup fi !merge_fragments | "hol" -> System_pp.pp_systemdefn_core_io m_hol sd lookup fi !merge_fragments | "lem" -> System_pp.pp_systemdefn_core_io m_lem sd lookup fi !merge_fragments | "twf" -> System_pp.pp_systemdefn_core_io m_twf sd lookup fi !merge_fragments | "ocaml" -> System_pp.pp_systemdefn_core_io m_caml (Auxl.caml_rename sd) lookup fi !merge_fragments | "lex" -> Lex_menhir_pp.pp_lex_systemdefn m_lex (Auxl.caml_rename sd) fi | "menhir" -> let sd_quotiented = Auxl.caml_rename sd in let sd_unquotiented = Auxl.caml_rename sd_unquotiented in let xd_quotiented = sd.syntax in let xd_unquotiented = sd_unquotiented.syntax in let xd_quotiented_unaux = sd_quotiented_unaux.syntax in (Lex_menhir_pp.pp_menhir_syntaxdefn m_menhir sd.sources xd_quotiented xd_unquotiented lookup !generate_aux_rules fi; Lex_menhir_pp.pp_pp_syntaxdefn m_menhir sd.sources xd_quotiented xd_unquotiented xd_quotiented_unaux !generate_aux_rules true fi "") | _ -> Auxl.int_error("unknown target "^t)) output_details; begin match !caml_pp_filename with | None -> () | Some filename -> let sd_quotiented = Auxl.caml_rename sd in let sd_unquotiented = Auxl.caml_rename sd_unquotiented in let xd_quotiented = sd.syntax in let xd_unquotiented = sd_unquotiented.syntax in let xd_quotiented_unaux = sd_quotiented_unaux.syntax in ( Lex_menhir_pp.pp_menhir_syntaxdefn m_menhir sd.sources xd_quotiented xd_unquotiented lookup ! generate_aux_rules fi ; Lex_menhir_pp.pp_pp_syntaxdefn m_menhir sd.sources xd_quotiented xd_unquotiented xd_quotiented_unaux (!generate_aux_rules && not !Global_option.aux_style_rules) false [] filename end; (match !test_parse_list with [] -> ()|_ -> print_string "\n"); (List.iter (function s -> print_string ("test parse: string \""^s^"\"\n"); let r = Str.regexp (Str.quote ":" ^ "\\(" ^ Term_parser.ident_string ^"\\)"^ Str.quote ":" ^ "\\(.*\\)") in if (Str.string_match r s 0 && Str.match_end () = String.length s) then let ntr = Str.matched_group 1 s in let term = Str.matched_group 4 s in let (ntr, concrete) = if Str.string_match (Str.regexp "concrete_") ntr 0 then (Str.string_after ntr 9, true) else (ntr, false) in print_string ("test parse: "^ntr^" \""^term^"\"\n"); Term_parser.test_parse m_ascii sd.syntax ntr concrete term; print_string "\n" else print_string ("test parse: string "^s ^" not of the required :ntr:term form\n")) !test_parse_list); let filter m (src_filename,dst_filename) = let fd_src = open_in src_filename in let fd_dst = open_out dst_filename in let lexbuf = Lexing.from_channel fd_src in lexbuf.Lexing.lex_curr_p <- { lexbuf.Lexing.lex_curr_p with Lexing.pos_fname = src_filename}; let unfiltered_document = try Grammar_parser.unfiltered_spec_el_list (Grammar_lexer.my_lexer true Grammar_lexer.filter) lexbuf with | Parsing.Parse_error -> Auxl.error None ("unfiltered document "^src_filename^" cannot be parsed\n") | My_parse_error (loc,s) -> Auxl.error loc s in Embed_pp.pp_embed_spec fd_dst m sd.syntax lookup (Auxl.collapse_embed_spec_el_list unfiltered_document); let _ = close_in fd_src in let _ = close_out fd_dst in () in (List.iter (filter m_tex) (!tex_filter_filenames)); (List.iter (filter m_coq) (!coq_filter_filenames)); (List.iter (filter m_isa) (!isa_filter_filenames)); (List.iter (filter m_hol) (!hol_filter_filenames)); (List.iter (filter m_lem) (!lem_filter_filenames)); (List.iter (filter m_twf) (!twf_filter_filenames)); (List.iter (filter m_caml) (!caml_filter_filenames)); let xd , targets document in if !process_defns then begin let bad, msg = Defns.pp_counts sd in print_string msg; if bad && !signal_parse_errors then exit 1 end; () set GC parameters to reasonable values let _ = Gc.set { (Gc.get()) with 8/16 MB in 32/64bit machines 40/80 MB in 32/64bit machines let _ = try ( match source_filenames, !read_systemdefn_filename_opt with | (_::_),None -> let (sd,lookup,sd_unquotiented,sd_quotiented_unaux) = process source_filenames in output_stage (sd,lookup,sd_unquotiented,sd_quotiented_unaux) | [], Some s -> let (sd,lookup,sd_unquotiented,sd_quotiented_unaux) = read_systemdefn s in output_stage (sd,lookup,sd_unquotiented,sd_quotiented_unaux) | [],None -> Arg.usage options usage_msg; Auxl.error None "\nError: must specify either some source filenames or a readsys option\n" | (_::_),Some _ -> Auxl.error None "\nError: must not specify both source filenames and a readsys option\n" ) with | Auxl.Located_Failure (l, s) -> Auxl.exit_with l s
e20d4c6e473acc18ba685203b96073a7bd004362abc34b048b1e3502a1eea614
bsansouci/bsb-native
odoc_info.ml
(***********************************************************************) (* *) (* OCamldoc *) (* *) , projet Cristal , INRIA Rocquencourt (* *) Copyright 2001 Institut National de Recherche en Informatique et en Automatique . All rights reserved . This file is distributed under the terms of the Q Public License version 1.0 . (* *) (***********************************************************************) (** Interface for analysing documented OCaml source files and to the collected information. *) type ref_kind = Odoc_types.ref_kind = RK_module | RK_module_type | RK_class | RK_class_type | RK_value | RK_type | RK_extension | RK_exception | RK_attribute | RK_method | RK_section of text | RK_recfield | RK_const and text_element = Odoc_types.text_element = | Raw of string | Code of string | CodePre of string | Verbatim of string | Bold of text | Italic of text | Emphasize of text | Center of text | Left of text | Right of text | List of text list | Enum of text list | Newline | Block of text | Title of int * string option * text | Latex of string | Link of string * text | Ref of string * ref_kind option * text option | Superscript of text | Subscript of text | Module_list of string list | Index_list | Custom of string * text | Target of string * string and text = text_element list exception Text_syntax = Odoc_text.Text_syntax type see_ref = Odoc_types.see_ref = See_url of string | See_file of string | See_doc of string type see = see_ref * text type param = (string * text) type raised_exception = (string * text) type info = Odoc_types.info = { i_desc : text option; i_authors : string list; i_version : string option; i_sees : see list; i_since : string option; i_before : (string * text) list ; i_deprecated : text option; i_params : param list; i_raised_exceptions : raised_exception list; i_return_value : text option ; i_custom : (string * text) list ; } type location = Odoc_types.location = { loc_impl : Location.t option ; loc_inter : Location.t option ; } let dummy_loc = { loc_impl = None ; loc_inter = None } module Name = Odoc_name module Parameter = Odoc_parameter module Extension = Odoc_extension module Exception = Odoc_exception module Type = Odoc_type module Value = Odoc_value module Class = Odoc_class module Module = Odoc_module let analyse_files ?(merge_options=([] : Odoc_types.merge_option list)) ?(include_dirs=([] : string list)) ?(labels=false) ?(sort_modules=false) ?(no_stop=false) ?(init=[]) files = Odoc_global.merge_options := merge_options; Odoc_global.include_dirs := include_dirs; Odoc_global.classic := not labels; Odoc_global.sort_modules := sort_modules; Odoc_global.no_stop := no_stop; Odoc_analyse.analyse_files ~init: init files let dump_modules = Odoc_analyse.dump_modules let load_modules = Odoc_analyse.load_modules let reset_type_names = Printtyp.reset let string_of_variance t (co,cn) = Odoc_str.string_of_variance t (co, cn) let string_of_type_expr t = Odoc_print.string_of_type_expr t let string_of_class_params = Odoc_str.string_of_class_params let string_of_type_list ?par sep type_list = Odoc_str.string_of_type_list ?par sep type_list let string_of_type_param_list t = Odoc_str.string_of_type_param_list t let string_of_type_extension_param_list te = Odoc_str.string_of_type_extension_param_list te let string_of_class_type_param_list l = Odoc_str.string_of_class_type_param_list l let string_of_module_type = Odoc_print.string_of_module_type let string_of_class_type = Odoc_print.string_of_class_type let string_of_text t = Odoc_misc.string_of_text t let string_of_info i = Odoc_misc.string_of_info i let string_of_type t = Odoc_str.string_of_type t let string_of_type_extension te = Odoc_str.string_of_type_extension te let string_of_exception e = Odoc_str.string_of_exception e let string_of_value v = Odoc_str.string_of_value v let string_of_attribute att = Odoc_str.string_of_attribute att let string_of_method m = Odoc_str.string_of_method m let first_sentence_of_text = Odoc_misc.first_sentence_of_text let first_sentence_and_rest_of_text = Odoc_misc.first_sentence_and_rest_of_text let text_no_title_no_list = Odoc_misc.text_no_title_no_list let text_concat = Odoc_misc.text_concat let get_titles_in_text = Odoc_misc.get_titles_in_text let create_index_lists = Odoc_misc.create_index_lists let remove_ending_newline = Odoc_misc.remove_ending_newline let remove_option = Odoc_misc.remove_option let is_optional = Odoc_misc.is_optional let label_name = Odoc_misc.label_name let use_hidden_modules n = Odoc_name.hide_given_modules !Odoc_global.hidden_modules n let verbose s = if !Odoc_global.verbose then (print_string s ; print_newline ()) else () let warning s = Odoc_global.pwarning s let print_warnings = Odoc_config.print_warnings let errors = Odoc_global.errors let apply_opt = Odoc_misc.apply_opt let apply_if_equal f v1 v2 = if v1 = v2 then f v1 else v2 let text_of_string = Odoc_text.Texter.text_of_string let text_string_of_text = Odoc_text.Texter.string_of_text let escape_arobas s = let len = String.length s in let b = Buffer.create len in for i = 0 to len - 1 do match s.[i] with '@' -> Buffer.add_string b "\\@" | c -> Buffer.add_char b c done; Buffer.contents b let info_string_of_info i = let b = Buffer.create 256 in let p = Printf.bprintf in ( match i.i_desc with None -> () | Some t -> p b "%s" (escape_arobas (text_string_of_text t)) ); List.iter (fun s -> p b "\n@@author %s" (escape_arobas s)) i.i_authors; ( match i.i_version with None -> () | Some s -> p b "\n@@version %s" (escape_arobas s) ); ( (* TODO: escape characters ? *) let f_see_ref = function See_url s -> Printf.sprintf "<%s>" s | See_file s -> Printf.sprintf "'%s'" s | See_doc s -> Printf.sprintf "\"%s\"" s in List.iter (fun (sref, t) -> p b "\n@@see %s %s" (escape_arobas (f_see_ref sref)) (escape_arobas (text_string_of_text t)) ) i.i_sees ); ( match i.i_since with None -> () | Some s -> p b "\n@@since %s" (escape_arobas s) ); ( match i.i_deprecated with None -> () | Some t -> p b "\n@@deprecated %s" (escape_arobas (text_string_of_text t)) ); List.iter (fun (s, t) -> p b "\n@@param %s %s" (escape_arobas s) (escape_arobas (text_string_of_text t)) ) i.i_params; List.iter (fun (s, t) -> p b "\n@@raise %s %s" (escape_arobas s) (escape_arobas (text_string_of_text t)) ) i.i_raised_exceptions; ( match i.i_return_value with None -> () | Some t -> p b "\n@@return %s" (escape_arobas (text_string_of_text t)) ); List.iter (fun (s, t) -> p b "\n@@%s %s" s (escape_arobas (text_string_of_text t)) ) i.i_custom; Buffer.contents b let info_of_string = Odoc_comments.info_of_string let info_of_comment_file = Odoc_comments.info_of_comment_file module Search = struct type result_element = Odoc_search.result_element = Res_module of Module.t_module | Res_module_type of Module.t_module_type | Res_class of Class.t_class | Res_class_type of Class.t_class_type | Res_value of Value.t_value | Res_type of Type.t_type | Res_extension of Extension.t_extension_constructor | Res_exception of Exception.t_exception | Res_attribute of Value.t_attribute | Res_method of Value.t_method | Res_section of string * text | Res_recfield of Type.t_type * Type.record_field | Res_const of Type.t_type * Type.variant_constructor type search_result = result_element list let search_by_name = Odoc_search.Search_by_name.search let values = Odoc_search.values let extensions = Odoc_search.extensions let exceptions = Odoc_search.exceptions let types = Odoc_search.types let attributes = Odoc_search.attributes let methods = Odoc_search.methods let classes = Odoc_search.classes let class_types = Odoc_search.class_types let modules = Odoc_search.modules let module_types = Odoc_search.module_types end module Scan = struct class scanner = Odoc_scan.scanner end module Dep = struct let kernel_deps_of_modules = Odoc_dep.kernel_deps_of_modules let deps_of_types = Odoc_dep.deps_of_types end module Global = Odoc_global
null
https://raw.githubusercontent.com/bsansouci/bsb-native/9a89457783d6e80deb0fba9ca7372c10a768a9ea/vendor/ocaml/ocamldoc/odoc_info.ml
ocaml
********************************************************************* OCamldoc ********************************************************************* * Interface for analysing documented OCaml source files and to the collected information. TODO: escape characters ?
, projet Cristal , INRIA Rocquencourt Copyright 2001 Institut National de Recherche en Informatique et en Automatique . All rights reserved . This file is distributed under the terms of the Q Public License version 1.0 . type ref_kind = Odoc_types.ref_kind = RK_module | RK_module_type | RK_class | RK_class_type | RK_value | RK_type | RK_extension | RK_exception | RK_attribute | RK_method | RK_section of text | RK_recfield | RK_const and text_element = Odoc_types.text_element = | Raw of string | Code of string | CodePre of string | Verbatim of string | Bold of text | Italic of text | Emphasize of text | Center of text | Left of text | Right of text | List of text list | Enum of text list | Newline | Block of text | Title of int * string option * text | Latex of string | Link of string * text | Ref of string * ref_kind option * text option | Superscript of text | Subscript of text | Module_list of string list | Index_list | Custom of string * text | Target of string * string and text = text_element list exception Text_syntax = Odoc_text.Text_syntax type see_ref = Odoc_types.see_ref = See_url of string | See_file of string | See_doc of string type see = see_ref * text type param = (string * text) type raised_exception = (string * text) type info = Odoc_types.info = { i_desc : text option; i_authors : string list; i_version : string option; i_sees : see list; i_since : string option; i_before : (string * text) list ; i_deprecated : text option; i_params : param list; i_raised_exceptions : raised_exception list; i_return_value : text option ; i_custom : (string * text) list ; } type location = Odoc_types.location = { loc_impl : Location.t option ; loc_inter : Location.t option ; } let dummy_loc = { loc_impl = None ; loc_inter = None } module Name = Odoc_name module Parameter = Odoc_parameter module Extension = Odoc_extension module Exception = Odoc_exception module Type = Odoc_type module Value = Odoc_value module Class = Odoc_class module Module = Odoc_module let analyse_files ?(merge_options=([] : Odoc_types.merge_option list)) ?(include_dirs=([] : string list)) ?(labels=false) ?(sort_modules=false) ?(no_stop=false) ?(init=[]) files = Odoc_global.merge_options := merge_options; Odoc_global.include_dirs := include_dirs; Odoc_global.classic := not labels; Odoc_global.sort_modules := sort_modules; Odoc_global.no_stop := no_stop; Odoc_analyse.analyse_files ~init: init files let dump_modules = Odoc_analyse.dump_modules let load_modules = Odoc_analyse.load_modules let reset_type_names = Printtyp.reset let string_of_variance t (co,cn) = Odoc_str.string_of_variance t (co, cn) let string_of_type_expr t = Odoc_print.string_of_type_expr t let string_of_class_params = Odoc_str.string_of_class_params let string_of_type_list ?par sep type_list = Odoc_str.string_of_type_list ?par sep type_list let string_of_type_param_list t = Odoc_str.string_of_type_param_list t let string_of_type_extension_param_list te = Odoc_str.string_of_type_extension_param_list te let string_of_class_type_param_list l = Odoc_str.string_of_class_type_param_list l let string_of_module_type = Odoc_print.string_of_module_type let string_of_class_type = Odoc_print.string_of_class_type let string_of_text t = Odoc_misc.string_of_text t let string_of_info i = Odoc_misc.string_of_info i let string_of_type t = Odoc_str.string_of_type t let string_of_type_extension te = Odoc_str.string_of_type_extension te let string_of_exception e = Odoc_str.string_of_exception e let string_of_value v = Odoc_str.string_of_value v let string_of_attribute att = Odoc_str.string_of_attribute att let string_of_method m = Odoc_str.string_of_method m let first_sentence_of_text = Odoc_misc.first_sentence_of_text let first_sentence_and_rest_of_text = Odoc_misc.first_sentence_and_rest_of_text let text_no_title_no_list = Odoc_misc.text_no_title_no_list let text_concat = Odoc_misc.text_concat let get_titles_in_text = Odoc_misc.get_titles_in_text let create_index_lists = Odoc_misc.create_index_lists let remove_ending_newline = Odoc_misc.remove_ending_newline let remove_option = Odoc_misc.remove_option let is_optional = Odoc_misc.is_optional let label_name = Odoc_misc.label_name let use_hidden_modules n = Odoc_name.hide_given_modules !Odoc_global.hidden_modules n let verbose s = if !Odoc_global.verbose then (print_string s ; print_newline ()) else () let warning s = Odoc_global.pwarning s let print_warnings = Odoc_config.print_warnings let errors = Odoc_global.errors let apply_opt = Odoc_misc.apply_opt let apply_if_equal f v1 v2 = if v1 = v2 then f v1 else v2 let text_of_string = Odoc_text.Texter.text_of_string let text_string_of_text = Odoc_text.Texter.string_of_text let escape_arobas s = let len = String.length s in let b = Buffer.create len in for i = 0 to len - 1 do match s.[i] with '@' -> Buffer.add_string b "\\@" | c -> Buffer.add_char b c done; Buffer.contents b let info_string_of_info i = let b = Buffer.create 256 in let p = Printf.bprintf in ( match i.i_desc with None -> () | Some t -> p b "%s" (escape_arobas (text_string_of_text t)) ); List.iter (fun s -> p b "\n@@author %s" (escape_arobas s)) i.i_authors; ( match i.i_version with None -> () | Some s -> p b "\n@@version %s" (escape_arobas s) ); ( let f_see_ref = function See_url s -> Printf.sprintf "<%s>" s | See_file s -> Printf.sprintf "'%s'" s | See_doc s -> Printf.sprintf "\"%s\"" s in List.iter (fun (sref, t) -> p b "\n@@see %s %s" (escape_arobas (f_see_ref sref)) (escape_arobas (text_string_of_text t)) ) i.i_sees ); ( match i.i_since with None -> () | Some s -> p b "\n@@since %s" (escape_arobas s) ); ( match i.i_deprecated with None -> () | Some t -> p b "\n@@deprecated %s" (escape_arobas (text_string_of_text t)) ); List.iter (fun (s, t) -> p b "\n@@param %s %s" (escape_arobas s) (escape_arobas (text_string_of_text t)) ) i.i_params; List.iter (fun (s, t) -> p b "\n@@raise %s %s" (escape_arobas s) (escape_arobas (text_string_of_text t)) ) i.i_raised_exceptions; ( match i.i_return_value with None -> () | Some t -> p b "\n@@return %s" (escape_arobas (text_string_of_text t)) ); List.iter (fun (s, t) -> p b "\n@@%s %s" s (escape_arobas (text_string_of_text t)) ) i.i_custom; Buffer.contents b let info_of_string = Odoc_comments.info_of_string let info_of_comment_file = Odoc_comments.info_of_comment_file module Search = struct type result_element = Odoc_search.result_element = Res_module of Module.t_module | Res_module_type of Module.t_module_type | Res_class of Class.t_class | Res_class_type of Class.t_class_type | Res_value of Value.t_value | Res_type of Type.t_type | Res_extension of Extension.t_extension_constructor | Res_exception of Exception.t_exception | Res_attribute of Value.t_attribute | Res_method of Value.t_method | Res_section of string * text | Res_recfield of Type.t_type * Type.record_field | Res_const of Type.t_type * Type.variant_constructor type search_result = result_element list let search_by_name = Odoc_search.Search_by_name.search let values = Odoc_search.values let extensions = Odoc_search.extensions let exceptions = Odoc_search.exceptions let types = Odoc_search.types let attributes = Odoc_search.attributes let methods = Odoc_search.methods let classes = Odoc_search.classes let class_types = Odoc_search.class_types let modules = Odoc_search.modules let module_types = Odoc_search.module_types end module Scan = struct class scanner = Odoc_scan.scanner end module Dep = struct let kernel_deps_of_modules = Odoc_dep.kernel_deps_of_modules let deps_of_types = Odoc_dep.deps_of_types end module Global = Odoc_global
e80e184011ed1ce9a9a8f4b8a68965abc3326c44c30491c6be0a8cf4538e8bdb
aroemers/sibiro
params.clj
(ns sibiro.params "ERPERIMENTAL! EVERYTHING IS SUBJECT TO CHANGE IN THIS NAMESPACE!") ;;; Private helpers. (defn- name-with-attrs [name [arg1 arg2 & argx :as args]] (let [[attrs args] (cond (and (string? arg1) (map? arg2)) [(assoc arg2 :doc arg1) argx] (string? arg1) [{:doc arg1} (cons arg2 argx)] (map? arg1) [arg1 (cons arg2 argx)] :otherwise [{} args])] [(with-meta name (merge (meta name) attrs)) args])) ;;; Main macro (defmacro with-params "Macro binding the given symbols around the body to the corresponding values in :route-params or :params (both keyword as string lookup) from the request. There are also some special keywords available: - Prepending a symbol with :as will bind that symbol with the entire request. Instead of a symbol, a destructuring expression can also be specified. - Prepending a map with :or defines default values. If no default value is specified, and the binding cannot be found in the request parameters, an exception is thrown. It basically asserts for you that all parameters are found or at least have a value. For example: (fn [req] (with-params [name email password :or {name \"Anonymous\"} :as {:keys [uri]}] req ...))" [bindings reqsym & body] (let [[syms specials] (reduce (fn [[syms specials keyw] binding] (if keyw [syms (assoc specials keyw binding) nil] (if (keyword? binding) [syms specials binding] [(conj syms binding) specials nil]))) [nil nil nil] bindings) assym (:as specials (gensym "request-")) ormap (:or specials)] (assert (every? symbol? syms) "bindings can only be symbols or special keywords") (assert (every? #{:as :or} (keys specials)) "supported binding keywords are :or, :as and :assert") (assert (or (nil? ormap) (map? ormap)) "binding for :or must be a map") (assert (every? (set syms) (keys ormap)) "keys in :or map must be subset of binding symbols") `(let [~assym ~reqsym ~@(for [sym syms form [sym `(or (some-> ~reqsym :route-params ~(keyword sym)) (some-> ~reqsym :params ~(keyword sym)) (some-> ~reqsym :params (get ~(str sym))) ~(if (contains? ormap sym) (get ormap sym) `(throw (ex-info ~(str "param not found: " sym) {:binding '~sym}))))]] form)] ~@body))) ;;; Convenience macros (defmacro fnp "Same as `(fn [req] (with-params bindings req body))`" [bindings & body] `(fn [reqsym#] (with-params ~bindings reqsym# ~@body))) (defmacro defnp "Same as `(def name (fnp bindings body))`. Supports docstring, attribute map, and metadata on the name symbol." [name & body] (let [[name [bindings & body]] (name-with-attrs name body)] `(def ~name (fnp ~bindings ~@body)))) (defmacro defnp- "Same as `defnp`, but private." [name & body] `(defnp ~(with-meta name (merge (meta name) {:private true})) ~@body)) (defmacro defmethodp "Same as `(defmethod name dispatch [req] (with-params bindings req body))`." [name dispatch bindings & body] `(defmethod ~name ~dispatch [request#] (with-params ~bindings request# ~@body)))
null
https://raw.githubusercontent.com/aroemers/sibiro/fd4728d1e496af2fbb60e37524f67faf17abb26e/src/sibiro/params.clj
clojure
Private helpers. Main macro Convenience macros
(ns sibiro.params "ERPERIMENTAL! EVERYTHING IS SUBJECT TO CHANGE IN THIS NAMESPACE!") (defn- name-with-attrs [name [arg1 arg2 & argx :as args]] (let [[attrs args] (cond (and (string? arg1) (map? arg2)) [(assoc arg2 :doc arg1) argx] (string? arg1) [{:doc arg1} (cons arg2 argx)] (map? arg1) [arg1 (cons arg2 argx)] :otherwise [{} args])] [(with-meta name (merge (meta name) attrs)) args])) (defmacro with-params "Macro binding the given symbols around the body to the corresponding values in :route-params or :params (both keyword as string lookup) from the request. There are also some special keywords available: - Prepending a symbol with :as will bind that symbol with the entire request. Instead of a symbol, a destructuring expression can also be specified. - Prepending a map with :or defines default values. If no default value is specified, and the binding cannot be found in the request parameters, an exception is thrown. It basically asserts for you that all parameters are found or at least have a value. For example: (fn [req] (with-params [name email password :or {name \"Anonymous\"} :as {:keys [uri]}] req ...))" [bindings reqsym & body] (let [[syms specials] (reduce (fn [[syms specials keyw] binding] (if keyw [syms (assoc specials keyw binding) nil] (if (keyword? binding) [syms specials binding] [(conj syms binding) specials nil]))) [nil nil nil] bindings) assym (:as specials (gensym "request-")) ormap (:or specials)] (assert (every? symbol? syms) "bindings can only be symbols or special keywords") (assert (every? #{:as :or} (keys specials)) "supported binding keywords are :or, :as and :assert") (assert (or (nil? ormap) (map? ormap)) "binding for :or must be a map") (assert (every? (set syms) (keys ormap)) "keys in :or map must be subset of binding symbols") `(let [~assym ~reqsym ~@(for [sym syms form [sym `(or (some-> ~reqsym :route-params ~(keyword sym)) (some-> ~reqsym :params ~(keyword sym)) (some-> ~reqsym :params (get ~(str sym))) ~(if (contains? ormap sym) (get ormap sym) `(throw (ex-info ~(str "param not found: " sym) {:binding '~sym}))))]] form)] ~@body))) (defmacro fnp "Same as `(fn [req] (with-params bindings req body))`" [bindings & body] `(fn [reqsym#] (with-params ~bindings reqsym# ~@body))) (defmacro defnp "Same as `(def name (fnp bindings body))`. Supports docstring, attribute map, and metadata on the name symbol." [name & body] (let [[name [bindings & body]] (name-with-attrs name body)] `(def ~name (fnp ~bindings ~@body)))) (defmacro defnp- "Same as `defnp`, but private." [name & body] `(defnp ~(with-meta name (merge (meta name) {:private true})) ~@body)) (defmacro defmethodp "Same as `(defmethod name dispatch [req] (with-params bindings req body))`." [name dispatch bindings & body] `(defmethod ~name ~dispatch [request#] (with-params ~bindings request# ~@body)))
f9dd34f3d26b5ad3e5fda2a408992b0b88d581ed2968177e5e9b7e6f6b884adf
bract/bract.core
inducer.clj
Copyright ( c ) . All rights reserved . ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (-1.0.php) ; which can be found in the file LICENSE at the root of this distribution. ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. ; You must not remove this notice, or any other, from this software. (ns bract.core.inducer "The inducer functions exposed by `bract.core` module." (:require [clojure.edn :as edn] [clojure.java.io :as io] [keypin.core :as keypin] [keypin.type :as kptype] [keypin.util :as kputil] [bract.core.echo :as echo] [bract.core.impl :as impl] [bract.core.keydef :as kdef] [bract.core.type :as type] [bract.core.util :as util]) (:import [java.net InetAddress UnknownHostException] [bract.core Echo])) ;; ----- utility for applying inducers ----- (def ^:dynamic *inducer-log* "Inducer log holder - :execs is expected to be bound to an `(atom [])`." {:level 0 :execs nil}) (defmacro with-inducer-log [context & body] `(let [level# (:level *inducer-log*) oldex# (:execs *inducer-log*) execs# (or oldex# (atom [(impl/induction-init level# ~context)]))] (try (binding [*inducer-log* {:level (inc (long level#)) :execs execs#}] ~@body) (finally (when (nil? oldex#) (echo/echo (str "Induction report:\n" (impl/make-report @execs#)))))))) (defn apply-inducer "Given a context and inducer-spec, apply the inducer to the context (and args if any) returning updated context." ([context inducer] (apply-inducer "inducer" context inducer)) ([inducer-type context inducer] (let [s (util/now-millis) f (type/ifunc inducer) n (type/iname inducer) a (type/iargs inducer) e (fn [log] (when-let [execs (:execs *inducer-log*)] (swap! execs conj log)))] (try (let [new-context (echo/with-latency-capture (format "Executing %s `%s`" inducer-type n) (echo/with-inducer-name n (apply f context a)))] (e (impl/inducer-success (:level *inducer-log*) inducer-type (cons (symbol n) a) context (unreduced new-context) (util/now-millis s))) new-context) (catch Exception ex (e (impl/inducer-failure (:level *inducer-log*) inducer-type (cons (symbol n) a) (util/now-millis s) (.getName (class ex)))) (throw ex)))))) (defn induce "Given a reducing function `(fn [context inducer-spec]) -> context` and a collection of inducer-specs, roll the seed context through each inducer successively, returning updated context. The chain may be broken by an inducer returning a reduced context, i.e. `(reduced context)`." ([context coll] (induce apply-inducer context coll)) ([f context coll] (with-inducer-log context (reduce (fn [context inducer-candidate] (if (kdef/ctx-exit? context) (reduced context) (f context inducer-candidate))) context coll)))) (defmacro when-context-has-key [[context context-key skipped-message] & body] `(let [context# ~context ctx-key# ~context-key] (if (contains? context# ctx-key#) (do ~@body) (do (echo/echof "Key %s not found in context, skipped %s" ctx-key# ~skipped-message) context#)))) ;; ----- inducers ----- (defn abort "Abort the entire inducer chain." ([context] (assoc context (key kdef/ctx-exit?) true)) ([context message] (echo/abort message) (util/err-println "ERROR:" message) (abort context))) (defn set-verbosity "Set Bract verbosity flag and return context." [context] (let [pre-verbose? (Echo/isVerbose) post-verbose? (kdef/ctx-verbose? context)] (Echo/setVerbose post-verbose?) (when (and (not pre-verbose?) post-verbose?) (echo/echo "Verbose mode enabled - override with env var APP_VERBOSE or system property app.verbose: value true/false"))) context) (defn read-context "Use context filename (when specified) in the context under key `:bract.core/context-file` to read from and merge into the context." [context] (if-let [context-file (kdef/ctx-context-file context)] (if (io/resource context-file) (kdef/resolve-context context context-file) (do (echo/echof "Context file '%s' not found in classpath" context-file) context)) (do (echo/echo "No context file is defined under the key" (key kdef/ctx-context-file)) context))) (defn read-config "Use config filenames in the context under key `:bract.core/config-files` to read and resolve config, and populate the context with it under the key `:bract.core/config`." [context] (let [config-files (kdef/ctx-config-files context)] (if (seq config-files) (->> config-files (kdef/resolve-config context) (assoc context (key kdef/ctx-config))) (do (echo/echo (format "No config files specified at %s for reading, skipping" (key kdef/ctx-config-files))) context)))) (defn run-context-inducers "Run the inducers specified in the context." ([context] (impl/with-lookup-key (key kdef/ctx-inducers) (->> (kdef/ctx-inducers context) (induce context)))) ([context lookup-key] (impl/with-lookup-key lookup-key (as-> (keypin/make-key {:the-key lookup-key :pred vector? :desc "Vector of inducer fns or their fully qualified names"}) <> (<> context) (induce context <>))))) (defn run-config-inducers "Run the inducers specified in the application config." ([context] (impl/with-lookup-key (key kdef/cfg-inducers) (->> (kdef/ctx-config context) kdef/cfg-inducers (induce context)))) ([context lookup-key] (impl/with-lookup-key lookup-key (->> (kdef/ctx-config context) ((keypin/make-key {:the-key lookup-key :pred vector? :desc "Vector of inducer fns or their fully qualified names"})) (induce context))))) (defn context-hook "Given context with config, invoke the context-hook fn with context as argument." [context function] (let [f (type/ifunc function)] (util/expected fn? (format "%s to be a function" function) f) (f context) context)) (defn export-as-sysprops "Given context with config, read the value of config key `\"bract.core.exports\"` as a vector of string config keys and export the key-value pairs for those config keys as system properties." [context] (let [config (kdef/ctx-config context) exlist (-> (kdef/cfg-exports config) (echo/->echo "Exporting as system properties"))] (doseq [each exlist] (util/expected string? "export property name as string" each) (when-not (contains? config each) (util/expected (format "export property name '%s' to exist in config" each) config)) (util/expected string? (format "value for export property name '%s' as string" each) (get config each)) (System/setProperty each (get config each))) context)) (defn unexport-sysprops "Given context with config, read the value of config key `\"bract.core.exports\"` as a vector of string config keys and remove them from system properties." [context] (let [config (kdef/ctx-config context) exlist (-> (kdef/cfg-exports config) (echo/->echo "Un-exporting (removing) system properties"))] (doseq [each exlist] (util/expected string? "export property name as string" each) (when-not (contains? config each) (util/expected (format "export property name '%s' to exist in config" each) config)) (util/expected string? (format "value for export property name '%s' as string" each) (get config each)) (System/clearProperty each)) context)) (defn invoke-launchers "Given context with key `:bract.core/launchers` read its value as a vector of launcher fns and invoke them like inducers `(fn [context]) -> context` when the context key `:bract.core/launch?` has the value `true`." ([context] (if (kdef/ctx-launch? context) (invoke-launchers context (kdef/ctx-launchers context)) (do (echo/echo "Launch not enabled, skipping launch.") context))) ([context launchers] (if (kdef/ctx-launch? context) (do (echo/echo "Launcher name:" launchers) (induce context launchers)) (do (echo/echo "Launch not enabled, skipping launch.") context)))) (defn invoke-deinit "Given context with `:bract.core/deinit` key and corresponding collection of `(fn [])` de-init functions for the app, invoke them in a sequence. Return context with empty deinit vector." ([context] (invoke-deinit context true)) ([context ignore-errors?] (let [coll (kdef/ctx-deinit context)] (if (seq coll) (doseq [f coll] (try (f) (catch Exception e (echo/echof "Application de-init error (%s): %s" (if ignore-errors? "ignored" "not ignored") (util/stack-trace-str e)) (when-not ignore-errors? (throw e))))) (echo/echo "Application de-init is not configured, skipping de-initialization."))) (assoc context (key kdef/ctx-deinit) []))) (defn invoke-stopper "Given context with `:bract.core/stopper` key and corresponding `(fn [])` stopper function for the app, invoke it." [context] (let [f (kdef/ctx-stopper context)] (f)) context) (defn add-shutdown-hook "Given context with `:bract.core/*shutdown-flag` and `:bract.core/shutdown-hooks` keys related to app shutdown, and config key `\"bract.core.drain.timeout\"`, add an inducer as a shutdown hook. Specified inducer ([[invoke-deinit]] by default) may be a function or a fully-qualified function name." ([context] (add-shutdown-hook context invoke-deinit)) ([context inducer] (let [flag (kdef/*ctx-shutdown-flag context) ; volatile of boolean timeout (-> (kdef/ctx-config context) kdef/cfg-drain-timeout timeout in millis t-messg "The JVM received a TERMINATE request, reached shutdown-hook" thread (Thread. (fn [] (if (Echo/isVerbose) (echo/echo t-messg) (util/err-println t-messg)) ;; set the flag (when flag (vswap! flag (fn [fval] (echo/echo (if fval "Shutdown flag is already set to true, leaving as is" "Shutdown flag was false, now set to true")) true))) ;; wait for timeout (let [last-alive-millis (long @(kdef/ctx-alive-tstamp context)) until-time-millis (if (pos? last-alive-millis) (unchecked-add last-alive-millis ^long timeout) (unchecked-add (util/now-millis) ^long timeout))] (while (< (util/now-millis) until-time-millis) (let [nap-millis (unchecked-subtract until-time-millis (util/now-millis)) nap-message (format "Waiting for current workload to drain, time remaing: %d ms" nap-millis)] (when (pos? nap-millis) (if (Echo/isVerbose) (echo/echo nap-message) (util/err-println nap-message)) (util/sleep-millis (min 500 nap-millis)))))) ;; invoke shutdown-hook inducer (echo/echo "Workload draining timed out, executing shutdown-hook inducer now") (apply-inducer context inducer)))] (.addShutdownHook ^Runtime (Runtime/getRuntime) thread) (update context (key kdef/ctx-shutdown-hooks) conj thread)))) (defn set-default-exception-handler "Set specified function (STDERR printer by default) as the default uncaught-exception handler for all JVM threads." ([context] (set-default-exception-handler context (fn [^Thread thread ^Throwable ex] (util/err-println (format "Uncaught exception in thread ID: %d, thread name: %s - %s" (.getId thread) (.getName thread) (util/stack-trace-str ex)))))) ([context exception-handler] (-> (type/ifunc exception-handler) util/set-default-uncaught-exception-handler) context)) ;; ----- inducers that inject config ----- (defn discover-hostname "Discover hostname and add to config if absent. Options: | Kwarg | Description | |-------------|-------------| |`:config-key`| configuration key to update discovered hostname at, default: `\"discovered.hostname\"`|" ([context] (discover-hostname context {})) ([context {:keys [config-key] :or {config-key "discovered.hostname"}}] (kdef/discover-config context config-key (fn [key-path] (try (let [^InetAddress localhost (InetAddress/getLocalHost)] (assoc-in context key-path (.getHostName localhost))) (catch UnknownHostException e (echo/echof "Cannot determine hostname (stack trace below), not adding config key '%s'" (pr-str config-key)) (.printStackTrace e System/err) context)))))) (defn discover-project-edn-version "Discover application version from project.edn file containing :version key, and add to config if absent. Options: | Kwarg | Description | |--------------|-------------| |`:config-key` | configuration key to update discovered version at, default: `\"discovered.app.version\"`| |`:project-edn`| resource path to the project EDN file, default: `\"project.edn\"` (in classpath) |" ([context] (discover-project-edn-version context {})) ([context {:keys [config-key project-edn] :or {config-key "discovered.app.version" project-edn "project.edn"}}] (kdef/discover-config context config-key (fn [key-path] (if-let [project-edn-resource (io/resource project-edn)] (try (let [proj-map (-> project-edn-resource slurp edn/read-string)] (if-let [version (:version proj-map)] (assoc-in context key-path version) (do (echo/echof "Cannot find key :version in the config read from classpath file '%s', not adding config key '%s'" (pr-str project-edn) (pr-str config-key)) context))) (catch Exception e (echo/echof "Error reading file '%s' in classpath as EDN (stack trace below), not adding config key '%s'" (pr-str project-edn) (pr-str config-key)) (.printStackTrace e System/err) context)) (do (echo/echof (str "Cannot find the file '%s' in classpath, not adding config key '%s'. " "This may help: -project-edn") (pr-str project-edn) (pr-str config-key)) context))))))
null
https://raw.githubusercontent.com/bract/bract.core/625b8738554b1e1b61bd8522397fb698fb12d3d3/src/bract/core/inducer.clj
clojure
The use and distribution terms for this software are covered by the Eclipse Public License 1.0 (-1.0.php) which can be found in the file LICENSE at the root of this distribution. By using this software in any fashion, you are agreeing to be bound by the terms of this license. You must not remove this notice, or any other, from this software. ----- utility for applying inducers ----- ----- inducers ----- volatile of boolean set the flag wait for timeout invoke shutdown-hook inducer ----- inducers that inject config -----
Copyright ( c ) . All rights reserved . (ns bract.core.inducer "The inducer functions exposed by `bract.core` module." (:require [clojure.edn :as edn] [clojure.java.io :as io] [keypin.core :as keypin] [keypin.type :as kptype] [keypin.util :as kputil] [bract.core.echo :as echo] [bract.core.impl :as impl] [bract.core.keydef :as kdef] [bract.core.type :as type] [bract.core.util :as util]) (:import [java.net InetAddress UnknownHostException] [bract.core Echo])) (def ^:dynamic *inducer-log* "Inducer log holder - :execs is expected to be bound to an `(atom [])`." {:level 0 :execs nil}) (defmacro with-inducer-log [context & body] `(let [level# (:level *inducer-log*) oldex# (:execs *inducer-log*) execs# (or oldex# (atom [(impl/induction-init level# ~context)]))] (try (binding [*inducer-log* {:level (inc (long level#)) :execs execs#}] ~@body) (finally (when (nil? oldex#) (echo/echo (str "Induction report:\n" (impl/make-report @execs#)))))))) (defn apply-inducer "Given a context and inducer-spec, apply the inducer to the context (and args if any) returning updated context." ([context inducer] (apply-inducer "inducer" context inducer)) ([inducer-type context inducer] (let [s (util/now-millis) f (type/ifunc inducer) n (type/iname inducer) a (type/iargs inducer) e (fn [log] (when-let [execs (:execs *inducer-log*)] (swap! execs conj log)))] (try (let [new-context (echo/with-latency-capture (format "Executing %s `%s`" inducer-type n) (echo/with-inducer-name n (apply f context a)))] (e (impl/inducer-success (:level *inducer-log*) inducer-type (cons (symbol n) a) context (unreduced new-context) (util/now-millis s))) new-context) (catch Exception ex (e (impl/inducer-failure (:level *inducer-log*) inducer-type (cons (symbol n) a) (util/now-millis s) (.getName (class ex)))) (throw ex)))))) (defn induce "Given a reducing function `(fn [context inducer-spec]) -> context` and a collection of inducer-specs, roll the seed context through each inducer successively, returning updated context. The chain may be broken by an inducer returning a reduced context, i.e. `(reduced context)`." ([context coll] (induce apply-inducer context coll)) ([f context coll] (with-inducer-log context (reduce (fn [context inducer-candidate] (if (kdef/ctx-exit? context) (reduced context) (f context inducer-candidate))) context coll)))) (defmacro when-context-has-key [[context context-key skipped-message] & body] `(let [context# ~context ctx-key# ~context-key] (if (contains? context# ctx-key#) (do ~@body) (do (echo/echof "Key %s not found in context, skipped %s" ctx-key# ~skipped-message) context#)))) (defn abort "Abort the entire inducer chain." ([context] (assoc context (key kdef/ctx-exit?) true)) ([context message] (echo/abort message) (util/err-println "ERROR:" message) (abort context))) (defn set-verbosity "Set Bract verbosity flag and return context." [context] (let [pre-verbose? (Echo/isVerbose) post-verbose? (kdef/ctx-verbose? context)] (Echo/setVerbose post-verbose?) (when (and (not pre-verbose?) post-verbose?) (echo/echo "Verbose mode enabled - override with env var APP_VERBOSE or system property app.verbose: value true/false"))) context) (defn read-context "Use context filename (when specified) in the context under key `:bract.core/context-file` to read from and merge into the context." [context] (if-let [context-file (kdef/ctx-context-file context)] (if (io/resource context-file) (kdef/resolve-context context context-file) (do (echo/echof "Context file '%s' not found in classpath" context-file) context)) (do (echo/echo "No context file is defined under the key" (key kdef/ctx-context-file)) context))) (defn read-config "Use config filenames in the context under key `:bract.core/config-files` to read and resolve config, and populate the context with it under the key `:bract.core/config`." [context] (let [config-files (kdef/ctx-config-files context)] (if (seq config-files) (->> config-files (kdef/resolve-config context) (assoc context (key kdef/ctx-config))) (do (echo/echo (format "No config files specified at %s for reading, skipping" (key kdef/ctx-config-files))) context)))) (defn run-context-inducers "Run the inducers specified in the context." ([context] (impl/with-lookup-key (key kdef/ctx-inducers) (->> (kdef/ctx-inducers context) (induce context)))) ([context lookup-key] (impl/with-lookup-key lookup-key (as-> (keypin/make-key {:the-key lookup-key :pred vector? :desc "Vector of inducer fns or their fully qualified names"}) <> (<> context) (induce context <>))))) (defn run-config-inducers "Run the inducers specified in the application config." ([context] (impl/with-lookup-key (key kdef/cfg-inducers) (->> (kdef/ctx-config context) kdef/cfg-inducers (induce context)))) ([context lookup-key] (impl/with-lookup-key lookup-key (->> (kdef/ctx-config context) ((keypin/make-key {:the-key lookup-key :pred vector? :desc "Vector of inducer fns or their fully qualified names"})) (induce context))))) (defn context-hook "Given context with config, invoke the context-hook fn with context as argument." [context function] (let [f (type/ifunc function)] (util/expected fn? (format "%s to be a function" function) f) (f context) context)) (defn export-as-sysprops "Given context with config, read the value of config key `\"bract.core.exports\"` as a vector of string config keys and export the key-value pairs for those config keys as system properties." [context] (let [config (kdef/ctx-config context) exlist (-> (kdef/cfg-exports config) (echo/->echo "Exporting as system properties"))] (doseq [each exlist] (util/expected string? "export property name as string" each) (when-not (contains? config each) (util/expected (format "export property name '%s' to exist in config" each) config)) (util/expected string? (format "value for export property name '%s' as string" each) (get config each)) (System/setProperty each (get config each))) context)) (defn unexport-sysprops "Given context with config, read the value of config key `\"bract.core.exports\"` as a vector of string config keys and remove them from system properties." [context] (let [config (kdef/ctx-config context) exlist (-> (kdef/cfg-exports config) (echo/->echo "Un-exporting (removing) system properties"))] (doseq [each exlist] (util/expected string? "export property name as string" each) (when-not (contains? config each) (util/expected (format "export property name '%s' to exist in config" each) config)) (util/expected string? (format "value for export property name '%s' as string" each) (get config each)) (System/clearProperty each)) context)) (defn invoke-launchers "Given context with key `:bract.core/launchers` read its value as a vector of launcher fns and invoke them like inducers `(fn [context]) -> context` when the context key `:bract.core/launch?` has the value `true`." ([context] (if (kdef/ctx-launch? context) (invoke-launchers context (kdef/ctx-launchers context)) (do (echo/echo "Launch not enabled, skipping launch.") context))) ([context launchers] (if (kdef/ctx-launch? context) (do (echo/echo "Launcher name:" launchers) (induce context launchers)) (do (echo/echo "Launch not enabled, skipping launch.") context)))) (defn invoke-deinit "Given context with `:bract.core/deinit` key and corresponding collection of `(fn [])` de-init functions for the app, invoke them in a sequence. Return context with empty deinit vector." ([context] (invoke-deinit context true)) ([context ignore-errors?] (let [coll (kdef/ctx-deinit context)] (if (seq coll) (doseq [f coll] (try (f) (catch Exception e (echo/echof "Application de-init error (%s): %s" (if ignore-errors? "ignored" "not ignored") (util/stack-trace-str e)) (when-not ignore-errors? (throw e))))) (echo/echo "Application de-init is not configured, skipping de-initialization."))) (assoc context (key kdef/ctx-deinit) []))) (defn invoke-stopper "Given context with `:bract.core/stopper` key and corresponding `(fn [])` stopper function for the app, invoke it." [context] (let [f (kdef/ctx-stopper context)] (f)) context) (defn add-shutdown-hook "Given context with `:bract.core/*shutdown-flag` and `:bract.core/shutdown-hooks` keys related to app shutdown, and config key `\"bract.core.drain.timeout\"`, add an inducer as a shutdown hook. Specified inducer ([[invoke-deinit]] by default) may be a function or a fully-qualified function name." ([context] (add-shutdown-hook context invoke-deinit)) ([context inducer] timeout (-> (kdef/ctx-config context) kdef/cfg-drain-timeout timeout in millis t-messg "The JVM received a TERMINATE request, reached shutdown-hook" thread (Thread. (fn [] (if (Echo/isVerbose) (echo/echo t-messg) (util/err-println t-messg)) (when flag (vswap! flag (fn [fval] (echo/echo (if fval "Shutdown flag is already set to true, leaving as is" "Shutdown flag was false, now set to true")) true))) (let [last-alive-millis (long @(kdef/ctx-alive-tstamp context)) until-time-millis (if (pos? last-alive-millis) (unchecked-add last-alive-millis ^long timeout) (unchecked-add (util/now-millis) ^long timeout))] (while (< (util/now-millis) until-time-millis) (let [nap-millis (unchecked-subtract until-time-millis (util/now-millis)) nap-message (format "Waiting for current workload to drain, time remaing: %d ms" nap-millis)] (when (pos? nap-millis) (if (Echo/isVerbose) (echo/echo nap-message) (util/err-println nap-message)) (util/sleep-millis (min 500 nap-millis)))))) (echo/echo "Workload draining timed out, executing shutdown-hook inducer now") (apply-inducer context inducer)))] (.addShutdownHook ^Runtime (Runtime/getRuntime) thread) (update context (key kdef/ctx-shutdown-hooks) conj thread)))) (defn set-default-exception-handler "Set specified function (STDERR printer by default) as the default uncaught-exception handler for all JVM threads." ([context] (set-default-exception-handler context (fn [^Thread thread ^Throwable ex] (util/err-println (format "Uncaught exception in thread ID: %d, thread name: %s - %s" (.getId thread) (.getName thread) (util/stack-trace-str ex)))))) ([context exception-handler] (-> (type/ifunc exception-handler) util/set-default-uncaught-exception-handler) context)) (defn discover-hostname "Discover hostname and add to config if absent. Options: | Kwarg | Description | |-------------|-------------| |`:config-key`| configuration key to update discovered hostname at, default: `\"discovered.hostname\"`|" ([context] (discover-hostname context {})) ([context {:keys [config-key] :or {config-key "discovered.hostname"}}] (kdef/discover-config context config-key (fn [key-path] (try (let [^InetAddress localhost (InetAddress/getLocalHost)] (assoc-in context key-path (.getHostName localhost))) (catch UnknownHostException e (echo/echof "Cannot determine hostname (stack trace below), not adding config key '%s'" (pr-str config-key)) (.printStackTrace e System/err) context)))))) (defn discover-project-edn-version "Discover application version from project.edn file containing :version key, and add to config if absent. Options: | Kwarg | Description | |--------------|-------------| |`:config-key` | configuration key to update discovered version at, default: `\"discovered.app.version\"`| |`:project-edn`| resource path to the project EDN file, default: `\"project.edn\"` (in classpath) |" ([context] (discover-project-edn-version context {})) ([context {:keys [config-key project-edn] :or {config-key "discovered.app.version" project-edn "project.edn"}}] (kdef/discover-config context config-key (fn [key-path] (if-let [project-edn-resource (io/resource project-edn)] (try (let [proj-map (-> project-edn-resource slurp edn/read-string)] (if-let [version (:version proj-map)] (assoc-in context key-path version) (do (echo/echof "Cannot find key :version in the config read from classpath file '%s', not adding config key '%s'" (pr-str project-edn) (pr-str config-key)) context))) (catch Exception e (echo/echof "Error reading file '%s' in classpath as EDN (stack trace below), not adding config key '%s'" (pr-str project-edn) (pr-str config-key)) (.printStackTrace e System/err) context)) (do (echo/echof (str "Cannot find the file '%s' in classpath, not adding config key '%s'. " "This may help: -project-edn") (pr-str project-edn) (pr-str config-key)) context))))))
3c94895a3be43395a68aacc05456ef8867fcf504af334ddbf69a27605658ff69
joelburget/react-haskell
PropTypes.hs
# LANGUAGE CPP , FlexibleInstances # #ifdef __GHCJS__ # LANGUAGE JavaScriptFFI # #else # OPTIONS_GHC -fno - warn - missing - methods # #endif module React.PropTypes where import Data.Monoid import Data.Text (Text) import React.GHCJS import React.Imports data FPropType_ type FPropType = JSRef FPropType_ #ifdef __GHCJS__ foreign import javascript unsafe "React.PropTypes.bool" fPropBool :: FPropType foreign import javascript unsafe "React.PropTypes.func" fPropFunc :: FPropType foreign import javascript unsafe "React.PropTypes.number" fPropNumber :: FPropType foreign import javascript unsafe "React.PropTypes.string" fPropString :: FPropType foreign import javascript unsafe "React.PropTypes.object" fPropObject :: FPropType foreign import javascript unsafe "$1.isRequired" fIsRequired :: FPropType -> FPropType #else fPropBool :: FPropType fPropBool = undefined fPropFunc :: FPropType fPropFunc = undefined fPropNumber :: FPropType fPropNumber = undefined fPropString :: FPropType fPropString = undefined fPropObject :: FPropType fPropObject = undefined fIsRequired :: FPropType -> FPropType fIsRequired = undefined #endif data PropRequired = IsRequired | IsntRequired -- | The equivalent to React propTypes. data PropType = = PropBool PropRequired | PropFunc PropRequired | PropNumber PropRequired | PropString PropRequired | PropObject PropRequired PropArray PropShape ( H.HashMap Text PropType ) -- PropEnum [Text] PropUnion [ PropType ] toJsPropType :: PropType -> FPropType toJsPropType (PropBool req) = ptReq req fPropBool toJsPropType (PropFunc req) = ptReq req fPropFunc toJsPropType (PropNumber req) = ptReq req fPropNumber toJsPropType (PropString req) = ptReq req fPropString toJsPropType (PropObject req) = ptReq req fPropObject ptReq :: PropRequired -> FPropType -> FPropType ptReq IsRequired = fIsRequired ptReq IsntRequired = id | Describe the PropType of a type -- -- Examples: -- -- @ propType ( _ : : JSString ) = PropString IsRequired -- propType ( _ : : ) = PropBool IsRequired -- @ class PropTypable a where propType :: a -> PropType instance PropTypable (JSRef ()) where -- TOOD(joel) instanceOf this propType _ = PropObject IsRequired instance PropTypable JSString where propType _ = PropString IsRequired
null
https://raw.githubusercontent.com/joelburget/react-haskell/5de76473b7cfdd6b85ac618bea31e658794b54e2/src/React/PropTypes.hs
haskell
| The equivalent to React propTypes. PropEnum [Text] Examples: @ @ TOOD(joel) instanceOf this
# LANGUAGE CPP , FlexibleInstances # #ifdef __GHCJS__ # LANGUAGE JavaScriptFFI # #else # OPTIONS_GHC -fno - warn - missing - methods # #endif module React.PropTypes where import Data.Monoid import Data.Text (Text) import React.GHCJS import React.Imports data FPropType_ type FPropType = JSRef FPropType_ #ifdef __GHCJS__ foreign import javascript unsafe "React.PropTypes.bool" fPropBool :: FPropType foreign import javascript unsafe "React.PropTypes.func" fPropFunc :: FPropType foreign import javascript unsafe "React.PropTypes.number" fPropNumber :: FPropType foreign import javascript unsafe "React.PropTypes.string" fPropString :: FPropType foreign import javascript unsafe "React.PropTypes.object" fPropObject :: FPropType foreign import javascript unsafe "$1.isRequired" fIsRequired :: FPropType -> FPropType #else fPropBool :: FPropType fPropBool = undefined fPropFunc :: FPropType fPropFunc = undefined fPropNumber :: FPropType fPropNumber = undefined fPropString :: FPropType fPropString = undefined fPropObject :: FPropType fPropObject = undefined fIsRequired :: FPropType -> FPropType fIsRequired = undefined #endif data PropRequired = IsRequired | IsntRequired data PropType = = PropBool PropRequired | PropFunc PropRequired | PropNumber PropRequired | PropString PropRequired | PropObject PropRequired PropArray PropShape ( H.HashMap Text PropType ) PropUnion [ PropType ] toJsPropType :: PropType -> FPropType toJsPropType (PropBool req) = ptReq req fPropBool toJsPropType (PropFunc req) = ptReq req fPropFunc toJsPropType (PropNumber req) = ptReq req fPropNumber toJsPropType (PropString req) = ptReq req fPropString toJsPropType (PropObject req) = ptReq req fPropObject ptReq :: PropRequired -> FPropType -> FPropType ptReq IsRequired = fIsRequired ptReq IsntRequired = id | Describe the PropType of a type propType ( _ : : JSString ) = PropString IsRequired propType ( _ : : ) = PropBool IsRequired class PropTypable a where propType :: a -> PropType instance PropTypable (JSRef ()) where propType _ = PropObject IsRequired instance PropTypable JSString where propType _ = PropString IsRequired
ae2e47aeac0016490c3e02add7d0195a54a59e288403e80f2812e0a0a46d3248
PhDP/Akarui
Fmt.hs
-- | Functions to print some common data stuctures in a specific format. This is mostly convenient for playing with Sphinx in the console . module Akarui.Fmt where import qualified Data.Text as T import Data.Map (Map) import qualified Data.Map as Map import Data.Set (Set) import qualified Data.Set as Set import Akarui.Text import Akarui.ShowTxt -- | Formats a set in the standard format (not a 'fromList'). fmtSet :: (ShowTxt k, Ord k) => Set k -> T.Text fmtSet s = addBrackets $ T.drop 2 $ Set.foldl' (\acc k -> T.concat [acc, ", ", showTxt k]) "" s -- | Formats a map. fmtMap :: (ShowTxt k, ShowTxt v, Ord k) => Map k v -> T.Text fmtMap = Map.foldrWithKey' (\k v acc -> T.concat [showTxt k, " -> ", showTxt v, "\n", acc]) "" -- | Formats a map of sets to something fmtMapOfSet :: (ShowTxt k, ShowTxt v, Ord k) => Map (Set k) v -> T.Text fmtMapOfSet = Map.foldrWithKey' (\k v acc -> T.concat [fmtSet k, " -> ", showTxt v, "\n", acc]) "" -- | Formats a map of sets (often used to represent undirected networks). fmtMapSet :: (ShowTxt k0, ShowTxt k1, Ord k0, Ord k1) => Map k0 (Set k1) -> T.Text fmtMapSet = Map.foldrWithKey' (\k v acc -> T.concat [showTxt k, " -> ", fmtSet v, "\n", acc]) "" -- | Formats a map of maps (often used to represent networks.) fmtMapMap :: (Show k0, Show k1, Show v, Ord k0, Ord k1) => Map k0 (Map k1 v) -> String fmtMapMap = Map.foldrWithKey' vertices "" where vertices k v acc = show k ++ " -> " ++ edges v ++ "\n" ++ acc edges = Map.foldrWithKey' (\k v acc -> "(" ++ show k ++ ", " ++ show v ++ "), " ++ acc) ""
null
https://raw.githubusercontent.com/PhDP/Akarui/4ad888d011f7115677e8f9ba18887865f5150746/Akarui/Fmt.hs
haskell
| Functions to print some common data stuctures in a specific format. This | Formats a set in the standard format (not a 'fromList'). | Formats a map. | Formats a map of sets to something | Formats a map of sets (often used to represent undirected networks). | Formats a map of maps (often used to represent networks.)
is mostly convenient for playing with Sphinx in the console . module Akarui.Fmt where import qualified Data.Text as T import Data.Map (Map) import qualified Data.Map as Map import Data.Set (Set) import qualified Data.Set as Set import Akarui.Text import Akarui.ShowTxt fmtSet :: (ShowTxt k, Ord k) => Set k -> T.Text fmtSet s = addBrackets $ T.drop 2 $ Set.foldl' (\acc k -> T.concat [acc, ", ", showTxt k]) "" s fmtMap :: (ShowTxt k, ShowTxt v, Ord k) => Map k v -> T.Text fmtMap = Map.foldrWithKey' (\k v acc -> T.concat [showTxt k, " -> ", showTxt v, "\n", acc]) "" fmtMapOfSet :: (ShowTxt k, ShowTxt v, Ord k) => Map (Set k) v -> T.Text fmtMapOfSet = Map.foldrWithKey' (\k v acc -> T.concat [fmtSet k, " -> ", showTxt v, "\n", acc]) "" fmtMapSet :: (ShowTxt k0, ShowTxt k1, Ord k0, Ord k1) => Map k0 (Set k1) -> T.Text fmtMapSet = Map.foldrWithKey' (\k v acc -> T.concat [showTxt k, " -> ", fmtSet v, "\n", acc]) "" fmtMapMap :: (Show k0, Show k1, Show v, Ord k0, Ord k1) => Map k0 (Map k1 v) -> String fmtMapMap = Map.foldrWithKey' vertices "" where vertices k v acc = show k ++ " -> " ++ edges v ++ "\n" ++ acc edges = Map.foldrWithKey' (\k v acc -> "(" ++ show k ++ ", " ++ show v ++ "), " ++ acc) ""
c5eabedab81eb1e6283a51e3a1f97d666f15ed30d5a3b8296a2d22a1432eac3c
fulcro-legacy/fulcro-tutorial
F_Fulcro_Client.cljs
(ns fulcro-tutorial.F-Fulcro-Client (:require [fulcro.client.primitives :as prim :refer-macros [defui]] [fulcro.client.dom :as dom] [devcards.core :as dc :refer-macros [defcard defcard-doc]])) (defcard-doc " # Building a Fulcro client We're now prepared to write a standalone Fulcro Client! Once you've understood how to build the UI and do a few mutations it actually takes very little code: The basic steps are: - Create the UI with queries, etc. - Give a DOM element in your HTML file an ID, and load your target compiled js - Create a Fulcro client - Mount the client on that DOM element We've covered the first step already. The second step is trivial: ```html <body> <div id=\"app\"></div> <!-- Your app will mount on this div --> <script src=\"js/my-app.js\"></script> <!-- this will load your app's generated js --> </body> ``` The final two steps are typically done such that you can track the overall application in an atom: ```clojure (ns app.core (:require [fulcro.client :as fc] [app.ui :as ui] [fulcro.client.primitives :as prim])) (defonce app (atom (fc/new-fulcro-client :initial-state { :some-data 42 }))) (reset! app (core/mount @app ui/Root \"app\")) ``` This tiny bit of code does a *lot*: - It creates an entire ecosystem: - A client-side ecosystem with i18n, state, query and mutation support. - Plumbing to make it possible to do networking to your server. - Complete handling of tempids, merging, attribute conflict resolution, and more! - Application locale handling. - Support VCR viewer recording with internal mutations that can submit support requests. - Support for refreshing the entire UI on hot code reload (with your help). - It mounts the application UI on the given DOM element (you can pass a real node or string ID). Some additional things that are available (which we'll cover soon): - The ability to load data on start using any queries you've placed on the UI or written elsewhere. - The ability to do deferred lazy-load on component fields (e.g. comments on an item). Wow! That's a lot for two lines of code. ## Running Fulcro in a Dev Card ```clojure (ns boo (:require [fulcro.client.cards :refer [defcard-fulcro]])) (defcard-fulcro sample \"Optional markdown\" ui/Root initial state from the card ( If empty , uses InitialAppState which is covered later ) . devcard options :fulcro {:started-callback (fn [app] ...) }) ; fulcro client options ``` ## The Reconciler The reconciler is a central component of the primitives in Fulcro. It is responsible for reconciling the state of your database with the UI. Many function in the `primitives` namespace require it. It is held on the application at the `:reconciler` key, and is passed to you inside of your mutation `env` under that same key. If you're expecting to have data changes that happen outside of the UI (e.g. web workers), you'll want to save the reconciler so you can get to it. If you've saved your top-level application in an atom, you can obviously get it from there, otherwise you might want to put it somewhere on startup. ## Initial Application State The `:initial-state` option of `new-fulcro-client` can accept a map (which will be assumed to be a TREE of non-normalized data), or an `atom` (which will be assumed to be a pre-normalized database). If you supply a map, it will be auto-normalized using your UI's query and ident, but if you supply an atom it will be used AS the normalized application database. We do *not* recommend initializing your application in *either* of these ways except in extremely simple circumstances, instead Fulcro allows you to co-locate your initial app state locally on the components so that you just don't have to think much about it. You should definitely read the next section about [the InitialAppState mechanism](#!/fulcro_tutorial.F_Fulcro_Initial_App_State). It will make your life easier. ")
null
https://raw.githubusercontent.com/fulcro-legacy/fulcro-tutorial/fe9bcd19908d4e24e723954e3804ceccfd07e989/src/tutorial/fulcro_tutorial/F_Fulcro_Client.cljs
clojure
fulcro client options
(ns fulcro-tutorial.F-Fulcro-Client (:require [fulcro.client.primitives :as prim :refer-macros [defui]] [fulcro.client.dom :as dom] [devcards.core :as dc :refer-macros [defcard defcard-doc]])) (defcard-doc " # Building a Fulcro client We're now prepared to write a standalone Fulcro Client! Once you've understood how to build the UI and do a few mutations it actually takes very little code: The basic steps are: - Create the UI with queries, etc. - Give a DOM element in your HTML file an ID, and load your target compiled js - Create a Fulcro client - Mount the client on that DOM element We've covered the first step already. The second step is trivial: ```html <body> <div id=\"app\"></div> <!-- Your app will mount on this div --> <script src=\"js/my-app.js\"></script> <!-- this will load your app's generated js --> </body> ``` The final two steps are typically done such that you can track the overall application in an atom: ```clojure (ns app.core (:require [fulcro.client :as fc] [app.ui :as ui] [fulcro.client.primitives :as prim])) (defonce app (atom (fc/new-fulcro-client :initial-state { :some-data 42 }))) (reset! app (core/mount @app ui/Root \"app\")) ``` This tiny bit of code does a *lot*: - It creates an entire ecosystem: - A client-side ecosystem with i18n, state, query and mutation support. - Plumbing to make it possible to do networking to your server. - Complete handling of tempids, merging, attribute conflict resolution, and more! - Application locale handling. - Support VCR viewer recording with internal mutations that can submit support requests. - Support for refreshing the entire UI on hot code reload (with your help). - It mounts the application UI on the given DOM element (you can pass a real node or string ID). Some additional things that are available (which we'll cover soon): - The ability to load data on start using any queries you've placed on the UI or written elsewhere. - The ability to do deferred lazy-load on component fields (e.g. comments on an item). Wow! That's a lot for two lines of code. ## Running Fulcro in a Dev Card ```clojure (ns boo (:require [fulcro.client.cards :refer [defcard-fulcro]])) (defcard-fulcro sample \"Optional markdown\" ui/Root initial state from the card ( If empty , uses InitialAppState which is covered later ) . devcard options ``` ## The Reconciler The reconciler is a central component of the primitives in Fulcro. It is responsible for reconciling the state of your database with the UI. Many function in the `primitives` namespace require it. It is held on the application at the `:reconciler` key, and is passed to you inside of your mutation `env` under that same key. If you're expecting to have data changes that happen outside of the UI (e.g. web workers), you'll want to save the reconciler so you can get to it. If you've saved your top-level application in an atom, you can obviously get it from there, otherwise you might want to put it somewhere on startup. ## Initial Application State The `:initial-state` option of `new-fulcro-client` can accept a map (which will be assumed to be a TREE of non-normalized data), or an `atom` (which will be assumed to be a pre-normalized database). If you supply a map, it will be auto-normalized using your UI's query and ident, but if you supply an atom it will be used AS the normalized application database. We do *not* recommend initializing your application in *either* of these ways except in extremely simple circumstances, instead Fulcro allows you to co-locate your initial app state locally on the components so that you just don't have to think much about it. You should definitely read the next section about [the InitialAppState mechanism](#!/fulcro_tutorial.F_Fulcro_Initial_App_State). It will make your life easier. ")
81f3772c7d4a2690a19d47a308db1908ab6710ef83c6e4cd3c3b2f8c6cc62757
nandor/llir-ocaml
t040-makeblock1.ml
TEST include tool - ocaml - lib flags = " -w a " ocaml_script_as_argument = " true " * setup - ocaml - build - env * * include tool-ocaml-lib flags = "-w a" ocaml_script_as_argument = "true" * setup-ocaml-build-env ** ocaml *) type t = { mutable a : int; };; { a = 0 };; * 0 CONST0 1 MAKEBLOCK1 0 3 ATOM0 4 SETGLOBAL T040 - makeblock1 6 STOP * 0 CONST0 1 MAKEBLOCK1 0 3 ATOM0 4 SETGLOBAL T040-makeblock1 6 STOP **)
null
https://raw.githubusercontent.com/nandor/llir-ocaml/9c019f15c444e30c825b1673cbe827e0497868fe/testsuite/tests/tool-ocaml/t040-makeblock1.ml
ocaml
TEST include tool - ocaml - lib flags = " -w a " ocaml_script_as_argument = " true " * setup - ocaml - build - env * * include tool-ocaml-lib flags = "-w a" ocaml_script_as_argument = "true" * setup-ocaml-build-env ** ocaml *) type t = { mutable a : int; };; { a = 0 };; * 0 CONST0 1 MAKEBLOCK1 0 3 ATOM0 4 SETGLOBAL T040 - makeblock1 6 STOP * 0 CONST0 1 MAKEBLOCK1 0 3 ATOM0 4 SETGLOBAL T040-makeblock1 6 STOP **)
6265732f9e63dc3525f85920bf63bebdfddee5f8fd559c65f9754bb079378674
skinkade/uniformity
pbkdf2.cljs
(ns uniformity.internals.js.pbkdf2 (:require [uniformity.internals.js.node-browser-compat :refer [crypto-type crypto]] [uniformity.internals.js.util :refer [str->utf8]] [cljs.core.async :as async] [cljs.core.async.interop :refer [p->c]] ;; [clojure.string :as string] [async-error.core :refer-macros [go-try <?]])) (def browser-hash-lookup {:sha1 "SHA-1" :sha256 "SHA-256" :sha384 "SHA-384" :sha512 "SHA-512"}) (def node-hash-lookup {:sha1 "SHA1" :sha256 "SHA256" :sha384 "SHA384" :sha512 "SHA512"}) (defn browser-pbkdf2 [^String password ^js/Uint8Array salt ^number iterations ^String hash ^number key-length] (go-try (when-not (or (= hash :sha1) (= hash :sha256) (= hash :sha384) (= hash :sha512)) (throw (js/Error. "PBKDF2 salt must be one of :sha1, :sha256, :sha384, or :sha512"))) (let [c (async/chan) password (str->utf8 password) hash (get browser-hash-lookup hash) kdf-params (clj->js {"name" "PBKDF2" "hash" (get browser-hash-lookup hash) "salt" salt "iterations" iterations}) subtle (.-subtle crypto)] (-> (.importKey ^Object subtle "raw" password #js {"name" "PBKDF2"} true ["deriveBits", "deriveKey"]) (.then (fn [pass-key] (.deriveBits subtle kdf-params pass-key key-length))) (.then (fn [key] (js/Uint8Array. key))) (.then (fn [key] (async/put! c key)))) (<? c)))) (defn node-pbkdf2 [^String password ^js/Uint8Array salt ^number iterations ^String hash ^number key-length] (go-try (when-not (or (= hash :sha1) (= hash :sha256) (= hash :sha384) (= hash :sha512)) (throw (js/Error. "PBKDF2 salt must be one of :sha1, :sha256, :sha384, or :sha512"))) (let [c (async/chan 1) password (str->utf8 password) hash (get node-hash-lookup hash) key-length (/ key-length 8)] (.pbkdf2 ^Object crypto password salt iterations key-length hash (fn [err key] (if (some? err) (async/put! c err) (async/put! c (js/Uint8Array. key))))) (<? c)))) (def pbkdf2 (if (= :browser crypto-type) #'browser-pbkdf2 #'node-pbkdf2))
null
https://raw.githubusercontent.com/skinkade/uniformity/e9d007a7be833e70b4358c02700fd81866de775a/src/uniformity/internals/js/pbkdf2.cljs
clojure
[clojure.string :as string]
(ns uniformity.internals.js.pbkdf2 (:require [uniformity.internals.js.node-browser-compat :refer [crypto-type crypto]] [uniformity.internals.js.util :refer [str->utf8]] [cljs.core.async :as async] [cljs.core.async.interop :refer [p->c]] [async-error.core :refer-macros [go-try <?]])) (def browser-hash-lookup {:sha1 "SHA-1" :sha256 "SHA-256" :sha384 "SHA-384" :sha512 "SHA-512"}) (def node-hash-lookup {:sha1 "SHA1" :sha256 "SHA256" :sha384 "SHA384" :sha512 "SHA512"}) (defn browser-pbkdf2 [^String password ^js/Uint8Array salt ^number iterations ^String hash ^number key-length] (go-try (when-not (or (= hash :sha1) (= hash :sha256) (= hash :sha384) (= hash :sha512)) (throw (js/Error. "PBKDF2 salt must be one of :sha1, :sha256, :sha384, or :sha512"))) (let [c (async/chan) password (str->utf8 password) hash (get browser-hash-lookup hash) kdf-params (clj->js {"name" "PBKDF2" "hash" (get browser-hash-lookup hash) "salt" salt "iterations" iterations}) subtle (.-subtle crypto)] (-> (.importKey ^Object subtle "raw" password #js {"name" "PBKDF2"} true ["deriveBits", "deriveKey"]) (.then (fn [pass-key] (.deriveBits subtle kdf-params pass-key key-length))) (.then (fn [key] (js/Uint8Array. key))) (.then (fn [key] (async/put! c key)))) (<? c)))) (defn node-pbkdf2 [^String password ^js/Uint8Array salt ^number iterations ^String hash ^number key-length] (go-try (when-not (or (= hash :sha1) (= hash :sha256) (= hash :sha384) (= hash :sha512)) (throw (js/Error. "PBKDF2 salt must be one of :sha1, :sha256, :sha384, or :sha512"))) (let [c (async/chan 1) password (str->utf8 password) hash (get node-hash-lookup hash) key-length (/ key-length 8)] (.pbkdf2 ^Object crypto password salt iterations key-length hash (fn [err key] (if (some? err) (async/put! c err) (async/put! c (js/Uint8Array. key))))) (<? c)))) (def pbkdf2 (if (= :browser crypto-type) #'browser-pbkdf2 #'node-pbkdf2))
87a3eed246bf55ac9d8edc620eee0230f393541011e97081054aa880b8cb227d
vaughnd/clojure-example-logback-integration
log.clj
(ns clojure-example-logback-integration.log (:require [clojure.pprint :as pprint]) (:import [ch.qos.logback.classic Level Logger] [java.io StringWriter] [org.slf4j LoggerFactory MDC])) (def logger ^ch.qos.logback.classic.Logger (LoggerFactory/getLogger "clojure-example-logback-integration")) (defn set-log-level! "Pass keyword :error :info :debug" [level] (case level :debug (.setLevel logger Level/DEBUG) :info (.setLevel logger Level/INFO) :error (.setLevel logger Level/ERROR))) (defmacro with-logging-context [context & body] "Use this to add a map to any logging wrapped in the macro. Macro can be nested. (with-logging-context {:key \"value\"} (log/info \"yay\")) " `(let [wrapped-context# ~context ctx# (MDC/getCopyOfContextMap)] (try (if (map? wrapped-context#) (doall (map (fn [[k# v#]] (MDC/put (name k#) (str v#))) wrapped-context#))) ~@body (finally (if ctx# (MDC/setContextMap ctx#) (MDC/clear)))))) (defmacro debug [& msg] `(.debug logger (print-str ~@msg))) (defmacro info [& msg] `(.info logger (print-str ~@msg))) (defmacro error [throwable & msg] `(if (instance? Throwable ~throwable) (.error logger (print-str ~@msg) ~throwable) (.error logger (print-str ~throwable ~@msg)))) (defmacro spy [expr] `(let [a# ~expr w# (StringWriter.)] (pprint/pprint '~expr w#) (.append w# " => ") (pprint/pprint a# w#) (error (.toString w#)) a#))
null
https://raw.githubusercontent.com/vaughnd/clojure-example-logback-integration/4bec2964ead9ff6f7bd1cf670572578f4421c44a/src/clojure_example_logback_integration/log.clj
clojure
(ns clojure-example-logback-integration.log (:require [clojure.pprint :as pprint]) (:import [ch.qos.logback.classic Level Logger] [java.io StringWriter] [org.slf4j LoggerFactory MDC])) (def logger ^ch.qos.logback.classic.Logger (LoggerFactory/getLogger "clojure-example-logback-integration")) (defn set-log-level! "Pass keyword :error :info :debug" [level] (case level :debug (.setLevel logger Level/DEBUG) :info (.setLevel logger Level/INFO) :error (.setLevel logger Level/ERROR))) (defmacro with-logging-context [context & body] "Use this to add a map to any logging wrapped in the macro. Macro can be nested. (with-logging-context {:key \"value\"} (log/info \"yay\")) " `(let [wrapped-context# ~context ctx# (MDC/getCopyOfContextMap)] (try (if (map? wrapped-context#) (doall (map (fn [[k# v#]] (MDC/put (name k#) (str v#))) wrapped-context#))) ~@body (finally (if ctx# (MDC/setContextMap ctx#) (MDC/clear)))))) (defmacro debug [& msg] `(.debug logger (print-str ~@msg))) (defmacro info [& msg] `(.info logger (print-str ~@msg))) (defmacro error [throwable & msg] `(if (instance? Throwable ~throwable) (.error logger (print-str ~@msg) ~throwable) (.error logger (print-str ~throwable ~@msg)))) (defmacro spy [expr] `(let [a# ~expr w# (StringWriter.)] (pprint/pprint '~expr w#) (.append w# " => ") (pprint/pprint a# w#) (error (.toString w#)) a#))
60107594ba86202e8b6ea787083a5c72e7baab28dbe8136b767cf88b81e0aacd
twilio/chessms
chessboard.erl
%%%------------------------------------------------------------------- @author chadrs ( C ) 2012 , %%% @doc %%% %%% @end Created : 2012 - 05 - 21 14:35:48.237300 %%%------------------------------------------------------------------- -module(chessboard). % board functions -export([board/0, board_to_fen/1, fen_to_board/1, print_board/1, render_board/2, render_board_ascii/2, render_board/5]). % moves functions -export([make_move/2, short_notation/2, expanded_notation/2, play/0]). -export([unicode_piece/1, unicode_square/1, ascii_piece/1, ascii_square/1]). -include("chessboard.hrl"). board() -> fen_to_board(?STARTPOS_FEN). play() -> play(board()). play(Board) -> io:format("~n~ts~n", [render_board(Board, white)]), io:format("board fen is ~s~n", [board_to_fen(Board)]), {ok, [Move]} = io:fread("white: ", "~s"), Board2 = make_move(Move, Board), io:format("~n~ts~n", [render_board(Board2, black)]), io:format("board fen is ~s~n", [board_to_fen(Board2)]), {ok, [Move2]} = io:fread("black: ", "~s"), play(make_move(Move2, Board2)). board_to_fen(Board=#chessboard{}) -> string:join([ fen_part(placements, Board#chessboard.placements), fen_part(active, Board#chessboard.active), fen_part(castling, Board#chessboard.castling), fen_part(enpassant, Board#chessboard.enpassant), fen_part(number, Board#chessboard.halfmove_clock), fen_part(number, Board#chessboard.fullmove_number) ], " "). fen_to_board(Fen) -> 1 . . Parts = string:tokens(Fen, " "), fen_parts_to_board(Parts). print_board(CB=#chessboard{}) -> io:format(render_board(CB, white)), io:format("~n"), io:format(render_board(CB, black)). render_board(Board, PointOfView) -> render_board(Board, PointOfView, fun unicode_piece/1, fun unicode_square/1, fun (Lines) -> string:join(Lines, "\n") end). render_board_ascii(Board, PointOfView) -> render_board(Board, PointOfView, fun ascii_piece/1, fun ascii_square/1, fun (Lines) -> string:join(Lines, "\n") end). render_board(#chessboard{placements=Board}, PointOfView, LookupPiece, LookupColor, JoinFunc) -> GetSquare = fun ({empty, Index}) -> LookupColor(color_of_square(Index)); ({Piece, _}) -> LookupPiece(Piece) end, BoardList = tuple_to_list(Board), Indexes = lists:seq(0, length(BoardList) - 1), PiecesList = lists:map(GetSquare, lists:zip(BoardList, Indexes)), Ranks = case PointOfView of white -> % print like this: 0 1 3 4 ... % 8 9 10 11 ... lists:reverse(octets(PiecesList)); black -> % print like this 63 62 61 ... 55 54 53 ... lists:map(fun lists:reverse/1, octets(PiecesList)) end, JoinFunc(Ranks). short_notation(_Board, _MoveStr) -> %%% XXX: Implement me #chessmove{}. -spec expanded_notation(iolist(), #chessboard{}) -> #chessmove{} | {'error', 'invalid_move', iolist()}. expanded_notation(MoveStr, #chessboard{placements=Placements, active=Active, enpassant=EnPassantSquare}) -> % XXX: factor out validation so it can be used in all the places I do the same thing. {From, To, Promotion} = case string:to_lower(MoveStr) of "(none)" -> {undefined, undefined, undefined}; "0000" -> {undefined, undefined, undefined}; [FFile, FRank, $x, TFile, TRank] -> {name_to_square([FFile, FRank]), name_to_square([TFile, TRank]), undefined}; [FFile, FRank, $x, TFile, TRank, Promote] -> {_Color, PromotePiece} = fen_to_piece(Promote), {name_to_square([FFile, FRank]), name_to_square([TFile, TRank]), PromotePiece}; [FFile, FRank, TFile, TRank] -> {name_to_square([FFile, FRank]), name_to_square([TFile, TRank]), undefined}; [FFile, FRank, TFile, TRank, Promote] -> {_Color, PromotePiece} = fen_to_piece(Promote), {name_to_square([FFile, FRank]), name_to_square([TFile, TRank]), PromotePiece}; _Other -> {undefined, undefined, undefined} end, case {From, To} of {undefined, undefined} -> {error, null_move}; {ToSquareNo, FromSquareNo} when is_integer(ToSquareNo) andalso is_integer(FromSquareNo) -> case element(From, Placements) of {Active, Piece} -> Move = #chessmove{ to=To, from=From, promotion=Promotion, chesspiece=Piece, special=special_kind({Active, Piece}, From, To, Promotion, EnPassantSquare), side=Active }, case element(To, Placements) of {Active, _KindOfPiece} -> % can't move on top of your own piece {error, invalid_move, "Can't capture your own piece"}; empty when Move#chessmove.special == enpassant -> Move#chessmove{capture=true}; empty -> Move; {_, _KindOfPiece} -> Move#chessmove{capture=true} end; empty -> {error, invalid_move, "No piece to move on that square."}; {_OtherColor, _Piece} -> {error, invalid_move, "Can't move a piece that isn't yours!"} end; {invalid_square, _} -> {error, invalid_move, "Invalid `from` square"}; {_, invalid_square} -> {error, invalid_move, "Invalid `to` square"}; _OtherMove -> {error, invalid_move, "Bad square input"} end. make_move(Move=#chessmove{chesspiece=PieceType, from=From, side=Color}, Board=#chessboard{placements=Placements}) -> % make sure there's at least a piece to move. case element(From, Placements) of {Color, PieceType} -> update_board_for_move(Move, Board); empty -> {error, invalid_move, "Can't move from an empty square"}; _ -> {error, invalid_move, "Not your piece"} end; make_move(MoveStr, Board) when is_list(MoveStr) -> ParsedMoved = expanded_notation(MoveStr, Board), case ParsedMoved of #chessmove{} -> make_move(ParsedMoved, Board); Other -> Other end. %%%=================================================================== Internal functions %%%=================================================================== square_file_index(Square) -> (Square - 1) rem 8. square_rank_index(Square) -> (Square - 1) div 8. square_to_name(Index) when is_integer(Index) -> Rank = square_rank_index(Index) + $1, File = square_file_index(Index) + $a, [File, Rank]. name_to_square([File, Rank]) when File >= $a andalso File =< $h andalso Rank >= $1 andalso Rank =< $8 -> (Rank - $1) * 8 + (File - $a) + 1; name_to_square([File, Rank]) when File >= $A andalso File =< $H -> name_to_square(string:to_lower([File, Rank])); name_to_square(_) -> invalid_square. color_of_square(Index) when ((Index rem 8) rem 2) == ((Index div 8) rem 2) -> dark; color_of_square(Index) when is_integer(Index) -> light. calc_halfmove_clock(_, #chessmove{chesspiece=pawn}) -> 0; calc_halfmove_clock(_, #chessmove{capture=true}) -> 0; calc_halfmove_clock(Clock, _) -> Clock + 1. fen_parts_to_board([Placement, Active, Castling, EnPassant, HalfMoves, Fullmoves]) -> Places = parse_fen_placements(Placement), #chessboard{ 2 . set placement board placements=Places, 3 . Set the easy stuff active=fen_part(active, Active), castling=fen_part(castling, Castling), enpassant=fen_part(enpassant, EnPassant), halfmove_clock=list_to_integer(HalfMoves), fullmove_number=list_to_integer(Fullmoves) }; fen_parts_to_board(_Invalid) -> {error, invalid_fen}. parse_fen_placements(String) -> % XXX: Also generate bitboards? Ranks = string:tokens(String, "/"), ParsedRanks = lists:map(fun parse_fen_rank/1, Ranks), list_to_tuple(lists:flatten(lists:reverse(ParsedRanks))). parse_fen_rank(RankString) -> lists:map(fun fen_to_piece/1, RankString). update_board_for_move(Move=#chessmove{to=To, from=From, side=Color, special=MoveType}, Board=#chessboard{placements=Placements}) -> % no validation, just makes the move! {MoveNo, Turn} = case Color of black -> {Board#chessboard.fullmove_number + 1, white}; white -> {Board#chessboard.fullmove_number, black} end, % move it in the placements tuple %Captured = element(To, Board#chessboard.placements), UpdatedPlacements = case MoveType of normal -> update_placements_for_move(From, To, Placements); castle -> KingMoved = update_placements_for_move(From, To, Placements), {RookFrom, RookTo} = rook_moves_for_castle(From, To), update_placements_for_move(RookFrom, RookTo, KingMoved); enpassant -> PawnMoved = update_placements_for_move(From, To, Placements), CapturedPawnSquare = enpassant_captured_pawn_square(From, To), setelement(CapturedPawnSquare, PawnMoved, empty); promotion when Move#chessmove.promotion =/= undefined -> Pickup = setelement(From, Placements, empty), setelement(To, Pickup, {Color, Move#chessmove.promotion}); promotion -> Pickup = setelement(From, Placements, empty), setelement(To, Pickup, {Color, queen}) end, HMC = calc_halfmove_clock(Board#chessboard.halfmove_clock, Move), EnPassant = detect_enpassant(Move), Castling = update_castling(Move, Board#chessboard.castling), Board#chessboard{ placements=UpdatedPlacements, fullmove_number=MoveNo, halfmove_clock=HMC, active=Turn, enpassant=EnPassant, castling=Castling}. update_placements_for_move(From, To, Placements) -> Piece = element(From, Placements), Pickup = setelement(From, Placements, empty), setelement(To, Pickup, Piece). fen_part(placements, Board) when is_tuple(Board)-> % "hard" part Ranks = lists:reverse(octets(tuple_to_list(Board))), FenLines = lists:map(fun fen_line_from_rank/1, Ranks), string:join(FenLines, "/"); fen_part(active, white) -> "w"; fen_part(active, black) -> "b"; fen_part(active, "w") -> white; fen_part(active, "b") -> black; fen_part(castling, CastleStr) when is_list(CastleStr) -> InitialStatus = #castling_rights{white_kingside=false, white_queenside=false, black_kingside=false, black_queenside=false}, Parse = fun (_, "-", Status) -> Status; (_, "", Status) -> Status; (Parse, [Head|Tail], Status) -> NewStatus = case Head of $K -> Status#castling_rights{white_kingside=true}; $Q -> Status#castling_rights{white_queenside=true}; $k -> Status#castling_rights{black_kingside=true}; $q -> Status#castling_rights{black_queenside=true} end, Parse(Parse, Tail, NewStatus) end, Parse(Parse, CastleStr, InitialStatus); fen_part(castling, CastleStr) when is_tuple(CastleStr) -> Symbols = [{CastleStr#castling_rights.white_kingside, $K}, {CastleStr#castling_rights.white_queenside, $Q}, {CastleStr#castling_rights.black_kingside, $k}, {CastleStr#castling_rights.black_queenside, $q}], lists:foldr(fun ({true, Val}, Acum) -> [Val|Acum]; ({false, _}, Acum) -> Acum end, "", Symbols); fen_part(number, Number) -> integer_to_list(Number); fen_part(enpassant, none) -> "-"; fen_part(enpassant, "-") -> none; fen_part(enpassant, Square) when is_integer(Square) -> square_to_name(Square); fen_part(enpassant, Square) when is_list(Square) -> name_to_square(Square); fen_part(_Other, Arg) -> %% Assume if we get here we can just iofmt to a string io_lib:format("~p", [Arg]). fen_line_from_rank(Rank) -> rev_fen_line_from_rank(Rank, 0). rev_fen_line_from_rank([], 0) -> []; rev_fen_line_from_rank([], Empties) -> integer_to_list(Empties); rev_fen_line_from_rank([Square|Rank], 0) -> case fen_piece(Square) of undefined -> rev_fen_line_from_rank(Rank, 1); FenChar -> [FenChar|rev_fen_line_from_rank(Rank, 0)] end; rev_fen_line_from_rank([Square|Rank], Empties) -> case fen_piece(Square) of undefined -> rev_fen_line_from_rank(Rank, Empties + 1); FenChar -> [$0 + Empties, FenChar|rev_fen_line_from_rank(Rank, 0)] end. unicode_piece({white, king}) -> 16#2654; unicode_piece({white, queen}) -> 16#2655; unicode_piece({white, rook}) -> 16#2656; unicode_piece({white, bishop}) -> 16#2657; unicode_piece({white, knight}) -> 16#2658; unicode_piece({white, pawn}) -> 16#2659; unicode_piece({black, king}) -> 16#265A; unicode_piece({black, queen}) -> 16#265B; unicode_piece({black, rook}) -> 16#265C; unicode_piece({black, bishop}) -> 16#265D; unicode_piece({black, knight}) -> 16#265E; unicode_piece({black, pawn}) -> 16#265F; unicode_piece(empty) -> undefined. unicode_square(dark) -> 16#2593; unicode_square(light) -> 16#2001. ascii_square(dark) -> $.; ascii_square(light) -> $_. % space ascii_piece(empty) -> undefined; ascii_piece(Piece) -> fen_piece(Piece). fen_piece({white, king}) -> $K; fen_piece({white, queen}) -> $Q; fen_piece({white, rook}) -> $R; fen_piece({white, bishop}) -> $B; fen_piece({white, knight}) -> $N; fen_piece({white, pawn}) -> $P; fen_piece({black, king}) -> $k; fen_piece({black, queen}) -> $q; fen_piece({black, rook}) -> $r; fen_piece({black, bishop}) -> $b; fen_piece({black, knight}) -> $n; fen_piece({black, pawn}) -> $p; fen_piece(empty) -> undefined. fen_to_piece(Piece) -> case Piece of $K -> {white, king}; $Q -> {white, queen}; $R -> {white, rook}; $B -> {white, bishop}; $N -> {white, knight}; $P -> {white, pawn}; $k -> {black, king}; $q -> {black, queen}; $r -> {black, rook}; $b -> {black, bishop}; $n -> {black, knight}; $p -> {black, pawn}; Blanks -> lists:duplicate(Blanks - $0, empty) end. special_kind({_, pawn}, _From, To, undefined, EnPassantSquare) when To == EnPassantSquare -> enpassant; special_kind({_, pawn}, _, _, Promoted, _) when Promoted =/= undefined -> promotion; sadly these functions depends on having 1 indexed board :( special_kind({white, king}, 5, 7, undefined, _) -> castle; special_kind({white, king}, 5, 3, undefined, _) -> castle; special_kind({black, king}, 61, 63, undefined, _) -> castle; special_kind({black, king}, 61, 59, undefined, _) -> castle; special_kind(_, _, _, undefined, _) -> normal. detect_enpassant(#chessmove{chesspiece=pawn, from=From, to=To}) -> {FRank, TRank} = {square_rank_index(From), square_rank_index(To)}, if the piece moved two spaces , then the enpassant square is their average case abs(FRank - TRank) of 2 -> (From + To) div 2; _Hopefully1 -> none end; detect_enpassant(_) -> none. % short circuit anyone who has no possible castling update_castling(_, CS=#castling_rights{white_kingside=false, white_queenside=false, black_kingside=false, black_queenside=false}) -> CS; % Reasons castling status would change: 1 . Move your king ( includes castling ) update_castling(#chessmove{chesspiece=king, side=white}, CS) -> CS#castling_rights{ white_kingside=false, white_queenside=false }; update_castling(#chessmove{chesspiece=king, side=black}, CS) -> CS#castling_rights{ black_kingside=false, black_queenside=false }; 2 . Move a rook for the first time update_castling(#chessmove{chesspiece=rook, side=white, from=1}, S=#castling_rights{white_queenside=true}) -> S#castling_rights{white_queenside=false}; update_castling(#chessmove{chesspiece=rook, side=white, from=8}, S=#castling_rights{white_kingside=true}) -> S#castling_rights{white_kingside=false}; update_castling(#chessmove{chesspiece=rook, side=black, from=57}, S=#castling_rights{black_queenside=true}) -> S#castling_rights{black_queenside=false}; update_castling(#chessmove{chesspiece=rook, side=black, from=64}, S=#castling_rights{black_kingside=true}) -> S#castling_rights{black_kingside=false}; 3 . Have a rook captured update_castling(#chessmove{capture=true, side=white, to=57}, S=#castling_rights{black_queenside=true}) -> S#castling_rights{black_queenside=false}; update_castling(#chessmove{capture=true, side=white, to=64}, S=#castling_rights{black_kingside=true}) -> S#castling_rights{black_kingside=false}; update_castling(#chessmove{capture=true, side=black, to=1}, S=#castling_rights{white_queenside=true}) -> S#castling_rights{white_queenside=false}; update_castling(#chessmove{capture=true, side=black, to=8}, S=#castling_rights{white_kingside=true}) -> S#castling_rights{white_kingside=false}; % I think that's it... update_castling(_, CS) -> CS. % probably could have use math to do this, but this seems easier. rook_moves_for_castle(5, 7) -> {8, 6}; rook_moves_for_castle(5, 3) -> {1, 4}; rook_moves_for_castle(61, 63) -> {64, 62}; rook_moves_for_castle(61, 59) -> {57, 60}. % captured square has the rank of the From and the file of the To enpassant_captured_pawn_square(From, To) -> 8 * square_rank_index(From) + square_file_index(To) + 1. octets([]) -> []; octets(List) -> {Rank, Rest} = lists:split(8, List), [Rank] ++ octets(Rest). -ifdef(TEST). -include_lib("eunit/include/eunit.hrl"). display_test() -> % not sure how to test the output of this, but % lets at least make sure it doesn't crash. ?assert(is_list(render_board(board(), white))), ?assert(is_list(render_board(board(), black))), ?assert(is_list(render_board_ascii(board(), black))), %print_board(board()). later. move_parse_test() -> TestingBoard = fen_to_board("r4knr/2PQ2pp/5p2/1B6/4P3/P4N2/P1P2PPP/R3K2R w KQkq - 0 12"), ?assertEqual( #chessmove{to=name_to_square("a4"), from=name_to_square("a2"), promotion=undefined, chesspiece=pawn, special=normal, side=white}, expanded_notation("A2A4", TestingBoard) ), ?assertEqual( #chessmove{to=name_to_square("g7"), from=name_to_square("d7"), promotion=undefined, chesspiece=queen, special=normal, side=white, capture=true}, expanded_notation("d7g7", TestingBoard) ), ?assertEqual(expanded_notation("d7g7", TestingBoard), expanded_notation("d7xg7", TestingBoard)), ?assertMatch({error, invalid_move, _}, expanded_notation("i2j4", TestingBoard)), ?assertMatch({error, invalid_move, _}, expanded_notation("a2j4", TestingBoard)), ?assertMatch({error, invalid_move, _}, expanded_notation("d7c7", TestingBoard)), ?assertMatch({error, null_move}, expanded_notation("(none)", TestingBoard)), ?assertMatch({error, null_move}, expanded_notation("adsfas", TestingBoard)), ?assertMatch({error, null_move}, expanded_notation("0000", TestingBoard)), ok. make_move_test() -> TestingBoard = fen_to_board("r4knr/2PQ2pp/5p2/1B6/4P3/P4N2/P1P2PPP/R3K2R w KQkq - 5 12"), % test haflmove clock with capture Capture = make_move("d7g7", TestingBoard), ?assertEqual(0, Capture#chessboard.halfmove_clock), % invalid moves ?assertMatch({error, null_move}, make_move("0000", TestingBoard)), ?assertMatch({error, invalid_move, _}, make_move("e2e4", TestingBoard)), ?assertMatch({error, invalid_move, _}, make_move("a8b8", TestingBoard)). fen_test() -> ?assertEqual({error, invalid_fen}, fen_to_board("k6K/8/8/8/8/8/8/8 wutever")), ?assertEqual({error, invalid_fen}, fen_to_board("k6K/8/8/8/8/8 - - 20 40")), ?assertEqual(?STARTPOS_FEN, board_to_fen(fen_to_board(?STARTPOS_FEN))). white_castling_test() -> TestingBoard = fen_to_board("r4knr/2PQ2pp/5p2/1B6/4P3/P4N2/P1P2PPP/R3K2R w KQkq - 0 12"), CastleQS = make_move("e1c1", TestingBoard), ?assertEqual("r4knr/2PQ2pp/5p2/1B6/4P3/P4N2/P1P2PPP/2KR3R b kq - 1 12", board_to_fen(CastleQS)), CastleKS = make_move("e1g1", TestingBoard), ?assertEqual("r4knr/2PQ2pp/5p2/1B6/4P3/P4N2/P1P2PPP/R4RK1 b kq - 1 12", board_to_fen(CastleKS)), % thing that take away castling rights. ?assertEqual(#castling_rights{ white_queenside=true, white_kingside=true, black_queenside=true, black_kingside=true }, TestingBoard#chessboard.castling), KingMoved = make_move("e1d1", TestingBoard), ?assertEqual(#castling_rights{ white_kingside=false, white_queenside=false, black_queenside=true, black_kingside=true }, KingMoved#chessboard.castling), ok. black_castling_test() -> TestingBoard = fen_to_board("r3k2r/8/8/8/8/8/8/R3K2R b KQkq - 0 12"), CastleKS = make_move("e8g8", TestingBoard), ?assertEqual("r4rk1/8/8/8/8/8/8/R3K2R w KQ - 1 13", board_to_fen(CastleKS)), CastleQS = make_move("e8c8", TestingBoard), ?assertEqual("2kr3r/8/8/8/8/8/8/R3K2R w KQ - 1 13", board_to_fen(CastleQS)), KingMoved = make_move("e8d8", TestingBoard), ?assertEqual(#castling_rights{ white_kingside=true, white_queenside=true, black_queenside=false, black_kingside=false }, KingMoved#chessboard.castling), % bad castle; board won't validate but shouldn't consider the move a "castle" CantCastle = fen_to_board("r3k2r/2PQ2pp/5p2/1B6/4P3/P4N2/P1P2PPP/R3K2R b - - 0 12"), ?assertMatch(#chessmove{special=normal}, expanded_notation("e8d8", CantCastle)), ok. promotion_test() -> TestingBoard = fen_to_board("r4knr/2PQ2pp/5p2/1B6/4P3/P4N2/P1P2PPP/R3K2R w KQkq - 0 12"), Promoted = make_move("c7c8q", TestingBoard), ?assertEqual("r1Q2knr/3Q2pp/5p2/1B6/4P3/P4N2/P1P2PPP/R3K2R b KQkq - 0 12", board_to_fen(Promoted)). en_passant_test() -> EnPassantPosition = fen_to_board("rnbqkbnr/p1pppppp/8/8/1pPP4/5N2/PP2PPPP/RNBQKB1R b KQkq c3 0 3"), ?assertMatch( #chessmove{side=black, special=enpassant, capture=true, chesspiece=pawn}, expanded_notation("b4c3", EnPassantPosition)), ?assertEqual("rnbqkbnr/p1pppppp/8/8/3P4/2p2N2/PP2PPPP/RNBQKB1R w KQkq - 0 4", board_to_fen(make_move("b4c3", EnPassantPosition))), TestBoard = fen_to_board("rnbqkb1r/pppppppp/5n2/3P4/8/8/PPP1PPPP/RNBQKBNR b KQkq - 0 2"), ?assertEqual("rnbqkb1r/pp1ppppp/5n2/2pP4/8/8/PPP1PPPP/RNBQKBNR w KQkq c6 0 3", board_to_fen(make_move("c7c5", TestBoard))), ok. -endif.
null
https://raw.githubusercontent.com/twilio/chessms/666c70553cf04f8f1c0bc0a77456b0b755998017/src/chessboard.erl
erlang
------------------------------------------------------------------- @doc @end ------------------------------------------------------------------- board functions moves functions print like this: 8 9 10 11 ... print like this XXX: Implement me XXX: factor out validation so it can be used in all the places I do the same thing. can't move on top of your own piece make sure there's at least a piece to move. =================================================================== =================================================================== XXX: Also generate bitboards? no validation, just makes the move! move it in the placements tuple Captured = element(To, Board#chessboard.placements), "hard" part Assume if we get here we can just iofmt to a string space short circuit anyone who has no possible castling Reasons castling status would change: I think that's it... probably could have use math to do this, but this seems easier. captured square has the rank of the From and the file of the To not sure how to test the output of this, but lets at least make sure it doesn't crash. print_board(board()). test haflmove clock with capture invalid moves thing that take away castling rights. bad castle; board won't validate but shouldn't consider the move a "castle"
@author chadrs ( C ) 2012 , Created : 2012 - 05 - 21 14:35:48.237300 -module(chessboard). -export([board/0, board_to_fen/1, fen_to_board/1, print_board/1, render_board/2, render_board_ascii/2, render_board/5]). -export([make_move/2, short_notation/2, expanded_notation/2, play/0]). -export([unicode_piece/1, unicode_square/1, ascii_piece/1, ascii_square/1]). -include("chessboard.hrl"). board() -> fen_to_board(?STARTPOS_FEN). play() -> play(board()). play(Board) -> io:format("~n~ts~n", [render_board(Board, white)]), io:format("board fen is ~s~n", [board_to_fen(Board)]), {ok, [Move]} = io:fread("white: ", "~s"), Board2 = make_move(Move, Board), io:format("~n~ts~n", [render_board(Board2, black)]), io:format("board fen is ~s~n", [board_to_fen(Board2)]), {ok, [Move2]} = io:fread("black: ", "~s"), play(make_move(Move2, Board2)). board_to_fen(Board=#chessboard{}) -> string:join([ fen_part(placements, Board#chessboard.placements), fen_part(active, Board#chessboard.active), fen_part(castling, Board#chessboard.castling), fen_part(enpassant, Board#chessboard.enpassant), fen_part(number, Board#chessboard.halfmove_clock), fen_part(number, Board#chessboard.fullmove_number) ], " "). fen_to_board(Fen) -> 1 . . Parts = string:tokens(Fen, " "), fen_parts_to_board(Parts). print_board(CB=#chessboard{}) -> io:format(render_board(CB, white)), io:format("~n"), io:format(render_board(CB, black)). render_board(Board, PointOfView) -> render_board(Board, PointOfView, fun unicode_piece/1, fun unicode_square/1, fun (Lines) -> string:join(Lines, "\n") end). render_board_ascii(Board, PointOfView) -> render_board(Board, PointOfView, fun ascii_piece/1, fun ascii_square/1, fun (Lines) -> string:join(Lines, "\n") end). render_board(#chessboard{placements=Board}, PointOfView, LookupPiece, LookupColor, JoinFunc) -> GetSquare = fun ({empty, Index}) -> LookupColor(color_of_square(Index)); ({Piece, _}) -> LookupPiece(Piece) end, BoardList = tuple_to_list(Board), Indexes = lists:seq(0, length(BoardList) - 1), PiecesList = lists:map(GetSquare, lists:zip(BoardList, Indexes)), Ranks = case PointOfView of white -> 0 1 3 4 ... lists:reverse(octets(PiecesList)); black -> 63 62 61 ... 55 54 53 ... lists:map(fun lists:reverse/1, octets(PiecesList)) end, JoinFunc(Ranks). short_notation(_Board, _MoveStr) -> #chessmove{}. -spec expanded_notation(iolist(), #chessboard{}) -> #chessmove{} | {'error', 'invalid_move', iolist()}. expanded_notation(MoveStr, #chessboard{placements=Placements, active=Active, enpassant=EnPassantSquare}) -> {From, To, Promotion} = case string:to_lower(MoveStr) of "(none)" -> {undefined, undefined, undefined}; "0000" -> {undefined, undefined, undefined}; [FFile, FRank, $x, TFile, TRank] -> {name_to_square([FFile, FRank]), name_to_square([TFile, TRank]), undefined}; [FFile, FRank, $x, TFile, TRank, Promote] -> {_Color, PromotePiece} = fen_to_piece(Promote), {name_to_square([FFile, FRank]), name_to_square([TFile, TRank]), PromotePiece}; [FFile, FRank, TFile, TRank] -> {name_to_square([FFile, FRank]), name_to_square([TFile, TRank]), undefined}; [FFile, FRank, TFile, TRank, Promote] -> {_Color, PromotePiece} = fen_to_piece(Promote), {name_to_square([FFile, FRank]), name_to_square([TFile, TRank]), PromotePiece}; _Other -> {undefined, undefined, undefined} end, case {From, To} of {undefined, undefined} -> {error, null_move}; {ToSquareNo, FromSquareNo} when is_integer(ToSquareNo) andalso is_integer(FromSquareNo) -> case element(From, Placements) of {Active, Piece} -> Move = #chessmove{ to=To, from=From, promotion=Promotion, chesspiece=Piece, special=special_kind({Active, Piece}, From, To, Promotion, EnPassantSquare), side=Active }, case element(To, Placements) of {Active, _KindOfPiece} -> {error, invalid_move, "Can't capture your own piece"}; empty when Move#chessmove.special == enpassant -> Move#chessmove{capture=true}; empty -> Move; {_, _KindOfPiece} -> Move#chessmove{capture=true} end; empty -> {error, invalid_move, "No piece to move on that square."}; {_OtherColor, _Piece} -> {error, invalid_move, "Can't move a piece that isn't yours!"} end; {invalid_square, _} -> {error, invalid_move, "Invalid `from` square"}; {_, invalid_square} -> {error, invalid_move, "Invalid `to` square"}; _OtherMove -> {error, invalid_move, "Bad square input"} end. make_move(Move=#chessmove{chesspiece=PieceType, from=From, side=Color}, Board=#chessboard{placements=Placements}) -> case element(From, Placements) of {Color, PieceType} -> update_board_for_move(Move, Board); empty -> {error, invalid_move, "Can't move from an empty square"}; _ -> {error, invalid_move, "Not your piece"} end; make_move(MoveStr, Board) when is_list(MoveStr) -> ParsedMoved = expanded_notation(MoveStr, Board), case ParsedMoved of #chessmove{} -> make_move(ParsedMoved, Board); Other -> Other end. Internal functions square_file_index(Square) -> (Square - 1) rem 8. square_rank_index(Square) -> (Square - 1) div 8. square_to_name(Index) when is_integer(Index) -> Rank = square_rank_index(Index) + $1, File = square_file_index(Index) + $a, [File, Rank]. name_to_square([File, Rank]) when File >= $a andalso File =< $h andalso Rank >= $1 andalso Rank =< $8 -> (Rank - $1) * 8 + (File - $a) + 1; name_to_square([File, Rank]) when File >= $A andalso File =< $H -> name_to_square(string:to_lower([File, Rank])); name_to_square(_) -> invalid_square. color_of_square(Index) when ((Index rem 8) rem 2) == ((Index div 8) rem 2) -> dark; color_of_square(Index) when is_integer(Index) -> light. calc_halfmove_clock(_, #chessmove{chesspiece=pawn}) -> 0; calc_halfmove_clock(_, #chessmove{capture=true}) -> 0; calc_halfmove_clock(Clock, _) -> Clock + 1. fen_parts_to_board([Placement, Active, Castling, EnPassant, HalfMoves, Fullmoves]) -> Places = parse_fen_placements(Placement), #chessboard{ 2 . set placement board placements=Places, 3 . Set the easy stuff active=fen_part(active, Active), castling=fen_part(castling, Castling), enpassant=fen_part(enpassant, EnPassant), halfmove_clock=list_to_integer(HalfMoves), fullmove_number=list_to_integer(Fullmoves) }; fen_parts_to_board(_Invalid) -> {error, invalid_fen}. parse_fen_placements(String) -> Ranks = string:tokens(String, "/"), ParsedRanks = lists:map(fun parse_fen_rank/1, Ranks), list_to_tuple(lists:flatten(lists:reverse(ParsedRanks))). parse_fen_rank(RankString) -> lists:map(fun fen_to_piece/1, RankString). update_board_for_move(Move=#chessmove{to=To, from=From, side=Color, special=MoveType}, Board=#chessboard{placements=Placements}) -> {MoveNo, Turn} = case Color of black -> {Board#chessboard.fullmove_number + 1, white}; white -> {Board#chessboard.fullmove_number, black} end, UpdatedPlacements = case MoveType of normal -> update_placements_for_move(From, To, Placements); castle -> KingMoved = update_placements_for_move(From, To, Placements), {RookFrom, RookTo} = rook_moves_for_castle(From, To), update_placements_for_move(RookFrom, RookTo, KingMoved); enpassant -> PawnMoved = update_placements_for_move(From, To, Placements), CapturedPawnSquare = enpassant_captured_pawn_square(From, To), setelement(CapturedPawnSquare, PawnMoved, empty); promotion when Move#chessmove.promotion =/= undefined -> Pickup = setelement(From, Placements, empty), setelement(To, Pickup, {Color, Move#chessmove.promotion}); promotion -> Pickup = setelement(From, Placements, empty), setelement(To, Pickup, {Color, queen}) end, HMC = calc_halfmove_clock(Board#chessboard.halfmove_clock, Move), EnPassant = detect_enpassant(Move), Castling = update_castling(Move, Board#chessboard.castling), Board#chessboard{ placements=UpdatedPlacements, fullmove_number=MoveNo, halfmove_clock=HMC, active=Turn, enpassant=EnPassant, castling=Castling}. update_placements_for_move(From, To, Placements) -> Piece = element(From, Placements), Pickup = setelement(From, Placements, empty), setelement(To, Pickup, Piece). fen_part(placements, Board) when is_tuple(Board)-> Ranks = lists:reverse(octets(tuple_to_list(Board))), FenLines = lists:map(fun fen_line_from_rank/1, Ranks), string:join(FenLines, "/"); fen_part(active, white) -> "w"; fen_part(active, black) -> "b"; fen_part(active, "w") -> white; fen_part(active, "b") -> black; fen_part(castling, CastleStr) when is_list(CastleStr) -> InitialStatus = #castling_rights{white_kingside=false, white_queenside=false, black_kingside=false, black_queenside=false}, Parse = fun (_, "-", Status) -> Status; (_, "", Status) -> Status; (Parse, [Head|Tail], Status) -> NewStatus = case Head of $K -> Status#castling_rights{white_kingside=true}; $Q -> Status#castling_rights{white_queenside=true}; $k -> Status#castling_rights{black_kingside=true}; $q -> Status#castling_rights{black_queenside=true} end, Parse(Parse, Tail, NewStatus) end, Parse(Parse, CastleStr, InitialStatus); fen_part(castling, CastleStr) when is_tuple(CastleStr) -> Symbols = [{CastleStr#castling_rights.white_kingside, $K}, {CastleStr#castling_rights.white_queenside, $Q}, {CastleStr#castling_rights.black_kingside, $k}, {CastleStr#castling_rights.black_queenside, $q}], lists:foldr(fun ({true, Val}, Acum) -> [Val|Acum]; ({false, _}, Acum) -> Acum end, "", Symbols); fen_part(number, Number) -> integer_to_list(Number); fen_part(enpassant, none) -> "-"; fen_part(enpassant, "-") -> none; fen_part(enpassant, Square) when is_integer(Square) -> square_to_name(Square); fen_part(enpassant, Square) when is_list(Square) -> name_to_square(Square); fen_part(_Other, Arg) -> io_lib:format("~p", [Arg]). fen_line_from_rank(Rank) -> rev_fen_line_from_rank(Rank, 0). rev_fen_line_from_rank([], 0) -> []; rev_fen_line_from_rank([], Empties) -> integer_to_list(Empties); rev_fen_line_from_rank([Square|Rank], 0) -> case fen_piece(Square) of undefined -> rev_fen_line_from_rank(Rank, 1); FenChar -> [FenChar|rev_fen_line_from_rank(Rank, 0)] end; rev_fen_line_from_rank([Square|Rank], Empties) -> case fen_piece(Square) of undefined -> rev_fen_line_from_rank(Rank, Empties + 1); FenChar -> [$0 + Empties, FenChar|rev_fen_line_from_rank(Rank, 0)] end. unicode_piece({white, king}) -> 16#2654; unicode_piece({white, queen}) -> 16#2655; unicode_piece({white, rook}) -> 16#2656; unicode_piece({white, bishop}) -> 16#2657; unicode_piece({white, knight}) -> 16#2658; unicode_piece({white, pawn}) -> 16#2659; unicode_piece({black, king}) -> 16#265A; unicode_piece({black, queen}) -> 16#265B; unicode_piece({black, rook}) -> 16#265C; unicode_piece({black, bishop}) -> 16#265D; unicode_piece({black, knight}) -> 16#265E; unicode_piece({black, pawn}) -> 16#265F; unicode_piece(empty) -> undefined. unicode_square(dark) -> 16#2593; unicode_square(light) -> 16#2001. ascii_square(dark) -> $.; ascii_piece(empty) -> undefined; ascii_piece(Piece) -> fen_piece(Piece). fen_piece({white, king}) -> $K; fen_piece({white, queen}) -> $Q; fen_piece({white, rook}) -> $R; fen_piece({white, bishop}) -> $B; fen_piece({white, knight}) -> $N; fen_piece({white, pawn}) -> $P; fen_piece({black, king}) -> $k; fen_piece({black, queen}) -> $q; fen_piece({black, rook}) -> $r; fen_piece({black, bishop}) -> $b; fen_piece({black, knight}) -> $n; fen_piece({black, pawn}) -> $p; fen_piece(empty) -> undefined. fen_to_piece(Piece) -> case Piece of $K -> {white, king}; $Q -> {white, queen}; $R -> {white, rook}; $B -> {white, bishop}; $N -> {white, knight}; $P -> {white, pawn}; $k -> {black, king}; $q -> {black, queen}; $r -> {black, rook}; $b -> {black, bishop}; $n -> {black, knight}; $p -> {black, pawn}; Blanks -> lists:duplicate(Blanks - $0, empty) end. special_kind({_, pawn}, _From, To, undefined, EnPassantSquare) when To == EnPassantSquare -> enpassant; special_kind({_, pawn}, _, _, Promoted, _) when Promoted =/= undefined -> promotion; sadly these functions depends on having 1 indexed board :( special_kind({white, king}, 5, 7, undefined, _) -> castle; special_kind({white, king}, 5, 3, undefined, _) -> castle; special_kind({black, king}, 61, 63, undefined, _) -> castle; special_kind({black, king}, 61, 59, undefined, _) -> castle; special_kind(_, _, _, undefined, _) -> normal. detect_enpassant(#chessmove{chesspiece=pawn, from=From, to=To}) -> {FRank, TRank} = {square_rank_index(From), square_rank_index(To)}, if the piece moved two spaces , then the enpassant square is their average case abs(FRank - TRank) of 2 -> (From + To) div 2; _Hopefully1 -> none end; detect_enpassant(_) -> none. update_castling(_, CS=#castling_rights{white_kingside=false, white_queenside=false, black_kingside=false, black_queenside=false}) -> CS; 1 . Move your king ( includes castling ) update_castling(#chessmove{chesspiece=king, side=white}, CS) -> CS#castling_rights{ white_kingside=false, white_queenside=false }; update_castling(#chessmove{chesspiece=king, side=black}, CS) -> CS#castling_rights{ black_kingside=false, black_queenside=false }; 2 . Move a rook for the first time update_castling(#chessmove{chesspiece=rook, side=white, from=1}, S=#castling_rights{white_queenside=true}) -> S#castling_rights{white_queenside=false}; update_castling(#chessmove{chesspiece=rook, side=white, from=8}, S=#castling_rights{white_kingside=true}) -> S#castling_rights{white_kingside=false}; update_castling(#chessmove{chesspiece=rook, side=black, from=57}, S=#castling_rights{black_queenside=true}) -> S#castling_rights{black_queenside=false}; update_castling(#chessmove{chesspiece=rook, side=black, from=64}, S=#castling_rights{black_kingside=true}) -> S#castling_rights{black_kingside=false}; 3 . Have a rook captured update_castling(#chessmove{capture=true, side=white, to=57}, S=#castling_rights{black_queenside=true}) -> S#castling_rights{black_queenside=false}; update_castling(#chessmove{capture=true, side=white, to=64}, S=#castling_rights{black_kingside=true}) -> S#castling_rights{black_kingside=false}; update_castling(#chessmove{capture=true, side=black, to=1}, S=#castling_rights{white_queenside=true}) -> S#castling_rights{white_queenside=false}; update_castling(#chessmove{capture=true, side=black, to=8}, S=#castling_rights{white_kingside=true}) -> S#castling_rights{white_kingside=false}; update_castling(_, CS) -> CS. rook_moves_for_castle(5, 7) -> {8, 6}; rook_moves_for_castle(5, 3) -> {1, 4}; rook_moves_for_castle(61, 63) -> {64, 62}; rook_moves_for_castle(61, 59) -> {57, 60}. enpassant_captured_pawn_square(From, To) -> 8 * square_rank_index(From) + square_file_index(To) + 1. octets([]) -> []; octets(List) -> {Rank, Rest} = lists:split(8, List), [Rank] ++ octets(Rest). -ifdef(TEST). -include_lib("eunit/include/eunit.hrl"). display_test() -> ?assert(is_list(render_board(board(), white))), ?assert(is_list(render_board(board(), black))), ?assert(is_list(render_board_ascii(board(), black))), later. move_parse_test() -> TestingBoard = fen_to_board("r4knr/2PQ2pp/5p2/1B6/4P3/P4N2/P1P2PPP/R3K2R w KQkq - 0 12"), ?assertEqual( #chessmove{to=name_to_square("a4"), from=name_to_square("a2"), promotion=undefined, chesspiece=pawn, special=normal, side=white}, expanded_notation("A2A4", TestingBoard) ), ?assertEqual( #chessmove{to=name_to_square("g7"), from=name_to_square("d7"), promotion=undefined, chesspiece=queen, special=normal, side=white, capture=true}, expanded_notation("d7g7", TestingBoard) ), ?assertEqual(expanded_notation("d7g7", TestingBoard), expanded_notation("d7xg7", TestingBoard)), ?assertMatch({error, invalid_move, _}, expanded_notation("i2j4", TestingBoard)), ?assertMatch({error, invalid_move, _}, expanded_notation("a2j4", TestingBoard)), ?assertMatch({error, invalid_move, _}, expanded_notation("d7c7", TestingBoard)), ?assertMatch({error, null_move}, expanded_notation("(none)", TestingBoard)), ?assertMatch({error, null_move}, expanded_notation("adsfas", TestingBoard)), ?assertMatch({error, null_move}, expanded_notation("0000", TestingBoard)), ok. make_move_test() -> TestingBoard = fen_to_board("r4knr/2PQ2pp/5p2/1B6/4P3/P4N2/P1P2PPP/R3K2R w KQkq - 5 12"), Capture = make_move("d7g7", TestingBoard), ?assertEqual(0, Capture#chessboard.halfmove_clock), ?assertMatch({error, null_move}, make_move("0000", TestingBoard)), ?assertMatch({error, invalid_move, _}, make_move("e2e4", TestingBoard)), ?assertMatch({error, invalid_move, _}, make_move("a8b8", TestingBoard)). fen_test() -> ?assertEqual({error, invalid_fen}, fen_to_board("k6K/8/8/8/8/8/8/8 wutever")), ?assertEqual({error, invalid_fen}, fen_to_board("k6K/8/8/8/8/8 - - 20 40")), ?assertEqual(?STARTPOS_FEN, board_to_fen(fen_to_board(?STARTPOS_FEN))). white_castling_test() -> TestingBoard = fen_to_board("r4knr/2PQ2pp/5p2/1B6/4P3/P4N2/P1P2PPP/R3K2R w KQkq - 0 12"), CastleQS = make_move("e1c1", TestingBoard), ?assertEqual("r4knr/2PQ2pp/5p2/1B6/4P3/P4N2/P1P2PPP/2KR3R b kq - 1 12", board_to_fen(CastleQS)), CastleKS = make_move("e1g1", TestingBoard), ?assertEqual("r4knr/2PQ2pp/5p2/1B6/4P3/P4N2/P1P2PPP/R4RK1 b kq - 1 12", board_to_fen(CastleKS)), ?assertEqual(#castling_rights{ white_queenside=true, white_kingside=true, black_queenside=true, black_kingside=true }, TestingBoard#chessboard.castling), KingMoved = make_move("e1d1", TestingBoard), ?assertEqual(#castling_rights{ white_kingside=false, white_queenside=false, black_queenside=true, black_kingside=true }, KingMoved#chessboard.castling), ok. black_castling_test() -> TestingBoard = fen_to_board("r3k2r/8/8/8/8/8/8/R3K2R b KQkq - 0 12"), CastleKS = make_move("e8g8", TestingBoard), ?assertEqual("r4rk1/8/8/8/8/8/8/R3K2R w KQ - 1 13", board_to_fen(CastleKS)), CastleQS = make_move("e8c8", TestingBoard), ?assertEqual("2kr3r/8/8/8/8/8/8/R3K2R w KQ - 1 13", board_to_fen(CastleQS)), KingMoved = make_move("e8d8", TestingBoard), ?assertEqual(#castling_rights{ white_kingside=true, white_queenside=true, black_queenside=false, black_kingside=false }, KingMoved#chessboard.castling), CantCastle = fen_to_board("r3k2r/2PQ2pp/5p2/1B6/4P3/P4N2/P1P2PPP/R3K2R b - - 0 12"), ?assertMatch(#chessmove{special=normal}, expanded_notation("e8d8", CantCastle)), ok. promotion_test() -> TestingBoard = fen_to_board("r4knr/2PQ2pp/5p2/1B6/4P3/P4N2/P1P2PPP/R3K2R w KQkq - 0 12"), Promoted = make_move("c7c8q", TestingBoard), ?assertEqual("r1Q2knr/3Q2pp/5p2/1B6/4P3/P4N2/P1P2PPP/R3K2R b KQkq - 0 12", board_to_fen(Promoted)). en_passant_test() -> EnPassantPosition = fen_to_board("rnbqkbnr/p1pppppp/8/8/1pPP4/5N2/PP2PPPP/RNBQKB1R b KQkq c3 0 3"), ?assertMatch( #chessmove{side=black, special=enpassant, capture=true, chesspiece=pawn}, expanded_notation("b4c3", EnPassantPosition)), ?assertEqual("rnbqkbnr/p1pppppp/8/8/3P4/2p2N2/PP2PPPP/RNBQKB1R w KQkq - 0 4", board_to_fen(make_move("b4c3", EnPassantPosition))), TestBoard = fen_to_board("rnbqkb1r/pppppppp/5n2/3P4/8/8/PPP1PPPP/RNBQKBNR b KQkq - 0 2"), ?assertEqual("rnbqkb1r/pp1ppppp/5n2/2pP4/8/8/PPP1PPPP/RNBQKBNR w KQkq c6 0 3", board_to_fen(make_move("c7c5", TestBoard))), ok. -endif.
5c5cb016b2b5b2f807805cea10d6a8c1dcb6341a8e80a07028c9e8e7e2f717de
kupl/LearnML
original.ml
type formula = | True | False | Not of formula | AndAlso of (formula * formula) | OrElse of (formula * formula) | Imply of (formula * formula) | Equal of (exp * exp) and exp = Num of int | Plus of (exp * exp) | Minus of (exp * exp) let eval (f : formula) : bool = match f with | True -> true | False -> false | Not f0 -> if f0 = True then false else true | AndAlso (f1, f2) -> if f1 = True && f2 = True then true else false | OrElse (f1, f2) -> if f1 = False && f2 = False then false else true | Imply (f1, f2) -> if f1 = True && f2 = False then false else true | Equal (e1, e2) -> if e1 = e2 then true else false let (_ : bool) = eval (Imply (Imply (True, False), True)) let rec num (n : exp) : int = match n with | Num i -> i | Plus (e1, e2) -> num e1 + num e2 | Minus (e1, e2) -> num e1 - num e2 let (_ : bool) = eval (Equal (Num 1, Plus (Num 1, Num 2)))
null
https://raw.githubusercontent.com/kupl/LearnML/c98ef2b95ef67e657b8158a2c504330e9cfb7700/result/cafe2/formula/sub104/original.ml
ocaml
type formula = | True | False | Not of formula | AndAlso of (formula * formula) | OrElse of (formula * formula) | Imply of (formula * formula) | Equal of (exp * exp) and exp = Num of int | Plus of (exp * exp) | Minus of (exp * exp) let eval (f : formula) : bool = match f with | True -> true | False -> false | Not f0 -> if f0 = True then false else true | AndAlso (f1, f2) -> if f1 = True && f2 = True then true else false | OrElse (f1, f2) -> if f1 = False && f2 = False then false else true | Imply (f1, f2) -> if f1 = True && f2 = False then false else true | Equal (e1, e2) -> if e1 = e2 then true else false let (_ : bool) = eval (Imply (Imply (True, False), True)) let rec num (n : exp) : int = match n with | Num i -> i | Plus (e1, e2) -> num e1 + num e2 | Minus (e1, e2) -> num e1 - num e2 let (_ : bool) = eval (Equal (Num 1, Plus (Num 1, Num 2)))
c7bc55cf606c11012ef1d361ec61a2b4992391f91acec5e89eaa2838d5bebfe7
zyrolasting/mind-map
tcgs.rkt
#lang mind-map Deck-building trading card games Expensive if you care about tournaments and copyright laws. Free if you don't. If your child is a fan, find them a new outlet for competition NOW. Magic: The Gathering (Win conditions) Reduce your opponent's life to zero Your opponent's deck is out of cards when they need to draw. Meet a win condition for a particular card. Yu-Gi-Oh MTG for people who think anime and Japanese culture are the same thing fRiEnDsHip cOnQuers AlL Win conditions similar to MTG Hearthstone Everything is digital except the money you pay Pretty colors Noisy
null
https://raw.githubusercontent.com/zyrolasting/mind-map/8401400f1dbc7956357cd27563b6926f4e429d7c/examples/tcgs.rkt
racket
#lang mind-map Deck-building trading card games Expensive if you care about tournaments and copyright laws. Free if you don't. If your child is a fan, find them a new outlet for competition NOW. Magic: The Gathering (Win conditions) Reduce your opponent's life to zero Your opponent's deck is out of cards when they need to draw. Meet a win condition for a particular card. Yu-Gi-Oh MTG for people who think anime and Japanese culture are the same thing fRiEnDsHip cOnQuers AlL Win conditions similar to MTG Hearthstone Everything is digital except the money you pay Pretty colors Noisy
66544e7a5b544e5541b96eb68f7f1b818a486895479cd5b37cf361951f2794cb
jordwalke/rehp
graphics_js.ml
Js_of_ocaml library * / * Copyright ( C ) 2014 Hugo Heuzard * * This program is free software ; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation , with linking exception ; * either version 2.1 of the License , or ( at your option ) any later version . * * This program is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the * GNU Lesser General Public License for more details . * * You should have received a copy of the GNU Lesser General Public License * along with this program ; if not , write to the Free Software * Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA . * / * Copyright (C) 2014 Hugo Heuzard * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, with linking exception; * either version 2.1 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *) open Js_of_ocaml open Js_of_ocaml_lwt include Graphics type context let _ = Callback.register_exception "Graphics.Graphic_failure" (Graphic_failure "") let ( >>= ) = Lwt.bind let get_context () = Js.Unsafe.(fun_call (variable "caml_gr_state_get") [||]) let set_context ctx = Js.Unsafe.(fun_call (variable "caml_gr_state_set") [|inject ctx|]) let create_context canvas w h = Js.Unsafe.( fun_call (variable "caml_gr_state_create") [|inject canvas; inject w; inject h|]) let document_of_context ctx = Js.Unsafe.(fun_call (variable "caml_gr_doc_of_state") [|inject ctx|]) let open_canvas x = let ctx = create_context x x##.width x##.height in set_context ctx let compute_real_pos elt = let rec loop elt left top = let top = elt##.offsetTop - elt##.scrollTop + top and left = elt##.offsetLeft - elt##.scrollLeft + left in match Js.Opt.to_option elt##.offsetParent with | None -> top, left | Some p -> loop p left top in loop elt 0 0 let mouse_pos () = let ctx = get_context () in let elt = ctx##.canvas in Lwt_js_events.mousemove elt >>= fun ev -> let top, left = compute_real_pos elt in Lwt.return ( Js.Optdef.get ev##.pageX (fun _ -> 0) - left , elt##.height - (Js.Optdef.get ev##.pageY (fun _ -> 0) - top) ) let button_down () = let ctx = get_context () in let elt = ctx##.canvas in Lwt_js_events.mousedown elt >>= fun _ev -> Lwt.return true let read_key () = (* let ctx = get_context() in *) (* let elt = ctx##canvas in *) let doc = document_of_context (get_context ()) in Lwt_js_events.keypress doc >>= fun ev -> Lwt.return (Char.chr ev##.keyCode) let loop elist f : unit = let ctx = get_context () in let elt = ctx##.canvas in let doc = document_of_context (get_context ()) in let button = ref false in let null = char_of_int 0 in let mouse_x, mouse_y = ref 0, ref 0 in let get_pos_mouse () = !mouse_x, !mouse_y in if List.mem Button_down elist then elt##.onmousedown := Dom_html.handler (fun _ev -> let mouse_x, mouse_y = get_pos_mouse () in button := true; let s = {mouse_x; mouse_y; button = true; keypressed = false; key = null} in f s; Js._true ); if List.mem Button_up elist then elt##.onmouseup := Dom_html.handler (fun _ev -> let mouse_x, mouse_y = get_pos_mouse () in button := false; let s = {mouse_x; mouse_y; button = false; keypressed = false; key = null} in f s; Js._true ); elt##.onmousemove := Dom_html.handler (fun ev -> let cy, cx = compute_real_pos elt in mouse_x := Js.Optdef.get ev##.pageX (fun _ -> 0) - cx; mouse_y := elt##.height - (Js.Optdef.get ev##.pageY (fun _ -> 0) - cy); ( if List.mem Mouse_motion elist then let mouse_x, mouse_y = get_pos_mouse () in let s = {mouse_x; mouse_y; button = !button; keypressed = false; key = null} in f s ); Js._true ); EventListener sur le doc car pas de moyen simple de le faire sur un canvasElement sur un canvasElement *) if List.mem Key_pressed elist then doc##.onkeypress := Dom_html.handler (fun ev -> (* Uncaught Invalid_argument char_of_int with key € for example *) let key = try char_of_int (Js.Optdef.get ev##.charCode (fun _ -> 0)) with Invalid_argument _ -> null in let mouse_x, mouse_y = get_pos_mouse () in let s = {mouse_x; mouse_y; button = !button; keypressed = true; key} in f s; Js._true ) let loop_at_exit events handler : unit = at_exit (fun _ -> loop events handler)
null
https://raw.githubusercontent.com/jordwalke/rehp/f122b94f0a3f06410ddba59e3c9c603b33aadabf/lib/lwt/graphics/graphics_js.ml
ocaml
let ctx = get_context() in let elt = ctx##canvas in Uncaught Invalid_argument char_of_int with key € for example
Js_of_ocaml library * / * Copyright ( C ) 2014 Hugo Heuzard * * This program is free software ; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation , with linking exception ; * either version 2.1 of the License , or ( at your option ) any later version . * * This program is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the * GNU Lesser General Public License for more details . * * You should have received a copy of the GNU Lesser General Public License * along with this program ; if not , write to the Free Software * Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA . * / * Copyright (C) 2014 Hugo Heuzard * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, with linking exception; * either version 2.1 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *) open Js_of_ocaml open Js_of_ocaml_lwt include Graphics type context let _ = Callback.register_exception "Graphics.Graphic_failure" (Graphic_failure "") let ( >>= ) = Lwt.bind let get_context () = Js.Unsafe.(fun_call (variable "caml_gr_state_get") [||]) let set_context ctx = Js.Unsafe.(fun_call (variable "caml_gr_state_set") [|inject ctx|]) let create_context canvas w h = Js.Unsafe.( fun_call (variable "caml_gr_state_create") [|inject canvas; inject w; inject h|]) let document_of_context ctx = Js.Unsafe.(fun_call (variable "caml_gr_doc_of_state") [|inject ctx|]) let open_canvas x = let ctx = create_context x x##.width x##.height in set_context ctx let compute_real_pos elt = let rec loop elt left top = let top = elt##.offsetTop - elt##.scrollTop + top and left = elt##.offsetLeft - elt##.scrollLeft + left in match Js.Opt.to_option elt##.offsetParent with | None -> top, left | Some p -> loop p left top in loop elt 0 0 let mouse_pos () = let ctx = get_context () in let elt = ctx##.canvas in Lwt_js_events.mousemove elt >>= fun ev -> let top, left = compute_real_pos elt in Lwt.return ( Js.Optdef.get ev##.pageX (fun _ -> 0) - left , elt##.height - (Js.Optdef.get ev##.pageY (fun _ -> 0) - top) ) let button_down () = let ctx = get_context () in let elt = ctx##.canvas in Lwt_js_events.mousedown elt >>= fun _ev -> Lwt.return true let read_key () = let doc = document_of_context (get_context ()) in Lwt_js_events.keypress doc >>= fun ev -> Lwt.return (Char.chr ev##.keyCode) let loop elist f : unit = let ctx = get_context () in let elt = ctx##.canvas in let doc = document_of_context (get_context ()) in let button = ref false in let null = char_of_int 0 in let mouse_x, mouse_y = ref 0, ref 0 in let get_pos_mouse () = !mouse_x, !mouse_y in if List.mem Button_down elist then elt##.onmousedown := Dom_html.handler (fun _ev -> let mouse_x, mouse_y = get_pos_mouse () in button := true; let s = {mouse_x; mouse_y; button = true; keypressed = false; key = null} in f s; Js._true ); if List.mem Button_up elist then elt##.onmouseup := Dom_html.handler (fun _ev -> let mouse_x, mouse_y = get_pos_mouse () in button := false; let s = {mouse_x; mouse_y; button = false; keypressed = false; key = null} in f s; Js._true ); elt##.onmousemove := Dom_html.handler (fun ev -> let cy, cx = compute_real_pos elt in mouse_x := Js.Optdef.get ev##.pageX (fun _ -> 0) - cx; mouse_y := elt##.height - (Js.Optdef.get ev##.pageY (fun _ -> 0) - cy); ( if List.mem Mouse_motion elist then let mouse_x, mouse_y = get_pos_mouse () in let s = {mouse_x; mouse_y; button = !button; keypressed = false; key = null} in f s ); Js._true ); EventListener sur le doc car pas de moyen simple de le faire sur un canvasElement sur un canvasElement *) if List.mem Key_pressed elist then doc##.onkeypress := Dom_html.handler (fun ev -> let key = try char_of_int (Js.Optdef.get ev##.charCode (fun _ -> 0)) with Invalid_argument _ -> null in let mouse_x, mouse_y = get_pos_mouse () in let s = {mouse_x; mouse_y; button = !button; keypressed = true; key} in f s; Js._true ) let loop_at_exit events handler : unit = at_exit (fun _ -> loop events handler)
a1535afca71e247c5cfc05fab7308cd62984a1d091e44f1c48b93a3d518b6e00
RichiH/git-annex
Form.hs
git - annex assistant webapp form utilities - - Copyright 2012 < > - - Licensed under the GNU AGPL version 3 or higher . - - Copyright 2012 Joey Hess <> - - Licensed under the GNU AGPL version 3 or higher. -} # LANGUAGE FlexibleContexts , TypeFamilies , QuasiQuotes # # LANGUAGE MultiParamTypeClasses , TemplateHaskell # # LANGUAGE OverloadedStrings , RankNTypes # module Assistant.WebApp.Form where import Assistant.WebApp.Types import Assistant.Gpg import Yesod hiding (textField, passwordField) import Yesod.Form.Fields as F import Yesod.Form.Bootstrap3 as Y hiding (bfs) import Data.Text (Text) Yesod 's sets the required attribute for required fields . - We do n't want this , because many of the forms used in this webapp - display a modal dialog when submitted , which interacts badly with - required field handling by the browser . - - Required fields are still checked by Yesod . - We don't want this, because many of the forms used in this webapp - display a modal dialog when submitted, which interacts badly with - required field handling by the browser. - - Required fields are still checked by Yesod. -} textField :: MkField Text textField = F.textField { fieldView = \theId name attrs val _isReq -> [whamlet| <input id="#{theId}" name="#{name}" *{attrs} type="text" value="#{either id id val}"> |] } readonlyTextField :: MkField Text readonlyTextField = F.textField { fieldView = \theId name attrs val _isReq -> [whamlet| <input id="#{theId}" name="#{name}" *{attrs} type="text" value="#{either id id val}" readonly="true"> |] } {- Also without required attribute. -} passwordField :: MkField Text passwordField = F.passwordField { fieldView = \theId name attrs val _isReq -> toWidget [hamlet| <input id="#{theId}" name="#{name}" *{attrs} type="password" value="#{either id id val}"> |] } {- Makes a note widget be displayed after a field. -} withNote :: (ToWidget (HandlerSite m) a) => Field m v -> a -> Field m v withNote field note = field { fieldView = newview } where newview theId name attrs val isReq = let fieldwidget = (fieldView field) theId name attrs val isReq in [whamlet|^{fieldwidget}&nbsp;&nbsp;<span>^{note}</span>|] {- Note that the toggle string must be unique on the form. -} withExpandableNote :: (ToWidget (HandlerSite m) w) => Field m v -> (String, w) -> Field m v withExpandableNote field (toggle, note) = withNote field $ [whamlet| <a .btn .btn-default data-toggle="collapse" data-target="##{ident}">#{toggle}</a> <div ##{ident} .collapse> ^{note} |] where ident = "toggle_" ++ toggle Adds a check box to an AForm to control encryption . enableEncryptionField :: (RenderMessage site FormMessage) => AForm (HandlerT site IO) EnableEncryption enableEncryptionField = areq (selectFieldList choices) (bfs "Encryption") (Just SharedEncryption) where choices :: [(Text, EnableEncryption)] choices = [ ("Encrypt all data", SharedEncryption) , ("Disable encryption", NoEncryption) ] Defines the layout used by the Bootstrap3 form helper bootstrapFormLayout :: BootstrapFormLayout bootstrapFormLayout = BootstrapHorizontalForm (ColSm 0) (ColSm 2) (ColSm 0) (ColSm 10) Adds the form - control class used by Bootstrap3 for layout to a field - This is the same as Yesod.Form.Bootstrap3.bfs except it takes just a Text - parameter as I could n't get the original bfs to compile due to type ambiguities . - This is the same as Yesod.Form.Bootstrap3.bfs except it takes just a Text - parameter as I couldn't get the original bfs to compile due to type ambiguities. -} bfs :: Text -> FieldSettings master bfs msg = FieldSettings { fsLabel = SomeMessage msg , fsName = Nothing , fsId = Nothing , fsAttrs = [("class", "form-control")] , fsTooltip = Nothing }
null
https://raw.githubusercontent.com/RichiH/git-annex/bbcad2b0af8cd9264d0cb86e6ca126ae626171f3/Assistant/WebApp/Form.hs
haskell
Also without required attribute. Makes a note widget be displayed after a field. Note that the toggle string must be unique on the form.
git - annex assistant webapp form utilities - - Copyright 2012 < > - - Licensed under the GNU AGPL version 3 or higher . - - Copyright 2012 Joey Hess <> - - Licensed under the GNU AGPL version 3 or higher. -} # LANGUAGE FlexibleContexts , TypeFamilies , QuasiQuotes # # LANGUAGE MultiParamTypeClasses , TemplateHaskell # # LANGUAGE OverloadedStrings , RankNTypes # module Assistant.WebApp.Form where import Assistant.WebApp.Types import Assistant.Gpg import Yesod hiding (textField, passwordField) import Yesod.Form.Fields as F import Yesod.Form.Bootstrap3 as Y hiding (bfs) import Data.Text (Text) Yesod 's sets the required attribute for required fields . - We do n't want this , because many of the forms used in this webapp - display a modal dialog when submitted , which interacts badly with - required field handling by the browser . - - Required fields are still checked by Yesod . - We don't want this, because many of the forms used in this webapp - display a modal dialog when submitted, which interacts badly with - required field handling by the browser. - - Required fields are still checked by Yesod. -} textField :: MkField Text textField = F.textField { fieldView = \theId name attrs val _isReq -> [whamlet| <input id="#{theId}" name="#{name}" *{attrs} type="text" value="#{either id id val}"> |] } readonlyTextField :: MkField Text readonlyTextField = F.textField { fieldView = \theId name attrs val _isReq -> [whamlet| <input id="#{theId}" name="#{name}" *{attrs} type="text" value="#{either id id val}" readonly="true"> |] } passwordField :: MkField Text passwordField = F.passwordField { fieldView = \theId name attrs val _isReq -> toWidget [hamlet| <input id="#{theId}" name="#{name}" *{attrs} type="password" value="#{either id id val}"> |] } withNote :: (ToWidget (HandlerSite m) a) => Field m v -> a -> Field m v withNote field note = field { fieldView = newview } where newview theId name attrs val isReq = let fieldwidget = (fieldView field) theId name attrs val isReq in [whamlet|^{fieldwidget}&nbsp;&nbsp;<span>^{note}</span>|] withExpandableNote :: (ToWidget (HandlerSite m) w) => Field m v -> (String, w) -> Field m v withExpandableNote field (toggle, note) = withNote field $ [whamlet| <a .btn .btn-default data-toggle="collapse" data-target="##{ident}">#{toggle}</a> <div ##{ident} .collapse> ^{note} |] where ident = "toggle_" ++ toggle Adds a check box to an AForm to control encryption . enableEncryptionField :: (RenderMessage site FormMessage) => AForm (HandlerT site IO) EnableEncryption enableEncryptionField = areq (selectFieldList choices) (bfs "Encryption") (Just SharedEncryption) where choices :: [(Text, EnableEncryption)] choices = [ ("Encrypt all data", SharedEncryption) , ("Disable encryption", NoEncryption) ] Defines the layout used by the Bootstrap3 form helper bootstrapFormLayout :: BootstrapFormLayout bootstrapFormLayout = BootstrapHorizontalForm (ColSm 0) (ColSm 2) (ColSm 0) (ColSm 10) Adds the form - control class used by Bootstrap3 for layout to a field - This is the same as Yesod.Form.Bootstrap3.bfs except it takes just a Text - parameter as I could n't get the original bfs to compile due to type ambiguities . - This is the same as Yesod.Form.Bootstrap3.bfs except it takes just a Text - parameter as I couldn't get the original bfs to compile due to type ambiguities. -} bfs :: Text -> FieldSettings master bfs msg = FieldSettings { fsLabel = SomeMessage msg , fsName = Nothing , fsId = Nothing , fsAttrs = [("class", "form-control")] , fsTooltip = Nothing }
1bf7a774135c6d584f5dda1b719692ddcd42963487c8e512ce8218a88f155a31
herbelin/coq-hh
coqtop.mli
(************************************************************************) v * The Coq Proof Assistant / The Coq Development Team < O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2010 \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * (* // * This file is distributed under the terms of the *) (* * GNU Lesser General Public License Version 2.1 *) (************************************************************************) * The Coq main module . The following function [ start ] will parse the command line , print the banner , initialize the load path , load the input state , load the files given on the command line , load the ressource file , produce the output state if any , and finally will launch [ Toplevel.loop ] . command line, print the banner, initialize the load path, load the input state, load the files given on the command line, load the ressource file, produce the output state if any, and finally will launch [Toplevel.loop]. *) val start : unit -> unit
null
https://raw.githubusercontent.com/herbelin/coq-hh/296d03d5049fea661e8bdbaf305ed4bf6d2001d2/toplevel/coqtop.mli
ocaml
********************************************************************** // * This file is distributed under the terms of the * GNU Lesser General Public License Version 2.1 **********************************************************************
v * The Coq Proof Assistant / The Coq Development Team < O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2010 \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * The Coq main module . The following function [ start ] will parse the command line , print the banner , initialize the load path , load the input state , load the files given on the command line , load the ressource file , produce the output state if any , and finally will launch [ Toplevel.loop ] . command line, print the banner, initialize the load path, load the input state, load the files given on the command line, load the ressource file, produce the output state if any, and finally will launch [Toplevel.loop]. *) val start : unit -> unit
8f5b8b4327880a9f710e31aa5bdcbfa7523a15745242c9511e59a230565f232c
akr/codegen
state.ml
Copyright ( C ) 2019- National Institute of Advanced Industrial Science and Technology ( AIST ) This library is free software ; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation ; either version 2.1 of the License , or ( at your option ) any later version . This library is distributed in the hope that it will be useful , but WITHOUT ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU Lesser General Public License for more details . You should have received a copy of the GNU Lesser General Public License along with this library ; if not , write to the Free Software Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , MA 02110 - 1301 USA Copyright (C) 2019- National Institute of Advanced Industrial Science and Technology (AIST) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *) open Names module ConstrMap = HMap.Make(Constr) module ConstrSet = CSet.Make(Constr) module StringSet = CSet.Make(String) Unset / Set Debug CodeGen Simplification . let opt_debug_simplification = ref false let () = let open Goptions in declare_bool_option { optdepr = false; optkey = ["Debug";"CodeGen";"Simplification"]; optread = (fun () -> !opt_debug_simplification); optwrite = (:=) opt_debug_simplification } Unset / Set Debug CodeGen NormalizeV. let opt_debug_normalizeV = ref false let () = let open Goptions in declare_bool_option { optdepr = false; optkey = ["Debug";"CodeGen";"NormalizeV"]; optread = (fun () -> !opt_debug_normalizeV); optwrite = (:=) opt_debug_normalizeV } Unset / Set Debug CodeGen Reduction . let opt_debug_reduction = ref false let () = let open Goptions in declare_bool_option { optdepr = false; optkey = ["Debug";"CodeGen";"Reduction"]; optread = (fun () -> !opt_debug_reduction); optwrite = (:=) opt_debug_reduction } Unset / Set Debug CodeGen ReduceExp . let opt_debug_reduce_exp = ref false let () = let open Goptions in declare_bool_option { optdepr = false; optkey = ["Debug";"CodeGen";"ReduceExp"]; optread = (fun () -> !opt_debug_reduce_exp); optwrite = (:=) opt_debug_reduce_exp } Unset / Set Debug CodeGen ReduceApp . let opt_debug_reduce_app = ref false let () = let open Goptions in declare_bool_option { optdepr = false; optkey = ["Debug";"CodeGen";"ReduceApp"]; optread = (fun () -> !opt_debug_reduce_app); optwrite = (:=) opt_debug_reduce_app } Unset / Set Debug CodeGen Replace . let opt_debug_replace = ref false let () = let open Goptions in declare_bool_option { optdepr = false; optkey = ["Debug";"CodeGen";"Replace"]; optread = (fun () -> !opt_debug_replace); optwrite = (:=) opt_debug_replace } Unset / Set Debug CodeGen ReduceEta . let opt_debug_reduce_eta = ref false let () = let open Goptions in declare_bool_option { optdepr = false; optkey = ["Debug";"CodeGen";"ReduceEta"]; optread = (fun () -> !opt_debug_reduce_eta); optwrite = (:=) opt_debug_reduce_eta } Unset / Set Debug CodeGen CompleteArguments . let opt_debug_complete_arguments = ref false let () = let open Goptions in declare_bool_option { optdepr = false; optkey = ["Debug";"CodeGen";"CompleteArguments"]; optread = (fun () -> !opt_debug_complete_arguments); optwrite = (:=) opt_debug_complete_arguments } Unset / Set Debug CodeGen ExpandEta . let opt_debug_expand_eta = ref false let () = let open Goptions in declare_bool_option { optdepr = false; optkey = ["Debug";"CodeGen";"ExpandEta"]; optread = (fun () -> !opt_debug_expand_eta); optwrite = (:=) opt_debug_expand_eta } Unset / Set Debug CodeGen DeleteLet . let opt_debug_delete_let = ref false let () = let open Goptions in declare_bool_option { optdepr = false; optkey = ["Debug";"CodeGen";"DeleteLet"]; optread = (fun () -> !opt_debug_delete_let); optwrite = (:=) opt_debug_delete_let } Unset / Set Debug CodeGen BorrowCheck . let opt_debug_borrowcheck = ref false let () = let open Goptions in declare_bool_option { optdepr = false; optkey = ["Debug";"CodeGen";"BorrowCheck"]; optread = (fun () -> !opt_debug_borrowcheck); optwrite = (:=) opt_debug_borrowcheck } Unset / Set Debug CodeGen MatchApp . let opt_debug_matchapp = ref false let () = let open Goptions in declare_bool_option { optdepr = false; optkey = ["Debug";"CodeGen";"MatchApp"]; optread = (fun () -> !opt_debug_matchapp); optwrite = (:=) opt_debug_matchapp } let gensym_id = Summary.ref 0 ~name:"CodegenGensymID" type string_or_qualid = StrOrQid_Str of string | StrOrQid_Qid of Libnames.qualid type cstr_config = { coq_cstr : Id.t; c_caselabel : string; (* meaningful if c_swfnc is not None *) c_accessors : string array (* meaningful if c_swfnc is not None *) } type c_typedata = { c_type_left : string; c_type_right : string; } type ind_config = { coq_type : Constr.t; c_type : c_typedata; c_swfunc : string option; cstr_configs : cstr_config array; is_void_type : bool; } type ind_cstr_caselabel_accessors = Id.t * string * string list type s_or_d = SorD_S | SorD_D type id_or_underscore = Id.t option type constr_or_underscore = Constrexpr.constr_expr option type sp_instance_names = { spi_cfunc_name : string option; spi_presimp_id : Id.t option; spi_simplified_id : Id.t option; } type ind_constructor = { ic_coq_cstr : Id.t; ic_c_cstr : string; } let ind_config_map = Summary.ref (ConstrMap.empty : ind_config ConstrMap.t) ~name:"CodegenIndInfo" let linearity_type_set = Summary.ref ConstrSet.empty ~name:"CodeGenLinearTypeSet" (* key is (ind args...) or (cstr args...). *) let deallocator_cfunc_map = Summary.ref (ConstrMap.empty : string ConstrMap.t) ~name:"CodeGenDeallocatorCfuncMap" let downward_type_set = Summary.ref (ConstrSet.empty : ConstrSet.t) ~name:"CodeGenDownwardTypeSet" let borrow_function_set = Summary.ref (Cset.empty : Cset.t) ~name:"CodeGenBorrowFuncSet" let borrow_type_set = Summary.ref (ConstrSet.empty : ConstrSet.t) ~name:"CodeGenBorrowTypeSet" type simplified_status = | SpNoSimplification (* constructor or primitive function *) | SpExpectedId of Id.t (* simplified_id *) | SpDefined of (Constant.t * StringSet.t) (* (defined-constant, referred-cfuncs) *) - CodeGenFunc Codegen - generated function . Gallina function only . Any dynamic argument . - CodeGenStaticFunc Codegen - generated function . Gallina function only . Any dynamic argument . The generated function is defined as static function . - CodeGenPrimitive User - defined function . Function or constructor . Any dynamic argument . - CodeGenConstant User - defined function . Function or constructor . No dynamic argument . Generate C constant " foo " , instead of function call " foo ( ) " . - CodeGenFunc Codegen-generated function. Gallina function only. Any dynamic argument. - CodeGenStaticFunc Codegen-generated function. Gallina function only. Any dynamic argument. The generated function is defined as static function. - CodeGenPrimitive User-defined function. Function or constructor. Any dynamic argument. - CodeGenConstant User-defined function. Function or constructor. No dynamic argument. Generate C constant "foo", instead of function call "foo()". *) type instance_command = | CodeGenFunc | CodeGenStaticFunc | CodeGenPrimitive | CodeGenConstant type specialization_instance = { sp_static_arguments : Constr.t list; (* The length should be equal to number of "s" in sp_sd_list *) sp_presimp_constr : Constr.t; (* constant or constructor *) sp_simplified_status : simplified_status; sp_presimp : Constr.t; sp_cfunc_name : string; sp_icommand : instance_command; } type specialization_config = { sp_func : Constr.t; (* constant or constructor *) sp_is_cstr : bool; (* sp_func is constructor *) sp_sd_list : s_or_d list; key is presimp } (* key is constant or constructor which is the target of specialization *) let specialize_config_map = Summary.ref (ConstrMap.empty : specialization_config ConstrMap.t) ~name:"CodegenSpecialize" key is a constant to refer a presimp ( codegen_pN_foo ) , the presimp itself ( @cons bool ) and a constant to refer the simplified definition ( codegen_sN_foo ) . key is a constant to refer a presimp (codegen_pN_foo), the presimp itself (@cons bool) and a constant to refer the simplified definition (codegen_sN_foo). *) let gallina_instance_map = Summary.ref ~name:"CodegenGallinaInstance" (ConstrMap.empty : (specialization_config * specialization_instance) ConstrMap.t) CodeGenFunc and CodeGenStaticFunc needs unique C function name but CodeGenPrimitive and CodeGenConstant do n't need . but CodeGenPrimitive and CodeGenConstant don't need. *) type cfunc_usage = CodeGenFunc or CodeGenStaticFunc | CodeGenCfuncPrimitive of (specialization_config * specialization_instance) list (* CodeGenPrimitive or CodeGenConstant *) let cfunc_instance_map = Summary.ref ~name:"CodegenCInstance" (CString.Map.empty : cfunc_usage CString.Map.t) type string_or_none = string option let current_header_filename = Summary.ref ~name:"CodegenCurrentHeaderFilename" (None : string option) let current_source_filename = Summary.ref ~name:"CodegenCurrentImplementationFilename" (None : string option) type code_generation = GenFunc of string (* C function name *) | GenMutual of string list (* C function names *) | GenPrototype of string (* C function name *) | GenSnippet of string (* code fragment *) * map from filename ( string ) to list of code_generation in reverse order . * CodeGen GenerateFile consumes this . * map from filename (string) to list of code_generation in reverse order. * CodeGen GenerateFile consumes this. *) let generation_map = Summary.ref ~name:"CodegenGenerationMap" (CString.Map.empty : (code_generation list) CString.Map.t) let codegen_add_generation filename (generation : code_generation) : unit = generation_map := CString.Map.update filename (fun entry -> match entry with | None -> Some [generation] | Some rest -> Some (generation :: rest)) !generation_map let codegen_add_source_generation (generation : code_generation) : unit = match !current_source_filename with | None -> Feedback.msg_warning (Pp.str "[codegen] no code will be generated because no CodeGen Source File.") | Some filename -> codegen_add_generation filename generation let codegen_add_header_generation (generation : code_generation) : unit = match !current_header_filename with | None -> () | Some filename -> codegen_add_generation filename generation let gensym_ps_num = Summary.ref 0 ~name:"CodegenSpecializationInstanceNum" let specialize_global_inline = Summary.ref (Cpred.empty : Cpred.t) ~name:"CodegenGlobalInline" let specialize_local_inline = Summary.ref (Cmap.empty : Cpred.t Cmap.t) ~name:"CodegenLocalInline" type genflag = DisableDependencyResolver | DisableMutualRecursionDetection
null
https://raw.githubusercontent.com/akr/codegen/47eab0f67b49e28d09c4b88adee03cf1643f1bf8/src/state.ml
ocaml
meaningful if c_swfnc is not None meaningful if c_swfnc is not None key is (ind args...) or (cstr args...). constructor or primitive function simplified_id (defined-constant, referred-cfuncs) The length should be equal to number of "s" in sp_sd_list constant or constructor constant or constructor sp_func is constructor key is constant or constructor which is the target of specialization CodeGenPrimitive or CodeGenConstant C function name C function names C function name code fragment
Copyright ( C ) 2019- National Institute of Advanced Industrial Science and Technology ( AIST ) This library is free software ; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation ; either version 2.1 of the License , or ( at your option ) any later version . This library is distributed in the hope that it will be useful , but WITHOUT ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU Lesser General Public License for more details . You should have received a copy of the GNU Lesser General Public License along with this library ; if not , write to the Free Software Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , MA 02110 - 1301 USA Copyright (C) 2019- National Institute of Advanced Industrial Science and Technology (AIST) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *) open Names module ConstrMap = HMap.Make(Constr) module ConstrSet = CSet.Make(Constr) module StringSet = CSet.Make(String) Unset / Set Debug CodeGen Simplification . let opt_debug_simplification = ref false let () = let open Goptions in declare_bool_option { optdepr = false; optkey = ["Debug";"CodeGen";"Simplification"]; optread = (fun () -> !opt_debug_simplification); optwrite = (:=) opt_debug_simplification } Unset / Set Debug CodeGen NormalizeV. let opt_debug_normalizeV = ref false let () = let open Goptions in declare_bool_option { optdepr = false; optkey = ["Debug";"CodeGen";"NormalizeV"]; optread = (fun () -> !opt_debug_normalizeV); optwrite = (:=) opt_debug_normalizeV } Unset / Set Debug CodeGen Reduction . let opt_debug_reduction = ref false let () = let open Goptions in declare_bool_option { optdepr = false; optkey = ["Debug";"CodeGen";"Reduction"]; optread = (fun () -> !opt_debug_reduction); optwrite = (:=) opt_debug_reduction } Unset / Set Debug CodeGen ReduceExp . let opt_debug_reduce_exp = ref false let () = let open Goptions in declare_bool_option { optdepr = false; optkey = ["Debug";"CodeGen";"ReduceExp"]; optread = (fun () -> !opt_debug_reduce_exp); optwrite = (:=) opt_debug_reduce_exp } Unset / Set Debug CodeGen ReduceApp . let opt_debug_reduce_app = ref false let () = let open Goptions in declare_bool_option { optdepr = false; optkey = ["Debug";"CodeGen";"ReduceApp"]; optread = (fun () -> !opt_debug_reduce_app); optwrite = (:=) opt_debug_reduce_app } Unset / Set Debug CodeGen Replace . let opt_debug_replace = ref false let () = let open Goptions in declare_bool_option { optdepr = false; optkey = ["Debug";"CodeGen";"Replace"]; optread = (fun () -> !opt_debug_replace); optwrite = (:=) opt_debug_replace } Unset / Set Debug CodeGen ReduceEta . let opt_debug_reduce_eta = ref false let () = let open Goptions in declare_bool_option { optdepr = false; optkey = ["Debug";"CodeGen";"ReduceEta"]; optread = (fun () -> !opt_debug_reduce_eta); optwrite = (:=) opt_debug_reduce_eta } Unset / Set Debug CodeGen CompleteArguments . let opt_debug_complete_arguments = ref false let () = let open Goptions in declare_bool_option { optdepr = false; optkey = ["Debug";"CodeGen";"CompleteArguments"]; optread = (fun () -> !opt_debug_complete_arguments); optwrite = (:=) opt_debug_complete_arguments } Unset / Set Debug CodeGen ExpandEta . let opt_debug_expand_eta = ref false let () = let open Goptions in declare_bool_option { optdepr = false; optkey = ["Debug";"CodeGen";"ExpandEta"]; optread = (fun () -> !opt_debug_expand_eta); optwrite = (:=) opt_debug_expand_eta } Unset / Set Debug CodeGen DeleteLet . let opt_debug_delete_let = ref false let () = let open Goptions in declare_bool_option { optdepr = false; optkey = ["Debug";"CodeGen";"DeleteLet"]; optread = (fun () -> !opt_debug_delete_let); optwrite = (:=) opt_debug_delete_let } Unset / Set Debug CodeGen BorrowCheck . let opt_debug_borrowcheck = ref false let () = let open Goptions in declare_bool_option { optdepr = false; optkey = ["Debug";"CodeGen";"BorrowCheck"]; optread = (fun () -> !opt_debug_borrowcheck); optwrite = (:=) opt_debug_borrowcheck } Unset / Set Debug CodeGen MatchApp . let opt_debug_matchapp = ref false let () = let open Goptions in declare_bool_option { optdepr = false; optkey = ["Debug";"CodeGen";"MatchApp"]; optread = (fun () -> !opt_debug_matchapp); optwrite = (:=) opt_debug_matchapp } let gensym_id = Summary.ref 0 ~name:"CodegenGensymID" type string_or_qualid = StrOrQid_Str of string | StrOrQid_Qid of Libnames.qualid type cstr_config = { coq_cstr : Id.t; } type c_typedata = { c_type_left : string; c_type_right : string; } type ind_config = { coq_type : Constr.t; c_type : c_typedata; c_swfunc : string option; cstr_configs : cstr_config array; is_void_type : bool; } type ind_cstr_caselabel_accessors = Id.t * string * string list type s_or_d = SorD_S | SorD_D type id_or_underscore = Id.t option type constr_or_underscore = Constrexpr.constr_expr option type sp_instance_names = { spi_cfunc_name : string option; spi_presimp_id : Id.t option; spi_simplified_id : Id.t option; } type ind_constructor = { ic_coq_cstr : Id.t; ic_c_cstr : string; } let ind_config_map = Summary.ref (ConstrMap.empty : ind_config ConstrMap.t) ~name:"CodegenIndInfo" let linearity_type_set = Summary.ref ConstrSet.empty ~name:"CodeGenLinearTypeSet" let deallocator_cfunc_map = Summary.ref (ConstrMap.empty : string ConstrMap.t) ~name:"CodeGenDeallocatorCfuncMap" let downward_type_set = Summary.ref (ConstrSet.empty : ConstrSet.t) ~name:"CodeGenDownwardTypeSet" let borrow_function_set = Summary.ref (Cset.empty : Cset.t) ~name:"CodeGenBorrowFuncSet" let borrow_type_set = Summary.ref (ConstrSet.empty : ConstrSet.t) ~name:"CodeGenBorrowTypeSet" type simplified_status = - CodeGenFunc Codegen - generated function . Gallina function only . Any dynamic argument . - CodeGenStaticFunc Codegen - generated function . Gallina function only . Any dynamic argument . The generated function is defined as static function . - CodeGenPrimitive User - defined function . Function or constructor . Any dynamic argument . - CodeGenConstant User - defined function . Function or constructor . No dynamic argument . Generate C constant " foo " , instead of function call " foo ( ) " . - CodeGenFunc Codegen-generated function. Gallina function only. Any dynamic argument. - CodeGenStaticFunc Codegen-generated function. Gallina function only. Any dynamic argument. The generated function is defined as static function. - CodeGenPrimitive User-defined function. Function or constructor. Any dynamic argument. - CodeGenConstant User-defined function. Function or constructor. No dynamic argument. Generate C constant "foo", instead of function call "foo()". *) type instance_command = | CodeGenFunc | CodeGenStaticFunc | CodeGenPrimitive | CodeGenConstant type specialization_instance = { sp_simplified_status : simplified_status; sp_presimp : Constr.t; sp_cfunc_name : string; sp_icommand : instance_command; } type specialization_config = { sp_sd_list : s_or_d list; key is presimp } let specialize_config_map = Summary.ref (ConstrMap.empty : specialization_config ConstrMap.t) ~name:"CodegenSpecialize" key is a constant to refer a presimp ( codegen_pN_foo ) , the presimp itself ( @cons bool ) and a constant to refer the simplified definition ( codegen_sN_foo ) . key is a constant to refer a presimp (codegen_pN_foo), the presimp itself (@cons bool) and a constant to refer the simplified definition (codegen_sN_foo). *) let gallina_instance_map = Summary.ref ~name:"CodegenGallinaInstance" (ConstrMap.empty : (specialization_config * specialization_instance) ConstrMap.t) CodeGenFunc and CodeGenStaticFunc needs unique C function name but CodeGenPrimitive and CodeGenConstant do n't need . but CodeGenPrimitive and CodeGenConstant don't need. *) type cfunc_usage = CodeGenFunc or CodeGenStaticFunc let cfunc_instance_map = Summary.ref ~name:"CodegenCInstance" (CString.Map.empty : cfunc_usage CString.Map.t) type string_or_none = string option let current_header_filename = Summary.ref ~name:"CodegenCurrentHeaderFilename" (None : string option) let current_source_filename = Summary.ref ~name:"CodegenCurrentImplementationFilename" (None : string option) type code_generation = * map from filename ( string ) to list of code_generation in reverse order . * CodeGen GenerateFile consumes this . * map from filename (string) to list of code_generation in reverse order. * CodeGen GenerateFile consumes this. *) let generation_map = Summary.ref ~name:"CodegenGenerationMap" (CString.Map.empty : (code_generation list) CString.Map.t) let codegen_add_generation filename (generation : code_generation) : unit = generation_map := CString.Map.update filename (fun entry -> match entry with | None -> Some [generation] | Some rest -> Some (generation :: rest)) !generation_map let codegen_add_source_generation (generation : code_generation) : unit = match !current_source_filename with | None -> Feedback.msg_warning (Pp.str "[codegen] no code will be generated because no CodeGen Source File.") | Some filename -> codegen_add_generation filename generation let codegen_add_header_generation (generation : code_generation) : unit = match !current_header_filename with | None -> () | Some filename -> codegen_add_generation filename generation let gensym_ps_num = Summary.ref 0 ~name:"CodegenSpecializationInstanceNum" let specialize_global_inline = Summary.ref (Cpred.empty : Cpred.t) ~name:"CodegenGlobalInline" let specialize_local_inline = Summary.ref (Cmap.empty : Cpred.t Cmap.t) ~name:"CodegenLocalInline" type genflag = DisableDependencyResolver | DisableMutualRecursionDetection
e2d5a349b69c25d6dbb4ca8ce56d7664c61aa04c165532d124f4fc4185795fd5
lambdaisland/harvest
poke.clj
(ns repl-sessions.poke (:require [lambdaisland.harvest :as h] [lambdaisland.harvest.kernel :as hk] [clojure.string :as str])) (def short-words ["bat" "bar" "cat" "dud" "lip" "map" "pap" "sip" "fig" "wip"]) (defn rand-id [] (str/join "-" (take 3 (shuffle (concat (map str/upper-case short-words) short-words))))) (h/defactory cycle {:type :cycle :id rand-id}) (h/defactory user {:type :user :id rand-id :name "Finn"}) (h/defactory organization {:type :organization :id rand-id}) (h/defactory organization-user {:type :organization-user :id rand-id :organization-id organization :user-id user}) (h/defactory property {:type :property :id rand-id :org-id organization :created-by user}) (h/defactory property-cycle-user {:type :property-cycle-user :id rand-id :cycle-id cycle :property-id property :user-id user}) (defrecord LVar [identity]) (property-cycle-user {:rules {[:created-by] (->LVar :user) [:user-id] (->LVar :user) [:org-id] (->LVar :org) [:organization-id] (->LVar :org)}}) (h/sel (h/build property-cycle-user) [:created-by]) (h/sel (h/build property-cycle-user) [#{:user-id :created-by}]) (h/sel (h/build property-cycle-user) [user]) (keys (:harvest.result/linked (h/build property-cycle-user))) (h/build property-cycle-user {:rules {[user :name] cycle [property] user}}) (some #(when (hk/path-match? '[repl-sessions.poke/property-cycle-user :user-id repl-sessions.poke/user :name] (key %)) (val %)) {[user :name] "Jake" [property] {:foo "bar"}}) (def kk2 (keys (:harvest.result/linked (h/build property-cycle-user #_{:rules {[user] (hk/->LVar :x)}})))) (count kk2) (remove (set kk) kk2) (h/build-val [property-cycle-user organization-user] {:rules {[#{:org-id :organization-id}] (hk/->LVar :x)}}) (h/build-val [property-cycle-user organization-user] {:rules {[organization] (hk/->LVar :x)}}) (hk/path-match? `[0 repl-sessions.poke/property-cycle-user :property-id repl-sessions.poke/property :org-id repl-sessions.poke/organization] [#{:org-id :organization-id}]) (h/defactory a {:a #(rand-int 100)}) (h/defactory b {:a1 a :a2 a :b "b"}) (h/defactory c {:b1 b :b2 b :c "c"}) (keys (:harvest.result/linked (h/build c {:rules {a (h/unify)}}))) ([repl-sessions.poke/c :b1 repl-sessions.poke/b :a1 repl-sessions.poke/a] [repl-sessions.poke/c :b1 repl-sessions.poke/b :a2 repl-sessions.poke/a] [repl-sessions.poke/c :b1 repl-sessions.poke/b] [repl-sessions.poke/c :b2 repl-sessions.poke/b :a1 repl-sessions.poke/a] [repl-sessions.poke/c :b2 repl-sessions.poke/b :a2 repl-sessions.poke/a] [repl-sessions.poke/c :b2 repl-sessions.poke/b] [repl-sessions.poke/c])
null
https://raw.githubusercontent.com/lambdaisland/harvest/17e601ee9718ef2c915e469ed62ea963c43db17e/repl_sessions/poke.clj
clojure
(ns repl-sessions.poke (:require [lambdaisland.harvest :as h] [lambdaisland.harvest.kernel :as hk] [clojure.string :as str])) (def short-words ["bat" "bar" "cat" "dud" "lip" "map" "pap" "sip" "fig" "wip"]) (defn rand-id [] (str/join "-" (take 3 (shuffle (concat (map str/upper-case short-words) short-words))))) (h/defactory cycle {:type :cycle :id rand-id}) (h/defactory user {:type :user :id rand-id :name "Finn"}) (h/defactory organization {:type :organization :id rand-id}) (h/defactory organization-user {:type :organization-user :id rand-id :organization-id organization :user-id user}) (h/defactory property {:type :property :id rand-id :org-id organization :created-by user}) (h/defactory property-cycle-user {:type :property-cycle-user :id rand-id :cycle-id cycle :property-id property :user-id user}) (defrecord LVar [identity]) (property-cycle-user {:rules {[:created-by] (->LVar :user) [:user-id] (->LVar :user) [:org-id] (->LVar :org) [:organization-id] (->LVar :org)}}) (h/sel (h/build property-cycle-user) [:created-by]) (h/sel (h/build property-cycle-user) [#{:user-id :created-by}]) (h/sel (h/build property-cycle-user) [user]) (keys (:harvest.result/linked (h/build property-cycle-user))) (h/build property-cycle-user {:rules {[user :name] cycle [property] user}}) (some #(when (hk/path-match? '[repl-sessions.poke/property-cycle-user :user-id repl-sessions.poke/user :name] (key %)) (val %)) {[user :name] "Jake" [property] {:foo "bar"}}) (def kk2 (keys (:harvest.result/linked (h/build property-cycle-user #_{:rules {[user] (hk/->LVar :x)}})))) (count kk2) (remove (set kk) kk2) (h/build-val [property-cycle-user organization-user] {:rules {[#{:org-id :organization-id}] (hk/->LVar :x)}}) (h/build-val [property-cycle-user organization-user] {:rules {[organization] (hk/->LVar :x)}}) (hk/path-match? `[0 repl-sessions.poke/property-cycle-user :property-id repl-sessions.poke/property :org-id repl-sessions.poke/organization] [#{:org-id :organization-id}]) (h/defactory a {:a #(rand-int 100)}) (h/defactory b {:a1 a :a2 a :b "b"}) (h/defactory c {:b1 b :b2 b :c "c"}) (keys (:harvest.result/linked (h/build c {:rules {a (h/unify)}}))) ([repl-sessions.poke/c :b1 repl-sessions.poke/b :a1 repl-sessions.poke/a] [repl-sessions.poke/c :b1 repl-sessions.poke/b :a2 repl-sessions.poke/a] [repl-sessions.poke/c :b1 repl-sessions.poke/b] [repl-sessions.poke/c :b2 repl-sessions.poke/b :a1 repl-sessions.poke/a] [repl-sessions.poke/c :b2 repl-sessions.poke/b :a2 repl-sessions.poke/a] [repl-sessions.poke/c :b2 repl-sessions.poke/b] [repl-sessions.poke/c])
d4120199d5b34efc32aef669d476fa0a68e976508bd6f6896e4afde9d4c135c3
alexandergunnarson/quantum
paths.cljc
(ns quantum.untyped.core.paths (:require [clojure.string :as str] [quantum.untyped.core.core :as ucore] [quantum.untyped.core.string :as ustr] [quantum.untyped.core.system :as usys] [quantum.untyped.core.vars :refer [defalias]])) (ucore/log-this-ns) (defn path "Joins system-specific string paths (file paths, etc.) ensuring correct separator interposition." {:usage '(path "foo/" "/bar" "baz/" "/qux/") :todo ["Configuration for system separator vs. 'standard' separator etc."]} [& parts] (apply ustr/join-once usys/separator parts)) (defn url-path [& parts] (apply ustr/join-once "/" parts))
null
https://raw.githubusercontent.com/alexandergunnarson/quantum/0c655af439734709566110949f9f2f482e468509/src-untyped/quantum/untyped/core/paths.cljc
clojure
(ns quantum.untyped.core.paths (:require [clojure.string :as str] [quantum.untyped.core.core :as ucore] [quantum.untyped.core.string :as ustr] [quantum.untyped.core.system :as usys] [quantum.untyped.core.vars :refer [defalias]])) (ucore/log-this-ns) (defn path "Joins system-specific string paths (file paths, etc.) ensuring correct separator interposition." {:usage '(path "foo/" "/bar" "baz/" "/qux/") :todo ["Configuration for system separator vs. 'standard' separator etc."]} [& parts] (apply ustr/join-once usys/separator parts)) (defn url-path [& parts] (apply ustr/join-once "/" parts))
6e2a650db3fabf9a5c268ab756041b3a9bc2a254459bad69f6e1b488771d4b6e
onedata/op-worker
dataset_path.erl
%%%------------------------------------------------------------------- @author ( C ) 2021 ACK CYFRONET AGH This software is released under the MIT license cited in ' LICENSE.txt ' . %%% @end %%%------------------------------------------------------------------- %%% @doc %%% This module is responsible for calculating paths that identify datasets. %%% These paths are of type file_meta:uuid_based_path() with only one difference : SpaceUuid is used instead of SpaceId on the first element of the path %%% (which is basically a bug in paths_cache). %%% @end %%%------------------------------------------------------------------- -module(dataset_path). -author("Jakub Kudzia"). %% API -export([get/2, get_space_path/1, to_id/1]). -compile({no_auto_import,[get/1]}). %%%=================================================================== %%% API functions %%%=================================================================== -spec get(od_space:id(), file_meta:uuid()) -> {ok, dataset:path()}. get(SpaceId, Uuid) -> {ok, DatasetPath} = paths_cache:get_uuid_based(SpaceId, Uuid), [Sep, SpaceId | Tail] = filename:split(DatasetPath), {ok, filename:join([Sep, fslogic_file_id:spaceid_to_space_dir_uuid(SpaceId) | Tail])}. -spec get_space_path(od_space:id()) -> {ok, dataset:path()}. get_space_path(SpaceId) -> get(SpaceId, fslogic_file_id:spaceid_to_space_dir_uuid(SpaceId)). -spec to_id(dataset:path()) -> dataset:id(). to_id(DatasetPath) -> lists:last(filepath_utils:split(DatasetPath)).
null
https://raw.githubusercontent.com/onedata/op-worker/239b30c6510ccf0f2f429dc5c48ecf04d192549a/src/modules/dataset/dataset_path.erl
erlang
------------------------------------------------------------------- @end ------------------------------------------------------------------- @doc This module is responsible for calculating paths that identify datasets. These paths are of type file_meta:uuid_based_path() (which is basically a bug in paths_cache). @end ------------------------------------------------------------------- API =================================================================== API functions ===================================================================
@author ( C ) 2021 ACK CYFRONET AGH This software is released under the MIT license cited in ' LICENSE.txt ' . with only one difference : SpaceUuid is used instead of SpaceId on the first element of the path -module(dataset_path). -author("Jakub Kudzia"). -export([get/2, get_space_path/1, to_id/1]). -compile({no_auto_import,[get/1]}). -spec get(od_space:id(), file_meta:uuid()) -> {ok, dataset:path()}. get(SpaceId, Uuid) -> {ok, DatasetPath} = paths_cache:get_uuid_based(SpaceId, Uuid), [Sep, SpaceId | Tail] = filename:split(DatasetPath), {ok, filename:join([Sep, fslogic_file_id:spaceid_to_space_dir_uuid(SpaceId) | Tail])}. -spec get_space_path(od_space:id()) -> {ok, dataset:path()}. get_space_path(SpaceId) -> get(SpaceId, fslogic_file_id:spaceid_to_space_dir_uuid(SpaceId)). -spec to_id(dataset:path()) -> dataset:id(). to_id(DatasetPath) -> lists:last(filepath_utils:split(DatasetPath)).
84f019d8dca5662240c818bd066d3732ba393343c03f182fbbc9b0887f3bb1d6
tud-fop/vanda-haskell
XFSA.hs
----------------------------------------------------------------------------- -- | Copyright : ( c ) Technische Universität Dresden 2018 -- License : BSD-style -- -- Stability : unknown -- Portability : portable ----------------------------------------------------------------------------- module Vanda.Grammar.XFSA.XFSA ( module Vanda.Grammar.XFSA.Internal ) where import Vanda.Grammar.XFSA.Internal (XFSA, empty, epsilon, singleton, fromList, expand)
null
https://raw.githubusercontent.com/tud-fop/vanda-haskell/3214966361b6dbf178155950c94423eee7f9453e/library/Vanda/Grammar/XFSA/XFSA.hs
haskell
--------------------------------------------------------------------------- | License : BSD-style Stability : unknown Portability : portable ---------------------------------------------------------------------------
Copyright : ( c ) Technische Universität Dresden 2018 module Vanda.Grammar.XFSA.XFSA ( module Vanda.Grammar.XFSA.Internal ) where import Vanda.Grammar.XFSA.Internal (XFSA, empty, epsilon, singleton, fromList, expand)
5fe4860b4bc05dbb1756441e4a8cf3376d416ee14867e0d24441162b175d7645
remyoudompheng/hs-language-go
Syntax.hs
-- | -- Module : Language.Go.Syntax Copyright : ( c ) 2011 License : ( see COPYING ) -- -- This module contains *synthesis* functions that take an abstract syntax tree (AST), and output Go source code . For more information , see one of the submodules . module Language.Go.Syntax ( module Language.Go.Syntax.AST ) where import Language.Go.Syntax.AST
null
https://raw.githubusercontent.com/remyoudompheng/hs-language-go/5440485f6404356892eab4832cff4f1378c11670/Language/Go/Syntax.hs
haskell
| Module : Language.Go.Syntax This module contains *synthesis* functions that take an abstract syntax tree (AST),
Copyright : ( c ) 2011 License : ( see COPYING ) and output Go source code . For more information , see one of the submodules . module Language.Go.Syntax ( module Language.Go.Syntax.AST ) where import Language.Go.Syntax.AST
7f5d2ebb734ef5ac9a5c0192152678924616364c8f93ba0262b15c4a63de3b8d
aryx/xix
eval_const.ml
Copyright 2016 , 2017 , see copyright.txt open Common open Ast module E = Check (*****************************************************************************) (* Prelude *) (*****************************************************************************) (*****************************************************************************) (* Types *) (*****************************************************************************) (* less: return also float at some point? *) type integer = int (* less: could do that in rewrite.ml so no need to pass is to eval *) type env = (Ast.fullname, integer * Type.integer_type) Hashtbl.t exception NotAConstant (* less: could factorize things in error.ml? *) type error = Check.error exception Error of error (*****************************************************************************) (* Entry point *) (*****************************************************************************) (* stricter: I do not handle float constants for enums *) let rec eval env e0 = match e0.e with (* todo: enough for big integers? * todo: we should also return an inttype in addition to the integer value. *) | Int (s, inttype) -> int_of_string s | Id fullname -> if Hashtbl.mem env fullname then let (i, inttype) = Hashtbl.find env fullname in i else raise NotAConstant | Binary (e1, op, e2) -> let i1 = eval env e1 in let i2 = eval env e2 in (match op with | Arith op -> (match op with | Plus -> i1 + i2 | Minus -> i1 - i2 | Mul -> i1 * i2 | Div -> (* stricter: error, not warning *) if i2 = 0 then raise (Error (E.Misc ("divide by zero", e0.e_loc))) else i1 / i2 | Mod -> if i2 = 0 then raise (Error (E.Misc ("modulo by zero", e0.e_loc))) else i1 mod i2 | And -> i1 land i2 | Or -> i1 lor i2 | Xor -> i1 lxor i2 | ShiftLeft -> i1 lsl i2 (* less: could be asr! need type information! *) | ShiftRight -> i1 lsr i2 ) | Logical op -> (match op with | Eq -> if i1 = i2 then 1 else 0 | NotEq -> if i1 <> i2 then 1 else 0 | Inf -> if i1 < i2 then 1 else 0 | Sup -> if i1 > i2 then 1 else 0 | InfEq -> if i1 <= i2 then 1 else 0 | SupEq -> if i1 >= i2 then 1 else 0 | AndLog -> raise Todo | OrLog -> raise Todo ) ) | Unary (op, e) -> let i = eval env e in (match op with | UnPlus -> i | UnMinus -> - i | Tilde -> lnot i (* sure? *) | _ -> raise Todo ) | _ -> raise NotAConstant (* todo: more opporunities? *)
null
https://raw.githubusercontent.com/aryx/xix/60ce1bd9a3f923e0e8bb2192f8938a9aa49c739c/compiler/eval_const.ml
ocaml
*************************************************************************** Prelude *************************************************************************** *************************************************************************** Types *************************************************************************** less: return also float at some point? less: could do that in rewrite.ml so no need to pass is to eval less: could factorize things in error.ml? *************************************************************************** Entry point *************************************************************************** stricter: I do not handle float constants for enums todo: enough for big integers? * todo: we should also return an inttype in addition to the integer value. stricter: error, not warning less: could be asr! need type information! sure? todo: more opporunities?
Copyright 2016 , 2017 , see copyright.txt open Common open Ast module E = Check type integer = int type env = (Ast.fullname, integer * Type.integer_type) Hashtbl.t exception NotAConstant type error = Check.error exception Error of error let rec eval env e0 = match e0.e with | Int (s, inttype) -> int_of_string s | Id fullname -> if Hashtbl.mem env fullname then let (i, inttype) = Hashtbl.find env fullname in i else raise NotAConstant | Binary (e1, op, e2) -> let i1 = eval env e1 in let i2 = eval env e2 in (match op with | Arith op -> (match op with | Plus -> i1 + i2 | Minus -> i1 - i2 | Mul -> i1 * i2 | Div -> if i2 = 0 then raise (Error (E.Misc ("divide by zero", e0.e_loc))) else i1 / i2 | Mod -> if i2 = 0 then raise (Error (E.Misc ("modulo by zero", e0.e_loc))) else i1 mod i2 | And -> i1 land i2 | Or -> i1 lor i2 | Xor -> i1 lxor i2 | ShiftLeft -> i1 lsl i2 | ShiftRight -> i1 lsr i2 ) | Logical op -> (match op with | Eq -> if i1 = i2 then 1 else 0 | NotEq -> if i1 <> i2 then 1 else 0 | Inf -> if i1 < i2 then 1 else 0 | Sup -> if i1 > i2 then 1 else 0 | InfEq -> if i1 <= i2 then 1 else 0 | SupEq -> if i1 >= i2 then 1 else 0 | AndLog -> raise Todo | OrLog -> raise Todo ) ) | Unary (op, e) -> let i = eval env e in (match op with | UnPlus -> i | UnMinus -> - i | _ -> raise Todo ) | _ ->
9223689e75d74e42628415c4ca0d230b0947e0baff64dddbfa2cd9c08c5dcca1
argp/bap
test_mappable.ml
open OUnit The purpose of this test file is to test properties that should be verified by all instances of a given interface , here BatInterfaces . Mappable . It is very minimal for now : it only check for one property , and only a few of the Mappable modules ( it is actually a regression test for a very specific bug ) . New properties will be added , and hopefully they will be verified against all Mappable modules . verified by all instances of a given interface, here BatInterfaces.Mappable. It is very minimal for now : it only check for one property, and only a few of the Mappable modules (it is actually a regression test for a very specific bug). New properties will be added, and hopefully they will be verified against all Mappable modules. *) module TestMappable (M : sig include BatEnum.Enumerable include BatInterfaces.Mappable with type 'a mappable = 'a enumerable end) = struct (* The property we test is that the order in which the [map] function traverse the structure (applying a given function on each element) is the same as the order of the [enum] function of the module (the order in which the elements are produced in the enumeration). *) let test_map_evaluation_order printer t = let elems_in_enum_order = BatList.of_enum (M.enum t) in let elems_in_map_order = let li = ref [] in ignore (M.map (fun x -> li := x :: !li) t); List.rev !li in assert_equal ~printer:(BatIO.to_string (BatList.print printer)) elems_in_enum_order elems_in_map_order end let test_list_mappable () = let module T = TestMappable(BatList) in T.test_map_evaluation_order BatInt.print [1; 2; 3] let test_array_mappable () = let module T = TestMappable(BatArray) in T.test_map_evaluation_order BatInt.print [|1; 2; 3|] let ( ) = let module T = TestMappable(BatTuple . Tuple2 ) in T.test_map_evaluation_order BatInt.print ( 1 , 2 ) let test_pair_mappable () = let module T = TestMappable(BatTuple.Tuple2) in T.test_map_evaluation_order BatInt.print (1, 2) *) let tests = "Mappable" >::: [ "Array" >:: test_array_mappable; "List" >:: test_list_mappable; " Pair " > : : ; ]
null
https://raw.githubusercontent.com/argp/bap/2f60a35e822200a1ec50eea3a947a322b45da363/batteries/testsuite/test_mappable.ml
ocaml
The property we test is that the order in which the [map] function traverse the structure (applying a given function on each element) is the same as the order of the [enum] function of the module (the order in which the elements are produced in the enumeration).
open OUnit The purpose of this test file is to test properties that should be verified by all instances of a given interface , here BatInterfaces . Mappable . It is very minimal for now : it only check for one property , and only a few of the Mappable modules ( it is actually a regression test for a very specific bug ) . New properties will be added , and hopefully they will be verified against all Mappable modules . verified by all instances of a given interface, here BatInterfaces.Mappable. It is very minimal for now : it only check for one property, and only a few of the Mappable modules (it is actually a regression test for a very specific bug). New properties will be added, and hopefully they will be verified against all Mappable modules. *) module TestMappable (M : sig include BatEnum.Enumerable include BatInterfaces.Mappable with type 'a mappable = 'a enumerable end) = struct let test_map_evaluation_order printer t = let elems_in_enum_order = BatList.of_enum (M.enum t) in let elems_in_map_order = let li = ref [] in ignore (M.map (fun x -> li := x :: !li) t); List.rev !li in assert_equal ~printer:(BatIO.to_string (BatList.print printer)) elems_in_enum_order elems_in_map_order end let test_list_mappable () = let module T = TestMappable(BatList) in T.test_map_evaluation_order BatInt.print [1; 2; 3] let test_array_mappable () = let module T = TestMappable(BatArray) in T.test_map_evaluation_order BatInt.print [|1; 2; 3|] let ( ) = let module T = TestMappable(BatTuple . Tuple2 ) in T.test_map_evaluation_order BatInt.print ( 1 , 2 ) let test_pair_mappable () = let module T = TestMappable(BatTuple.Tuple2) in T.test_map_evaluation_order BatInt.print (1, 2) *) let tests = "Mappable" >::: [ "Array" >:: test_array_mappable; "List" >:: test_list_mappable; " Pair " > : : ; ]
b4ba04beff3286c38a86abcd76c965d147bd32935a69343547092f797564fd6e
pixlsus/registry.gimp.org_static
gimp_diving.scm
;; FILE gimp_diving.scm DATE 2008 - 09 - 25 COPYRIGHT 2008 AUTHOR and < > The credit for this process goes to a posting on DigitalDiver.net by ( nickname - " mandrake " ) . ;; and this website -kine.info/adjustments.htm ;; ;; DESCRIPTION ;; This script acts as a red fitler on diving photos. ;; To launch it, goto the menu <Image>/Script-Fu/Enhance/Diving red filter ;; ;; Basically, create a new layer containing the corrected picture ;; You can adjust the red level (sometimes, green might works better !) ;; and set if the white balance has to be performed... ;; Enjoy ! ;; LICENCE GNU Emacs is free software ; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation ; either version 2 , or ( at your option ) ;; any later version. GNU Emacs is distributed in the hope that it will be useful , ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. You should have received a copy of the GNU General Public License along with GNU Emacs ; see the file COPYING . If not , write to the Free Software Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , , USA . (define (script-fu-diving img drawable balance red-level) (gimp-progress-update 0.0) ;;progress bar duplicate selected layer 3 times (define dup1 (car (gimp-layer-copy drawable TRUE))) (gimp-image-add-layer img dup1 0) (gimp-progress-update 0.1) ;;progress bar (define dup2 (car (gimp-layer-copy drawable TRUE))) (gimp-image-add-layer img dup2 0) (gimp-progress-update 0.2) ;;progress bar (define dup3 (car (gimp-layer-copy drawable TRUE))) (gimp-image-add-layer img dup3 0) (gimp-progress-update 0.3) ;;progress bar ;;desaturate the dup2 (gimp-desaturate dup2) (gimp-progress-update 0.4) ;;progress bar ;; fill dup3 with red-level color, define in parameter of the function (gimp-context-set-foreground red-level) (gimp-drawable-fill dup3 FOREGROUND-FILL) (gimp-progress-update 0.5) ;;progress bar ;;merge it down with multiply operation (gimp-layer-set-mode dup3 MULTIPLY-MODE) (define dup5 (car (gimp-image-merge-down img dup3 0))) (gimp-progress-update 0.6) ;;progress bar merge this new layer with the third one with screen operation (gimp-layer-set-mode dup5 SCREEN-MODE) (define dup6 (car (gimp-image-merge-down img dup5 0))) (gimp-progress-update 0.7) ;;progress bar ;;perform white balance if needed (if (= balance TRUE) (begin (gimp-levels-stretch dup6) ) ) (gimp-progress-update 0.9) ;;progress bar ;;refresh display (gimp-displays-flush) (gimp-progress-update 1.0) ;;progress bar ) ;; RECORD this script in the (script-fu-register "script-fu-diving" ;; nom du script "<Image>/Script-Fu/Enhance/Diving red filter" "This script acts as a red fitler on diving photos.\nTo launch it, goto the menu <Image>/Script-Fu/Enhance/Diving red filter\n\nBasically, create a new layer containing the corrected picture. You can adjust the red level (sometimes, green might works better !) and set if the white balance has to be performed...\nEnjoy !" ;; commentaires "Jeremy Bluteau and Thomas Amory" ;; auteur "2008 under GPL" ;; copyright "2008-09-25" ;; date "" ;; types d'images supportés par le script image dans lequel SF-TOGGLE "Balance des blancs ?" TRUE SF-COLOR "Couleur rouge" '(255 0 0) SF - ADJUSTMENT " Niveau de rouge " ' ( 100 0 100 1 10 0 1 ) ) ;; fin du register
null
https://raw.githubusercontent.com/pixlsus/registry.gimp.org_static/ffcde7400f402728373ff6579947c6ffe87d1a5e/registry.gimp.org/files/gimp_diving.scm
scheme
FILE gimp_diving.scm and this website -kine.info/adjustments.htm DESCRIPTION This script acts as a red fitler on diving photos. To launch it, goto the menu <Image>/Script-Fu/Enhance/Diving red filter Basically, create a new layer containing the corrected picture You can adjust the red level (sometimes, green might works better !) and set if the white balance has to be performed... Enjoy ! LICENCE you can redistribute it and/or modify either version 2 , or ( at your option ) any later version. but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. see the file COPYING . If not , write to the progress bar progress bar progress bar progress bar desaturate the dup2 progress bar fill dup3 with red-level color, define in parameter of the function progress bar merge it down with multiply operation progress bar progress bar perform white balance if needed progress bar refresh display progress bar RECORD this script in the nom du script commentaires auteur copyright date types d'images supportés par le script fin du register
DATE 2008 - 09 - 25 COPYRIGHT 2008 AUTHOR and < > The credit for this process goes to a posting on DigitalDiver.net by ( nickname - " mandrake " ) . it under the terms of the GNU General Public License as published by GNU Emacs is distributed in the hope that it will be useful , You should have received a copy of the GNU General Public License Free Software Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , , USA . (define (script-fu-diving img drawable balance red-level) duplicate selected layer 3 times (define dup1 (car (gimp-layer-copy drawable TRUE))) (gimp-image-add-layer img dup1 0) (define dup2 (car (gimp-layer-copy drawable TRUE))) (gimp-image-add-layer img dup2 0) (define dup3 (car (gimp-layer-copy drawable TRUE))) (gimp-image-add-layer img dup3 0) (gimp-desaturate dup2) (gimp-context-set-foreground red-level) (gimp-drawable-fill dup3 FOREGROUND-FILL) (gimp-layer-set-mode dup3 MULTIPLY-MODE) (define dup5 (car (gimp-image-merge-down img dup3 0))) merge this new layer with the third one with screen operation (gimp-layer-set-mode dup5 SCREEN-MODE) (define dup6 (car (gimp-image-merge-down img dup5 0))) (if (= balance TRUE) (begin (gimp-levels-stretch dup6) ) ) (gimp-displays-flush) ) "<Image>/Script-Fu/Enhance/Diving red filter" "This script acts as a red fitler on diving photos.\nTo launch it, goto the menu <Image>/Script-Fu/Enhance/Diving red filter\n\nBasically, create a new layer containing the corrected picture. You can adjust the red level (sometimes, green might works better !) image dans lequel SF-TOGGLE "Balance des blancs ?" TRUE SF-COLOR "Couleur rouge" '(255 0 0) SF - ADJUSTMENT " Niveau de rouge " ' ( 100 0 100 1 10 0 1 )
e8e590361060a64e7d81401d274b6c6759d5d07a97f7cad1b1b6ef7aeb9d0565
haskell/cabal
cabal.test.hs
import Test.Cabal.Prelude -- Impossible version range for internal library. main = cabalTest $ fails $ cabal "check" []
null
https://raw.githubusercontent.com/haskell/cabal/1cfe7c4c7257aa7ae450209d34b4a359e6703a10/cabal-testsuite/PackageTests/Check/ConfiguredPackage/Fields/ImpossibleVersionRangeLib/cabal.test.hs
haskell
Impossible version range for internal library.
import Test.Cabal.Prelude main = cabalTest $ fails $ cabal "check" []
010c6143ad6d4ce1b2bfd71aa106798a4d6e61f03f27801fcdc1408369ca0449
triffon/fp-2019-20
solutions.rkt
# lang racket 1 . length (define (length* lst) (if (null? lst) 0 (+ 1 (length* (cdr lst))))) 2 . sum (define (sum lst) (if (null? lst) 0 (+ (car lst) (sum (cdr lst))))) 3 . last (define (last* lst) (if (null? (cdr lst)) (car lst) (last (cdr lst)))) 4 . nth (define (nth n lst) (define (help i lst) (cond [(null? lst) 'not-found] [(= i n) (car lst)] [else (help (+ 1 i) (cdr lst))])) (help 0)) 5 . concat (define (concat lst1 lst2) (if (null? lst1) lst2 (cons (car lst1) (concat (cdr lst1) lst2)))) 6 . map (define (map* f lst) (if (null? lst) lst (cons (f (car lst)) (map* f (cdr lst))))) 7 . filter (define (filter* p lst) (cond [(null? lst) lst] [(p (car lst)) (cons (car lst) (filter* p (cdr lst)))] [else (filter* p (cdr lst))])) 8 . partition (define (partition* p lst) (define (help truthy falsy lst) (cond [(null? lst) (cons truthy (list falsy))] [(p (car lst)) (help (cons (car lst) truthy) falsy (cdr lst))] [else (help truthy (cons (car lst) falsy) (cdr lst))])) (help '() '() lst))
null
https://raw.githubusercontent.com/triffon/fp-2019-20/7efb13ff4de3ea13baa2c5c59eb57341fac15641/exercises/computer-science-4/04/solutions.rkt
racket
# lang racket 1 . length (define (length* lst) (if (null? lst) 0 (+ 1 (length* (cdr lst))))) 2 . sum (define (sum lst) (if (null? lst) 0 (+ (car lst) (sum (cdr lst))))) 3 . last (define (last* lst) (if (null? (cdr lst)) (car lst) (last (cdr lst)))) 4 . nth (define (nth n lst) (define (help i lst) (cond [(null? lst) 'not-found] [(= i n) (car lst)] [else (help (+ 1 i) (cdr lst))])) (help 0)) 5 . concat (define (concat lst1 lst2) (if (null? lst1) lst2 (cons (car lst1) (concat (cdr lst1) lst2)))) 6 . map (define (map* f lst) (if (null? lst) lst (cons (f (car lst)) (map* f (cdr lst))))) 7 . filter (define (filter* p lst) (cond [(null? lst) lst] [(p (car lst)) (cons (car lst) (filter* p (cdr lst)))] [else (filter* p (cdr lst))])) 8 . partition (define (partition* p lst) (define (help truthy falsy lst) (cond [(null? lst) (cons truthy (list falsy))] [(p (car lst)) (help (cons (car lst) truthy) falsy (cdr lst))] [else (help truthy (cons (car lst) falsy) (cdr lst))])) (help '() '() lst))
2085e4928f27baf6a436f7276b81e2b90f606f7228a69c7c19c6a32fbb581d9c
freizl/hoauth2
Dropbox.hs
# LANGUAGE DeriveGeneric # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE QuasiQuotes # # LANGUAGE RecordWildCards # # LANGUAGE TypeFamilies # | [ DropBox oauth guide]( / oauth - guide ) module Network.OAuth2.Provider.Dropbox where import Data.Aeson import Data.Map.Strict qualified as Map import Data.Set qualified as Set import Data.Text.Lazy (Text) import GHC.Generics import Network.OAuth.OAuth2 import Network.OAuth2.Experiment import URI.ByteString.QQ data Dropbox = Dropbox deriving (Eq, Show) type instance IdpUserInfo Dropbox = DropboxUser defaultDropboxApp :: IdpApplication 'AuthorizationCode Dropbox defaultDropboxApp = AuthorizationCodeIdpApplication { idpAppClientId = "" , idpAppClientSecret = "" , idpAppScope = Set.empty , idpAppAuthorizeState = "CHANGE_ME" , idpAppAuthorizeExtraParams = Map.empty , idpAppRedirectUri = [uri||] , idpAppName = "default-dropbox-App" , idpAppTokenRequestAuthenticationMethod = ClientSecretBasic , idp = defaultDropboxIdp } defaultDropboxIdp :: Idp Dropbox defaultDropboxIdp = Idp { idpFetchUserInfo = \mgr at url -> authPostJSON @(IdpUserInfo Dropbox) mgr at url [] , idpAuthorizeEndpoint = [uri||] , idpTokenEndpoint = [uri||] , idpUserInfoEndpoint = [uri||] } newtype DropboxUserName = DropboxUserName {displayName :: Text} deriving (Show, Generic) data DropboxUser = DropboxUser { email :: Text , name :: DropboxUserName } deriving (Show, Generic) instance FromJSON DropboxUserName where parseJSON = genericParseJSON defaultOptions {fieldLabelModifier = camelTo2 '_'} instance FromJSON DropboxUser
null
https://raw.githubusercontent.com/freizl/hoauth2/8610da5ec2565e5d70c590fbde8689c6af025b78/hoauth2-providers/src/Network/OAuth2/Provider/Dropbox.hs
haskell
# LANGUAGE OverloadedStrings #
# LANGUAGE DeriveGeneric # # LANGUAGE QuasiQuotes # # LANGUAGE RecordWildCards # # LANGUAGE TypeFamilies # | [ DropBox oauth guide]( / oauth - guide ) module Network.OAuth2.Provider.Dropbox where import Data.Aeson import Data.Map.Strict qualified as Map import Data.Set qualified as Set import Data.Text.Lazy (Text) import GHC.Generics import Network.OAuth.OAuth2 import Network.OAuth2.Experiment import URI.ByteString.QQ data Dropbox = Dropbox deriving (Eq, Show) type instance IdpUserInfo Dropbox = DropboxUser defaultDropboxApp :: IdpApplication 'AuthorizationCode Dropbox defaultDropboxApp = AuthorizationCodeIdpApplication { idpAppClientId = "" , idpAppClientSecret = "" , idpAppScope = Set.empty , idpAppAuthorizeState = "CHANGE_ME" , idpAppAuthorizeExtraParams = Map.empty , idpAppRedirectUri = [uri||] , idpAppName = "default-dropbox-App" , idpAppTokenRequestAuthenticationMethod = ClientSecretBasic , idp = defaultDropboxIdp } defaultDropboxIdp :: Idp Dropbox defaultDropboxIdp = Idp { idpFetchUserInfo = \mgr at url -> authPostJSON @(IdpUserInfo Dropbox) mgr at url [] , idpAuthorizeEndpoint = [uri||] , idpTokenEndpoint = [uri||] , idpUserInfoEndpoint = [uri||] } newtype DropboxUserName = DropboxUserName {displayName :: Text} deriving (Show, Generic) data DropboxUser = DropboxUser { email :: Text , name :: DropboxUserName } deriving (Show, Generic) instance FromJSON DropboxUserName where parseJSON = genericParseJSON defaultOptions {fieldLabelModifier = camelTo2 '_'} instance FromJSON DropboxUser
e381efd5362e5ac7e0bd2ef331490a9a6a7842c4c20902ff5a761e28bb99adf7
db48x/xe2
cube.lisp
(in-package :void) (defcell cube-wall (name :initform "Cube wall") (tile :initform "cube-wall") (categories :initform '(:opaque :obstacle)) (descriptions :initform "Ultra-hard yellow surface inscribed with angular marks.")) (defcell cube-floor (name :initform "Cube floor") (tile :initform "cube-floor") (description :initform "You will use 1 unit of oxygen for each square moved, or each turn waited. Melee combat uses 2 units per hit.")) (defcell blue-arrowbox (name :initform "Cube box") (color :initform :blue) (stepping :initform t) (tile :initform "blue-arrowbox") (categories :initform '(:obstacle :pushable :arrowbox)) (description :initform "Strange boxes appear to have almost no weight, and bullets move them around.")) (define-method push blue-arrowbox (dir) (when (or (not [obstacle-in-direction-p *world* <row> <column> dir]) [category-in-direction-p *world* <row> <column> dir :arrowbox-receptacle]) [move self dir :ignore-obstacles])) (define-prototype turquoise-arrowbox (:parent =blue-arrowbox=) (color :initform :turquoise) (tile :initform "turquoise-arrowbox")) (define-prototype red-arrowbox (:parent =blue-arrowbox=) (color :initform :red) (tile :initform "red-arrowbox")) (defparameter *receptacle-colors* '(:red :turquoise :blue)) (defun random-receptacle-color () (car (one-of *receptacle-colors*))) (defparameter *receptacle-tiles* '(:red "red-arrowbox-receptacle" :turquoise "turquoise-arrowbox-receptacle" :blue "blue-arrowbox-receptacle" )) (defcell arrowbox-receptacle (categories :initform '(:obstacle :opaque :arrowbox-receptacle)) color) (define-method initialize arrowbox-receptacle (&optional (color (random-receptacle-color))) (setf <color> color) (setf <tile> (getf *receptacle-tiles* color))) (define-method step arrowbox-receptacle (stepper) (when (and [in-category stepper :arrowbox] (eq <color> (field-value :color stepper))) [play-sample self "worp"] [say self "The box and lock both disappear."] [drop self (clone =energy=)] [die self] [die stepper])) ;;; Enemies of the cube (define-prototype bit (:parent =laser-drone=) (tile :initform "bit2") (categories :initform '(:actor :obstacle :enemy :target)) (direction :initform :north) (state :initform nil)) (define-method loadout bit () [make-inventory self] [make-equipment self] [equip self [add-item self (clone =ray-caster=)]]) (define-method flip bit () (setf <state> (if <state> nil t)) (setf <direction> (nth (random 2) (if <state> '(:north :south) '(:east :west)))) (setf <tile> (if <state> "bit" "bit2"))) (define-method run bit () (when (< [distance-to-player self] 5) [fire self]) (when [obstacle-in-direction-p *world* <row> <column> <direction>] [flip self]) [move self <direction>]) (define-method die bit () [play-sample self "aagh"] [delete-from-world self]) ;;; The cube world (define-prototype cube (:parent =world=) (scale :initform '(10 m)) (room-size :initform 10) (required-modes :initform '(:spacesuit :olvac :vomac :vehicle)) (width :initform 50) (height :initform 50) (name :initform "Ancient cube") (ambient-light :initform 10)) (define-method begin-ambient-loop cube () (play-music "ancients" :loop t)) (define-method generate cube (&key sequence-number) [create-default-grid self] (clon:with-field-values (height width) self ;; drop floors (dotimes (i height) (dotimes (j width) [drop-cell self (clone =cube-floor=) i j])) ;; create walls (labels ((drop-wall (x y) (prog1 nil [drop-cell self (clone =cube-wall=) y x])) (drop-box (x y) (prog1 nil [drop-cell self (clone (car (one-of (list =blue-arrowbox= =turquoise-arrowbox= =red-arrowbox=)))) y x :no-collisions t]))) ;; create border around world (trace-rectangle #'drop-wall 0 0 width height) ;; [drop-maze self] [drop-specials self] (dotimes (i 120) (drop-box (random height) (random width))) (dotimes (i 40) [drop-cell self (clone =bit=) (random height) (random width) :loadout t])) [drop-cell self (clone =launchpad=) 10 10])) (define-method drop-maze cube () (clon:with-field-values (height width room-size) self (labels ((drop-wall (r c) (prog1 nil [drop-cell self (clone =cube-wall=) r c])) (drop-room (r c) (trace-rectangle #'drop-wall r c (1+ <room-size>) (1+ <room-size>))) (maybe-remove-obstacles (r c probability) (percent-of-time probability (let (obstacle) (loop while (setf obstacle [category-at-p *world* r c :obstacle]) do [delete-from-world obstacle])))) (maybe-drop-lock (r c probability) (percent-of-time probability [drop-cell self (clone =arrowbox-receptacle=) r c])) (open-room (r c side) (dotimes (i 4) (multiple-value-bind (row column) (ecase side (:top (values r (+ c (random room-size)))) (:bottom (values (+ r room-size) (+ c (random room-size)))) (:left (values (+ r (random room-size)) c)) (:right (values (+ r (random room-size)) (+ c room-size)))) (maybe-remove-obstacles row column 100) (maybe-drop-lock row column 95))))) (dotimes (i (truncate (/ width room-size))) (dotimes (j (truncate (/ height room-size))) (let ((r0 (1- (* i room-size))) (c0 (1- (* j room-size)))) (drop-room r0 c0) (dotimes (i 3) (open-room r0 c0 (car (one-of '(:top :bottom :left :right))))))))))) (define-method drop-specials cube () (dotimes (i 3) [drop-cell self (clone =mystery-box=) (random <height>) (random <width>)]) (dotimes (i 2) [drop-cell self (clone =beta-muon-upgrade=) (random <height>) (random <width>)]))
null
https://raw.githubusercontent.com/db48x/xe2/7896fcc69f5c6e28eaf6f6abb7966d6663370a66/void/cube.lisp
lisp
Enemies of the cube The cube world drop floors create walls create border around world
(in-package :void) (defcell cube-wall (name :initform "Cube wall") (tile :initform "cube-wall") (categories :initform '(:opaque :obstacle)) (descriptions :initform "Ultra-hard yellow surface inscribed with angular marks.")) (defcell cube-floor (name :initform "Cube floor") (tile :initform "cube-floor") (description :initform "You will use 1 unit of oxygen for each square moved, or each turn waited. Melee combat uses 2 units per hit.")) (defcell blue-arrowbox (name :initform "Cube box") (color :initform :blue) (stepping :initform t) (tile :initform "blue-arrowbox") (categories :initform '(:obstacle :pushable :arrowbox)) (description :initform "Strange boxes appear to have almost no weight, and bullets move them around.")) (define-method push blue-arrowbox (dir) (when (or (not [obstacle-in-direction-p *world* <row> <column> dir]) [category-in-direction-p *world* <row> <column> dir :arrowbox-receptacle]) [move self dir :ignore-obstacles])) (define-prototype turquoise-arrowbox (:parent =blue-arrowbox=) (color :initform :turquoise) (tile :initform "turquoise-arrowbox")) (define-prototype red-arrowbox (:parent =blue-arrowbox=) (color :initform :red) (tile :initform "red-arrowbox")) (defparameter *receptacle-colors* '(:red :turquoise :blue)) (defun random-receptacle-color () (car (one-of *receptacle-colors*))) (defparameter *receptacle-tiles* '(:red "red-arrowbox-receptacle" :turquoise "turquoise-arrowbox-receptacle" :blue "blue-arrowbox-receptacle" )) (defcell arrowbox-receptacle (categories :initform '(:obstacle :opaque :arrowbox-receptacle)) color) (define-method initialize arrowbox-receptacle (&optional (color (random-receptacle-color))) (setf <color> color) (setf <tile> (getf *receptacle-tiles* color))) (define-method step arrowbox-receptacle (stepper) (when (and [in-category stepper :arrowbox] (eq <color> (field-value :color stepper))) [play-sample self "worp"] [say self "The box and lock both disappear."] [drop self (clone =energy=)] [die self] [die stepper])) (define-prototype bit (:parent =laser-drone=) (tile :initform "bit2") (categories :initform '(:actor :obstacle :enemy :target)) (direction :initform :north) (state :initform nil)) (define-method loadout bit () [make-inventory self] [make-equipment self] [equip self [add-item self (clone =ray-caster=)]]) (define-method flip bit () (setf <state> (if <state> nil t)) (setf <direction> (nth (random 2) (if <state> '(:north :south) '(:east :west)))) (setf <tile> (if <state> "bit" "bit2"))) (define-method run bit () (when (< [distance-to-player self] 5) [fire self]) (when [obstacle-in-direction-p *world* <row> <column> <direction>] [flip self]) [move self <direction>]) (define-method die bit () [play-sample self "aagh"] [delete-from-world self]) (define-prototype cube (:parent =world=) (scale :initform '(10 m)) (room-size :initform 10) (required-modes :initform '(:spacesuit :olvac :vomac :vehicle)) (width :initform 50) (height :initform 50) (name :initform "Ancient cube") (ambient-light :initform 10)) (define-method begin-ambient-loop cube () (play-music "ancients" :loop t)) (define-method generate cube (&key sequence-number) [create-default-grid self] (clon:with-field-values (height width) self (dotimes (i height) (dotimes (j width) [drop-cell self (clone =cube-floor=) i j])) (labels ((drop-wall (x y) (prog1 nil [drop-cell self (clone =cube-wall=) y x])) (drop-box (x y) (prog1 nil [drop-cell self (clone (car (one-of (list =blue-arrowbox= =turquoise-arrowbox= =red-arrowbox=)))) y x :no-collisions t]))) (trace-rectangle #'drop-wall 0 0 width height) [drop-maze self] [drop-specials self] (dotimes (i 120) (drop-box (random height) (random width))) (dotimes (i 40) [drop-cell self (clone =bit=) (random height) (random width) :loadout t])) [drop-cell self (clone =launchpad=) 10 10])) (define-method drop-maze cube () (clon:with-field-values (height width room-size) self (labels ((drop-wall (r c) (prog1 nil [drop-cell self (clone =cube-wall=) r c])) (drop-room (r c) (trace-rectangle #'drop-wall r c (1+ <room-size>) (1+ <room-size>))) (maybe-remove-obstacles (r c probability) (percent-of-time probability (let (obstacle) (loop while (setf obstacle [category-at-p *world* r c :obstacle]) do [delete-from-world obstacle])))) (maybe-drop-lock (r c probability) (percent-of-time probability [drop-cell self (clone =arrowbox-receptacle=) r c])) (open-room (r c side) (dotimes (i 4) (multiple-value-bind (row column) (ecase side (:top (values r (+ c (random room-size)))) (:bottom (values (+ r room-size) (+ c (random room-size)))) (:left (values (+ r (random room-size)) c)) (:right (values (+ r (random room-size)) (+ c room-size)))) (maybe-remove-obstacles row column 100) (maybe-drop-lock row column 95))))) (dotimes (i (truncate (/ width room-size))) (dotimes (j (truncate (/ height room-size))) (let ((r0 (1- (* i room-size))) (c0 (1- (* j room-size)))) (drop-room r0 c0) (dotimes (i 3) (open-room r0 c0 (car (one-of '(:top :bottom :left :right))))))))))) (define-method drop-specials cube () (dotimes (i 3) [drop-cell self (clone =mystery-box=) (random <height>) (random <width>)]) (dotimes (i 2) [drop-cell self (clone =beta-muon-upgrade=) (random <height>) (random <width>)]))
f7cb2f9f0b74949c44a1d5b2999fb8b5b0d125320d35c23d5bcc8db64e79d494
rvantonder/hack_parallel
sys_utils.ml
* * Copyright ( c ) 2015 , Facebook , Inc. * All rights reserved . * * This source code is licensed under the BSD - style license found in the * LICENSE file in the " hack " directory of this source tree . An additional grant * of patent rights can be found in the PATENTS file in the same directory . * * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the "hack" directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * *) open Hack_core exception NotADirectory of string external realpath: string -> string option = "hh_realpath" external is_nfs: string -> bool = "hh_is_nfs" (** Hack_option type intead of exception throwing. *) let get_env name = try Some (Sys.getenv name) with | Not_found -> None let getenv_user () = let user_var = if Sys.win32 then "USERNAME" else "USER" in let logname_var = "LOGNAME" in let user = get_env user_var in let logname = get_env logname_var in Hack_option.first_some user logname let getenv_home () = let home_var = if Sys.win32 then "APPDATA" else "HOME" in get_env home_var let getenv_term () = let term_var = "TERM" in (* This variable does not exist on windows. *) get_env term_var let path_sep = if Sys.win32 then ";" else ":" let null_path = if Sys.win32 then "nul" else "/dev/null" let temp_dir_name = if Sys.win32 then Filename.get_temp_dir_name () else "/tmp" let getenv_path () = let path_var = "PATH" in (* Same variable on windows *) get_env path_var let open_in_no_fail fn = try open_in fn with e -> let e = Printexc.to_string e in Printf.fprintf stderr "Could not open_in: '%s' (%s)\n" fn e; exit 3 let open_in_bin_no_fail fn = try open_in_bin fn with e -> let e = Printexc.to_string e in Printf.fprintf stderr "Could not open_in_bin: '%s' (%s)\n" fn e; exit 3 let close_in_no_fail fn ic = try close_in ic with e -> let e = Printexc.to_string e in Printf.fprintf stderr "Could not close: '%s' (%s)\n" fn e; exit 3 let open_out_no_fail fn = try open_out fn with e -> let e = Printexc.to_string e in Printf.fprintf stderr "Could not open_out: '%s' (%s)\n" fn e; exit 3 let open_out_bin_no_fail fn = try open_out_bin fn with e -> let e = Printexc.to_string e in Printf.fprintf stderr "Could not open_out_bin: '%s' (%s)\n" fn e; exit 3 let close_out_no_fail fn oc = try close_out oc with e -> let e = Printexc.to_string e in Printf.fprintf stderr "Could not close: '%s' (%s)\n" fn e; exit 3 let cat = Disk.cat let cat_no_fail filename = let ic = open_in_bin_no_fail filename in let len = in_channel_length ic in let buf = Buffer.create len in Buffer.add_channel buf ic len; let content = Buffer.contents buf in close_in_no_fail filename ic; content let nl_regexp = Str.regexp "[\r\n]" let split_lines = Str.split nl_regexp (** Returns true if substring occurs somewhere inside str. *) let string_contains str substring = (* regexp_string matches only this string and nothing else. *) let re = Str.regexp_string substring in try (Str.search_forward re str 0) >= 0 with Not_found -> false let exec_read cmd = let ic = Unix.open_process_in cmd in let result = input_line ic in assert (Unix.close_process_in ic = Unix.WEXITED 0); result let exec_read_lines ?(reverse=false) cmd = let ic = Unix.open_process_in cmd in let result = ref [] in (try while true do result := input_line ic :: !result done; with End_of_file -> ()); assert (Unix.close_process_in ic = Unix.WEXITED 0); if not reverse then List.rev !result else !result (** Deletes the file given by "path". If it is a directory, recursively * deletes all its contents then removes the directory itself. *) let rec rm_dir_tree path = try begin let stats = Unix.lstat path in match stats.Unix.st_kind with | Unix.S_DIR -> let contents = Sys.readdir path in List.iter (Array.to_list contents) ~f:(fun name -> let name = Filename.concat path name in rm_dir_tree name); Unix.rmdir path | Unix.S_LNK | Unix.S_REG | Unix.S_CHR | Unix.S_BLK | Unix.S_FIFO | Unix.S_SOCK -> Unix.unlink path end with (* Path has been deleted out from under us - can ignore it. *) | Sys_error(s) when s = Printf.sprintf "%s: No such file or directory" path -> () | Unix.Unix_error(Unix.ENOENT, _, _) -> () let restart () = let cmd = Sys.argv.(0) in let argv = Sys.argv in Unix.execv cmd argv let logname_impl () = match getenv_user () with | Some user -> user | None -> (* If this function is generally useful, it can be lifted to toplevel in this file, but this is the only place we need it for now. *) let exec_try_read cmd = let ic = Unix.open_process_in cmd in let out = try Some (input_line ic) with End_of_file -> None in let status = Unix.close_process_in ic in match out, status with | Some _, Unix.WEXITED 0 -> out | _ -> None in try Utils.unsafe_opt (exec_try_read "logname") with Invalid_argument _ -> try Utils.unsafe_opt (exec_try_read "id -un") with Invalid_argument _ -> "[unknown]" let logname_ref = ref None let logname () = if !logname_ref = None then logname_ref := Some (logname_impl ()); Utils.unsafe_opt !logname_ref let with_umask umask f = let old_umask = ref 0 in Utils.with_context ~enter:(fun () -> old_umask := Unix.umask umask) ~exit:(fun () -> ignore (Unix.umask !old_umask)) ~do_:f let with_umask umask f = if Sys.win32 then f () else with_umask umask f let read_stdin_to_string () = let buf = Buffer.create 4096 in try while true do Buffer.add_string buf (input_line stdin); Buffer.add_char buf '\n' done; assert false with End_of_file -> Buffer.contents buf let read_all ?(buf_size=4096) ic = let buf = Buffer.create buf_size in (try while true do let data = Bytes.create buf_size in let bytes_read = input ic data 0 buf_size in if bytes_read = 0 then raise Exit; Buffer.add_subbytes buf data 0 bytes_read; done with Exit -> ()); Buffer.contents buf * * Like 's os.path.expanduser , though probably does n't cover some cases . * Roughly follow 's bash 's tilde expansion : * -Expansion.html * * ~/foo - > /home / bob / foo if $ HOME = " /home / bob " * ~joe / foo - > /home / / foo if 's home is /home / * Like Python's os.path.expanduser, though probably doesn't cover some cases. * Roughly follow's bash's tilde expansion: * -Expansion.html * * ~/foo -> /home/bob/foo if $HOME = "/home/bob" * ~joe/foo -> /home/joe/foo if joe's home is /home/joe *) let expanduser path = Str.substitute_first (Str.regexp "^~\\([^/]*\\)") begin fun s -> match Str.matched_group 1 s with | "" -> begin match getenv_home () with | None -> (Unix.getpwuid (Unix.getuid())).Unix.pw_dir | Some home -> home end | unixname -> try (Unix.getpwnam unixname).Unix.pw_dir with Not_found -> Str.matched_string s end path Turns out it 's surprisingly complex to figure out the path to the current executable , which we need in order to extract its embedded libraries . If argv[0 ] is a path , then we can use that ; sometimes it 's just the exe name , so we have to search $ PATH for it the same way shells do . for example : -Search-and-Execution.html There are other options which might be more reliable when they exist , like using the ` _ ` env var set by bash , or /proc / self / exe on Linux , but they are not portable . executable, which we need in order to extract its embedded libraries. If argv[0] is a path, then we can use that; sometimes it's just the exe name, so we have to search $PATH for it the same way shells do. for example: -Search-and-Execution.html There are other options which might be more reliable when they exist, like using the `_` env var set by bash, or /proc/self/exe on Linux, but they are not portable. *) let executable_path : unit -> string = let executable_path_ = ref None in let dir_sep = Filename.dir_sep.[0] in let search_path path = let paths = match getenv_path () with | None -> failwith "Unable to determine executable path" | Some paths -> Str.split (Str.regexp_string path_sep) paths in let path = List.fold_left paths ~f:begin fun acc p -> match acc with | Some _ -> acc | None -> realpath (expanduser (Filename.concat p path)) end ~init:None in match path with | Some path -> path | None -> failwith "Unable to determine executable path" in fun () -> match !executable_path_ with | Some path -> path | None -> let path = Sys.executable_name in let path = if String.contains path dir_sep then match realpath path with | Some path -> path | None -> failwith "Unable to determine executable path" else search_path path in executable_path_ := Some path; path let lines_of_in_channel ic = let rec loop accum = match try Some(input_line ic) with _e -> None with | None -> List.rev accum | Some(line) -> loop (line::accum) in loop [] let lines_of_file filename = let ic = open_in filename in try let result = lines_of_in_channel ic in let _ = close_in ic in result with _ -> close_in ic; [] let read_file file = let ic = open_in_bin file in let size = in_channel_length ic in let buf = String.create size in really_input ic buf 0 size; close_in ic; buf let write_file ~file s = let chan = open_out file in (output_string chan s; close_out chan) let append_file ~file s = let chan = open_out_gen [Open_wronly; Open_append; Open_creat] 0o666 file in (output_string chan s; close_out chan) (* could be in control section too *) let filemtime file = (Unix.stat file).Unix.st_mtime external lutimes : string -> unit = "hh_lutimes" let try_touch ~follow_symlinks file = try if follow_symlinks then Unix.utimes file 0.0 0.0 else lutimes file with _ -> () let rec mkdir_p = function | "" -> failwith "Unexpected empty directory, should never happen" | d when not (Sys.file_exists d) -> mkdir_p (Filename.dirname d); Unix.mkdir d 0o770; | d when Sys.is_directory d -> () | d -> raise (NotADirectory d) (* Emulate "mkdir -p", i.e., no error if already exists. *) let mkdir_no_fail dir = with_umask 0 begin fun () -> (* Don't set sticky bit since the socket opening code wants to remove any * old sockets it finds, which may be owned by a different user. *) try Unix.mkdir dir 0o777 with Unix.Unix_error (Unix.EEXIST, _, _) -> () end let unlink_no_fail fn = try Unix.unlink fn with Unix.Unix_error (Unix.ENOENT, _, _) -> () let readlink_no_fail fn = if Sys.win32 && Sys.file_exists fn then cat fn else try Unix.readlink fn with _ -> fn let splitext filename = let root = Filename.chop_extension filename in let root_length = String.length root in (* -1 because the extension includes the period, e.g. ".foo" *) let ext_length = String.length filename - root_length - 1 in let ext = String.sub filename (root_length + 1) ext_length in root, ext let is_test_mode () = try ignore @@ Sys.getenv "HH_TEST_MODE"; true with _ -> false let symlink = Dummy implementation of ` symlink ` on Windows : we create a text file containing the targeted - file 's path . Symlink are available on Windows since Vista , but until Seven ( included ) , one should have administratrive rights in order to create symlink . file containing the targeted-file's path. Symlink are available on Windows since Vista, but until Seven (included), one should have administratrive rights in order to create symlink. *) let win32_symlink source dest = write_file ~file:dest source in if Sys.win32 then win32_symlink else 4.03 adds an optional argument to Unix.symlink that we want to ignore *) fun source dest -> Unix.symlink source dest (* Creates a symlink at <dir>/<linkname.ext> to * <dir>/<pluralized ext>/<linkname>-<timestamp>.<ext> *) let make_link_of_timestamped linkname = let open Unix in let dir = Filename.dirname linkname in mkdir_no_fail dir; let base = Filename.basename linkname in let base, ext = splitext base in let dir = Filename.concat dir (Printf.sprintf "%ss" ext) in mkdir_no_fail dir; let tm = localtime (time ()) in let year = tm.tm_year + 1900 in let time_str = Printf.sprintf "%d-%02d-%02d-%02d-%02d-%02d" year (tm.tm_mon + 1) tm.tm_mday tm.tm_hour tm.tm_min tm.tm_sec in let filename = Filename.concat dir (Printf.sprintf "%s-%s.%s" base time_str ext) in unlink_no_fail linkname; symlink filename linkname; filename let setsid = Not implemented on Windows . Let 's just return the pid if Sys.win32 then Unix.getpid else Unix.setsid let set_signal = if not Sys.win32 then Sys.set_signal else (fun _ _ -> ()) let signal = if not Sys.win32 then (fun a b -> ignore (Sys.signal a b)) else (fun _ _ -> ()) external get_total_ram : unit -> int = "hh_sysinfo_totalram" external uptime : unit -> int = "hh_sysinfo_uptime" external nproc: unit -> int = "nproc" let total_ram = get_total_ram () let nbr_procs = nproc () external set_priorities : cpu_priority:int -> io_priority:int -> unit = "hh_set_priorities" external pid_of_handle: int -> int = "pid_of_handle" external handle_of_pid_for_termination: int -> int = "handle_of_pid_for_termination" let terminate_process pid = Unix.kill pid Sys.sigkill let lstat path = WTF , on Windows ` lstat ` fails if a directory path ends with an ' / ' ( or a ' \ ' , whatever ) '/' (or a '\', whatever) *) Unix.lstat @@ if Sys.win32 && String_utils.string_ends_with path Filename.dir_sep then String.sub path 0 (String.length path - 1) else path let normalize_filename_dir_sep = let dir_sep_char = String.get Filename.dir_sep 0 in String.map (fun c -> if c = dir_sep_char then '/' else c) let name_of_signal = function | s when s = Sys.sigabrt -> "SIGABRT (Abnormal termination)" | s when s = Sys.sigalrm -> "SIGALRM (Timeout)" | s when s = Sys.sigfpe -> "SIGFPE (Arithmetic exception)" | s when s = Sys.sighup -> "SIGHUP (Hangup on controlling terminal)" | s when s = Sys.sigill -> "SIGILL (Invalid hardware instruction)" | s when s = Sys.sigint -> "SIGINT (Interactive interrupt (ctrl-C))" | s when s = Sys.sigkill -> "SIGKILL (Termination)" | s when s = Sys.sigpipe -> "SIGPIPE (Broken pipe)" | s when s = Sys.sigquit -> "SIGQUIT (Interactive termination)" | s when s = Sys.sigsegv -> "SIGSEGV (Invalid memory reference)" | s when s = Sys.sigterm -> "SIGTERM (Termination)" | s when s = Sys.sigusr1 -> "SIGUSR1 (Application-defined signal 1)" | s when s = Sys.sigusr2 -> "SIGUSR2 (Application-defined signal 2)" | s when s = Sys.sigchld -> "SIGCHLD (Child process terminated)" | s when s = Sys.sigcont -> "SIGCONT (Continue)" | s when s = Sys.sigstop -> "SIGSTOP (Stop)" | s when s = Sys.sigtstp -> "SIGTSTP (Interactive stop)" | s when s = Sys.sigttin -> "SIGTTIN (Terminal read from background process)" | s when s = Sys.sigttou -> "SIGTTOU (Terminal write from background process)" | s when s = Sys.sigvtalrm -> "SIGVTALRM (Timeout in virtual time)" | s when s = Sys.sigprof -> "SIGPROF (Profiling interrupt)" | s when s = Sys.sigbus -> "SIGBUS (Bus error)" | s when s = Sys.sigpoll -> "SIGPOLL (Pollable event)" | s when s = Sys.sigsys -> "SIGSYS (Bad argument to routine)" | s when s = Sys.sigtrap -> "SIGTRAP (Trace/breakpoint trap)" | s when s = Sys.sigurg -> "SIGURG (Urgent condition on socket)" | s when s = Sys.sigxcpu -> "SIGXCPU (Timeout in cpu time)" | s when s = Sys.sigxfsz -> "SIGXFSZ (File size limit exceeded)" | other -> string_of_int other
null
https://raw.githubusercontent.com/rvantonder/hack_parallel/c9d0714785adc100345835c1989f7c657e01f629/src/utils/sys_utils.ml
ocaml
* Hack_option type intead of exception throwing. This variable does not exist on windows. Same variable on windows * Returns true if substring occurs somewhere inside str. regexp_string matches only this string and nothing else. * Deletes the file given by "path". If it is a directory, recursively * deletes all its contents then removes the directory itself. Path has been deleted out from under us - can ignore it. If this function is generally useful, it can be lifted to toplevel in this file, but this is the only place we need it for now. could be in control section too Emulate "mkdir -p", i.e., no error if already exists. Don't set sticky bit since the socket opening code wants to remove any * old sockets it finds, which may be owned by a different user. -1 because the extension includes the period, e.g. ".foo" Creates a symlink at <dir>/<linkname.ext> to * <dir>/<pluralized ext>/<linkname>-<timestamp>.<ext>
* * Copyright ( c ) 2015 , Facebook , Inc. * All rights reserved . * * This source code is licensed under the BSD - style license found in the * LICENSE file in the " hack " directory of this source tree . An additional grant * of patent rights can be found in the PATENTS file in the same directory . * * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the "hack" directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * *) open Hack_core exception NotADirectory of string external realpath: string -> string option = "hh_realpath" external is_nfs: string -> bool = "hh_is_nfs" let get_env name = try Some (Sys.getenv name) with | Not_found -> None let getenv_user () = let user_var = if Sys.win32 then "USERNAME" else "USER" in let logname_var = "LOGNAME" in let user = get_env user_var in let logname = get_env logname_var in Hack_option.first_some user logname let getenv_home () = let home_var = if Sys.win32 then "APPDATA" else "HOME" in get_env home_var let getenv_term () = get_env term_var let path_sep = if Sys.win32 then ";" else ":" let null_path = if Sys.win32 then "nul" else "/dev/null" let temp_dir_name = if Sys.win32 then Filename.get_temp_dir_name () else "/tmp" let getenv_path () = get_env path_var let open_in_no_fail fn = try open_in fn with e -> let e = Printexc.to_string e in Printf.fprintf stderr "Could not open_in: '%s' (%s)\n" fn e; exit 3 let open_in_bin_no_fail fn = try open_in_bin fn with e -> let e = Printexc.to_string e in Printf.fprintf stderr "Could not open_in_bin: '%s' (%s)\n" fn e; exit 3 let close_in_no_fail fn ic = try close_in ic with e -> let e = Printexc.to_string e in Printf.fprintf stderr "Could not close: '%s' (%s)\n" fn e; exit 3 let open_out_no_fail fn = try open_out fn with e -> let e = Printexc.to_string e in Printf.fprintf stderr "Could not open_out: '%s' (%s)\n" fn e; exit 3 let open_out_bin_no_fail fn = try open_out_bin fn with e -> let e = Printexc.to_string e in Printf.fprintf stderr "Could not open_out_bin: '%s' (%s)\n" fn e; exit 3 let close_out_no_fail fn oc = try close_out oc with e -> let e = Printexc.to_string e in Printf.fprintf stderr "Could not close: '%s' (%s)\n" fn e; exit 3 let cat = Disk.cat let cat_no_fail filename = let ic = open_in_bin_no_fail filename in let len = in_channel_length ic in let buf = Buffer.create len in Buffer.add_channel buf ic len; let content = Buffer.contents buf in close_in_no_fail filename ic; content let nl_regexp = Str.regexp "[\r\n]" let split_lines = Str.split nl_regexp let string_contains str substring = let re = Str.regexp_string substring in try (Str.search_forward re str 0) >= 0 with Not_found -> false let exec_read cmd = let ic = Unix.open_process_in cmd in let result = input_line ic in assert (Unix.close_process_in ic = Unix.WEXITED 0); result let exec_read_lines ?(reverse=false) cmd = let ic = Unix.open_process_in cmd in let result = ref [] in (try while true do result := input_line ic :: !result done; with End_of_file -> ()); assert (Unix.close_process_in ic = Unix.WEXITED 0); if not reverse then List.rev !result else !result let rec rm_dir_tree path = try begin let stats = Unix.lstat path in match stats.Unix.st_kind with | Unix.S_DIR -> let contents = Sys.readdir path in List.iter (Array.to_list contents) ~f:(fun name -> let name = Filename.concat path name in rm_dir_tree name); Unix.rmdir path | Unix.S_LNK | Unix.S_REG | Unix.S_CHR | Unix.S_BLK | Unix.S_FIFO | Unix.S_SOCK -> Unix.unlink path end with | Sys_error(s) when s = Printf.sprintf "%s: No such file or directory" path -> () | Unix.Unix_error(Unix.ENOENT, _, _) -> () let restart () = let cmd = Sys.argv.(0) in let argv = Sys.argv in Unix.execv cmd argv let logname_impl () = match getenv_user () with | Some user -> user | None -> let exec_try_read cmd = let ic = Unix.open_process_in cmd in let out = try Some (input_line ic) with End_of_file -> None in let status = Unix.close_process_in ic in match out, status with | Some _, Unix.WEXITED 0 -> out | _ -> None in try Utils.unsafe_opt (exec_try_read "logname") with Invalid_argument _ -> try Utils.unsafe_opt (exec_try_read "id -un") with Invalid_argument _ -> "[unknown]" let logname_ref = ref None let logname () = if !logname_ref = None then logname_ref := Some (logname_impl ()); Utils.unsafe_opt !logname_ref let with_umask umask f = let old_umask = ref 0 in Utils.with_context ~enter:(fun () -> old_umask := Unix.umask umask) ~exit:(fun () -> ignore (Unix.umask !old_umask)) ~do_:f let with_umask umask f = if Sys.win32 then f () else with_umask umask f let read_stdin_to_string () = let buf = Buffer.create 4096 in try while true do Buffer.add_string buf (input_line stdin); Buffer.add_char buf '\n' done; assert false with End_of_file -> Buffer.contents buf let read_all ?(buf_size=4096) ic = let buf = Buffer.create buf_size in (try while true do let data = Bytes.create buf_size in let bytes_read = input ic data 0 buf_size in if bytes_read = 0 then raise Exit; Buffer.add_subbytes buf data 0 bytes_read; done with Exit -> ()); Buffer.contents buf * * Like 's os.path.expanduser , though probably does n't cover some cases . * Roughly follow 's bash 's tilde expansion : * -Expansion.html * * ~/foo - > /home / bob / foo if $ HOME = " /home / bob " * ~joe / foo - > /home / / foo if 's home is /home / * Like Python's os.path.expanduser, though probably doesn't cover some cases. * Roughly follow's bash's tilde expansion: * -Expansion.html * * ~/foo -> /home/bob/foo if $HOME = "/home/bob" * ~joe/foo -> /home/joe/foo if joe's home is /home/joe *) let expanduser path = Str.substitute_first (Str.regexp "^~\\([^/]*\\)") begin fun s -> match Str.matched_group 1 s with | "" -> begin match getenv_home () with | None -> (Unix.getpwuid (Unix.getuid())).Unix.pw_dir | Some home -> home end | unixname -> try (Unix.getpwnam unixname).Unix.pw_dir with Not_found -> Str.matched_string s end path Turns out it 's surprisingly complex to figure out the path to the current executable , which we need in order to extract its embedded libraries . If argv[0 ] is a path , then we can use that ; sometimes it 's just the exe name , so we have to search $ PATH for it the same way shells do . for example : -Search-and-Execution.html There are other options which might be more reliable when they exist , like using the ` _ ` env var set by bash , or /proc / self / exe on Linux , but they are not portable . executable, which we need in order to extract its embedded libraries. If argv[0] is a path, then we can use that; sometimes it's just the exe name, so we have to search $PATH for it the same way shells do. for example: -Search-and-Execution.html There are other options which might be more reliable when they exist, like using the `_` env var set by bash, or /proc/self/exe on Linux, but they are not portable. *) let executable_path : unit -> string = let executable_path_ = ref None in let dir_sep = Filename.dir_sep.[0] in let search_path path = let paths = match getenv_path () with | None -> failwith "Unable to determine executable path" | Some paths -> Str.split (Str.regexp_string path_sep) paths in let path = List.fold_left paths ~f:begin fun acc p -> match acc with | Some _ -> acc | None -> realpath (expanduser (Filename.concat p path)) end ~init:None in match path with | Some path -> path | None -> failwith "Unable to determine executable path" in fun () -> match !executable_path_ with | Some path -> path | None -> let path = Sys.executable_name in let path = if String.contains path dir_sep then match realpath path with | Some path -> path | None -> failwith "Unable to determine executable path" else search_path path in executable_path_ := Some path; path let lines_of_in_channel ic = let rec loop accum = match try Some(input_line ic) with _e -> None with | None -> List.rev accum | Some(line) -> loop (line::accum) in loop [] let lines_of_file filename = let ic = open_in filename in try let result = lines_of_in_channel ic in let _ = close_in ic in result with _ -> close_in ic; [] let read_file file = let ic = open_in_bin file in let size = in_channel_length ic in let buf = String.create size in really_input ic buf 0 size; close_in ic; buf let write_file ~file s = let chan = open_out file in (output_string chan s; close_out chan) let append_file ~file s = let chan = open_out_gen [Open_wronly; Open_append; Open_creat] 0o666 file in (output_string chan s; close_out chan) let filemtime file = (Unix.stat file).Unix.st_mtime external lutimes : string -> unit = "hh_lutimes" let try_touch ~follow_symlinks file = try if follow_symlinks then Unix.utimes file 0.0 0.0 else lutimes file with _ -> () let rec mkdir_p = function | "" -> failwith "Unexpected empty directory, should never happen" | d when not (Sys.file_exists d) -> mkdir_p (Filename.dirname d); Unix.mkdir d 0o770; | d when Sys.is_directory d -> () | d -> raise (NotADirectory d) let mkdir_no_fail dir = with_umask 0 begin fun () -> try Unix.mkdir dir 0o777 with Unix.Unix_error (Unix.EEXIST, _, _) -> () end let unlink_no_fail fn = try Unix.unlink fn with Unix.Unix_error (Unix.ENOENT, _, _) -> () let readlink_no_fail fn = if Sys.win32 && Sys.file_exists fn then cat fn else try Unix.readlink fn with _ -> fn let splitext filename = let root = Filename.chop_extension filename in let root_length = String.length root in let ext_length = String.length filename - root_length - 1 in let ext = String.sub filename (root_length + 1) ext_length in root, ext let is_test_mode () = try ignore @@ Sys.getenv "HH_TEST_MODE"; true with _ -> false let symlink = Dummy implementation of ` symlink ` on Windows : we create a text file containing the targeted - file 's path . Symlink are available on Windows since Vista , but until Seven ( included ) , one should have administratrive rights in order to create symlink . file containing the targeted-file's path. Symlink are available on Windows since Vista, but until Seven (included), one should have administratrive rights in order to create symlink. *) let win32_symlink source dest = write_file ~file:dest source in if Sys.win32 then win32_symlink else 4.03 adds an optional argument to Unix.symlink that we want to ignore *) fun source dest -> Unix.symlink source dest let make_link_of_timestamped linkname = let open Unix in let dir = Filename.dirname linkname in mkdir_no_fail dir; let base = Filename.basename linkname in let base, ext = splitext base in let dir = Filename.concat dir (Printf.sprintf "%ss" ext) in mkdir_no_fail dir; let tm = localtime (time ()) in let year = tm.tm_year + 1900 in let time_str = Printf.sprintf "%d-%02d-%02d-%02d-%02d-%02d" year (tm.tm_mon + 1) tm.tm_mday tm.tm_hour tm.tm_min tm.tm_sec in let filename = Filename.concat dir (Printf.sprintf "%s-%s.%s" base time_str ext) in unlink_no_fail linkname; symlink filename linkname; filename let setsid = Not implemented on Windows . Let 's just return the pid if Sys.win32 then Unix.getpid else Unix.setsid let set_signal = if not Sys.win32 then Sys.set_signal else (fun _ _ -> ()) let signal = if not Sys.win32 then (fun a b -> ignore (Sys.signal a b)) else (fun _ _ -> ()) external get_total_ram : unit -> int = "hh_sysinfo_totalram" external uptime : unit -> int = "hh_sysinfo_uptime" external nproc: unit -> int = "nproc" let total_ram = get_total_ram () let nbr_procs = nproc () external set_priorities : cpu_priority:int -> io_priority:int -> unit = "hh_set_priorities" external pid_of_handle: int -> int = "pid_of_handle" external handle_of_pid_for_termination: int -> int = "handle_of_pid_for_termination" let terminate_process pid = Unix.kill pid Sys.sigkill let lstat path = WTF , on Windows ` lstat ` fails if a directory path ends with an ' / ' ( or a ' \ ' , whatever ) '/' (or a '\', whatever) *) Unix.lstat @@ if Sys.win32 && String_utils.string_ends_with path Filename.dir_sep then String.sub path 0 (String.length path - 1) else path let normalize_filename_dir_sep = let dir_sep_char = String.get Filename.dir_sep 0 in String.map (fun c -> if c = dir_sep_char then '/' else c) let name_of_signal = function | s when s = Sys.sigabrt -> "SIGABRT (Abnormal termination)" | s when s = Sys.sigalrm -> "SIGALRM (Timeout)" | s when s = Sys.sigfpe -> "SIGFPE (Arithmetic exception)" | s when s = Sys.sighup -> "SIGHUP (Hangup on controlling terminal)" | s when s = Sys.sigill -> "SIGILL (Invalid hardware instruction)" | s when s = Sys.sigint -> "SIGINT (Interactive interrupt (ctrl-C))" | s when s = Sys.sigkill -> "SIGKILL (Termination)" | s when s = Sys.sigpipe -> "SIGPIPE (Broken pipe)" | s when s = Sys.sigquit -> "SIGQUIT (Interactive termination)" | s when s = Sys.sigsegv -> "SIGSEGV (Invalid memory reference)" | s when s = Sys.sigterm -> "SIGTERM (Termination)" | s when s = Sys.sigusr1 -> "SIGUSR1 (Application-defined signal 1)" | s when s = Sys.sigusr2 -> "SIGUSR2 (Application-defined signal 2)" | s when s = Sys.sigchld -> "SIGCHLD (Child process terminated)" | s when s = Sys.sigcont -> "SIGCONT (Continue)" | s when s = Sys.sigstop -> "SIGSTOP (Stop)" | s when s = Sys.sigtstp -> "SIGTSTP (Interactive stop)" | s when s = Sys.sigttin -> "SIGTTIN (Terminal read from background process)" | s when s = Sys.sigttou -> "SIGTTOU (Terminal write from background process)" | s when s = Sys.sigvtalrm -> "SIGVTALRM (Timeout in virtual time)" | s when s = Sys.sigprof -> "SIGPROF (Profiling interrupt)" | s when s = Sys.sigbus -> "SIGBUS (Bus error)" | s when s = Sys.sigpoll -> "SIGPOLL (Pollable event)" | s when s = Sys.sigsys -> "SIGSYS (Bad argument to routine)" | s when s = Sys.sigtrap -> "SIGTRAP (Trace/breakpoint trap)" | s when s = Sys.sigurg -> "SIGURG (Urgent condition on socket)" | s when s = Sys.sigxcpu -> "SIGXCPU (Timeout in cpu time)" | s when s = Sys.sigxfsz -> "SIGXFSZ (File size limit exceeded)" | other -> string_of_int other
5e965b5581ef92b5dfc876484e32ffe996b4ce5a3d5ee084fe2d9082b19ddbf6
monadbobo/ocaml-core
string_zipper.ml
open Core.Std type t = char List_zipper.t open List_zipper let drop_before = drop_before let drop_after = drop_after let drop_all_before = drop_all_before let drop_all_after = drop_all_after let insert_before = insert_before let insert_after = insert_after let previous = previous let next = next let contents zip = let ll = List.length zip.l and lr = List.length zip.r in let res = String.create (ll+lr) in List.iteri zip.l ~f:(fun i c -> res.[ll-1-i] <- c); List.iteri zip.r ~f:(fun i c -> res.[ll+i] <- c); res let left_contents zip = let len = List.length zip.l in let res = String.create len in List.iteri zip.l ~f:(fun i c -> res.[len-1-i] <- c); res let right_contents zip = let len = List.length zip.r in let res = String.create len in List.iteri zip.r ~f:(fun i c -> res.[i] <- c); res let first zip = { l = []; r = List.rev zip.l @ zip.r; } let last zip = { l = List.rev zip.r @ zip.l; r = []; } let create left right = { l = String.to_list_rev left; r = String.to_list right } let replace_left z l = replace_left z (String.to_list_rev l) let replace_right z r = replace_right z (String.to_list r)
null
https://raw.githubusercontent.com/monadbobo/ocaml-core/9c1c06e7a1af7e15b6019a325d7dbdbd4cdb4020/base/core/extended/lib/string_zipper.ml
ocaml
open Core.Std type t = char List_zipper.t open List_zipper let drop_before = drop_before let drop_after = drop_after let drop_all_before = drop_all_before let drop_all_after = drop_all_after let insert_before = insert_before let insert_after = insert_after let previous = previous let next = next let contents zip = let ll = List.length zip.l and lr = List.length zip.r in let res = String.create (ll+lr) in List.iteri zip.l ~f:(fun i c -> res.[ll-1-i] <- c); List.iteri zip.r ~f:(fun i c -> res.[ll+i] <- c); res let left_contents zip = let len = List.length zip.l in let res = String.create len in List.iteri zip.l ~f:(fun i c -> res.[len-1-i] <- c); res let right_contents zip = let len = List.length zip.r in let res = String.create len in List.iteri zip.r ~f:(fun i c -> res.[i] <- c); res let first zip = { l = []; r = List.rev zip.l @ zip.r; } let last zip = { l = List.rev zip.r @ zip.l; r = []; } let create left right = { l = String.to_list_rev left; r = String.to_list right } let replace_left z l = replace_left z (String.to_list_rev l) let replace_right z r = replace_right z (String.to_list r)
1f42b1ac11caa826c21a6f42b557a52a7c663387ee4b2eba38a26bf70dda5566
haskoin/haskoin-core
KeysSpec.hs
{-# LANGUAGE OverloadedStrings #-} module Haskoin.KeysSpec (spec) where import Control.Lens import Control.Monad import Data.Aeson as A import Data.Aeson.Lens import qualified Data.ByteString as BS import qualified Data.ByteString.Char8 as C import Data.Bytes.Get import Data.Bytes.Put import Data.Bytes.Serial import Data.Maybe import qualified Data.Serialize as S import Data.String (fromString) import Data.String.Conversions (cs) import Data.Text (Text) import Haskoin.Address import Haskoin.Constants import Haskoin.Crypto import Haskoin.Keys import Haskoin.Script import Haskoin.Util import Haskoin.Util.Arbitrary import Haskoin.UtilSpec (readTestFile) import Test.HUnit import Test.Hspec import Test.Hspec.QuickCheck import Test.QuickCheck serialVals :: [SerialBox] serialVals = [ SerialBox (snd <$> arbitraryKeyPair) -- PubKeyI ] readVals :: [ReadBox] readVals = [ ReadBox (arbitrary :: Gen SecKey) , ReadBox arbitrarySecKeyI , ReadBox (snd <$> arbitraryKeyPair) -- PubKeyI ] jsonVals :: [JsonBox] jsonVals = [ JsonBox (snd <$> arbitraryKeyPair) -- PubKeyI ] spec :: Spec spec = do testIdentity serialVals readVals jsonVals [] describe "PubKey properties" $ do prop "Public key is canonical" $ forAll arbitraryKeyPair (isCanonicalPubKey . snd) prop "Public key fromString identity" $ forAll arbitraryKeyPair $ \(_, k) -> fromString (cs . encodeHex $ runPutS $ serialize k) == k describe "SecKey properties" $ prop "fromWif . toWif identity" $ forAll arbitraryNetwork $ \net -> forAll arbitraryKeyPair $ \(pk, _) -> fromWif net (toWif net pk) == Just pk describe "Bitcoin core vectors /src/test/key_tests.cpp" $ do it "Passes WIF decoding tests" testPrivkey it "Passes SecKey compression tests" testPrvKeyCompressed it "Passes PubKey compression tests" testKeyCompressed it "Passes address matching tests" testMatchingAddress it "Passes signature verification" testSigs it "Passes deterministic signing tests" testDetSigning describe "MiniKey vectors" $ it "Passes MiniKey decoding tests" testMiniKey describe "key_io_valid.json vectors" $ do vectors <- runIO (readTestFile "key_io_valid.json" :: IO [(Text, Text, A.Value)]) it "Passes the key_io_valid.json vectors" $ mapM_ testKeyIOValidVector vectors describe "key_io_invalid.json vectors" $ do vectors <- runIO (readTestFile "key_io_invalid.json" :: IO [[Text]]) it "Passes the key_io_invalid.json vectors" $ mapM_ testKeyIOInvalidVector vectors -- github.com/bitcoin/bitcoin/blob/master/src/script.cpp -- from function IsCanonicalPubKey isCanonicalPubKey :: PubKeyI -> Bool isCanonicalPubKey p = not $ -- Non-canonical public key: too short (BS.length bs < 33) || -- Non-canonical public key: invalid length for uncompressed key (BS.index bs 0 == 4 && BS.length bs /= 65) || -- Non-canonical public key: invalid length for compressed key (BS.index bs 0 `elem` [2, 3] && BS.length bs /= 33) || -- Non-canonical public key: compressed nor uncompressed (BS.index bs 0 `notElem` [2, 3, 4]) where bs = runPutS $ serialize p testMiniKey :: Assertion testMiniKey = assertEqual "fromMiniKey" (Just res) (go "S6c56bnXQiBjk9mqSYE7ykVQ7NzrRy") where go = fmap (encodeHex . runPutS . S.put . secKeyData) . fromMiniKey res = "4c7a9640c72dc2099f23715d0c8a0d8a35f8906e3cab61dd3f78b67bf887c9ab" -- Test vectors from: -- testKeyIOValidVector :: (Text, Text, A.Value) -> Assertion testKeyIOValidVector (a, payload, obj) There are invalid version 1 bech32 addresses | isPrv = do Test from WIF to SecKey let isComp = obj ^?! key "isCompressed" . _Bool prvKeyM = fromWif net a prvKeyHexM = encodeHex . runPutS . S.put . secKeyData <$> prvKeyM assertBool "Valid PrvKey" $ isJust prvKeyM assertEqual "Valid compression" (Just isComp) (secKeyCompressed <$> prvKeyM) assertEqual "WIF matches payload" (Just payload) prvKeyHexM let prvAsPubM = (eitherToMaybe . decodeOutputBS <=< decodeHex) a assertBool "PrvKey is invalid ScriptOutput" $ isNothing prvAsPubM Test from SecKey to WIF let secM = eitherToMaybe . runGetS S.get =<< decodeHex payload wifM = toWif net . wrapSecKey isComp <$> secM assertEqual "Payload matches WIF" (Just a) wifM | otherwise = do Test Addr to Script let addrM = textToAddr net a scriptM = encodeHex . encodeOutputBS . addressToOutput <$> addrM assertBool ("Valid Address " <> cs a) $ isJust addrM assertEqual "Address matches payload" (Just payload) scriptM let pubAsWifM = fromWif net a pubAsSecM = eitherToMaybe . runGetS S.get =<< decodeHex a :: Maybe SecKey assertBool "Address is invalid Wif" $ isNothing pubAsWifM assertBool "Address is invalid PrvKey" $ isNothing pubAsSecM Test Script to let outM = eitherToMaybe . decodeOutputBS =<< decodeHex payload resM = addrToText net =<< outputAddress =<< outM assertEqual "Payload matches address" (Just a) resM where isPrv = obj ^?! key "isPrivkey" . _Bool disabled = fromMaybe False $ obj ^? key "disabled" . _Bool chain = obj ^?! key "chain" . _String net = case chain of "main" -> btc "test" -> btcTest "regtest" -> btcRegTest _ -> error "Invalid chain key in key_io_valid.json" testKeyIOInvalidVector :: [Text] -> Assertion testKeyIOInvalidVector [a] = do let wifMs = (`fromWif` a) <$> allNets secKeyM = (eitherToMaybe . runGetS S.get <=< decodeHex) a :: Maybe SecKey scriptM = (eitherToMaybe . decodeOutputBS <=< decodeHex) a :: Maybe ScriptOutput assertBool "Payload is invalid WIF" $ all isNothing wifMs assertBool "Payload is invalid SecKey" $ isNothing secKeyM assertBool "Payload is invalid Script" $ isNothing scriptM testKeyIOInvalidVector _ = assertFailure "Invalid test vector" -- Test vectors from: -- testPrivkey :: Assertion testPrivkey = do assertBool "Key 1" $ isJust $ fromWif btc strSecret1 assertBool "Key 2" $ isJust $ fromWif btc strSecret2 assertBool "Key 1C" $ isJust $ fromWif btc strSecret1C assertBool "Key 2C" $ isJust $ fromWif btc strSecret2C assertBool "Bad key" $ isNothing $ fromWif btc strAddressBad testPrvKeyCompressed :: Assertion testPrvKeyCompressed = do assertBool "Key 1" $ not $ secKeyCompressed sec1 assertBool "Key 2" $ not $ secKeyCompressed sec2 assertBool "Key 1C" $ secKeyCompressed sec1C assertBool "Key 2C" $ secKeyCompressed sec2C testKeyCompressed :: Assertion testKeyCompressed = do assertBool "Key 1" $ not $ pubKeyCompressed pub1 assertBool "Key 2" $ not $ pubKeyCompressed pub2 assertBool "Key 1C" $ pubKeyCompressed pub1C assertBool "Key 2C" $ pubKeyCompressed pub2C testMatchingAddress :: Assertion testMatchingAddress = do assertEqual "Key 1" (Just addr1) $ addrToText btc (pubKeyAddr pub1) assertEqual "Key 2" (Just addr2) $ addrToText btc (pubKeyAddr pub2) assertEqual "Key 1C" (Just addr1C) $ addrToText btc (pubKeyAddr pub1C) assertEqual "Key 2C" (Just addr2C) $ addrToText btc (pubKeyAddr pub2C) testSigs :: Assertion testSigs = forM_ sigMsg $ testSignature . doubleSHA256 sigMsg :: [BS.ByteString] sigMsg = [ mconcat ["Very secret message ", C.pack (show (i :: Int)), ": 11"] | i <- [0 .. 15] ] testSignature :: Hash256 -> Assertion testSignature h = do let sign1 = signHash (secKeyData sec1) h sign2 = signHash (secKeyData sec2) h sign1C = signHash (secKeyData sec1C) h sign2C = signHash (secKeyData sec2C) h assertBool "Key 1, Sign1" $ verifyHashSig h sign1 (pubKeyPoint pub1) assertBool "Key 1, Sign2" $ not $ verifyHashSig h sign2 (pubKeyPoint pub1) assertBool "Key 1, Sign1C" $ verifyHashSig h sign1C (pubKeyPoint pub1) assertBool "Key 1, Sign2C" $ not $ verifyHashSig h sign2C (pubKeyPoint pub1) assertBool "Key 2, Sign1" $ not $ verifyHashSig h sign1 (pubKeyPoint pub2) assertBool "Key 2, Sign2" $ verifyHashSig h sign2 (pubKeyPoint pub2) assertBool "Key 2, Sign1C" $ not $ verifyHashSig h sign1C (pubKeyPoint pub2) assertBool "Key 2, Sign2C" $ verifyHashSig h sign2C (pubKeyPoint pub2) assertBool "Key 1C, Sign1" $ verifyHashSig h sign1 (pubKeyPoint pub1C) assertBool "Key 1C, Sign2" $ not $ verifyHashSig h sign2 (pubKeyPoint pub1C) assertBool "Key 1C, Sign1C" $ verifyHashSig h sign1C (pubKeyPoint pub1C) assertBool "Key 1C, Sign2C" $ not $ verifyHashSig h sign2C (pubKeyPoint pub1C) assertBool "Key 2C, Sign1" $ not $ verifyHashSig h sign1 (pubKeyPoint pub2C) assertBool "Key 2C, Sign2" $ verifyHashSig h sign2 (pubKeyPoint pub2C) assertBool "Key 2C, Sign1C" $ not $ verifyHashSig h sign1C (pubKeyPoint pub2C) assertBool "Key 2C, Sign2C" $ verifyHashSig h sign2C (pubKeyPoint pub2C) testDetSigning :: Assertion testDetSigning = do let m = doubleSHA256 ("Very deterministic message" :: BS.ByteString) assertEqual "Det sig 1" (signHash (secKeyData sec1) m) (signHash (secKeyData sec1C) m) assertEqual "Det sig 2" (signHash (secKeyData sec2) m) (signHash (secKeyData sec2C) m) strSecret1, strSecret2, strSecret1C, strSecret2C :: Text strSecret1 = "5HxWvvfubhXpYYpS3tJkw6fq9jE9j18THftkZjHHfmFiWtmAbrj" strSecret2 = "5KC4ejrDjv152FGwP386VD1i2NYc5KkfSMyv1nGy1VGDxGHqVY3" strSecret1C = "Kwr371tjA9u2rFSMZjTNun2PXXP3WPZu2afRHTcta6KxEUdm1vEw" strSecret2C = "L3Hq7a8FEQwJkW1M2GNKDW28546Vp5miewcCzSqUD9kCAXrJdS3g" sec1, sec2, sec1C, sec2C :: SecKeyI sec1 = fromJust $ fromWif btc strSecret1 sec2 = fromJust $ fromWif btc strSecret2 sec1C = fromJust $ fromWif btc strSecret1C sec2C = fromJust $ fromWif btc strSecret2C addr1, addr2, addr1C, addr2C :: Text addr1 = "1QFqqMUD55ZV3PJEJZtaKCsQmjLT6JkjvJ" addr2 = "1F5y5E5FMc5YzdJtB9hLaUe43GDxEKXENJ" addr1C = "1NoJrossxPBKfCHuJXT4HadJrXRE9Fxiqs" addr2C = "1CRj2HyM1CXWzHAXLQtiGLyggNT9WQqsDs" strAddressBad :: Text strAddressBad = "1HV9Lc3sNHZxwj4Zk6fB38tEmBryq2cBiF" pub1, pub2, pub1C, pub2C :: PubKeyI pub1 = derivePubKeyI sec1 pub2 = derivePubKeyI sec2 pub1C = derivePubKeyI sec1C pub2C = derivePubKeyI sec2C
null
https://raw.githubusercontent.com/haskoin/haskoin-core/d49455a27735dbe636453e870cf4e8720fb3a80a/test/Haskoin/KeysSpec.hs
haskell
# LANGUAGE OverloadedStrings # PubKeyI PubKeyI PubKeyI github.com/bitcoin/bitcoin/blob/master/src/script.cpp from function IsCanonicalPubKey Non-canonical public key: too short Non-canonical public key: invalid length for uncompressed key Non-canonical public key: invalid length for compressed key Non-canonical public key: compressed nor uncompressed Test vectors from: Test vectors from:
module Haskoin.KeysSpec (spec) where import Control.Lens import Control.Monad import Data.Aeson as A import Data.Aeson.Lens import qualified Data.ByteString as BS import qualified Data.ByteString.Char8 as C import Data.Bytes.Get import Data.Bytes.Put import Data.Bytes.Serial import Data.Maybe import qualified Data.Serialize as S import Data.String (fromString) import Data.String.Conversions (cs) import Data.Text (Text) import Haskoin.Address import Haskoin.Constants import Haskoin.Crypto import Haskoin.Keys import Haskoin.Script import Haskoin.Util import Haskoin.Util.Arbitrary import Haskoin.UtilSpec (readTestFile) import Test.HUnit import Test.Hspec import Test.Hspec.QuickCheck import Test.QuickCheck serialVals :: [SerialBox] serialVals = ] readVals :: [ReadBox] readVals = [ ReadBox (arbitrary :: Gen SecKey) , ReadBox arbitrarySecKeyI ] jsonVals :: [JsonBox] jsonVals = ] spec :: Spec spec = do testIdentity serialVals readVals jsonVals [] describe "PubKey properties" $ do prop "Public key is canonical" $ forAll arbitraryKeyPair (isCanonicalPubKey . snd) prop "Public key fromString identity" $ forAll arbitraryKeyPair $ \(_, k) -> fromString (cs . encodeHex $ runPutS $ serialize k) == k describe "SecKey properties" $ prop "fromWif . toWif identity" $ forAll arbitraryNetwork $ \net -> forAll arbitraryKeyPair $ \(pk, _) -> fromWif net (toWif net pk) == Just pk describe "Bitcoin core vectors /src/test/key_tests.cpp" $ do it "Passes WIF decoding tests" testPrivkey it "Passes SecKey compression tests" testPrvKeyCompressed it "Passes PubKey compression tests" testKeyCompressed it "Passes address matching tests" testMatchingAddress it "Passes signature verification" testSigs it "Passes deterministic signing tests" testDetSigning describe "MiniKey vectors" $ it "Passes MiniKey decoding tests" testMiniKey describe "key_io_valid.json vectors" $ do vectors <- runIO (readTestFile "key_io_valid.json" :: IO [(Text, Text, A.Value)]) it "Passes the key_io_valid.json vectors" $ mapM_ testKeyIOValidVector vectors describe "key_io_invalid.json vectors" $ do vectors <- runIO (readTestFile "key_io_invalid.json" :: IO [[Text]]) it "Passes the key_io_invalid.json vectors" $ mapM_ testKeyIOInvalidVector vectors isCanonicalPubKey :: PubKeyI -> Bool isCanonicalPubKey p = not $ (BS.length bs < 33) || (BS.index bs 0 == 4 && BS.length bs /= 65) || (BS.index bs 0 `elem` [2, 3] && BS.length bs /= 33) || (BS.index bs 0 `notElem` [2, 3, 4]) where bs = runPutS $ serialize p testMiniKey :: Assertion testMiniKey = assertEqual "fromMiniKey" (Just res) (go "S6c56bnXQiBjk9mqSYE7ykVQ7NzrRy") where go = fmap (encodeHex . runPutS . S.put . secKeyData) . fromMiniKey res = "4c7a9640c72dc2099f23715d0c8a0d8a35f8906e3cab61dd3f78b67bf887c9ab" testKeyIOValidVector :: (Text, Text, A.Value) -> Assertion testKeyIOValidVector (a, payload, obj) There are invalid version 1 bech32 addresses | isPrv = do Test from WIF to SecKey let isComp = obj ^?! key "isCompressed" . _Bool prvKeyM = fromWif net a prvKeyHexM = encodeHex . runPutS . S.put . secKeyData <$> prvKeyM assertBool "Valid PrvKey" $ isJust prvKeyM assertEqual "Valid compression" (Just isComp) (secKeyCompressed <$> prvKeyM) assertEqual "WIF matches payload" (Just payload) prvKeyHexM let prvAsPubM = (eitherToMaybe . decodeOutputBS <=< decodeHex) a assertBool "PrvKey is invalid ScriptOutput" $ isNothing prvAsPubM Test from SecKey to WIF let secM = eitherToMaybe . runGetS S.get =<< decodeHex payload wifM = toWif net . wrapSecKey isComp <$> secM assertEqual "Payload matches WIF" (Just a) wifM | otherwise = do Test Addr to Script let addrM = textToAddr net a scriptM = encodeHex . encodeOutputBS . addressToOutput <$> addrM assertBool ("Valid Address " <> cs a) $ isJust addrM assertEqual "Address matches payload" (Just payload) scriptM let pubAsWifM = fromWif net a pubAsSecM = eitherToMaybe . runGetS S.get =<< decodeHex a :: Maybe SecKey assertBool "Address is invalid Wif" $ isNothing pubAsWifM assertBool "Address is invalid PrvKey" $ isNothing pubAsSecM Test Script to let outM = eitherToMaybe . decodeOutputBS =<< decodeHex payload resM = addrToText net =<< outputAddress =<< outM assertEqual "Payload matches address" (Just a) resM where isPrv = obj ^?! key "isPrivkey" . _Bool disabled = fromMaybe False $ obj ^? key "disabled" . _Bool chain = obj ^?! key "chain" . _String net = case chain of "main" -> btc "test" -> btcTest "regtest" -> btcRegTest _ -> error "Invalid chain key in key_io_valid.json" testKeyIOInvalidVector :: [Text] -> Assertion testKeyIOInvalidVector [a] = do let wifMs = (`fromWif` a) <$> allNets secKeyM = (eitherToMaybe . runGetS S.get <=< decodeHex) a :: Maybe SecKey scriptM = (eitherToMaybe . decodeOutputBS <=< decodeHex) a :: Maybe ScriptOutput assertBool "Payload is invalid WIF" $ all isNothing wifMs assertBool "Payload is invalid SecKey" $ isNothing secKeyM assertBool "Payload is invalid Script" $ isNothing scriptM testKeyIOInvalidVector _ = assertFailure "Invalid test vector" testPrivkey :: Assertion testPrivkey = do assertBool "Key 1" $ isJust $ fromWif btc strSecret1 assertBool "Key 2" $ isJust $ fromWif btc strSecret2 assertBool "Key 1C" $ isJust $ fromWif btc strSecret1C assertBool "Key 2C" $ isJust $ fromWif btc strSecret2C assertBool "Bad key" $ isNothing $ fromWif btc strAddressBad testPrvKeyCompressed :: Assertion testPrvKeyCompressed = do assertBool "Key 1" $ not $ secKeyCompressed sec1 assertBool "Key 2" $ not $ secKeyCompressed sec2 assertBool "Key 1C" $ secKeyCompressed sec1C assertBool "Key 2C" $ secKeyCompressed sec2C testKeyCompressed :: Assertion testKeyCompressed = do assertBool "Key 1" $ not $ pubKeyCompressed pub1 assertBool "Key 2" $ not $ pubKeyCompressed pub2 assertBool "Key 1C" $ pubKeyCompressed pub1C assertBool "Key 2C" $ pubKeyCompressed pub2C testMatchingAddress :: Assertion testMatchingAddress = do assertEqual "Key 1" (Just addr1) $ addrToText btc (pubKeyAddr pub1) assertEqual "Key 2" (Just addr2) $ addrToText btc (pubKeyAddr pub2) assertEqual "Key 1C" (Just addr1C) $ addrToText btc (pubKeyAddr pub1C) assertEqual "Key 2C" (Just addr2C) $ addrToText btc (pubKeyAddr pub2C) testSigs :: Assertion testSigs = forM_ sigMsg $ testSignature . doubleSHA256 sigMsg :: [BS.ByteString] sigMsg = [ mconcat ["Very secret message ", C.pack (show (i :: Int)), ": 11"] | i <- [0 .. 15] ] testSignature :: Hash256 -> Assertion testSignature h = do let sign1 = signHash (secKeyData sec1) h sign2 = signHash (secKeyData sec2) h sign1C = signHash (secKeyData sec1C) h sign2C = signHash (secKeyData sec2C) h assertBool "Key 1, Sign1" $ verifyHashSig h sign1 (pubKeyPoint pub1) assertBool "Key 1, Sign2" $ not $ verifyHashSig h sign2 (pubKeyPoint pub1) assertBool "Key 1, Sign1C" $ verifyHashSig h sign1C (pubKeyPoint pub1) assertBool "Key 1, Sign2C" $ not $ verifyHashSig h sign2C (pubKeyPoint pub1) assertBool "Key 2, Sign1" $ not $ verifyHashSig h sign1 (pubKeyPoint pub2) assertBool "Key 2, Sign2" $ verifyHashSig h sign2 (pubKeyPoint pub2) assertBool "Key 2, Sign1C" $ not $ verifyHashSig h sign1C (pubKeyPoint pub2) assertBool "Key 2, Sign2C" $ verifyHashSig h sign2C (pubKeyPoint pub2) assertBool "Key 1C, Sign1" $ verifyHashSig h sign1 (pubKeyPoint pub1C) assertBool "Key 1C, Sign2" $ not $ verifyHashSig h sign2 (pubKeyPoint pub1C) assertBool "Key 1C, Sign1C" $ verifyHashSig h sign1C (pubKeyPoint pub1C) assertBool "Key 1C, Sign2C" $ not $ verifyHashSig h sign2C (pubKeyPoint pub1C) assertBool "Key 2C, Sign1" $ not $ verifyHashSig h sign1 (pubKeyPoint pub2C) assertBool "Key 2C, Sign2" $ verifyHashSig h sign2 (pubKeyPoint pub2C) assertBool "Key 2C, Sign1C" $ not $ verifyHashSig h sign1C (pubKeyPoint pub2C) assertBool "Key 2C, Sign2C" $ verifyHashSig h sign2C (pubKeyPoint pub2C) testDetSigning :: Assertion testDetSigning = do let m = doubleSHA256 ("Very deterministic message" :: BS.ByteString) assertEqual "Det sig 1" (signHash (secKeyData sec1) m) (signHash (secKeyData sec1C) m) assertEqual "Det sig 2" (signHash (secKeyData sec2) m) (signHash (secKeyData sec2C) m) strSecret1, strSecret2, strSecret1C, strSecret2C :: Text strSecret1 = "5HxWvvfubhXpYYpS3tJkw6fq9jE9j18THftkZjHHfmFiWtmAbrj" strSecret2 = "5KC4ejrDjv152FGwP386VD1i2NYc5KkfSMyv1nGy1VGDxGHqVY3" strSecret1C = "Kwr371tjA9u2rFSMZjTNun2PXXP3WPZu2afRHTcta6KxEUdm1vEw" strSecret2C = "L3Hq7a8FEQwJkW1M2GNKDW28546Vp5miewcCzSqUD9kCAXrJdS3g" sec1, sec2, sec1C, sec2C :: SecKeyI sec1 = fromJust $ fromWif btc strSecret1 sec2 = fromJust $ fromWif btc strSecret2 sec1C = fromJust $ fromWif btc strSecret1C sec2C = fromJust $ fromWif btc strSecret2C addr1, addr2, addr1C, addr2C :: Text addr1 = "1QFqqMUD55ZV3PJEJZtaKCsQmjLT6JkjvJ" addr2 = "1F5y5E5FMc5YzdJtB9hLaUe43GDxEKXENJ" addr1C = "1NoJrossxPBKfCHuJXT4HadJrXRE9Fxiqs" addr2C = "1CRj2HyM1CXWzHAXLQtiGLyggNT9WQqsDs" strAddressBad :: Text strAddressBad = "1HV9Lc3sNHZxwj4Zk6fB38tEmBryq2cBiF" pub1, pub2, pub1C, pub2C :: PubKeyI pub1 = derivePubKeyI sec1 pub2 = derivePubKeyI sec2 pub1C = derivePubKeyI sec1C pub2C = derivePubKeyI sec2C
eb97efee7a01e47e8738ee2266097c485a21203c86c70379949bef9ccc4c5d59
con-kitty/categorifier-c
Prim.hs
-- | Primitive types for all C code generation systems. -- -- === Performance note -- -- A bunch of type class instances were recently converted to derived instances (from handwritten ones ) using the new @-XDerivingVia@ feature in GHC 8.6 . This has the unfortunate side effect of -- removing @INLINEABLE@ pragmas that previously qualified many of the methods. If needed, these -- can be re-exposed for other modules to inline by passing the @-fexpose-all-unfoldings@ and @-fspecialize - aggressively@ flags to GHC . module Categorifier.C.Prim ( module Base, module Helpers, module Patterns, module ArrayName, module ArrayCount, module ArrayVec, module ArrayLens, module ConstArrays, ) where import Categorifier.C.Prim.ArrayCount as ArrayCount import Categorifier.C.Prim.ArrayLens as ArrayLens import Categorifier.C.Prim.ArrayName as ArrayName import Categorifier.C.Prim.ArrayVec as ArrayVec import Categorifier.C.Prim.Base as Base import Categorifier.C.Prim.ConstArrays as ConstArrays import Categorifier.C.Prim.Helpers as Helpers import Categorifier.C.Prim.Patterns as Patterns
null
https://raw.githubusercontent.com/con-kitty/categorifier-c/a34ff2603529b4da7ad6ffe681dad095f102d1b9/Categorifier/C/Prim.hs
haskell
| Primitive types for all C code generation systems. === Performance note A bunch of type class instances were recently converted to derived instances (from handwritten removing @INLINEABLE@ pragmas that previously qualified many of the methods. If needed, these can be re-exposed for other modules to inline by passing the @-fexpose-all-unfoldings@ and
ones ) using the new @-XDerivingVia@ feature in GHC 8.6 . This has the unfortunate side effect of @-fspecialize - aggressively@ flags to GHC . module Categorifier.C.Prim ( module Base, module Helpers, module Patterns, module ArrayName, module ArrayCount, module ArrayVec, module ArrayLens, module ConstArrays, ) where import Categorifier.C.Prim.ArrayCount as ArrayCount import Categorifier.C.Prim.ArrayLens as ArrayLens import Categorifier.C.Prim.ArrayName as ArrayName import Categorifier.C.Prim.ArrayVec as ArrayVec import Categorifier.C.Prim.Base as Base import Categorifier.C.Prim.ConstArrays as ConstArrays import Categorifier.C.Prim.Helpers as Helpers import Categorifier.C.Prim.Patterns as Patterns
fc8f6e60828a24bf9aebba19a05a9eac831408d67438b18603d59748f233650b
yutopp/rill
scheme.ml
* Copyright yutopp 2019 - . * * Distributed under the Boost Software License , Version 1.0 . * ( See accompanying file LICENSE_1_0.txt or copy at * ) * Copyright yutopp 2019 - . * * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE_1_0.txt or copy at * ) *) open! Base type t = | ForAll of { implicits : Type.t list; vars : Type.t list; ty : Pred.t } [@@deriving show, yojson_of] let of_ty ty = ForAll { implicits = []; vars = []; ty } let of_trait ~implicits ty = ForAll { implicits; vars = []; ty } let raw_ty sc = let (ForAll { ty; _ }) = sc in let (Pred.Pred { ty; _ }) = ty in ty and assume_has_no_generics ty_sc = match ty_sc with | ForAll { implicits = []; vars = []; ty } -> ty | _ -> failwith "NOTE: generics is not allowed here" let eliminate_type_of ty_sc = let (ForAll { ty = pred; implicits; vars }) = ty_sc in let (Pred.Pred { ty; conds }) = pred in let ty = Type.of_type_ty ty in let pred = Pred.Pred { ty; conds } in ForAll { ty = pred; implicits; vars } let rec to_string ty_sc : string = match ty_sc with | ForAll { implicits = []; vars = []; ty } -> Pred.to_string ty | ForAll { implicits; vars; ty } -> let implicits_s = implicits |> List.map ~f:Type.assume_var_id |> List.map ~f:Common.Type_var.to_string |> String.concat ~sep:"," in let vars_s = vars |> List.map ~f:Type.assume_var_id |> List.map ~f:Common.Type_var.to_string |> String.concat ~sep:"," in Printf.sprintf "forall <[%s], i[%s]>.%s" vars_s implicits_s (Pred.to_string ty)
null
https://raw.githubusercontent.com/yutopp/rill/375b67c03ab2087d0a2a833bd9e80f3e51e2694f/rillc/lib/typing/scheme.ml
ocaml
* Copyright yutopp 2019 - . * * Distributed under the Boost Software License , Version 1.0 . * ( See accompanying file LICENSE_1_0.txt or copy at * ) * Copyright yutopp 2019 - . * * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE_1_0.txt or copy at * ) *) open! Base type t = | ForAll of { implicits : Type.t list; vars : Type.t list; ty : Pred.t } [@@deriving show, yojson_of] let of_ty ty = ForAll { implicits = []; vars = []; ty } let of_trait ~implicits ty = ForAll { implicits; vars = []; ty } let raw_ty sc = let (ForAll { ty; _ }) = sc in let (Pred.Pred { ty; _ }) = ty in ty and assume_has_no_generics ty_sc = match ty_sc with | ForAll { implicits = []; vars = []; ty } -> ty | _ -> failwith "NOTE: generics is not allowed here" let eliminate_type_of ty_sc = let (ForAll { ty = pred; implicits; vars }) = ty_sc in let (Pred.Pred { ty; conds }) = pred in let ty = Type.of_type_ty ty in let pred = Pred.Pred { ty; conds } in ForAll { ty = pred; implicits; vars } let rec to_string ty_sc : string = match ty_sc with | ForAll { implicits = []; vars = []; ty } -> Pred.to_string ty | ForAll { implicits; vars; ty } -> let implicits_s = implicits |> List.map ~f:Type.assume_var_id |> List.map ~f:Common.Type_var.to_string |> String.concat ~sep:"," in let vars_s = vars |> List.map ~f:Type.assume_var_id |> List.map ~f:Common.Type_var.to_string |> String.concat ~sep:"," in Printf.sprintf "forall <[%s], i[%s]>.%s" vars_s implicits_s (Pred.to_string ty)
1445de932611e60bb744dce818779f92c152cce1ab87ab6c9f71d91beea5ece6
webyrd/n-grams-for-synthesis
testing.scm
Copyright ( c ) 2005 , 2006 , 2007 , 2012 , 2013 Per Bothner Added " full " support for Chicken , Gauche , and SISC . , Copyright ( c ) 2005 . Modified for Scheme Spheres by , Copyright ( c ) 2012 . Support for Guile 2 by < > , Copyright ( c ) 2014 . ;; ;; Permission is hereby granted, free of charge, to any person ;; obtaining a copy of this software and associated documentation files ( the " Software " ) , to deal in the Software without ;; restriction, including without limitation the rights to use, copy, ;; modify, merge, publish, distribute, sublicense, and/or sell copies of the Software , and to permit persons to whom the Software is ;; furnished to do so, subject to the following conditions: ;; ;; The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software . ;; THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , ;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF ;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND ;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM , DAMAGES OR OTHER LIABILITY , WHETHER IN AN ;; ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN ;; CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE ;; SOFTWARE. (cond-expand (chicken (require-extension syntax-case)) (guile-2 (use-modules (srfi srfi-9) In 2.0.9 , srfi-34 and srfi-35 are not well integrated with either 's native exceptions or R6RS exceptions . ( srfi srfi-34 ) ( srfi srfi-35 ) (srfi srfi-39))) (guile (use-modules (ice-9 syncase) (srfi srfi-9) ( srfi srfi-34 ) ( srfi srfi-35 ) - not in 1.6.7 (srfi srfi-39))) (sisc (require-extension (srfi 9 34 35 39))) (kawa (module-compile-options warn-undefined-variable: #t warn-invoke-unknown-method: #t) (provide 'srfi-64) (provide 'testing) (require 'srfi-34) (require 'srfi-35)) (else )) (cond-expand (kawa (define-syntax %test-export (syntax-rules () ((%test-export test-begin . other-names) (module-export %test-begin . other-names))))) (else (define-syntax %test-export (syntax-rules () ((%test-export . names) (if #f #f)))))) ;; List of exported names (%test-export must be listed first , since in ( at least ) it is " magic " . test-end test-assert test-eqv test-eq test-equal test-approximate test-assert test-error test-apply test-with-runner test-match-nth test-match-all test-match-any test-match-name test-skip test-expect-fail test-read-eval-string test-runner-group-path test-group test-group-with-cleanup test-result-ref test-result-set! test-result-clear test-result-remove test-result-kind test-passed? test-log-to-file ; Misc test-runner functions test-runner? test-runner-reset test-runner-null test-runner-simple test-runner-current test-runner-factory test-runner-get test-runner-create test-runner-test-name ;; test-runner field setter and getter functions - see %test-record-define: test-runner-pass-count test-runner-pass-count! test-runner-fail-count test-runner-fail-count! test-runner-xpass-count test-runner-xpass-count! test-runner-xfail-count test-runner-xfail-count! test-runner-skip-count test-runner-skip-count! test-runner-group-stack test-runner-group-stack! test-runner-on-test-begin test-runner-on-test-begin! test-runner-on-test-end test-runner-on-test-end! test-runner-on-group-begin test-runner-on-group-begin! test-runner-on-group-end test-runner-on-group-end! test-runner-on-final test-runner-on-final! test-runner-on-bad-count test-runner-on-bad-count! test-runner-on-bad-end-name test-runner-on-bad-end-name! test-result-alist test-result-alist! test-runner-aux-value test-runner-aux-value! ;; default/simple call-back functions, used in default test-runner, ;; but can be called to construct more complex ones. test-on-group-begin-simple test-on-group-end-simple test-on-bad-count-simple test-on-bad-end-name-simple test-on-final-simple test-on-test-end-simple test-on-final-simple) (cond-expand (srfi-9 (define-syntax %test-record-define (syntax-rules () ((%test-record-define alloc runner? (name index setter getter) ...) (define-record-type test-runner (alloc) runner? (name setter getter) ...))))) (else (define %test-runner-cookie (list "test-runner")) (define-syntax %test-record-define (syntax-rules () ((%test-record-define alloc runner? (name index getter setter) ...) (begin (define (runner? obj) (and (vector? obj) (> (vector-length obj) 1) (eq? (vector-ref obj 0) %test-runner-cookie))) (define (alloc) (let ((runner (make-vector 23))) (vector-set! runner 0 %test-runner-cookie) runner)) (begin (define (getter runner) (vector-ref runner index)) ...) (begin (define (setter runner value) (vector-set! runner index value)) ...))))))) (%test-record-define %test-runner-alloc test-runner? Cumulate count of all tests that have passed and were expected to . (pass-count 1 test-runner-pass-count test-runner-pass-count!) (fail-count 2 test-runner-fail-count test-runner-fail-count!) (xpass-count 3 test-runner-xpass-count test-runner-xpass-count!) (xfail-count 4 test-runner-xfail-count test-runner-xfail-count!) (skip-count 5 test-runner-skip-count test-runner-skip-count!) (skip-list 6 %test-runner-skip-list %test-runner-skip-list!) (fail-list 7 %test-runner-fail-list %test-runner-fail-list!) ;; Normally #t, except when in a test-apply. (run-list 8 %test-runner-run-list %test-runner-run-list!) (skip-save 9 %test-runner-skip-save %test-runner-skip-save!) (fail-save 10 %test-runner-fail-save %test-runner-fail-save!) (group-stack 11 test-runner-group-stack test-runner-group-stack!) (on-test-begin 12 test-runner-on-test-begin test-runner-on-test-begin!) (on-test-end 13 test-runner-on-test-end test-runner-on-test-end!) ;; Call-back when entering a group. Takes (runner suite-name count). (on-group-begin 14 test-runner-on-group-begin test-runner-on-group-begin!) ;; Call-back when leaving a group. (on-group-end 15 test-runner-on-group-end test-runner-on-group-end!) ;; Call-back when leaving the outermost group. (on-final 16 test-runner-on-final test-runner-on-final!) ;; Call-back when expected number of tests was wrong. (on-bad-count 17 test-runner-on-bad-count test-runner-on-bad-count!) ;; Call-back when name in test=end doesn't match test-begin. (on-bad-end-name 18 test-runner-on-bad-end-name test-runner-on-bad-end-name!) Cumulate count of all tests that have been done . (total-count 19 %test-runner-total-count %test-runner-total-count!) Stack ( list ) of ( count - at - start . expected - count ): (count-list 20 %test-runner-count-list %test-runner-count-list!) (result-alist 21 test-result-alist test-result-alist!) Field can be used by test - runner for any purpose . ;; test-runner-simple uses it for a log file. (aux-value 22 test-runner-aux-value test-runner-aux-value!) ) (define (test-runner-reset runner) (test-result-alist! runner '()) (test-runner-pass-count! runner 0) (test-runner-fail-count! runner 0) (test-runner-xpass-count! runner 0) (test-runner-xfail-count! runner 0) (test-runner-skip-count! runner 0) (%test-runner-total-count! runner 0) (%test-runner-count-list! runner '()) (%test-runner-run-list! runner #t) (%test-runner-skip-list! runner '()) (%test-runner-fail-list! runner '()) (%test-runner-skip-save! runner '()) (%test-runner-fail-save! runner '()) (test-runner-group-stack! runner '())) (define (test-runner-group-path runner) (reverse (test-runner-group-stack runner))) (define (%test-null-callback runner) #f) (define (test-runner-null) (let ((runner (%test-runner-alloc))) (test-runner-reset runner) (test-runner-on-group-begin! runner (lambda (runner name count) #f)) (test-runner-on-group-end! runner %test-null-callback) (test-runner-on-final! runner %test-null-callback) (test-runner-on-test-begin! runner %test-null-callback) (test-runner-on-test-end! runner %test-null-callback) (test-runner-on-bad-count! runner (lambda (runner count expected) #f)) (test-runner-on-bad-end-name! runner (lambda (runner begin end) #f)) runner)) Not part of the specification . FIXME ;; Controls whether a log file is generated. (define test-log-to-file #t) (define (test-runner-simple) (let ((runner (%test-runner-alloc))) (test-runner-reset runner) (test-runner-on-group-begin! runner test-on-group-begin-simple) (test-runner-on-group-end! runner test-on-group-end-simple) (test-runner-on-final! runner test-on-final-simple) (test-runner-on-test-begin! runner test-on-test-begin-simple) (test-runner-on-test-end! runner test-on-test-end-simple) (test-runner-on-bad-count! runner test-on-bad-count-simple) (test-runner-on-bad-end-name! runner test-on-bad-end-name-simple) runner)) (cond-expand (srfi-39 (define test-runner-current (make-parameter #f)) (define test-runner-factory (make-parameter test-runner-simple))) (else (define %test-runner-current #f) (define-syntax test-runner-current (syntax-rules () ((test-runner-current) %test-runner-current) ((test-runner-current runner) (set! %test-runner-current runner)))) (define %test-runner-factory test-runner-simple) (define-syntax test-runner-factory (syntax-rules () ((test-runner-factory) %test-runner-factory) ((test-runner-factory runner) (set! %test-runner-factory runner)))))) ;; A safer wrapper to test-runner-current. (define (test-runner-get) (let ((r (test-runner-current))) (if (not r) (cond-expand (srfi-23 (error "test-runner not initialized - test-begin missing?")) (else #t))) r)) (define (%test-specifier-matches spec runner) (spec runner)) (define (test-runner-create) ((test-runner-factory))) (define (%test-any-specifier-matches list runner) (let ((result #f)) (let loop ((l list)) (cond ((null? l) result) (else (if (%test-specifier-matches (car l) runner) (set! result #t)) (loop (cdr l))))))) ;; Returns #f, #t, or 'xfail. (define (%test-should-execute runner) (let ((run (%test-runner-run-list runner))) (cond ((or (not (or (eqv? run #t) (%test-any-specifier-matches run runner))) (%test-any-specifier-matches (%test-runner-skip-list runner) runner)) (test-result-set! runner 'result-kind 'skip) #f) ((%test-any-specifier-matches (%test-runner-fail-list runner) runner) (test-result-set! runner 'result-kind 'xfail) 'xfail) (else #t)))) (define (%test-begin suite-name count) (if (not (test-runner-current)) (test-runner-current (test-runner-create))) (let ((runner (test-runner-current))) ((test-runner-on-group-begin runner) runner suite-name count) (%test-runner-skip-save! runner (cons (%test-runner-skip-list runner) (%test-runner-skip-save runner))) (%test-runner-fail-save! runner (cons (%test-runner-fail-list runner) (%test-runner-fail-save runner))) (%test-runner-count-list! runner (cons (cons (%test-runner-total-count runner) count) (%test-runner-count-list runner))) (test-runner-group-stack! runner (cons suite-name (test-runner-group-stack runner))))) (cond-expand (kawa Kawa has test - begin built in , implemented as : ;; (begin ( cond - expand ( srfi-64 # ! void ) ( else ( require ' srfi-64 ) ) ) ;; (%test-begin suite-name [count])) ;; This puts test-begin but only test-begin in the default environment., ;; which makes normal test suites loadable without non-portable commands. ) (else (define-syntax test-begin (syntax-rules () ((test-begin suite-name) (%test-begin suite-name #f)) ((test-begin suite-name count) (%test-begin suite-name count)))))) (define (test-on-group-begin-simple runner suite-name count) (if (null? (test-runner-group-stack runner)) (begin (display "%%%% Starting test ") (display suite-name) (if test-log-to-file (let* ((log-file-name (if (string? test-log-to-file) test-log-to-file (string-append suite-name ".log"))) (log-file (cond-expand (mzscheme (open-output-file log-file-name 'truncate/replace)) (else (open-output-file log-file-name))))) (display "%%%% Starting test " log-file) (display suite-name log-file) (newline log-file) (test-runner-aux-value! runner log-file) (display " (Writing full log to \"") (display log-file-name) (display "\")"))) (newline))) (let ((log (test-runner-aux-value runner))) (if (output-port? log) (begin (display "Group begin: " log) (display suite-name log) (newline log)))) #f) (define (test-on-group-end-simple runner) (let ((log (test-runner-aux-value runner))) (if (output-port? log) (begin (display "Group end: " log) (display (car (test-runner-group-stack runner)) log) (newline log)))) #f) (define (%test-on-bad-count-write runner count expected-count port) (display "*** Total number of tests was " port) (display count port) (display " but should be " port) (display expected-count port) (display ". ***" port) (newline port) (display "*** Discrepancy indicates testsuite error or exceptions. ***" port) (newline port)) (define (test-on-bad-count-simple runner count expected-count) (%test-on-bad-count-write runner count expected-count (current-output-port)) (let ((log (test-runner-aux-value runner))) (if (output-port? log) (%test-on-bad-count-write runner count expected-count log)))) (define (test-on-bad-end-name-simple runner begin-name end-name) (let ((msg (string-append (%test-format-line runner) "test-end " begin-name " does not match test-begin " end-name))) (cond-expand (srfi-23 (error msg)) (else (display msg) (newline))))) (define (%test-final-report1 value label port) (if (> value 0) (begin (display label port) (display value port) (newline port)))) (define (%test-final-report-simple runner port) (%test-final-report1 (test-runner-pass-count runner) "# of expected passes " port) (%test-final-report1 (test-runner-xfail-count runner) "# of expected failures " port) (%test-final-report1 (test-runner-xpass-count runner) "# of unexpected successes " port) (%test-final-report1 (test-runner-fail-count runner) "# of unexpected failures " port) (%test-final-report1 (test-runner-skip-count runner) "# of skipped tests " port)) (define (test-on-final-simple runner) (%test-final-report-simple runner (current-output-port)) (let ((log (test-runner-aux-value runner))) (if (output-port? log) (%test-final-report-simple runner log)))) (define (%test-format-line runner) (let* ((line-info (test-result-alist runner)) (source-file (assq 'source-file line-info)) (source-line (assq 'source-line line-info)) (file (if source-file (cdr source-file) ""))) (if source-line (string-append file ":" (number->string (cdr source-line)) ": ") ""))) (define (%test-end suite-name line-info) (let* ((r (test-runner-get)) (groups (test-runner-group-stack r)) (line (%test-format-line r))) (test-result-alist! r line-info) (if (null? groups) (let ((msg (string-append line "test-end not in a group"))) (cond-expand (srfi-23 (error msg)) (else (display msg) (newline))))) (if (and suite-name (not (equal? suite-name (car groups)))) ((test-runner-on-bad-end-name r) r suite-name (car groups))) (let* ((count-list (%test-runner-count-list r)) (expected-count (cdar count-list)) (saved-count (caar count-list)) (group-count (- (%test-runner-total-count r) saved-count))) (if (and expected-count (not (= expected-count group-count))) ((test-runner-on-bad-count r) r group-count expected-count)) ((test-runner-on-group-end r) r) (test-runner-group-stack! r (cdr (test-runner-group-stack r))) (%test-runner-skip-list! r (car (%test-runner-skip-save r))) (%test-runner-skip-save! r (cdr (%test-runner-skip-save r))) (%test-runner-fail-list! r (car (%test-runner-fail-save r))) (%test-runner-fail-save! r (cdr (%test-runner-fail-save r))) (%test-runner-count-list! r (cdr count-list)) (if (null? (test-runner-group-stack r)) ((test-runner-on-final r) r))))) (define-syntax test-group (syntax-rules () ((test-group suite-name . body) (let ((r (test-runner-current))) ;; Ideally should also set line-number, if available. (test-result-alist! r (list (cons 'test-name suite-name))) (if (%test-should-execute r) (dynamic-wind (lambda () (test-begin suite-name)) (lambda () . body) (lambda () (test-end suite-name)))))))) (define-syntax test-group-with-cleanup (syntax-rules () ((test-group-with-cleanup suite-name form cleanup-form) (test-group suite-name (dynamic-wind (lambda () #f) (lambda () form) (lambda () cleanup-form)))) ((test-group-with-cleanup suite-name cleanup-form) (test-group-with-cleanup suite-name #f cleanup-form)) ((test-group-with-cleanup suite-name form1 form2 form3 . rest) (test-group-with-cleanup suite-name (begin form1 form2) form3 . rest)))) (define (test-on-test-begin-simple runner) (let ((log (test-runner-aux-value runner))) (if (output-port? log) (let* ((results (test-result-alist runner)) (source-file (assq 'source-file results)) (source-line (assq 'source-line results)) (source-form (assq 'source-form results)) (test-name (assq 'test-name results))) (display "Test begin:" log) (newline log) (if test-name (%test-write-result1 test-name log)) (if source-file (%test-write-result1 source-file log)) (if source-line (%test-write-result1 source-line log)) (if source-form (%test-write-result1 source-form log)))))) (define-syntax test-result-ref (syntax-rules () ((test-result-ref runner pname) (test-result-ref runner pname #f)) ((test-result-ref runner pname default) (let ((p (assq pname (test-result-alist runner)))) (if p (cdr p) default))))) (define (test-on-test-end-simple runner) (let ((log (test-runner-aux-value runner)) (kind (test-result-ref runner 'result-kind))) (if (memq kind '(fail xpass)) (let* ((results (test-result-alist runner)) (source-file (assq 'source-file results)) (source-line (assq 'source-line results)) (test-name (assq 'test-name results))) (if (or source-file source-line) (begin (if source-file (display (cdr source-file))) (display ":") (if source-line (display (cdr source-line))) (display ": "))) (display (if (eq? kind 'xpass) "XPASS" "FAIL")) (if test-name (begin (display " ") (display (cdr test-name)))) (newline))) (if (output-port? log) (begin (display "Test end:" log) (newline log) (let loop ((list (test-result-alist runner))) (if (pair? list) (let ((pair (car list))) ;; Write out properties not written out by on-test-begin. (if (not (memq (car pair) '(test-name source-file source-line source-form))) (%test-write-result1 pair log)) (loop (cdr list))))))))) (define (%test-write-result1 pair port) (display " " port) (display (car pair) port) (display ": " port) (write (cdr pair) port) (newline port)) (define (test-result-set! runner pname value) (let* ((alist (test-result-alist runner)) (p (assq pname alist))) (if p (set-cdr! p value) (test-result-alist! runner (cons (cons pname value) alist))))) (define (test-result-clear runner) (test-result-alist! runner '())) (define (test-result-remove runner pname) (let* ((alist (test-result-alist runner)) (p (assq pname alist))) (if p (test-result-alist! runner (let loop ((r alist)) (if (eq? r p) (cdr r) (cons (car r) (loop (cdr r))))))))) (define (test-result-kind . rest) (let ((runner (if (pair? rest) (car rest) (test-runner-current)))) (test-result-ref runner 'result-kind))) (define (test-passed? . rest) (let ((runner (if (pair? rest) (car rest) (test-runner-get)))) (memq (test-result-ref runner 'result-kind) '(pass xpass)))) (define (%test-report-result) (let* ((r (test-runner-get)) (result-kind (test-result-kind r))) (case result-kind ((pass) (test-runner-pass-count! r (+ 1 (test-runner-pass-count r)))) ((fail) (test-runner-fail-count! r (+ 1 (test-runner-fail-count r)))) ((xpass) (test-runner-xpass-count! r (+ 1 (test-runner-xpass-count r)))) ((xfail) (test-runner-xfail-count! r (+ 1 (test-runner-xfail-count r)))) (else (test-runner-skip-count! r (+ 1 (test-runner-skip-count r))))) (%test-runner-total-count! r (+ 1 (%test-runner-total-count r))) ((test-runner-on-test-end r) r))) (cond-expand (guile (define-syntax %test-evaluate-with-catch (syntax-rules () ((%test-evaluate-with-catch test-expression) (catch #t (lambda () test-expression) (lambda (key . args) (test-result-set! (test-runner-current) 'actual-error (cons key args)) #f)))))) (kawa (define-syntax %test-evaluate-with-catch (syntax-rules () ((%test-evaluate-with-catch test-expression) (try-catch test-expression (ex <java.lang.Throwable> (test-result-set! (test-runner-current) 'actual-error ex) #f)))))) (srfi-34 (define-syntax %test-evaluate-with-catch (syntax-rules () ((%test-evaluate-with-catch test-expression) (guard (err (else #f)) test-expression))))) (chicken (define-syntax %test-evaluate-with-catch (syntax-rules () ((%test-evaluate-with-catch test-expression) (condition-case test-expression (ex () #f)))))) (else (define-syntax %test-evaluate-with-catch (syntax-rules () ((%test-evaluate-with-catch test-expression) test-expression))))) (cond-expand ((or kawa mzscheme) (cond-expand (mzscheme (define-for-syntax (%test-syntax-file form) (let ((source (syntax-source form))) (cond ((string? source) file) ((path? source) (path->string source)) (else #f))))) (kawa (define (%test-syntax-file form) (syntax-source form)))) (define (%test-source-line2 form) (let* ((line (syntax-line form)) (file (%test-syntax-file form)) (line-pair (if line (list (cons 'source-line line)) '()))) (cons (cons 'source-form (syntax-object->datum form)) (if file (cons (cons 'source-file file) line-pair) line-pair))))) (guile-2 (define (%test-source-line2 form) (let* ((src-props (syntax-source form)) (file (and src-props (assq-ref src-props 'filename))) (line (and src-props (assq-ref src-props 'line))) (file-alist (if file `((source-file . ,file)) '())) (line-alist (if line `((source-line . ,(+ line 1))) '()))) (datum->syntax (syntax here) `((source-form . ,(syntax->datum form)) ,@file-alist ,@line-alist))))) (else (define (%test-source-line2 form) '()))) (define (%test-on-test-begin r) (%test-should-execute r) ((test-runner-on-test-begin r) r) (not (eq? 'skip (test-result-ref r 'result-kind)))) (define (%test-on-test-end r result) (test-result-set! r 'result-kind (if (eq? (test-result-ref r 'result-kind) 'xfail) (if result 'xpass 'xfail) (if result 'pass 'fail)))) (define (test-runner-test-name runner) (test-result-ref runner 'test-name "")) (define-syntax %test-comp2body (syntax-rules () ((%test-comp2body r comp expected expr) (let () (if (%test-on-test-begin r) (let ((exp expected)) (test-result-set! r 'expected-value exp) (let ((res (%test-evaluate-with-catch expr))) (test-result-set! r 'actual-value res) (%test-on-test-end r (comp exp res))))) (%test-report-result))))) (define (%test-approximate= error) (lambda (value expected) (let ((rval (real-part value)) (ival (imag-part value)) (rexp (real-part expected)) (iexp (imag-part expected))) (and (>= rval (- rexp error)) (>= ival (- iexp error)) (<= rval (+ rexp error)) (<= ival (+ iexp error)))))) (define-syntax %test-comp1body (syntax-rules () ((%test-comp1body r expr) (let () (if (%test-on-test-begin r) (let () (let ((res (%test-evaluate-with-catch expr))) (test-result-set! r 'actual-value res) (%test-on-test-end r res)))) (%test-report-result))))) (cond-expand ((or kawa mzscheme guile-2) ;; Should be made to work for any Scheme with syntax-case However , I have n't gotten the quoting working . FIXME . (define-syntax test-end (lambda (x) (syntax-case (list x (list (syntax quote) (%test-source-line2 x))) () (((mac suite-name) line) (syntax (%test-end suite-name line))) (((mac) line) (syntax (%test-end #f line)))))) (define-syntax test-assert (lambda (x) (syntax-case (list x (list (syntax quote) (%test-source-line2 x))) () (((mac tname expr) line) (syntax (let* ((r (test-runner-get)) (name tname)) (test-result-alist! r (cons (cons 'test-name tname) line)) (%test-comp1body r expr)))) (((mac expr) line) (syntax (let* ((r (test-runner-get))) (test-result-alist! r line) (%test-comp1body r expr))))))) (define (%test-comp2 comp x) (syntax-case (list x (list (syntax quote) (%test-source-line2 x)) comp) () (((mac tname expected expr) line comp) (syntax (let* ((r (test-runner-get)) (name tname)) (test-result-alist! r (cons (cons 'test-name tname) line)) (%test-comp2body r comp expected expr)))) (((mac expected expr) line comp) (syntax (let* ((r (test-runner-get))) (test-result-alist! r line) (%test-comp2body r comp expected expr)))))) (define-syntax test-eqv (lambda (x) (%test-comp2 (syntax eqv?) x))) (define-syntax test-eq (lambda (x) (%test-comp2 (syntax eq?) x))) (define-syntax test-equal (lambda (x) (%test-comp2 (syntax equal?) x))) FIXME - needed for (lambda (x) (syntax-case (list x (list (syntax quote) (%test-source-line2 x))) () (((mac tname expected expr error) line) (syntax (let* ((r (test-runner-get)) (name tname)) (test-result-alist! r (cons (cons 'test-name tname) line)) (%test-comp2body r (%test-approximate= error) expected expr)))) (((mac expected expr error) line) (syntax (let* ((r (test-runner-get))) (test-result-alist! r line) (%test-comp2body r (%test-approximate= error) expected expr)))))))) (else (define-syntax test-end (syntax-rules () ((test-end) (%test-end #f '())) ((test-end suite-name) (%test-end suite-name '())))) (define-syntax test-assert (syntax-rules () ((test-assert tname test-expression) (let* ((r (test-runner-get)) (name tname)) (test-result-alist! r '((test-name . tname))) (%test-comp1body r test-expression))) ((test-assert test-expression) (let* ((r (test-runner-get))) (test-result-alist! r '()) (%test-comp1body r test-expression))))) (define-syntax %test-comp2 (syntax-rules () ((%test-comp2 comp tname expected expr) (let* ((r (test-runner-get)) (name tname)) (test-result-alist! r (list (cons 'test-name tname))) (%test-comp2body r comp expected expr))) ((%test-comp2 comp expected expr) (let* ((r (test-runner-get))) (test-result-alist! r '()) (%test-comp2body r comp expected expr))))) (define-syntax test-equal (syntax-rules () ((test-equal . rest) (%test-comp2 equal? . rest)))) (define-syntax test-eqv (syntax-rules () ((test-eqv . rest) (%test-comp2 eqv? . rest)))) (define-syntax test-eq (syntax-rules () ((test-eq . rest) (%test-comp2 eq? . rest)))) (define-syntax test-approximate (syntax-rules () ((test-approximate tname expected expr error) (%test-comp2 (%test-approximate= error) tname expected expr)) ((test-approximate expected expr error) (%test-comp2 (%test-approximate= error) expected expr)))))) (cond-expand (guile (define-syntax %test-error (syntax-rules () ((%test-error r etype expr) (cond ((%test-on-test-begin r) (let ((et etype)) (test-result-set! r 'expected-error et) (%test-on-test-end r (catch #t (lambda () (test-result-set! r 'actual-value expr) #f) (lambda (key . args) ;; TODO: decide how to specify expected error types for . (test-result-set! r 'actual-error (cons key args)) #t))) (%test-report-result)))))))) (mzscheme (define-syntax %test-error (syntax-rules () ((%test-error r etype expr) (%test-comp1body r (with-handlers (((lambda (h) #t) (lambda (h) #t))) (let () (test-result-set! r 'actual-value expr) #f))))))) (chicken (define-syntax %test-error (syntax-rules () ((%test-error r etype expr) (%test-comp1body r (condition-case expr (ex () #t))))))) (kawa (define-syntax %test-error (syntax-rules () ((%test-error r #t expr) (cond ((%test-on-test-begin r) (test-result-set! r 'expected-error #t) (%test-on-test-end r (try-catch (let () (test-result-set! r 'actual-value expr) #f) (ex <java.lang.Throwable> (test-result-set! r 'actual-error ex) #t))) (%test-report-result)))) ((%test-error r etype expr) (if (%test-on-test-begin r) (let ((et etype)) (test-result-set! r 'expected-error et) (%test-on-test-end r (try-catch (let () (test-result-set! r 'actual-value expr) #f) (ex <java.lang.Throwable> (test-result-set! r 'actual-error ex) (cond ((and (instance? et <gnu.bytecode.ClassType>) (gnu.bytecode.ClassType:isSubclass et <java.lang.Throwable>)) (instance? ex et)) (else #t))))) (%test-report-result))))))) ((and srfi-34 srfi-35) (define-syntax %test-error (syntax-rules () ((%test-error r etype expr) (%test-comp1body r (guard (ex ((condition-type? etype) (and (condition? ex) (condition-has-type? ex etype))) ((procedure? etype) (etype ex)) ((equal? etype #t) #t) (else #t)) expr #f)))))) (srfi-34 (define-syntax %test-error (syntax-rules () ((%test-error r etype expr) (%test-comp1body r (guard (ex (else #t)) expr #f)))))) (else (define-syntax %test-error (syntax-rules () ((%test-error r etype expr) (begin ((test-runner-on-test-begin r) r) (test-result-set! r 'result-kind 'skip) (%test-report-result))))))) (cond-expand ((or kawa mzscheme guile-2) (define-syntax test-error (lambda (x) (syntax-case (list x (list (syntax quote) (%test-source-line2 x))) () (((mac tname etype expr) line) (syntax (let* ((r (test-runner-get)) (name tname)) (test-result-alist! r (cons (cons 'test-name tname) line)) (%test-error r etype expr)))) (((mac etype expr) line) (syntax (let* ((r (test-runner-get))) (test-result-alist! r line) (%test-error r etype expr)))) (((mac expr) line) (syntax (let* ((r (test-runner-get))) (test-result-alist! r line) (%test-error r #t expr)))))))) (else (define-syntax test-error (syntax-rules () ((test-error name etype expr) (let ((r (test-runner-get))) (test-result-alist! r `((test-name . ,name))) (%test-error r etype expr))) ((test-error etype expr) (let ((r (test-runner-get))) (test-result-alist! r '()) (%test-error r etype expr))) ((test-error expr) (let ((r (test-runner-get))) (test-result-alist! r '()) (%test-error r #t expr))))))) (define (test-apply first . rest) (if (test-runner? first) (test-with-runner first (apply test-apply rest)) (let ((r (test-runner-current))) (if r (let ((run-list (%test-runner-run-list r))) (cond ((null? rest) (%test-runner-run-list! r (reverse run-list)) (first)) ;; actually apply procedure thunk (else (%test-runner-run-list! r (if (eq? run-list #t) (list first) (cons first run-list))) (apply test-apply rest) (%test-runner-run-list! r run-list)))) (let ((r (test-runner-create))) (test-with-runner r (apply test-apply first rest)) ((test-runner-on-final r) r)))))) (define-syntax test-with-runner (syntax-rules () ((test-with-runner runner form ...) (let ((saved-runner (test-runner-current))) (dynamic-wind (lambda () (test-runner-current runner)) (lambda () form ...) (lambda () (test-runner-current saved-runner))))))) ;;; Predicates (define (%test-match-nth n count) (let ((i 0)) (lambda (runner) (set! i (+ i 1)) (and (>= i n) (< i (+ n count)))))) (define-syntax test-match-nth (syntax-rules () ((test-match-nth n) (test-match-nth n 1)) ((test-match-nth n count) (%test-match-nth n count)))) (define (%test-match-all . pred-list) (lambda (runner) (let ((result #t)) (let loop ((l pred-list)) (if (null? l) result (begin (if (not ((car l) runner)) (set! result #f)) (loop (cdr l)))))))) (define-syntax test-match-all (syntax-rules () ((test-match-all pred ...) (%test-match-all (%test-as-specifier pred) ...)))) (define (%test-match-any . pred-list) (lambda (runner) (let ((result #f)) (let loop ((l pred-list)) (if (null? l) result (begin (if ((car l) runner) (set! result #t)) (loop (cdr l)))))))) (define-syntax test-match-any (syntax-rules () ((test-match-any pred ...) (%test-match-any (%test-as-specifier pred) ...)))) Coerce to a predicate function : (define (%test-as-specifier specifier) (cond ((procedure? specifier) specifier) ((integer? specifier) (test-match-nth 1 specifier)) ((string? specifier) (test-match-name specifier)) (else (error "not a valid test specifier")))) (define-syntax test-skip (syntax-rules () ((test-skip pred ...) (let ((runner (test-runner-get))) (%test-runner-skip-list! runner (cons (test-match-all (%test-as-specifier pred) ...) (%test-runner-skip-list runner))))))) (define-syntax test-expect-fail (syntax-rules () ((test-expect-fail pred ...) (let ((runner (test-runner-get))) (%test-runner-fail-list! runner (cons (test-match-all (%test-as-specifier pred) ...) (%test-runner-fail-list runner))))))) (define (test-match-name name) (lambda (runner) (equal? name (test-runner-test-name runner)))) (define (test-read-eval-string string) (let* ((port (open-input-string string)) (form (read port))) (if (eof-object? (read-char port)) (cond-expand (guile (eval form (current-module))) (else (eval form))) (cond-expand (srfi-23 (error "(not at eof)")) (else "error")))))
null
https://raw.githubusercontent.com/webyrd/n-grams-for-synthesis/b53b071e53445337d3fe20db0249363aeb9f3e51/datasets/srfi/srfi-154/srfi/64/testing.scm
scheme
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. List of exported names Misc test-runner functions test-runner field setter and getter functions - see %test-record-define: default/simple call-back functions, used in default test-runner, but can be called to construct more complex ones. Normally #t, except when in a test-apply. Call-back when entering a group. Takes (runner suite-name count). Call-back when leaving a group. Call-back when leaving the outermost group. Call-back when expected number of tests was wrong. Call-back when name in test=end doesn't match test-begin. test-runner-simple uses it for a log file. Controls whether a log file is generated. A safer wrapper to test-runner-current. Returns #f, #t, or 'xfail. (begin (%test-begin suite-name [count])) This puts test-begin but only test-begin in the default environment., which makes normal test suites loadable without non-portable commands. Ideally should also set line-number, if available. Write out properties not written out by on-test-begin. Should be made to work for any Scheme with syntax-case TODO: decide how to specify expected actually apply procedure thunk Predicates
Copyright ( c ) 2005 , 2006 , 2007 , 2012 , 2013 Per Bothner Added " full " support for Chicken , Gauche , and SISC . , Copyright ( c ) 2005 . Modified for Scheme Spheres by , Copyright ( c ) 2012 . Support for Guile 2 by < > , Copyright ( c ) 2014 . files ( the " Software " ) , to deal in the Software without of the Software , and to permit persons to whom the Software is included in all copies or substantial portions of the Software . THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , BE LIABLE FOR ANY CLAIM , DAMAGES OR OTHER LIABILITY , WHETHER IN AN (cond-expand (chicken (require-extension syntax-case)) (guile-2 (use-modules (srfi srfi-9) In 2.0.9 , srfi-34 and srfi-35 are not well integrated with either 's native exceptions or R6RS exceptions . ( srfi srfi-34 ) ( srfi srfi-35 ) (srfi srfi-39))) (guile (use-modules (ice-9 syncase) (srfi srfi-9) ( srfi srfi-34 ) ( srfi srfi-35 ) - not in 1.6.7 (srfi srfi-39))) (sisc (require-extension (srfi 9 34 35 39))) (kawa (module-compile-options warn-undefined-variable: #t warn-invoke-unknown-method: #t) (provide 'srfi-64) (provide 'testing) (require 'srfi-34) (require 'srfi-35)) (else )) (cond-expand (kawa (define-syntax %test-export (syntax-rules () ((%test-export test-begin . other-names) (module-export %test-begin . other-names))))) (else (define-syntax %test-export (syntax-rules () ((%test-export . names) (if #f #f)))))) (%test-export must be listed first , since in ( at least ) it is " magic " . test-end test-assert test-eqv test-eq test-equal test-approximate test-assert test-error test-apply test-with-runner test-match-nth test-match-all test-match-any test-match-name test-skip test-expect-fail test-read-eval-string test-runner-group-path test-group test-group-with-cleanup test-result-ref test-result-set! test-result-clear test-result-remove test-result-kind test-passed? test-log-to-file test-runner? test-runner-reset test-runner-null test-runner-simple test-runner-current test-runner-factory test-runner-get test-runner-create test-runner-test-name test-runner-pass-count test-runner-pass-count! test-runner-fail-count test-runner-fail-count! test-runner-xpass-count test-runner-xpass-count! test-runner-xfail-count test-runner-xfail-count! test-runner-skip-count test-runner-skip-count! test-runner-group-stack test-runner-group-stack! test-runner-on-test-begin test-runner-on-test-begin! test-runner-on-test-end test-runner-on-test-end! test-runner-on-group-begin test-runner-on-group-begin! test-runner-on-group-end test-runner-on-group-end! test-runner-on-final test-runner-on-final! test-runner-on-bad-count test-runner-on-bad-count! test-runner-on-bad-end-name test-runner-on-bad-end-name! test-result-alist test-result-alist! test-runner-aux-value test-runner-aux-value! test-on-group-begin-simple test-on-group-end-simple test-on-bad-count-simple test-on-bad-end-name-simple test-on-final-simple test-on-test-end-simple test-on-final-simple) (cond-expand (srfi-9 (define-syntax %test-record-define (syntax-rules () ((%test-record-define alloc runner? (name index setter getter) ...) (define-record-type test-runner (alloc) runner? (name setter getter) ...))))) (else (define %test-runner-cookie (list "test-runner")) (define-syntax %test-record-define (syntax-rules () ((%test-record-define alloc runner? (name index getter setter) ...) (begin (define (runner? obj) (and (vector? obj) (> (vector-length obj) 1) (eq? (vector-ref obj 0) %test-runner-cookie))) (define (alloc) (let ((runner (make-vector 23))) (vector-set! runner 0 %test-runner-cookie) runner)) (begin (define (getter runner) (vector-ref runner index)) ...) (begin (define (setter runner value) (vector-set! runner index value)) ...))))))) (%test-record-define %test-runner-alloc test-runner? Cumulate count of all tests that have passed and were expected to . (pass-count 1 test-runner-pass-count test-runner-pass-count!) (fail-count 2 test-runner-fail-count test-runner-fail-count!) (xpass-count 3 test-runner-xpass-count test-runner-xpass-count!) (xfail-count 4 test-runner-xfail-count test-runner-xfail-count!) (skip-count 5 test-runner-skip-count test-runner-skip-count!) (skip-list 6 %test-runner-skip-list %test-runner-skip-list!) (fail-list 7 %test-runner-fail-list %test-runner-fail-list!) (run-list 8 %test-runner-run-list %test-runner-run-list!) (skip-save 9 %test-runner-skip-save %test-runner-skip-save!) (fail-save 10 %test-runner-fail-save %test-runner-fail-save!) (group-stack 11 test-runner-group-stack test-runner-group-stack!) (on-test-begin 12 test-runner-on-test-begin test-runner-on-test-begin!) (on-test-end 13 test-runner-on-test-end test-runner-on-test-end!) (on-group-begin 14 test-runner-on-group-begin test-runner-on-group-begin!) (on-group-end 15 test-runner-on-group-end test-runner-on-group-end!) (on-final 16 test-runner-on-final test-runner-on-final!) (on-bad-count 17 test-runner-on-bad-count test-runner-on-bad-count!) (on-bad-end-name 18 test-runner-on-bad-end-name test-runner-on-bad-end-name!) Cumulate count of all tests that have been done . (total-count 19 %test-runner-total-count %test-runner-total-count!) Stack ( list ) of ( count - at - start . expected - count ): (count-list 20 %test-runner-count-list %test-runner-count-list!) (result-alist 21 test-result-alist test-result-alist!) Field can be used by test - runner for any purpose . (aux-value 22 test-runner-aux-value test-runner-aux-value!) ) (define (test-runner-reset runner) (test-result-alist! runner '()) (test-runner-pass-count! runner 0) (test-runner-fail-count! runner 0) (test-runner-xpass-count! runner 0) (test-runner-xfail-count! runner 0) (test-runner-skip-count! runner 0) (%test-runner-total-count! runner 0) (%test-runner-count-list! runner '()) (%test-runner-run-list! runner #t) (%test-runner-skip-list! runner '()) (%test-runner-fail-list! runner '()) (%test-runner-skip-save! runner '()) (%test-runner-fail-save! runner '()) (test-runner-group-stack! runner '())) (define (test-runner-group-path runner) (reverse (test-runner-group-stack runner))) (define (%test-null-callback runner) #f) (define (test-runner-null) (let ((runner (%test-runner-alloc))) (test-runner-reset runner) (test-runner-on-group-begin! runner (lambda (runner name count) #f)) (test-runner-on-group-end! runner %test-null-callback) (test-runner-on-final! runner %test-null-callback) (test-runner-on-test-begin! runner %test-null-callback) (test-runner-on-test-end! runner %test-null-callback) (test-runner-on-bad-count! runner (lambda (runner count expected) #f)) (test-runner-on-bad-end-name! runner (lambda (runner begin end) #f)) runner)) Not part of the specification . FIXME (define test-log-to-file #t) (define (test-runner-simple) (let ((runner (%test-runner-alloc))) (test-runner-reset runner) (test-runner-on-group-begin! runner test-on-group-begin-simple) (test-runner-on-group-end! runner test-on-group-end-simple) (test-runner-on-final! runner test-on-final-simple) (test-runner-on-test-begin! runner test-on-test-begin-simple) (test-runner-on-test-end! runner test-on-test-end-simple) (test-runner-on-bad-count! runner test-on-bad-count-simple) (test-runner-on-bad-end-name! runner test-on-bad-end-name-simple) runner)) (cond-expand (srfi-39 (define test-runner-current (make-parameter #f)) (define test-runner-factory (make-parameter test-runner-simple))) (else (define %test-runner-current #f) (define-syntax test-runner-current (syntax-rules () ((test-runner-current) %test-runner-current) ((test-runner-current runner) (set! %test-runner-current runner)))) (define %test-runner-factory test-runner-simple) (define-syntax test-runner-factory (syntax-rules () ((test-runner-factory) %test-runner-factory) ((test-runner-factory runner) (set! %test-runner-factory runner)))))) (define (test-runner-get) (let ((r (test-runner-current))) (if (not r) (cond-expand (srfi-23 (error "test-runner not initialized - test-begin missing?")) (else #t))) r)) (define (%test-specifier-matches spec runner) (spec runner)) (define (test-runner-create) ((test-runner-factory))) (define (%test-any-specifier-matches list runner) (let ((result #f)) (let loop ((l list)) (cond ((null? l) result) (else (if (%test-specifier-matches (car l) runner) (set! result #t)) (loop (cdr l))))))) (define (%test-should-execute runner) (let ((run (%test-runner-run-list runner))) (cond ((or (not (or (eqv? run #t) (%test-any-specifier-matches run runner))) (%test-any-specifier-matches (%test-runner-skip-list runner) runner)) (test-result-set! runner 'result-kind 'skip) #f) ((%test-any-specifier-matches (%test-runner-fail-list runner) runner) (test-result-set! runner 'result-kind 'xfail) 'xfail) (else #t)))) (define (%test-begin suite-name count) (if (not (test-runner-current)) (test-runner-current (test-runner-create))) (let ((runner (test-runner-current))) ((test-runner-on-group-begin runner) runner suite-name count) (%test-runner-skip-save! runner (cons (%test-runner-skip-list runner) (%test-runner-skip-save runner))) (%test-runner-fail-save! runner (cons (%test-runner-fail-list runner) (%test-runner-fail-save runner))) (%test-runner-count-list! runner (cons (cons (%test-runner-total-count runner) count) (%test-runner-count-list runner))) (test-runner-group-stack! runner (cons suite-name (test-runner-group-stack runner))))) (cond-expand (kawa Kawa has test - begin built in , implemented as : ( cond - expand ( srfi-64 # ! void ) ( else ( require ' srfi-64 ) ) ) ) (else (define-syntax test-begin (syntax-rules () ((test-begin suite-name) (%test-begin suite-name #f)) ((test-begin suite-name count) (%test-begin suite-name count)))))) (define (test-on-group-begin-simple runner suite-name count) (if (null? (test-runner-group-stack runner)) (begin (display "%%%% Starting test ") (display suite-name) (if test-log-to-file (let* ((log-file-name (if (string? test-log-to-file) test-log-to-file (string-append suite-name ".log"))) (log-file (cond-expand (mzscheme (open-output-file log-file-name 'truncate/replace)) (else (open-output-file log-file-name))))) (display "%%%% Starting test " log-file) (display suite-name log-file) (newline log-file) (test-runner-aux-value! runner log-file) (display " (Writing full log to \"") (display log-file-name) (display "\")"))) (newline))) (let ((log (test-runner-aux-value runner))) (if (output-port? log) (begin (display "Group begin: " log) (display suite-name log) (newline log)))) #f) (define (test-on-group-end-simple runner) (let ((log (test-runner-aux-value runner))) (if (output-port? log) (begin (display "Group end: " log) (display (car (test-runner-group-stack runner)) log) (newline log)))) #f) (define (%test-on-bad-count-write runner count expected-count port) (display "*** Total number of tests was " port) (display count port) (display " but should be " port) (display expected-count port) (display ". ***" port) (newline port) (display "*** Discrepancy indicates testsuite error or exceptions. ***" port) (newline port)) (define (test-on-bad-count-simple runner count expected-count) (%test-on-bad-count-write runner count expected-count (current-output-port)) (let ((log (test-runner-aux-value runner))) (if (output-port? log) (%test-on-bad-count-write runner count expected-count log)))) (define (test-on-bad-end-name-simple runner begin-name end-name) (let ((msg (string-append (%test-format-line runner) "test-end " begin-name " does not match test-begin " end-name))) (cond-expand (srfi-23 (error msg)) (else (display msg) (newline))))) (define (%test-final-report1 value label port) (if (> value 0) (begin (display label port) (display value port) (newline port)))) (define (%test-final-report-simple runner port) (%test-final-report1 (test-runner-pass-count runner) "# of expected passes " port) (%test-final-report1 (test-runner-xfail-count runner) "# of expected failures " port) (%test-final-report1 (test-runner-xpass-count runner) "# of unexpected successes " port) (%test-final-report1 (test-runner-fail-count runner) "# of unexpected failures " port) (%test-final-report1 (test-runner-skip-count runner) "# of skipped tests " port)) (define (test-on-final-simple runner) (%test-final-report-simple runner (current-output-port)) (let ((log (test-runner-aux-value runner))) (if (output-port? log) (%test-final-report-simple runner log)))) (define (%test-format-line runner) (let* ((line-info (test-result-alist runner)) (source-file (assq 'source-file line-info)) (source-line (assq 'source-line line-info)) (file (if source-file (cdr source-file) ""))) (if source-line (string-append file ":" (number->string (cdr source-line)) ": ") ""))) (define (%test-end suite-name line-info) (let* ((r (test-runner-get)) (groups (test-runner-group-stack r)) (line (%test-format-line r))) (test-result-alist! r line-info) (if (null? groups) (let ((msg (string-append line "test-end not in a group"))) (cond-expand (srfi-23 (error msg)) (else (display msg) (newline))))) (if (and suite-name (not (equal? suite-name (car groups)))) ((test-runner-on-bad-end-name r) r suite-name (car groups))) (let* ((count-list (%test-runner-count-list r)) (expected-count (cdar count-list)) (saved-count (caar count-list)) (group-count (- (%test-runner-total-count r) saved-count))) (if (and expected-count (not (= expected-count group-count))) ((test-runner-on-bad-count r) r group-count expected-count)) ((test-runner-on-group-end r) r) (test-runner-group-stack! r (cdr (test-runner-group-stack r))) (%test-runner-skip-list! r (car (%test-runner-skip-save r))) (%test-runner-skip-save! r (cdr (%test-runner-skip-save r))) (%test-runner-fail-list! r (car (%test-runner-fail-save r))) (%test-runner-fail-save! r (cdr (%test-runner-fail-save r))) (%test-runner-count-list! r (cdr count-list)) (if (null? (test-runner-group-stack r)) ((test-runner-on-final r) r))))) (define-syntax test-group (syntax-rules () ((test-group suite-name . body) (let ((r (test-runner-current))) (test-result-alist! r (list (cons 'test-name suite-name))) (if (%test-should-execute r) (dynamic-wind (lambda () (test-begin suite-name)) (lambda () . body) (lambda () (test-end suite-name)))))))) (define-syntax test-group-with-cleanup (syntax-rules () ((test-group-with-cleanup suite-name form cleanup-form) (test-group suite-name (dynamic-wind (lambda () #f) (lambda () form) (lambda () cleanup-form)))) ((test-group-with-cleanup suite-name cleanup-form) (test-group-with-cleanup suite-name #f cleanup-form)) ((test-group-with-cleanup suite-name form1 form2 form3 . rest) (test-group-with-cleanup suite-name (begin form1 form2) form3 . rest)))) (define (test-on-test-begin-simple runner) (let ((log (test-runner-aux-value runner))) (if (output-port? log) (let* ((results (test-result-alist runner)) (source-file (assq 'source-file results)) (source-line (assq 'source-line results)) (source-form (assq 'source-form results)) (test-name (assq 'test-name results))) (display "Test begin:" log) (newline log) (if test-name (%test-write-result1 test-name log)) (if source-file (%test-write-result1 source-file log)) (if source-line (%test-write-result1 source-line log)) (if source-form (%test-write-result1 source-form log)))))) (define-syntax test-result-ref (syntax-rules () ((test-result-ref runner pname) (test-result-ref runner pname #f)) ((test-result-ref runner pname default) (let ((p (assq pname (test-result-alist runner)))) (if p (cdr p) default))))) (define (test-on-test-end-simple runner) (let ((log (test-runner-aux-value runner)) (kind (test-result-ref runner 'result-kind))) (if (memq kind '(fail xpass)) (let* ((results (test-result-alist runner)) (source-file (assq 'source-file results)) (source-line (assq 'source-line results)) (test-name (assq 'test-name results))) (if (or source-file source-line) (begin (if source-file (display (cdr source-file))) (display ":") (if source-line (display (cdr source-line))) (display ": "))) (display (if (eq? kind 'xpass) "XPASS" "FAIL")) (if test-name (begin (display " ") (display (cdr test-name)))) (newline))) (if (output-port? log) (begin (display "Test end:" log) (newline log) (let loop ((list (test-result-alist runner))) (if (pair? list) (let ((pair (car list))) (if (not (memq (car pair) '(test-name source-file source-line source-form))) (%test-write-result1 pair log)) (loop (cdr list))))))))) (define (%test-write-result1 pair port) (display " " port) (display (car pair) port) (display ": " port) (write (cdr pair) port) (newline port)) (define (test-result-set! runner pname value) (let* ((alist (test-result-alist runner)) (p (assq pname alist))) (if p (set-cdr! p value) (test-result-alist! runner (cons (cons pname value) alist))))) (define (test-result-clear runner) (test-result-alist! runner '())) (define (test-result-remove runner pname) (let* ((alist (test-result-alist runner)) (p (assq pname alist))) (if p (test-result-alist! runner (let loop ((r alist)) (if (eq? r p) (cdr r) (cons (car r) (loop (cdr r))))))))) (define (test-result-kind . rest) (let ((runner (if (pair? rest) (car rest) (test-runner-current)))) (test-result-ref runner 'result-kind))) (define (test-passed? . rest) (let ((runner (if (pair? rest) (car rest) (test-runner-get)))) (memq (test-result-ref runner 'result-kind) '(pass xpass)))) (define (%test-report-result) (let* ((r (test-runner-get)) (result-kind (test-result-kind r))) (case result-kind ((pass) (test-runner-pass-count! r (+ 1 (test-runner-pass-count r)))) ((fail) (test-runner-fail-count! r (+ 1 (test-runner-fail-count r)))) ((xpass) (test-runner-xpass-count! r (+ 1 (test-runner-xpass-count r)))) ((xfail) (test-runner-xfail-count! r (+ 1 (test-runner-xfail-count r)))) (else (test-runner-skip-count! r (+ 1 (test-runner-skip-count r))))) (%test-runner-total-count! r (+ 1 (%test-runner-total-count r))) ((test-runner-on-test-end r) r))) (cond-expand (guile (define-syntax %test-evaluate-with-catch (syntax-rules () ((%test-evaluate-with-catch test-expression) (catch #t (lambda () test-expression) (lambda (key . args) (test-result-set! (test-runner-current) 'actual-error (cons key args)) #f)))))) (kawa (define-syntax %test-evaluate-with-catch (syntax-rules () ((%test-evaluate-with-catch test-expression) (try-catch test-expression (ex <java.lang.Throwable> (test-result-set! (test-runner-current) 'actual-error ex) #f)))))) (srfi-34 (define-syntax %test-evaluate-with-catch (syntax-rules () ((%test-evaluate-with-catch test-expression) (guard (err (else #f)) test-expression))))) (chicken (define-syntax %test-evaluate-with-catch (syntax-rules () ((%test-evaluate-with-catch test-expression) (condition-case test-expression (ex () #f)))))) (else (define-syntax %test-evaluate-with-catch (syntax-rules () ((%test-evaluate-with-catch test-expression) test-expression))))) (cond-expand ((or kawa mzscheme) (cond-expand (mzscheme (define-for-syntax (%test-syntax-file form) (let ((source (syntax-source form))) (cond ((string? source) file) ((path? source) (path->string source)) (else #f))))) (kawa (define (%test-syntax-file form) (syntax-source form)))) (define (%test-source-line2 form) (let* ((line (syntax-line form)) (file (%test-syntax-file form)) (line-pair (if line (list (cons 'source-line line)) '()))) (cons (cons 'source-form (syntax-object->datum form)) (if file (cons (cons 'source-file file) line-pair) line-pair))))) (guile-2 (define (%test-source-line2 form) (let* ((src-props (syntax-source form)) (file (and src-props (assq-ref src-props 'filename))) (line (and src-props (assq-ref src-props 'line))) (file-alist (if file `((source-file . ,file)) '())) (line-alist (if line `((source-line . ,(+ line 1))) '()))) (datum->syntax (syntax here) `((source-form . ,(syntax->datum form)) ,@file-alist ,@line-alist))))) (else (define (%test-source-line2 form) '()))) (define (%test-on-test-begin r) (%test-should-execute r) ((test-runner-on-test-begin r) r) (not (eq? 'skip (test-result-ref r 'result-kind)))) (define (%test-on-test-end r result) (test-result-set! r 'result-kind (if (eq? (test-result-ref r 'result-kind) 'xfail) (if result 'xpass 'xfail) (if result 'pass 'fail)))) (define (test-runner-test-name runner) (test-result-ref runner 'test-name "")) (define-syntax %test-comp2body (syntax-rules () ((%test-comp2body r comp expected expr) (let () (if (%test-on-test-begin r) (let ((exp expected)) (test-result-set! r 'expected-value exp) (let ((res (%test-evaluate-with-catch expr))) (test-result-set! r 'actual-value res) (%test-on-test-end r (comp exp res))))) (%test-report-result))))) (define (%test-approximate= error) (lambda (value expected) (let ((rval (real-part value)) (ival (imag-part value)) (rexp (real-part expected)) (iexp (imag-part expected))) (and (>= rval (- rexp error)) (>= ival (- iexp error)) (<= rval (+ rexp error)) (<= ival (+ iexp error)))))) (define-syntax %test-comp1body (syntax-rules () ((%test-comp1body r expr) (let () (if (%test-on-test-begin r) (let () (let ((res (%test-evaluate-with-catch expr))) (test-result-set! r 'actual-value res) (%test-on-test-end r res)))) (%test-report-result))))) (cond-expand ((or kawa mzscheme guile-2) However , I have n't gotten the quoting working . FIXME . (define-syntax test-end (lambda (x) (syntax-case (list x (list (syntax quote) (%test-source-line2 x))) () (((mac suite-name) line) (syntax (%test-end suite-name line))) (((mac) line) (syntax (%test-end #f line)))))) (define-syntax test-assert (lambda (x) (syntax-case (list x (list (syntax quote) (%test-source-line2 x))) () (((mac tname expr) line) (syntax (let* ((r (test-runner-get)) (name tname)) (test-result-alist! r (cons (cons 'test-name tname) line)) (%test-comp1body r expr)))) (((mac expr) line) (syntax (let* ((r (test-runner-get))) (test-result-alist! r line) (%test-comp1body r expr))))))) (define (%test-comp2 comp x) (syntax-case (list x (list (syntax quote) (%test-source-line2 x)) comp) () (((mac tname expected expr) line comp) (syntax (let* ((r (test-runner-get)) (name tname)) (test-result-alist! r (cons (cons 'test-name tname) line)) (%test-comp2body r comp expected expr)))) (((mac expected expr) line comp) (syntax (let* ((r (test-runner-get))) (test-result-alist! r line) (%test-comp2body r comp expected expr)))))) (define-syntax test-eqv (lambda (x) (%test-comp2 (syntax eqv?) x))) (define-syntax test-eq (lambda (x) (%test-comp2 (syntax eq?) x))) (define-syntax test-equal (lambda (x) (%test-comp2 (syntax equal?) x))) FIXME - needed for (lambda (x) (syntax-case (list x (list (syntax quote) (%test-source-line2 x))) () (((mac tname expected expr error) line) (syntax (let* ((r (test-runner-get)) (name tname)) (test-result-alist! r (cons (cons 'test-name tname) line)) (%test-comp2body r (%test-approximate= error) expected expr)))) (((mac expected expr error) line) (syntax (let* ((r (test-runner-get))) (test-result-alist! r line) (%test-comp2body r (%test-approximate= error) expected expr)))))))) (else (define-syntax test-end (syntax-rules () ((test-end) (%test-end #f '())) ((test-end suite-name) (%test-end suite-name '())))) (define-syntax test-assert (syntax-rules () ((test-assert tname test-expression) (let* ((r (test-runner-get)) (name tname)) (test-result-alist! r '((test-name . tname))) (%test-comp1body r test-expression))) ((test-assert test-expression) (let* ((r (test-runner-get))) (test-result-alist! r '()) (%test-comp1body r test-expression))))) (define-syntax %test-comp2 (syntax-rules () ((%test-comp2 comp tname expected expr) (let* ((r (test-runner-get)) (name tname)) (test-result-alist! r (list (cons 'test-name tname))) (%test-comp2body r comp expected expr))) ((%test-comp2 comp expected expr) (let* ((r (test-runner-get))) (test-result-alist! r '()) (%test-comp2body r comp expected expr))))) (define-syntax test-equal (syntax-rules () ((test-equal . rest) (%test-comp2 equal? . rest)))) (define-syntax test-eqv (syntax-rules () ((test-eqv . rest) (%test-comp2 eqv? . rest)))) (define-syntax test-eq (syntax-rules () ((test-eq . rest) (%test-comp2 eq? . rest)))) (define-syntax test-approximate (syntax-rules () ((test-approximate tname expected expr error) (%test-comp2 (%test-approximate= error) tname expected expr)) ((test-approximate expected expr error) (%test-comp2 (%test-approximate= error) expected expr)))))) (cond-expand (guile (define-syntax %test-error (syntax-rules () ((%test-error r etype expr) (cond ((%test-on-test-begin r) (let ((et etype)) (test-result-set! r 'expected-error et) (%test-on-test-end r (catch #t (lambda () (test-result-set! r 'actual-value expr) #f) (lambda (key . args) error types for . (test-result-set! r 'actual-error (cons key args)) #t))) (%test-report-result)))))))) (mzscheme (define-syntax %test-error (syntax-rules () ((%test-error r etype expr) (%test-comp1body r (with-handlers (((lambda (h) #t) (lambda (h) #t))) (let () (test-result-set! r 'actual-value expr) #f))))))) (chicken (define-syntax %test-error (syntax-rules () ((%test-error r etype expr) (%test-comp1body r (condition-case expr (ex () #t))))))) (kawa (define-syntax %test-error (syntax-rules () ((%test-error r #t expr) (cond ((%test-on-test-begin r) (test-result-set! r 'expected-error #t) (%test-on-test-end r (try-catch (let () (test-result-set! r 'actual-value expr) #f) (ex <java.lang.Throwable> (test-result-set! r 'actual-error ex) #t))) (%test-report-result)))) ((%test-error r etype expr) (if (%test-on-test-begin r) (let ((et etype)) (test-result-set! r 'expected-error et) (%test-on-test-end r (try-catch (let () (test-result-set! r 'actual-value expr) #f) (ex <java.lang.Throwable> (test-result-set! r 'actual-error ex) (cond ((and (instance? et <gnu.bytecode.ClassType>) (gnu.bytecode.ClassType:isSubclass et <java.lang.Throwable>)) (instance? ex et)) (else #t))))) (%test-report-result))))))) ((and srfi-34 srfi-35) (define-syntax %test-error (syntax-rules () ((%test-error r etype expr) (%test-comp1body r (guard (ex ((condition-type? etype) (and (condition? ex) (condition-has-type? ex etype))) ((procedure? etype) (etype ex)) ((equal? etype #t) #t) (else #t)) expr #f)))))) (srfi-34 (define-syntax %test-error (syntax-rules () ((%test-error r etype expr) (%test-comp1body r (guard (ex (else #t)) expr #f)))))) (else (define-syntax %test-error (syntax-rules () ((%test-error r etype expr) (begin ((test-runner-on-test-begin r) r) (test-result-set! r 'result-kind 'skip) (%test-report-result))))))) (cond-expand ((or kawa mzscheme guile-2) (define-syntax test-error (lambda (x) (syntax-case (list x (list (syntax quote) (%test-source-line2 x))) () (((mac tname etype expr) line) (syntax (let* ((r (test-runner-get)) (name tname)) (test-result-alist! r (cons (cons 'test-name tname) line)) (%test-error r etype expr)))) (((mac etype expr) line) (syntax (let* ((r (test-runner-get))) (test-result-alist! r line) (%test-error r etype expr)))) (((mac expr) line) (syntax (let* ((r (test-runner-get))) (test-result-alist! r line) (%test-error r #t expr)))))))) (else (define-syntax test-error (syntax-rules () ((test-error name etype expr) (let ((r (test-runner-get))) (test-result-alist! r `((test-name . ,name))) (%test-error r etype expr))) ((test-error etype expr) (let ((r (test-runner-get))) (test-result-alist! r '()) (%test-error r etype expr))) ((test-error expr) (let ((r (test-runner-get))) (test-result-alist! r '()) (%test-error r #t expr))))))) (define (test-apply first . rest) (if (test-runner? first) (test-with-runner first (apply test-apply rest)) (let ((r (test-runner-current))) (if r (let ((run-list (%test-runner-run-list r))) (cond ((null? rest) (%test-runner-run-list! r (reverse run-list)) (else (%test-runner-run-list! r (if (eq? run-list #t) (list first) (cons first run-list))) (apply test-apply rest) (%test-runner-run-list! r run-list)))) (let ((r (test-runner-create))) (test-with-runner r (apply test-apply first rest)) ((test-runner-on-final r) r)))))) (define-syntax test-with-runner (syntax-rules () ((test-with-runner runner form ...) (let ((saved-runner (test-runner-current))) (dynamic-wind (lambda () (test-runner-current runner)) (lambda () form ...) (lambda () (test-runner-current saved-runner))))))) (define (%test-match-nth n count) (let ((i 0)) (lambda (runner) (set! i (+ i 1)) (and (>= i n) (< i (+ n count)))))) (define-syntax test-match-nth (syntax-rules () ((test-match-nth n) (test-match-nth n 1)) ((test-match-nth n count) (%test-match-nth n count)))) (define (%test-match-all . pred-list) (lambda (runner) (let ((result #t)) (let loop ((l pred-list)) (if (null? l) result (begin (if (not ((car l) runner)) (set! result #f)) (loop (cdr l)))))))) (define-syntax test-match-all (syntax-rules () ((test-match-all pred ...) (%test-match-all (%test-as-specifier pred) ...)))) (define (%test-match-any . pred-list) (lambda (runner) (let ((result #f)) (let loop ((l pred-list)) (if (null? l) result (begin (if ((car l) runner) (set! result #t)) (loop (cdr l)))))))) (define-syntax test-match-any (syntax-rules () ((test-match-any pred ...) (%test-match-any (%test-as-specifier pred) ...)))) Coerce to a predicate function : (define (%test-as-specifier specifier) (cond ((procedure? specifier) specifier) ((integer? specifier) (test-match-nth 1 specifier)) ((string? specifier) (test-match-name specifier)) (else (error "not a valid test specifier")))) (define-syntax test-skip (syntax-rules () ((test-skip pred ...) (let ((runner (test-runner-get))) (%test-runner-skip-list! runner (cons (test-match-all (%test-as-specifier pred) ...) (%test-runner-skip-list runner))))))) (define-syntax test-expect-fail (syntax-rules () ((test-expect-fail pred ...) (let ((runner (test-runner-get))) (%test-runner-fail-list! runner (cons (test-match-all (%test-as-specifier pred) ...) (%test-runner-fail-list runner))))))) (define (test-match-name name) (lambda (runner) (equal? name (test-runner-test-name runner)))) (define (test-read-eval-string string) (let* ((port (open-input-string string)) (form (read port))) (if (eof-object? (read-char port)) (cond-expand (guile (eval form (current-module))) (else (eval form))) (cond-expand (srfi-23 (error "(not at eof)")) (else "error")))))
54ecbe972dcd6aef7e38ba439a4f915babc3559f3135019527c8ee2422bc9414
mirage/digestif
baijiu_blake2s.ml
module By = Digestif_by module Bi = Digestif_bi let failwith fmt = Format.kasprintf failwith fmt module Int32 = struct include Int32 let ( lsl ) = Int32.shift_left let ( lsr ) = Int32.shift_right_logical let ( asr ) = Int32.shift_right let ( lor ) = Int32.logor let ( lxor ) = Int32.logxor let ( land ) = Int32.logand let lnot = Int32.lognot let ( + ) = Int32.add let rol32 a n = (a lsl n) lor (a lsr (32 - n)) let ror32 a n = (a lsr n) lor (a lsl (32 - n)) end module Int64 = struct include Int64 let ( land ) = Int64.logand let ( lsl ) = Int64.shift_left let ( lsr ) = Int64.shift_right_logical let ( lor ) = Int64.logor let ( asr ) = Int64.shift_right let ( lxor ) = Int64.logxor let ( + ) = Int64.add let rol64 a n = (a lsl n) lor (a lsr (64 - n)) let ror64 a n = (a lsr n) lor (a lsl (64 - n)) end module type S = sig type ctx type kind = [ `BLAKE2S ] val init : unit -> ctx val with_outlen_and_bytes_key : int -> By.t -> int -> int -> ctx val with_outlen_and_bigstring_key : int -> Bi.t -> int -> int -> ctx val unsafe_feed_bytes : ctx -> By.t -> int -> int -> unit val unsafe_feed_bigstring : ctx -> Bi.t -> int -> int -> unit val unsafe_get : ctx -> By.t val dup : ctx -> ctx val max_outlen : int end module Unsafe : S = struct type kind = [ `BLAKE2S ] type param = { digest_length : int; key_length : int; fanout : int; depth : int; leaf_length : int32; node_offset : int32; xof_length : int; node_depth : int; inner_length : int; salt : int array; personal : int array; } type ctx = { mutable buflen : int; outlen : int; mutable last_node : int; buf : Bytes.t; h : int32 array; t : int32 array; f : int32 array; } let dup ctx = { buflen = ctx.buflen; outlen = ctx.outlen; last_node = ctx.last_node; buf = By.copy ctx.buf; h = Array.copy ctx.h; t = Array.copy ctx.t; f = Array.copy ctx.f; } let param_to_bytes param = let arr = [| param.digest_length land 0xFF; param.key_length land 0xFF; param.fanout land 0xFF; param.depth land 0xFF (* store to little-endian *); Int32.(to_int ((param.leaf_length lsr 0) land 0xFFl)); Int32.(to_int ((param.leaf_length lsr 8) land 0xFFl)); Int32.(to_int ((param.leaf_length lsr 16) land 0xFFl)); Int32.(to_int ((param.leaf_length lsr 24) land 0xFFl)) (* store to little-endian *); Int32.(to_int ((param.node_offset lsr 0) land 0xFFl)); Int32.(to_int ((param.node_offset lsr 8) land 0xFFl)); Int32.(to_int ((param.node_offset lsr 16) land 0xFFl)); Int32.(to_int ((param.node_offset lsr 24) land 0xFFl)) (* store to little-endian *); (param.xof_length lsr 0) land 0xFF; (param.xof_length lsr 8) land 0xFF; param.node_depth land 0xFF; param.inner_length land 0xFF; param.salt.(0) land 0xFF; param.salt.(1) land 0xFF; param.salt.(2) land 0xFF; param.salt.(3) land 0xFF; param.salt.(4) land 0xFF; param.salt.(5) land 0xFF; param.salt.(6) land 0xFF; param.salt.(7) land 0xFF; param.personal.(0) land 0xFF; param.personal.(1) land 0xFF; param.personal.(2) land 0xFF; param.personal.(3) land 0xFF; param.personal.(4) land 0xFF; param.personal.(5) land 0xFF; param.personal.(6) land 0xFF; param.personal.(7) land 0xFF; |] in By.init 32 (fun i -> Char.unsafe_chr arr.(i)) let max_outlen = 32 let default_param = { digest_length = max_outlen; key_length = 0; fanout = 1; depth = 1; leaf_length = 0l; node_offset = 0l; xof_length = 0; node_depth = 0; inner_length = 0; salt = [| 0; 0; 0; 0; 0; 0; 0; 0 |]; personal = [| 0; 0; 0; 0; 0; 0; 0; 0 |]; } let iv = [| 0x6A09E667l; 0xBB67AE85l; 0x3C6EF372l; 0xA54FF53Al; 0x510E527Fl; 0x9B05688Cl; 0x1F83D9ABl; 0x5BE0CD19l; |] let increment_counter ctx inc = let open Int32 in ctx.t.(0) <- ctx.t.(0) + inc ; ctx.t.(1) <- (ctx.t.(1) + if ctx.t.(0) < inc then 1l else 0l) let set_lastnode ctx = ctx.f.(1) <- Int32.minus_one let set_lastblock ctx = if ctx.last_node <> 0 then set_lastnode ctx ; ctx.f.(0) <- Int32.minus_one let init () = let buf = By.make 64 '\x00' in let ctx = { buflen = 0; outlen = default_param.digest_length; last_node = 0; buf; h = Array.make 8 0l; t = Array.make 2 0l; f = Array.make 2 0l; } in let param_bytes = param_to_bytes default_param in for i = 0 to 7 do ctx.h.(i) <- Int32.(iv.(i) lxor By.le32_to_cpu param_bytes (i * 4)) done ; ctx let sigma = [| [| 0; 1; 2; 3; 4; 5; 6; 7; 8; 9; 10; 11; 12; 13; 14; 15 |]; [| 14; 10; 4; 8; 9; 15; 13; 6; 1; 12; 0; 2; 11; 7; 5; 3 |]; [| 11; 8; 12; 0; 5; 2; 15; 13; 10; 14; 3; 6; 7; 1; 9; 4 |]; [| 7; 9; 3; 1; 13; 12; 11; 14; 2; 6; 5; 10; 4; 0; 15; 8 |]; [| 9; 0; 5; 7; 2; 4; 10; 15; 14; 1; 11; 12; 6; 8; 3; 13 |]; [| 2; 12; 6; 10; 0; 11; 8; 3; 4; 13; 7; 5; 15; 14; 1; 9 |]; [| 12; 5; 1; 15; 14; 13; 4; 10; 0; 7; 6; 3; 9; 2; 8; 11 |]; [| 13; 11; 7; 14; 12; 1; 3; 9; 5; 0; 15; 4; 8; 6; 2; 10 |]; [| 6; 15; 14; 9; 11; 3; 0; 8; 12; 2; 13; 7; 1; 4; 10; 5 |]; [| 10; 2; 8; 4; 7; 6; 1; 5; 15; 11; 9; 14; 3; 12; 13; 0 |]; |] let compress : type a. le32_to_cpu:(a -> int -> int32) -> ctx -> a -> int -> unit = fun ~le32_to_cpu ctx block off -> let v = Array.make 16 0l in let m = Array.make 16 0l in let g r i a_idx b_idx c_idx d_idx = let ( ++ ) = ( + ) in let open Int32 in v.(a_idx) <- v.(a_idx) + v.(b_idx) + m.(sigma.(r).((2 * i) ++ 0)) ; v.(d_idx) <- ror32 (v.(d_idx) lxor v.(a_idx)) 16 ; v.(c_idx) <- v.(c_idx) + v.(d_idx) ; v.(b_idx) <- ror32 (v.(b_idx) lxor v.(c_idx)) 12 ; v.(a_idx) <- v.(a_idx) + v.(b_idx) + m.(sigma.(r).((2 * i) ++ 1)) ; v.(d_idx) <- ror32 (v.(d_idx) lxor v.(a_idx)) 8 ; v.(c_idx) <- v.(c_idx) + v.(d_idx) ; v.(b_idx) <- ror32 (v.(b_idx) lxor v.(c_idx)) 7 in let r r = g r 0 0 4 8 12 ; g r 1 1 5 9 13 ; g r 2 2 6 10 14 ; g r 3 3 7 11 15 ; g r 4 0 5 10 15 ; g r 5 1 6 11 12 ; g r 6 2 7 8 13 ; g r 7 3 4 9 14 in for i = 0 to 15 do m.(i) <- le32_to_cpu block (off + (i * 4)) done ; for i = 0 to 7 do v.(i) <- ctx.h.(i) done ; v.(8) <- iv.(0) ; v.(9) <- iv.(1) ; v.(10) <- iv.(2) ; v.(11) <- iv.(3) ; v.(12) <- Int32.(iv.(4) lxor ctx.t.(0)) ; v.(13) <- Int32.(iv.(5) lxor ctx.t.(1)) ; v.(14) <- Int32.(iv.(6) lxor ctx.f.(0)) ; v.(15) <- Int32.(iv.(7) lxor ctx.f.(1)) ; r 0 ; r 1 ; r 2 ; r 3 ; r 4 ; r 5 ; r 6 ; r 7 ; r 8 ; r 9 ; let ( ++ ) = ( + ) in for i = 0 to 7 do ctx.h.(i) <- Int32.(ctx.h.(i) lxor v.(i) lxor v.(i ++ 8)) done ; () let feed : type a. blit:(a -> int -> By.t -> int -> int -> unit) -> le32_to_cpu:(a -> int -> int32) -> ctx -> a -> int -> int -> unit = fun ~blit ~le32_to_cpu ctx buf off len -> let in_off = ref off in let in_len = ref len in if !in_len > 0 then ( let left = ctx.buflen in let fill = 64 - left in if !in_len > fill then ( ctx.buflen <- 0 ; blit buf !in_off ctx.buf left fill ; increment_counter ctx 64l ; compress ~le32_to_cpu:By.le32_to_cpu ctx ctx.buf 0 ; in_off := !in_off + fill ; in_len := !in_len - fill ; while !in_len > 64 do increment_counter ctx 64l ; compress ~le32_to_cpu ctx buf !in_off ; in_off := !in_off + 64 ; in_len := !in_len - 64 done) ; blit buf !in_off ctx.buf ctx.buflen !in_len ; ctx.buflen <- ctx.buflen + !in_len) ; () let unsafe_feed_bytes = feed ~blit:By.blit ~le32_to_cpu:By.le32_to_cpu let unsafe_feed_bigstring = feed ~blit:By.blit_from_bigstring ~le32_to_cpu:Bi.le32_to_cpu let with_outlen_and_key ~blit outlen key off len = if outlen > max_outlen then failwith "out length can not be upper than %d (out length: %d)" max_outlen outlen ; let buf = By.make 64 '\x00' in let ctx = { buflen = 0; outlen; last_node = 0; buf; h = Array.make 8 0l; t = Array.make 2 0l; f = Array.make 2 0l; } in let param_bytes = param_to_bytes { default_param with key_length = len; digest_length = outlen } in for i = 0 to 7 do ctx.h.(i) <- Int32.(iv.(i) lxor By.le32_to_cpu param_bytes (i * 4)) done ; if len > 0 then ( let block = By.make 64 '\x00' in blit key off block 0 len ; unsafe_feed_bytes ctx block 0 64) ; ctx let with_outlen_and_bytes_key outlen key off len = with_outlen_and_key ~blit:By.blit outlen key off len let with_outlen_and_bigstring_key outlen key off len = with_outlen_and_key ~blit:By.blit_from_bigstring outlen key off len let unsafe_get ctx = let res = By.make default_param.digest_length '\x00' in increment_counter ctx (Int32.of_int ctx.buflen) ; set_lastblock ctx ; By.fill ctx.buf ctx.buflen (64 - ctx.buflen) '\x00' ; compress ~le32_to_cpu:By.le32_to_cpu ctx ctx.buf 0 ; for i = 0 to 7 do By.cpu_to_le32 res (i * 4) ctx.h.(i) done ; if ctx.outlen < default_param.digest_length then By.sub res 0 ctx.outlen else if ctx.outlen > default_param.digest_length then assert false (* XXX(dinosaure): [ctx] can not be initialized with [outlen > digest_length = max_outlen]. *) else res end
null
https://raw.githubusercontent.com/mirage/digestif/a94075cfec70fbcb31e15f94e28cb715c9e4d9dd/src-ocaml/baijiu_blake2s.ml
ocaml
store to little-endian store to little-endian store to little-endian XXX(dinosaure): [ctx] can not be initialized with [outlen > digest_length = max_outlen].
module By = Digestif_by module Bi = Digestif_bi let failwith fmt = Format.kasprintf failwith fmt module Int32 = struct include Int32 let ( lsl ) = Int32.shift_left let ( lsr ) = Int32.shift_right_logical let ( asr ) = Int32.shift_right let ( lor ) = Int32.logor let ( lxor ) = Int32.logxor let ( land ) = Int32.logand let lnot = Int32.lognot let ( + ) = Int32.add let rol32 a n = (a lsl n) lor (a lsr (32 - n)) let ror32 a n = (a lsr n) lor (a lsl (32 - n)) end module Int64 = struct include Int64 let ( land ) = Int64.logand let ( lsl ) = Int64.shift_left let ( lsr ) = Int64.shift_right_logical let ( lor ) = Int64.logor let ( asr ) = Int64.shift_right let ( lxor ) = Int64.logxor let ( + ) = Int64.add let rol64 a n = (a lsl n) lor (a lsr (64 - n)) let ror64 a n = (a lsr n) lor (a lsl (64 - n)) end module type S = sig type ctx type kind = [ `BLAKE2S ] val init : unit -> ctx val with_outlen_and_bytes_key : int -> By.t -> int -> int -> ctx val with_outlen_and_bigstring_key : int -> Bi.t -> int -> int -> ctx val unsafe_feed_bytes : ctx -> By.t -> int -> int -> unit val unsafe_feed_bigstring : ctx -> Bi.t -> int -> int -> unit val unsafe_get : ctx -> By.t val dup : ctx -> ctx val max_outlen : int end module Unsafe : S = struct type kind = [ `BLAKE2S ] type param = { digest_length : int; key_length : int; fanout : int; depth : int; leaf_length : int32; node_offset : int32; xof_length : int; node_depth : int; inner_length : int; salt : int array; personal : int array; } type ctx = { mutable buflen : int; outlen : int; mutable last_node : int; buf : Bytes.t; h : int32 array; t : int32 array; f : int32 array; } let dup ctx = { buflen = ctx.buflen; outlen = ctx.outlen; last_node = ctx.last_node; buf = By.copy ctx.buf; h = Array.copy ctx.h; t = Array.copy ctx.t; f = Array.copy ctx.f; } let param_to_bytes param = let arr = [| param.digest_length land 0xFF; param.key_length land 0xFF; param.fanout land 0xFF; Int32.(to_int ((param.leaf_length lsr 0) land 0xFFl)); Int32.(to_int ((param.leaf_length lsr 8) land 0xFFl)); Int32.(to_int ((param.leaf_length lsr 16) land 0xFFl)); Int32.(to_int ((param.leaf_length lsr 24) land 0xFFl)) Int32.(to_int ((param.node_offset lsr 0) land 0xFFl)); Int32.(to_int ((param.node_offset lsr 8) land 0xFFl)); Int32.(to_int ((param.node_offset lsr 16) land 0xFFl)); Int32.(to_int ((param.node_offset lsr 24) land 0xFFl)) (param.xof_length lsr 8) land 0xFF; param.node_depth land 0xFF; param.inner_length land 0xFF; param.salt.(0) land 0xFF; param.salt.(1) land 0xFF; param.salt.(2) land 0xFF; param.salt.(3) land 0xFF; param.salt.(4) land 0xFF; param.salt.(5) land 0xFF; param.salt.(6) land 0xFF; param.salt.(7) land 0xFF; param.personal.(0) land 0xFF; param.personal.(1) land 0xFF; param.personal.(2) land 0xFF; param.personal.(3) land 0xFF; param.personal.(4) land 0xFF; param.personal.(5) land 0xFF; param.personal.(6) land 0xFF; param.personal.(7) land 0xFF; |] in By.init 32 (fun i -> Char.unsafe_chr arr.(i)) let max_outlen = 32 let default_param = { digest_length = max_outlen; key_length = 0; fanout = 1; depth = 1; leaf_length = 0l; node_offset = 0l; xof_length = 0; node_depth = 0; inner_length = 0; salt = [| 0; 0; 0; 0; 0; 0; 0; 0 |]; personal = [| 0; 0; 0; 0; 0; 0; 0; 0 |]; } let iv = [| 0x6A09E667l; 0xBB67AE85l; 0x3C6EF372l; 0xA54FF53Al; 0x510E527Fl; 0x9B05688Cl; 0x1F83D9ABl; 0x5BE0CD19l; |] let increment_counter ctx inc = let open Int32 in ctx.t.(0) <- ctx.t.(0) + inc ; ctx.t.(1) <- (ctx.t.(1) + if ctx.t.(0) < inc then 1l else 0l) let set_lastnode ctx = ctx.f.(1) <- Int32.minus_one let set_lastblock ctx = if ctx.last_node <> 0 then set_lastnode ctx ; ctx.f.(0) <- Int32.minus_one let init () = let buf = By.make 64 '\x00' in let ctx = { buflen = 0; outlen = default_param.digest_length; last_node = 0; buf; h = Array.make 8 0l; t = Array.make 2 0l; f = Array.make 2 0l; } in let param_bytes = param_to_bytes default_param in for i = 0 to 7 do ctx.h.(i) <- Int32.(iv.(i) lxor By.le32_to_cpu param_bytes (i * 4)) done ; ctx let sigma = [| [| 0; 1; 2; 3; 4; 5; 6; 7; 8; 9; 10; 11; 12; 13; 14; 15 |]; [| 14; 10; 4; 8; 9; 15; 13; 6; 1; 12; 0; 2; 11; 7; 5; 3 |]; [| 11; 8; 12; 0; 5; 2; 15; 13; 10; 14; 3; 6; 7; 1; 9; 4 |]; [| 7; 9; 3; 1; 13; 12; 11; 14; 2; 6; 5; 10; 4; 0; 15; 8 |]; [| 9; 0; 5; 7; 2; 4; 10; 15; 14; 1; 11; 12; 6; 8; 3; 13 |]; [| 2; 12; 6; 10; 0; 11; 8; 3; 4; 13; 7; 5; 15; 14; 1; 9 |]; [| 12; 5; 1; 15; 14; 13; 4; 10; 0; 7; 6; 3; 9; 2; 8; 11 |]; [| 13; 11; 7; 14; 12; 1; 3; 9; 5; 0; 15; 4; 8; 6; 2; 10 |]; [| 6; 15; 14; 9; 11; 3; 0; 8; 12; 2; 13; 7; 1; 4; 10; 5 |]; [| 10; 2; 8; 4; 7; 6; 1; 5; 15; 11; 9; 14; 3; 12; 13; 0 |]; |] let compress : type a. le32_to_cpu:(a -> int -> int32) -> ctx -> a -> int -> unit = fun ~le32_to_cpu ctx block off -> let v = Array.make 16 0l in let m = Array.make 16 0l in let g r i a_idx b_idx c_idx d_idx = let ( ++ ) = ( + ) in let open Int32 in v.(a_idx) <- v.(a_idx) + v.(b_idx) + m.(sigma.(r).((2 * i) ++ 0)) ; v.(d_idx) <- ror32 (v.(d_idx) lxor v.(a_idx)) 16 ; v.(c_idx) <- v.(c_idx) + v.(d_idx) ; v.(b_idx) <- ror32 (v.(b_idx) lxor v.(c_idx)) 12 ; v.(a_idx) <- v.(a_idx) + v.(b_idx) + m.(sigma.(r).((2 * i) ++ 1)) ; v.(d_idx) <- ror32 (v.(d_idx) lxor v.(a_idx)) 8 ; v.(c_idx) <- v.(c_idx) + v.(d_idx) ; v.(b_idx) <- ror32 (v.(b_idx) lxor v.(c_idx)) 7 in let r r = g r 0 0 4 8 12 ; g r 1 1 5 9 13 ; g r 2 2 6 10 14 ; g r 3 3 7 11 15 ; g r 4 0 5 10 15 ; g r 5 1 6 11 12 ; g r 6 2 7 8 13 ; g r 7 3 4 9 14 in for i = 0 to 15 do m.(i) <- le32_to_cpu block (off + (i * 4)) done ; for i = 0 to 7 do v.(i) <- ctx.h.(i) done ; v.(8) <- iv.(0) ; v.(9) <- iv.(1) ; v.(10) <- iv.(2) ; v.(11) <- iv.(3) ; v.(12) <- Int32.(iv.(4) lxor ctx.t.(0)) ; v.(13) <- Int32.(iv.(5) lxor ctx.t.(1)) ; v.(14) <- Int32.(iv.(6) lxor ctx.f.(0)) ; v.(15) <- Int32.(iv.(7) lxor ctx.f.(1)) ; r 0 ; r 1 ; r 2 ; r 3 ; r 4 ; r 5 ; r 6 ; r 7 ; r 8 ; r 9 ; let ( ++ ) = ( + ) in for i = 0 to 7 do ctx.h.(i) <- Int32.(ctx.h.(i) lxor v.(i) lxor v.(i ++ 8)) done ; () let feed : type a. blit:(a -> int -> By.t -> int -> int -> unit) -> le32_to_cpu:(a -> int -> int32) -> ctx -> a -> int -> int -> unit = fun ~blit ~le32_to_cpu ctx buf off len -> let in_off = ref off in let in_len = ref len in if !in_len > 0 then ( let left = ctx.buflen in let fill = 64 - left in if !in_len > fill then ( ctx.buflen <- 0 ; blit buf !in_off ctx.buf left fill ; increment_counter ctx 64l ; compress ~le32_to_cpu:By.le32_to_cpu ctx ctx.buf 0 ; in_off := !in_off + fill ; in_len := !in_len - fill ; while !in_len > 64 do increment_counter ctx 64l ; compress ~le32_to_cpu ctx buf !in_off ; in_off := !in_off + 64 ; in_len := !in_len - 64 done) ; blit buf !in_off ctx.buf ctx.buflen !in_len ; ctx.buflen <- ctx.buflen + !in_len) ; () let unsafe_feed_bytes = feed ~blit:By.blit ~le32_to_cpu:By.le32_to_cpu let unsafe_feed_bigstring = feed ~blit:By.blit_from_bigstring ~le32_to_cpu:Bi.le32_to_cpu let with_outlen_and_key ~blit outlen key off len = if outlen > max_outlen then failwith "out length can not be upper than %d (out length: %d)" max_outlen outlen ; let buf = By.make 64 '\x00' in let ctx = { buflen = 0; outlen; last_node = 0; buf; h = Array.make 8 0l; t = Array.make 2 0l; f = Array.make 2 0l; } in let param_bytes = param_to_bytes { default_param with key_length = len; digest_length = outlen } in for i = 0 to 7 do ctx.h.(i) <- Int32.(iv.(i) lxor By.le32_to_cpu param_bytes (i * 4)) done ; if len > 0 then ( let block = By.make 64 '\x00' in blit key off block 0 len ; unsafe_feed_bytes ctx block 0 64) ; ctx let with_outlen_and_bytes_key outlen key off len = with_outlen_and_key ~blit:By.blit outlen key off len let with_outlen_and_bigstring_key outlen key off len = with_outlen_and_key ~blit:By.blit_from_bigstring outlen key off len let unsafe_get ctx = let res = By.make default_param.digest_length '\x00' in increment_counter ctx (Int32.of_int ctx.buflen) ; set_lastblock ctx ; By.fill ctx.buf ctx.buflen (64 - ctx.buflen) '\x00' ; compress ~le32_to_cpu:By.le32_to_cpu ctx ctx.buf 0 ; for i = 0 to 7 do By.cpu_to_le32 res (i * 4) ctx.h.(i) done ; if ctx.outlen < default_param.digest_length then By.sub res 0 ctx.outlen else if ctx.outlen > default_param.digest_length then assert false else res end
5cb2331715b6ddf681e7c3d65695374eefc0df780077b71720bcaf1c642b4f1e
flosell/lambdacd
state_test.cljs
(ns lambdacd.state-test (:require [cljs.test :refer-macros [deftest is testing run-tests]] [dommy.core :refer-macros [sel sel1]] [lambdacd.testdata :refer [some-build-step with-step-id with-status with-children]] [lambdacd.state :as state])) (def cwd-child-a {:name "do-stuff" :step-id [1 1 1] :children []}) (def cwd-child-b {:name "do-other-stuff" :step-id [1 2 1] :result {:status :running :some-key :some-value} :children []}) (def parallel-child-a {:name "in-cwd" :step-id [1 1] :children [cwd-child-a]}) (def parallel-child-b {:name "in-cwd" :step-id [2 1] :children [cwd-child-b]}) (def root-step {:name "in-parallel" :step-id [1] :children [parallel-child-a parallel-child-b]}) (def root-step2 {:name "some-step" :step-id [2] :children []}) (def step-with-running-children (-> some-build-step (with-step-id [1]) (with-status "running") (with-children [(-> some-build-step (with-step-id [1 1]) (with-status "failure")) (-> some-build-step (with-step-id [2 1]) (with-status "running"))]))) (def waiting-step (-> some-build-step (with-step-id [1]) (with-status "waiting"))) (def some-pipeline-state [root-step root-step2]) (def flattened-pipeline-state [root-step parallel-child-a cwd-child-a parallel-child-b cwd-child-b root-step2]) (deftest flatten-test (testing "that we can flatten a pipeline-state-representation" (is (= flattened-pipeline-state (into [] (state/flatten-state some-pipeline-state)))))) (deftest get-by-step-id-test (testing "that we can find a step by it's id even if it's nested" (is (= cwd-child-b (state/find-by-step-id some-pipeline-state [1 2 1]))))) (deftest is-active-test (testing "that running steps are active" (is (= true (state/is-active? (-> some-build-step (with-status "running")))))) (testing "that waiting steps are active" (is (= true (state/is-active? (-> some-build-step (with-status "waiting")))))) (testing "that finished steps are inactive" (is (= false (state/is-active? (-> some-build-step (with-status "success"))))) (is (= false (state/is-active? (-> some-build-step (with-status "failure"))))) (is (= false (state/is-active? (-> some-build-step (with-status "killed")))))) (testing "that steps with undefined state are inactive" (is (= false (state/is-active? (-> some-build-step (with-status nil)))))))
null
https://raw.githubusercontent.com/flosell/lambdacd/e9ba3cebb2d5f0070a2e0e1e08fc85fc99ee7135/test/cljs/lambdacd/state_test.cljs
clojure
(ns lambdacd.state-test (:require [cljs.test :refer-macros [deftest is testing run-tests]] [dommy.core :refer-macros [sel sel1]] [lambdacd.testdata :refer [some-build-step with-step-id with-status with-children]] [lambdacd.state :as state])) (def cwd-child-a {:name "do-stuff" :step-id [1 1 1] :children []}) (def cwd-child-b {:name "do-other-stuff" :step-id [1 2 1] :result {:status :running :some-key :some-value} :children []}) (def parallel-child-a {:name "in-cwd" :step-id [1 1] :children [cwd-child-a]}) (def parallel-child-b {:name "in-cwd" :step-id [2 1] :children [cwd-child-b]}) (def root-step {:name "in-parallel" :step-id [1] :children [parallel-child-a parallel-child-b]}) (def root-step2 {:name "some-step" :step-id [2] :children []}) (def step-with-running-children (-> some-build-step (with-step-id [1]) (with-status "running") (with-children [(-> some-build-step (with-step-id [1 1]) (with-status "failure")) (-> some-build-step (with-step-id [2 1]) (with-status "running"))]))) (def waiting-step (-> some-build-step (with-step-id [1]) (with-status "waiting"))) (def some-pipeline-state [root-step root-step2]) (def flattened-pipeline-state [root-step parallel-child-a cwd-child-a parallel-child-b cwd-child-b root-step2]) (deftest flatten-test (testing "that we can flatten a pipeline-state-representation" (is (= flattened-pipeline-state (into [] (state/flatten-state some-pipeline-state)))))) (deftest get-by-step-id-test (testing "that we can find a step by it's id even if it's nested" (is (= cwd-child-b (state/find-by-step-id some-pipeline-state [1 2 1]))))) (deftest is-active-test (testing "that running steps are active" (is (= true (state/is-active? (-> some-build-step (with-status "running")))))) (testing "that waiting steps are active" (is (= true (state/is-active? (-> some-build-step (with-status "waiting")))))) (testing "that finished steps are inactive" (is (= false (state/is-active? (-> some-build-step (with-status "success"))))) (is (= false (state/is-active? (-> some-build-step (with-status "failure"))))) (is (= false (state/is-active? (-> some-build-step (with-status "killed")))))) (testing "that steps with undefined state are inactive" (is (= false (state/is-active? (-> some-build-step (with-status nil)))))))
70164da0f27cd9b6f7ad5aff99a35b38857cee66d0b1cb80a26fcee0ca447d74
softwarelanguageslab/maf
R5RS_various_regex-1.scm
; Changes: * removed : 1 * added : 3 * swaps : 0 * negated predicates : 2 ; * swapped branches: 0 ; * calls to id fun: 0 (letrec ((debug-trace (lambda () 'do-nothing)) (regex-NULL #f) (regex-BLANK #t) (regex-alt? (lambda (re) (if (pair? re) (eq? (car re) 'alt) #f))) (regex-seq? (lambda (re) (if (pair? re) (eq? (car re) 'seq) #f))) (regex-rep? (lambda (re) (if (<change> (pair? re) (not (pair? re))) (eq? (car re) 'rep) #f))) (regex-null? (lambda (re) (eq? re #f))) (regex-empty? (lambda (re) (eq? re #t))) (regex-atom? (lambda (re) (let ((__or_res (char? re))) (if __or_res __or_res (symbol? re))))) (match-seq (lambda (re f) (if (regex-seq? re) (f (cadr re) (caddr re)) #f))) (match-alt (lambda (re f) (if (regex-alt? re) (f (cadr re) (caddr re)) #f))) (match-rep (lambda (re f) (if (regex-rep? re) (f (cadr re)) #f))) (seq (lambda (pat1 pat2) (if (regex-null? pat1) regex-NULL (if (regex-null? pat2) regex-NULL (if (regex-empty? pat1) pat2 (if (regex-empty? pat2) pat1 (cons 'seq (cons pat1 (cons pat2 ()))))))))) (alt (lambda (pat1 pat2) (if (regex-null? pat1) pat2 (if (regex-null? pat2) pat1 (cons 'alt (cons pat1 (cons pat2 ()))))))) (rep (lambda (pat) (if (regex-null? pat) regex-BLANK (if (regex-empty? pat) regex-BLANK (cons 'rep (cons pat ())))))) (regex-empty (lambda (re) (if (regex-empty? re) #t (if (regex-null? re) #f (if (regex-atom? re) #f (let ((__cond-empty-body (match-seq re (lambda (pat1 pat2) (seq (regex-empty pat1) (regex-empty pat2)))))) (if (<change> __cond-empty-body (not __cond-empty-body)) __cond-empty-body (let ((__cond-empty-body (match-alt re (lambda (pat1 pat2) (<change> () (display (regex-empty pat1))) (<change> () (alt (regex-empty pat1) (regex-empty pat2))) (alt (regex-empty pat1) (regex-empty pat2)))))) (if __cond-empty-body __cond-empty-body (if (regex-rep? re) #t #f)))))))))) (regex-derivative (lambda (re c) (<change> (debug-trace) ()) (if (regex-empty? re) regex-NULL (if (regex-null? re) regex-NULL (if (eq? c re) regex-BLANK (if (regex-atom? re) regex-NULL (let ((__cond-empty-body (match-seq re (lambda (pat1 pat2) (alt (seq (d/dc pat1 c) pat2) (seq (regex-empty pat1) (d/dc pat2 c))))))) (if __cond-empty-body __cond-empty-body (let ((__cond-empty-body (match-alt re (lambda (pat1 pat2) (alt (d/dc pat1 c) (d/dc pat2 c)))))) (if __cond-empty-body __cond-empty-body (let ((__cond-empty-body (match-rep re (lambda (pat) (seq (d/dc pat c) (rep pat)))))) (if __cond-empty-body __cond-empty-body regex-NULL)))))))))))) (d/dc regex-derivative) (regex-match (lambda (pattern data) (<change> () (display regex-match)) (if (null? data) (regex-empty? (regex-empty pattern)) (regex-match (d/dc pattern (car data)) (cdr data))))) (check-expect (lambda (check expect) (equal? check expect))) (res (check-expect (regex-match (__toplevel_cons 'seq (__toplevel_cons 'foo (__toplevel_cons (__toplevel_cons 'rep (__toplevel_cons 'bar ())) ()))) (__toplevel_cons 'foo (__toplevel_cons 'bar ()))) #t))) res)
null
https://raw.githubusercontent.com/softwarelanguageslab/maf/11acedf56b9bf0c8e55ddb6aea754b6766d8bb40/test/changes/scheme/generated/R5RS_various_regex-1.scm
scheme
Changes: * swapped branches: 0 * calls to id fun: 0
* removed : 1 * added : 3 * swaps : 0 * negated predicates : 2 (letrec ((debug-trace (lambda () 'do-nothing)) (regex-NULL #f) (regex-BLANK #t) (regex-alt? (lambda (re) (if (pair? re) (eq? (car re) 'alt) #f))) (regex-seq? (lambda (re) (if (pair? re) (eq? (car re) 'seq) #f))) (regex-rep? (lambda (re) (if (<change> (pair? re) (not (pair? re))) (eq? (car re) 'rep) #f))) (regex-null? (lambda (re) (eq? re #f))) (regex-empty? (lambda (re) (eq? re #t))) (regex-atom? (lambda (re) (let ((__or_res (char? re))) (if __or_res __or_res (symbol? re))))) (match-seq (lambda (re f) (if (regex-seq? re) (f (cadr re) (caddr re)) #f))) (match-alt (lambda (re f) (if (regex-alt? re) (f (cadr re) (caddr re)) #f))) (match-rep (lambda (re f) (if (regex-rep? re) (f (cadr re)) #f))) (seq (lambda (pat1 pat2) (if (regex-null? pat1) regex-NULL (if (regex-null? pat2) regex-NULL (if (regex-empty? pat1) pat2 (if (regex-empty? pat2) pat1 (cons 'seq (cons pat1 (cons pat2 ()))))))))) (alt (lambda (pat1 pat2) (if (regex-null? pat1) pat2 (if (regex-null? pat2) pat1 (cons 'alt (cons pat1 (cons pat2 ()))))))) (rep (lambda (pat) (if (regex-null? pat) regex-BLANK (if (regex-empty? pat) regex-BLANK (cons 'rep (cons pat ())))))) (regex-empty (lambda (re) (if (regex-empty? re) #t (if (regex-null? re) #f (if (regex-atom? re) #f (let ((__cond-empty-body (match-seq re (lambda (pat1 pat2) (seq (regex-empty pat1) (regex-empty pat2)))))) (if (<change> __cond-empty-body (not __cond-empty-body)) __cond-empty-body (let ((__cond-empty-body (match-alt re (lambda (pat1 pat2) (<change> () (display (regex-empty pat1))) (<change> () (alt (regex-empty pat1) (regex-empty pat2))) (alt (regex-empty pat1) (regex-empty pat2)))))) (if __cond-empty-body __cond-empty-body (if (regex-rep? re) #t #f)))))))))) (regex-derivative (lambda (re c) (<change> (debug-trace) ()) (if (regex-empty? re) regex-NULL (if (regex-null? re) regex-NULL (if (eq? c re) regex-BLANK (if (regex-atom? re) regex-NULL (let ((__cond-empty-body (match-seq re (lambda (pat1 pat2) (alt (seq (d/dc pat1 c) pat2) (seq (regex-empty pat1) (d/dc pat2 c))))))) (if __cond-empty-body __cond-empty-body (let ((__cond-empty-body (match-alt re (lambda (pat1 pat2) (alt (d/dc pat1 c) (d/dc pat2 c)))))) (if __cond-empty-body __cond-empty-body (let ((__cond-empty-body (match-rep re (lambda (pat) (seq (d/dc pat c) (rep pat)))))) (if __cond-empty-body __cond-empty-body regex-NULL)))))))))))) (d/dc regex-derivative) (regex-match (lambda (pattern data) (<change> () (display regex-match)) (if (null? data) (regex-empty? (regex-empty pattern)) (regex-match (d/dc pattern (car data)) (cdr data))))) (check-expect (lambda (check expect) (equal? check expect))) (res (check-expect (regex-match (__toplevel_cons 'seq (__toplevel_cons 'foo (__toplevel_cons (__toplevel_cons 'rep (__toplevel_cons 'bar ())) ()))) (__toplevel_cons 'foo (__toplevel_cons 'bar ()))) #t))) res)
d04b0f059b453afcd60ba4c5451def5ece545f3bc6fea652a8082c593024c973
K2InformaticsGmbH/imem
imem_meta_ct.erl
%%%------------------------------------------------------------------- %%% File : imem_meta_ct.erl %%% Description : Common testing imem_meta. %%% %%% Created : 09.11.2017 %%% Copyright ( C ) 2017 K2 Informatics GmbH %%%------------------------------------------------------------------- -module(imem_meta_ct). -include_lib("common_test/include/ct.hrl"). -include_lib("eunit/include/eunit.hrl"). -export([ end_per_testcase/2 , meta_concurrency/1 , meta_operations/1 , meta_partitions/1 , meta_preparations/1 , physical_table_names/1 ]). -define(LOG_TABLE_OPTS, [{record_name, ddLog} , {type, ordered_set} 430000 = 5 Days - 2000 sec ]). -define(TPTEST, tpTest). -define(TPTEST_1, tpTest_1). -define(TPTEST_2, tpTest_2). -define(TPTEST_3, tpTest_3). -define(TPTEST_3@, tpTest_3@). -define(TPTEST_100@, tpTest_100@). -define(TPTEST_1000@, tpTest_1000@). -define(TPTEST_999999999@_, tpTest_999999999@_). -define(TPTEST_1999999998@_, tpTest_1999999998@_). -define(TPTEST_1IDX, tpTest_1Idx). -define(NODEBUG, true). -define(TEST_SLAVE_IMEM_NODE_NAME, "metaslave"). -include_lib("imem.hrl"). -include_lib("imem_meta.hrl"). -include("imem_ct.hrl"). %%-------------------------------------------------------------------- %% Test case related setup and teardown functions. %%-------------------------------------------------------------------- end_per_testcase(TestCase, _Config) -> ?CTPAL("End ~p",[TestCase]), catch imem_meta:drop_table(?TPTEST_1), catch imem_meta:drop_table(?TPTEST_2), catch imem_meta:drop_table(?TPTEST_3), catch imem_meta:drop_table(?TPTEST_1000@), catch imem_meta:drop_table(?TPTEST_999999999@_), catch imem_meta:drop_table(?TPTEST_100@), catch imem_meta:drop_table(?TPTEST_3@), catch imem_test_slave:stop(?TEST_SLAVE_IMEM_NODE_NAME), ok. %%==================================================================== %% Test cases. %%==================================================================== physical_table_names(_Config) -> ?CTPAL("Start test single node"), LocalCacheStr = "ddCache@"++imem_meta:node_shard(), LocalCacheName = list_to_atom(LocalCacheStr), % ddCache@WKS018 ?assertEqual([ddTable], imem_meta:physical_table_names(ddTable)), ?assertEqual([ddTable], imem_meta:physical_table_names("ddTable")), ?assertEqual([ddTable], imem_meta:physical_table_names(<<"ddTable">>)), ?assertEqual([ddTable], imem_meta:physical_table_names({imem_meta:schema(), ddTable})), [ ?assertEqual([Type], imem_meta:physical_table_names(atom_to_list(Type))) || Type <- ?DataTypes ], ?assertEqual([LocalCacheName], imem_meta:physical_table_names(ddCache@local)), ?assertEqual([LocalCacheName], imem_meta:physical_table_names(LocalCacheStr)), ?assertEqual([LocalCacheName], imem_meta:physical_table_names(LocalCacheName)), ?assertEqual([LocalCacheName], imem_meta:physical_table_names({imem_meta:schema(), LocalCacheName})), ?assertEqual([], imem_meta:physical_table_names("ddCache@123")), ?assertEqual([LocalCacheName], imem_meta:physical_table_names("ddCache@")), ?assertEqual([s_tab_1568764800@_], imem_meta:simple_or_local_node_sharded_tables(s_tab_1568764800@_)), Result1 = [{node(),imem_meta:schema(),ddTable}], ?assertEqual(Result1, imem_meta:cluster_table_names(ddTable)), ?assertEqual(Result1, imem_meta:cluster_table_names("ddTable")), ?assertEqual(Result1, imem_meta:cluster_table_names(<<"ddTable">>)), [ ?assertEqual([{node(),imem_meta:schema(),Type}], imem_meta:cluster_table_names(atom_to_list(Type))) || Type <- ?DataTypes ], ?assertEqual([{node(),imem_meta:schema(),LocalCacheName}], imem_meta:cluster_table_names(ddCache@local)), ?assertEqual([{node(),imem_meta:schema(),LocalCacheName}], imem_meta:cluster_table_names(LocalCacheStr)), ?assertEqual([{node(),imem_meta:schema(),LocalCacheName}], imem_meta:cluster_table_names(LocalCacheName)), ?assertEqual([], imem_meta:cluster_table_names("ddCache@123")), ?assertEqual([{node(),imem_meta:schema(),LocalCacheName}], imem_meta:cluster_table_names("ddCache@")), ?assertEqual([{node(),<<"csv$">>,<<"\"TestCsvFile.csv\"">>}], imem_meta:cluster_table_names(<<"csv$.\"TestCsvFile.csv\"">>)), ?CTPAL("Start test slave node"), ?assertNot(imem_test_slave:is_running(?TEST_SLAVE_IMEM_NODE_NAME)), Slave = imem_test_slave:start(?TEST_SLAVE_IMEM_NODE_NAME), ?CTPAL("Slave ~p", [Slave]), ct:sleep(5000), ?CTPAL("slave nodes ~p", [imem_meta:nodes()]), ?assert(imem_test_slave:is_running(?TEST_SLAVE_IMEM_NODE_NAME)), ?CTPAL("data_nodes ~p", [imem_meta:data_nodes()]), ?CTPAL("node_shards ~p", [imem_meta:node_shards()]), ?assert(lists:member({imem_meta:schema(),node()}, imem_meta:data_nodes())), ?assert(lists:member(imem_meta:node_shard(), imem_meta:node_shards())), ?assert(lists:member({imem_meta:schema(), Slave}, imem_meta:data_nodes())), ?assert(lists:member(?TEST_SLAVE_IMEM_NODE_NAME, imem_meta:node_shards())), DDCacheNames = imem_meta:physical_table_names("ddCache@"), SlaveCacheName = list_to_atom("ddCache@" ++ ?TEST_SLAVE_IMEM_NODE_NAME), ?CTPAL("ddCache@ -> ~p", [DDCacheNames]), ?assert(lists:member(LocalCacheName, DDCacheNames)), ?assert(lists:member(SlaveCacheName, DDCacheNames)), ?assertEqual([SlaveCacheName], imem_meta:physical_table_names("ddCache@" ++ ?TEST_SLAVE_IMEM_NODE_NAME)), LogNames = imem_meta:physical_table_names("ddLog_86400@"), LocalLogName = imem_meta:physical_table_name("ddLog_86400@"), [BaseName,_] = string:tokens(atom_to_list(LocalLogName),"@"), SlaveLogName = list_to_atom(BaseName ++ "@" ++ ?TEST_SLAVE_IMEM_NODE_NAME), ?CTPAL("ddLog_86400@ -> ~p", [LogNames]), ?assert(lists:member(LocalLogName, LogNames)), ?assert(lists:member(SlaveLogName, LogNames)), ?assertEqual([SlaveLogName], imem_meta:physical_table_names("ddLog_86400@" ++ ?TEST_SLAVE_IMEM_NODE_NAME)), ?assertEqual([], imem_meta:physical_table_names("ddAccount@" ++ ?TEST_SLAVE_IMEM_NODE_NAME)), ?assertEqual([{Slave,<<"csv$">>,<<"\"TestCsvFile.csv\"">>}], imem_meta:cluster_table_names("csv$.\"TestCsvFile.csv\"@"++?TEST_SLAVE_IMEM_NODE_NAME)), DDCacheClusterNames = imem_meta:cluster_table_names("ddCache@"), ?CTPAL("ddCache@ -> ~p", [DDCacheClusterNames]), ?assert(lists:member({node(),imem_meta:schema(),LocalCacheName}, DDCacheClusterNames)), ?assert(lists:member({Slave,imem_meta:schema(),SlaveCacheName}, DDCacheClusterNames)), ?assertEqual([{Slave,imem_meta:schema(),SlaveCacheName}], imem_meta:cluster_table_names("ddCache@" ++ ?TEST_SLAVE_IMEM_NODE_NAME)), LogClusterNames = imem_meta:cluster_table_names("ddLog_86400@"), ?CTPAL("ddLog_86400@ -> ~p", [LogClusterNames]), ?assert(lists:member({node(),imem_meta:schema(),LocalLogName}, LogClusterNames)), ?assert(lists:member({Slave,imem_meta:schema(),SlaveLogName}, LogClusterNames)), ?assertEqual([{Slave,imem_meta:schema(),SlaveLogName}], imem_meta:cluster_table_names("ddLog_86400@" ++ ?TEST_SLAVE_IMEM_NODE_NAME)), ?assertEqual([{Slave,imem_meta:schema(),ddAccount}], imem_meta:cluster_table_names("ddAccount@" ++ ?TEST_SLAVE_IMEM_NODE_NAME)), ?assertEqual([{Slave,imem_meta:schema(),integer}], imem_meta:cluster_table_names("integer@" ++ ?TEST_SLAVE_IMEM_NODE_NAME)), ?assertEqual(ok, imem_test_slave:stop(Slave)), ct:sleep(1000), ?assertNot(imem_test_slave:is_running(?TEST_SLAVE_IMEM_NODE_NAME)), ok. meta_concurrency(_Config) -> ?CTPAL("create_table"), ?assertMatch({ok, _}, imem_meta:create_table(?TPTEST_1, [hlk, val], [])), Self = self(), Key = [sum], ?CTPAL("write"), ?assertEqual(ok, imem_meta:write(?TPTEST_1, {?TPTEST_1, Key, 0})), [spawn(fun() -> Self ! {N, read_write_test(?TPTEST_1, Key, N)} end) || N <- lists:seq(1, 10)], ?CTPAL("ReadWriteResult"), ReadWriteResult = receive_results(10, []), ?assertEqual(10, length(ReadWriteResult)), ?assertEqual([{?TPTEST_1, Key, 55}], imem_meta:read(?TPTEST_1, Key)), ?assertEqual([{atomic, ok}], lists:usort([R || {_, R} <- ReadWriteResult])), ?assertEqual(ok, imem_meta:drop_table(?TPTEST_1)), ok. meta_operations(_Config) -> ?CTPAL("Start"), ClEr = 'ClientError', SyEx = 'SystemException', ?CTPAL("schema ~p",[imem_meta:schema()]), ?CTPAL("data nodes ~p", [imem_meta:data_nodes()]), ?assertEqual(true, is_atom(imem_meta:schema())), ?assertEqual(true, lists:member({imem_meta:schema(), node()}, imem_meta:data_nodes())), ?assertEqual([imem_meta:node_shard()], imem_meta:node_shards()), ?assertEqual(ok, imem_meta:check_table_meta(ddTable, record_info(fields, ddTable))), ?assertMatch({ok, _}, imem_meta:create_check_table(?LOG_TABLE, {record_info(fields, ddLog), ?ddLog, #ddLog{}}, ?LOG_TABLE_OPTS, system)), ?assertException(throw, {SyEx, {"Wrong table owner", {_, [system, admin]}}}, imem_meta:create_check_table(?LOG_TABLE, {record_info(fields, ddLog), ?ddLog, #ddLog{}}, [{record_name, ddLog}, {type, ordered_set}], admin)), ?assertException(throw, {SyEx, {"Wrong table options", {_, _}}}, imem_meta:create_check_table(?LOG_TABLE, {record_info(fields, ddLog), ?ddLog, #ddLog{}}, [{record_name, ddLog1}, {type, ordered_set}], system)), ?assertEqual(ok, imem_meta:check_table(?LOG_TABLE)), ?assertEqual(ok, imem_meta:check_table(?CACHE_TABLE)), Now = ?TIME_UID, LogCount1 = imem_meta:table_size(?LOG_TABLE), ?CTPAL("ddLog@ count ~p", [LogCount1]), Fields = [{test_criterium_1, value1}, {test_criterium_2, value2}], LogRec0 = #ddLog{logTime = Now, logLevel = info, pid = self() , module = ?MODULE, function = meta_operations, node = node() , fields = Fields, message = <<"some log message">>}, ?assertEqual(ok, imem_meta:write(?LOG_TABLE, LogRec0)), LogCount2 = imem_meta:table_size(?LOG_TABLE), ?CTPAL("ddLog@ count ~p", [LogCount2]), ?assert(LogCount2 > LogCount1), _Log1 = imem_meta:read(?LOG_TABLE, Now), ?CTPAL("ddLog@ count ~p", [_Log1]), ?assertEqual(ok, imem_meta:log_to_db(info, ?MODULE, test, [{test_3, value3}, {test_4, value4}], "Message")), ?assertEqual(ok, imem_meta:log_to_db(info, ?MODULE, test, [{test_3, value3}, {test_4, value4}], [])), ?assertEqual(ok, imem_meta:log_to_db(info, ?MODULE, test, [{test_3, value3}, {test_4, value4}], [stupid_error_message, 1])), ?assertEqual(ok, imem_meta:log_to_db(info, ?MODULE, test, [{test_3, value3}, {test_4, value4}], {stupid_error_message, 2})), LogCount2a = imem_meta:table_size(?LOG_TABLE), ?assert(LogCount2a >= LogCount2 + 4), ?CTPAL("test_database_operations"), Types1 = [#ddColumn{name = a, type = string, len = 10} %% key value 1 value 2 ], Types2 = [#ddColumn{name = a, type = integer, len = 10} %% key , #ddColumn{name = b2, type = float, len = 8, prec = 3} %% value ], BadTypes0 = [#ddColumn{name = 'a', type = integer, len = 10} ], BadTypes1 = [#ddColumn{name = 'a', type = integer, len = 10} , #ddColumn{name = 'a:b', type = integer, len = 10} ], BadTypes2 = [#ddColumn{name = 'a', type = integer, len = 10} , #ddColumn{name = current, type = integer, len = 10} ], BadTypes3 = [#ddColumn{name = 'a', type = integer, len = 10} , #ddColumn{name = b, type = iinteger, len = 10} ], BadNames1 = [#ddColumn{name = 'a', type = integer, len = 10} , #ddColumn{name = a, type = integer, len = 10} ], ?assertMatch({ok, _}, imem_meta:create_table(?TPTEST_1, Types1, [])), ?assertEqual(ok, imem_meta:create_index(?TPTEST_1, [])), ?assertMatch(ok, imem_meta:check_table(?TPTEST_1IDX)), ?CTPAL("ddTable for ?TPTEST_1 ~p", [imem_meta:read(ddTable, {imem_meta:schema(), ?TPTEST_1})]), ?assertEqual(ok, imem_meta:drop_index(?TPTEST_1)), ?assertException(throw, {'ClientError', {"Table does not exist", ?TPTEST_1IDX}}, imem_meta:check_table(?TPTEST_1IDX)), ?assertEqual(ok, imem_meta:create_index(?TPTEST_1, [])), ?assertException(throw, {'ClientError', {"Index already exists", {?TPTEST_1}}}, imem_meta:create_index(?TPTEST_1, [])), ?assertEqual([], imem_meta:read(?TPTEST_1IDX)), ?assertEqual(ok, imem_meta:write(?TPTEST_1IDX, #ddIndex{stu = {1, 2, 3}})), ?assertEqual([#ddIndex{stu = {1, 2, 3}}], imem_meta:read(?TPTEST_1IDX)), Idx1Def = #ddIdxDef{id = 1, name = <<"string index on b1">>, type = ivk, pl = [<<"b1">>]}, ?assertEqual(ok, imem_meta:create_or_replace_index(?TPTEST_1, [Idx1Def])), ?assertEqual([], imem_meta:read(?TPTEST_1IDX)), ?assertEqual([<<"table">>], imem_index:vnf_lcase_ascii_ne(<<"täble"/utf8>>)), ?assertEqual({?TPTEST_1, "meta", <<"täble"/utf8>>, "1"}, imem_meta:insert(?TPTEST_1, {?TPTEST_1, "meta", <<"täble"/utf8>>, "1"})), ?assertEqual([{?TPTEST_1, "meta", <<"täble"/utf8>>, "1"}], imem_meta:read(?TPTEST_1)), ?assertEqual([#ddIndex{stu = {1, <<"table">>, "meta"}}], imem_meta:read(?TPTEST_1IDX)), ?assertEqual([<<"tuble">>], imem_index:vnf_lcase_ascii_ne(<<"tüble"/utf8>>)), ?assertException(throw, {'ConcurrencyException', {"Data is modified by someone else", _}}, imem_meta:update(?TPTEST_1, {{?TPTEST_1, "meta", <<"tible"/utf8>>, "1"}, {?TPTEST_1, "meta", <<"tüble"/utf8>>, "1"}})), ?assertEqual({?TPTEST_1, "meta", <<"tüble"/utf8>>, "1"}, imem_meta:update(?TPTEST_1, {{?TPTEST_1, "meta", <<"täble"/utf8>>, "1"}, {?TPTEST_1, "meta", <<"tüble"/utf8>>, "1"}})), ?assertEqual([{?TPTEST_1, "meta", <<"tüble"/utf8>>, "1"}], imem_meta:read(?TPTEST_1)), ?assertEqual([#ddIndex{stu = {1, <<"tuble">>, "meta"}}], imem_meta:read(?TPTEST_1IDX)), ?assertEqual(ok, imem_meta:drop_index(?TPTEST_1)), ?assertEqual(ok, imem_meta:create_index(?TPTEST_1, [Idx1Def])), ?assertEqual([#ddIndex{stu = {1, <<"tuble">>, "meta"}}], imem_meta:read(?TPTEST_1IDX)), ?assertException(throw, {'ConcurrencyException', {"Data is modified by someone else", _}}, imem_meta:remove(?TPTEST_1, {?TPTEST_1, "meta", <<"tible"/utf8>>, "1"})), ?assertEqual({?TPTEST_1, "meta", <<"tüble"/utf8>>, "1"}, imem_meta:remove(?TPTEST_1, {?TPTEST_1, "meta", <<"tüble"/utf8>>, "1"})), ?assertEqual([], imem_meta:read(?TPTEST_1)), ?assertEqual([], imem_meta:read(?TPTEST_1IDX)), Idx2Def = #ddIdxDef{id = 2, name = <<"unique string index on b1">>, type = iv_k, pl = [<<"b1">>]}, ?assertEqual(ok, imem_meta:create_or_replace_index(?TPTEST_1, [Idx2Def])), ?assertEqual({?TPTEST_1, "meta", <<"täble"/utf8>>, "1"}, imem_meta:insert(?TPTEST_1, {?TPTEST_1, "meta", <<"täble"/utf8>>, "1"})), ?assertEqual(1, length(imem_meta:read(?TPTEST_1))), ?assertEqual(1, length(imem_meta:read(?TPTEST_1IDX))), ?assertEqual({?TPTEST_1, "meta1", <<"tüble"/utf8>>, "2"}, imem_meta:insert(?TPTEST_1, {?TPTEST_1, "meta1", <<"tüble"/utf8>>, "2"})), ?assertEqual(2, length(imem_meta:read(?TPTEST_1))), ?assertEqual(2, length(imem_meta:read(?TPTEST_1IDX))), ?assertException(throw, {'ClientError', {"Unique index violation", {?TPTEST_1IDX, 2, <<"table">>, "meta"}}}, imem_meta:insert(?TPTEST_1, {?TPTEST_1, "meta2", <<"table"/utf8>>, "2"})), ?assertEqual(2, length(imem_meta:read(?TPTEST_1))), ?assertEqual(2, length(imem_meta:read(?TPTEST_1IDX))), Idx3Def = #ddIdxDef{id = 3, name = <<"json index on b1:b">>, type = ivk, pl = [<<"b1:b">>, <<"b1:c:a">>]}, ?assertEqual(ok, imem_meta:create_or_replace_index(?TPTEST_1, [Idx3Def])), ?assertEqual(2, length(imem_meta:read(?TPTEST_1))), ?assertEqual(0, length(imem_meta:read(?TPTEST_1IDX))), JSON1 = << "{" "\"a\":\"Value-a\"," "\"b\":\"Value-b\"," "\"c\":{" "\"a\":\"Value-ca\"," "\"b\":\"Value-cb\"" "}" "}" >>, % { % "a": "Value-a", % "b": "Value-b", % "c": { % "a": "Value-ca", % "b": "Value-cb" % } % } PROP1 = [{<<"a">>, <<"Value-a">>} , {<<"b">>, <<"Value-b">>} , {<<"c">>, [ {<<"a">>, <<"Value-ca">>} , {<<"b">>, <<"Value-cb">>} ] } ], ?assertEqual(PROP1, imem_json:decode(JSON1)), ?assertEqual({?TPTEST_1, "json1", JSON1, "3"}, imem_meta:insert(?TPTEST_1, {?TPTEST_1, "json1", JSON1, "3"})), ?assertEqual([#ddIndex{stu = {3, <<"value-b">>, "json1"}} , #ddIndex{stu = {3, <<"value-ca">>, "json1"}} ], imem_meta:read(?TPTEST_1IDX)), % Drop individual indices ?assertEqual(ok, imem_meta:drop_index(?TPTEST_1)), ?assertEqual(ok, imem_meta:create_index(?TPTEST_1, [Idx1Def, Idx2Def, Idx3Def])), ?assertEqual(ok, imem_meta:drop_index(?TPTEST_1, <<"json index on b1:b">>)), ?assertException(throw, {'ClientError', {"Index does not exist for" , ?TPTEST_1 , <<"non existent index">>}} , imem_meta:drop_index(?TPTEST_1, <<"non existent index">>)), ?assertException(throw, {'ClientError', {"Index does not exist for" , ?TPTEST_1 , 7}} , imem_meta:drop_index(?TPTEST_1, 7)), ?assertEqual(ok, imem_meta:drop_index(?TPTEST_1, 2)), ?assertEqual(ok, imem_meta:drop_index(?TPTEST_1, 1)), ?assertEqual({'ClientError', {"Table does not exist", ?TPTEST_1IDX}} , imem_meta:drop_index(?TPTEST_1)), ?CTPAL("?TPTEST_1 ~p", [imem_meta:read(?TPTEST_1)]), Idx4Def = #ddIdxDef{id = 4, name = <<"integer index on b1">>, type = ivk, pl = [<<"c1">>], vnf = <<"fun imem_index:vnf_integer/1">>}, ?assertEqual(ok, imem_meta:create_or_replace_index(?TPTEST_1, [Idx4Def])), ?assertEqual(3, length(imem_meta:read(?TPTEST_1IDX))), imem_meta:insert(?TPTEST_1, {?TPTEST_1, "11", <<"11">>, "11"}), ?assertEqual(4, length(imem_meta:read(?TPTEST_1IDX))), imem_meta:insert(?TPTEST_1, {?TPTEST_1, "12", <<"12">>, "c112"}), IdxExpect4 = [{ddIndex, {4, 1, "meta"}, 0} , {ddIndex, {4, 2, "meta1"}, 0} , {ddIndex, {4, 3, "json1"}, 0} , {ddIndex, {4, 11, "11"}, 0} ], ?assertEqual(IdxExpect4, imem_meta:read(?TPTEST_1IDX)), Vnf5 = <<"fun(__X) -> case imem_index:vnf_integer(__X) of ['$not_a_value'] -> ['$not_a_value']; [__V] -> [2*__V] end end">>, Idx5Def = #ddIdxDef{id = 5, name = <<"integer times 2 on b1">>, type = ivk, pl = [<<"c1">>], vnf = Vnf5}, ?assertEqual(ok, imem_meta:create_or_replace_index(?TPTEST_1, [Idx5Def])), ?CTPAL("?TPTEST_1IDX ~p", [imem_meta:read(?TPTEST_1IDX)]), IdxExpect5 = [{ddIndex, {5, 2, "meta"}, 0} , {ddIndex, {5, 4, "meta1"}, 0} , {ddIndex, {5, 6, "json1"}, 0} , {ddIndex, {5, 22, "11"}, 0} ], ?assertEqual(IdxExpect5, imem_meta:read(?TPTEST_1IDX)), ?assertMatch({ok, _}, imem_meta:create_table(?TPTEST_2, Types2, [])), ?assertMatch({ok, _}, imem_meta:create_table(?TPTEST_3, {[a, ?nav], [datetime, term], {?TPTEST_3, ?nav, undefined}}, [])), ?CTPAL("create_or_replace_trigger"), Trig = <<"fun(O,N,T,U,TO) -> imem_meta:log_to_db(debug,imem_meta,trigger,[{table,T},{old,O},{new,N},{user,U},{tropts,TO}],\"trigger\") end.">>, ?assertEqual(ok, imem_meta:create_or_replace_trigger(?TPTEST_3, Trig)), ?assertEqual(Trig, imem_meta:get_trigger(?TPTEST_3)), ?assertException(throw, {ClEr, {"No columns given in create table", bad_table_0}}, imem_meta:create_table('bad_table_0', [], [])), ?assertException(throw, {ClEr, {"No value column given in create table, add dummy value column", bad_table_0}}, imem_meta:create_table('bad_table_0', BadTypes0, [])), ?assertException(throw, {ClEr, {"Invalid character(s) in table name", 'bad_?table_1'}}, imem_meta:create_table('bad_?table_1', BadTypes1, [])), ?assertEqual({ok,{imem,select}}, imem_meta:create_table(select, BadTypes2, [])), ?assertException(throw, {ClEr, {"Invalid character(s) in column name", 'a:b'}}, imem_meta:create_table(bad_table_1, BadTypes1, [])), ?assertEqual({ok,{imem,bad_table_1}}, imem_meta:create_table(bad_table_1, BadTypes2, [])), ?assertException(throw, {ClEr, {"Invalid data type", iinteger}}, imem_meta:create_table(bad_table_1, BadTypes3, [])), ?assertException(throw, {ClEr, {"Duplicate column name",a}}, imem_meta:create_table(bad_table_1, BadNames1, [])), ?CTPAL("?TPTEST_3"), LogCount3 = imem_meta:table_size(?LOG_TABLE), ?assertEqual({?TPTEST_3, {{2000, 1, 1}, {12, 45, 55}}, undefined}, imem_meta:insert(?TPTEST_3, {?TPTEST_3, {{2000, 01, 01}, {12, 45, 55}}, ?nav})), ?assertEqual(1, imem_meta:table_size(?TPTEST_3)), trigger inserted one line ?assertException(throw, {ClEr, {"Not null constraint violation", {?TPTEST_3, _}}}, imem_meta:insert(?TPTEST_3, {?TPTEST_3, ?nav, undefined})), error inserted one line ?assertEqual({?TPTEST_3, {{2000, 1, 1}, {12, 45, 55}}, undefined}, imem_meta:update(?TPTEST_3, {{?TPTEST_3, {{2000, 1, 1}, {12, 45, 55}}, undefined}, {?TPTEST_3, {{2000, 01, 01}, {12, 45, 55}}, ?nav}})), ?assertEqual(1, imem_meta:table_size(?TPTEST_3)), trigger inserted one line ?assertEqual({?TPTEST_3, {{2000, 1, 1}, {12, 45, 56}}, undefined}, imem_meta:merge(?TPTEST_3, {?TPTEST_3, {{2000, 01, 01}, {12, 45, 56}}, ?nav})), ?assertEqual(2, imem_meta:table_size(?TPTEST_3)), trigger inserted one line ?assertEqual({?TPTEST_3, {{2000, 1, 1}, {12, 45, 56}}, undefined}, imem_meta:remove(?TPTEST_3, {?TPTEST_3, {{2000, 01, 01}, {12, 45, 56}}, undefined})), ?assertEqual(1, imem_meta:table_size(?TPTEST_3)), trigger inserted one line ?assertEqual(ok, imem_meta:drop_trigger(?TPTEST_3)), ?CTPAL("?TPTEST_3 before update ~p", [imem_meta:read(?TPTEST_3)]), Trans3 = fun() -> %% key update imem_meta:update(?TPTEST_3, {{?TPTEST_3, {{2000, 01, 01}, {12, 45, 55}}, undefined}, {?TPTEST_3, {{2000, 01, 01}, {12, 45, 56}}, "alternative"}}), imem_meta:insert(?TPTEST_3, {?TPTEST_3, {{2000, 01, 01}, {12, 45, 57}}, ?nav}) %% return last result only end, ?assertEqual({?TPTEST_3, {{2000, 1, 1}, {12, 45, 57}}, undefined}, imem_meta:return_atomic(imem_meta:transaction(Trans3))), ?CTPAL("?TPTEST_3 after update ~p", [imem_meta:read(?TPTEST_3)]), ?assertEqual(2, imem_meta:table_size(?TPTEST_3)), ?assertEqual(LogCount3 + 5, imem_meta:table_size(?LOG_TABLE)), %% no trigger, no more log Keys4 = [ {1, {?TPTEST_3, {{2000, 1, 1}, {12, 45, 59}}, undefined}} ], U = unknown, {_, _DefRec, TrigFun} = imem_meta:trigger_infos(?TPTEST_3), ?assertEqual(Keys4, imem_meta:update_tables([[{imem, ?TPTEST_3, set}, 1, {}, {?TPTEST_3, {{2000, 01, 01}, {12, 45, 59}}, undefined}, TrigFun, U, []]], optimistic)), ?assertException(throw, {ClEr, {"Not null constraint violation", {1, {?TPTEST_3, _}}}}, imem_meta:update_tables([[{imem, ?TPTEST_3, set}, 1, {}, {?TPTEST_3, ?nav, undefined}, TrigFun, U, []]], optimistic)), ?assertException(throw, {ClEr, {"Not null constraint violation", {1, {?TPTEST_3, _}}}}, imem_meta:update_tables([[{imem, ?TPTEST_3, set}, 1, {}, {?TPTEST_3, {{2000, 01, 01}, {12, 45, 59}}, ?nav}, TrigFun, U, []]], optimistic)), ?assertEqual([?TPTEST_1, ?TPTEST_1IDX, ?TPTEST_2, ?TPTEST_3], lists:sort(imem_meta:tables_starting_with(?TPTEST))), ?assertEqual([?TPTEST_1, ?TPTEST_1IDX, ?TPTEST_2, ?TPTEST_3], lists:sort(imem_meta:tables_starting_with(?TPTEST))), _DdNode0 = imem_meta:read(ddNode), ?CTPAL("ddNode0 ~p", [_DdNode0]), _DdNode1 = imem_meta:read(ddNode, node()), ?CTPAL("ddNode1 ~p", [_DdNode1]), _DdNode2 = imem_meta:select(ddNode, ?MatchAllRecords), ?CTPAL("ddNode2 ~p", [_DdNode2]), Schema0 = [{ddSchema, {imem_meta:schema(), node()}, []}], ?assertEqual(Schema0, imem_meta:read(ddSchema)), ?assertEqual({Schema0, true}, imem_meta:select(ddSchema, ?MatchAllRecords, 1000)), ?assertEqual(ok, imem_meta:drop_table(?TPTEST_3)), ?assertEqual(ok, imem_meta:drop_table(?TPTEST_2)), ?assertEqual(ok, imem_meta:drop_table(?TPTEST_1)), ok. meta_partitions(_Config) -> ?CTPAL("Start"), ClEr = 'ClientError', UiEx = 'UnimplementedException', LogTable = imem_meta:physical_table_name(?LOG_TABLE), ?assert(lists:member(LogTable, imem_meta:physical_table_names(?LOG_TABLE))), ?assertEqual(LogTable, imem_meta:physical_table_name(atom_to_list(?LOG_TABLE) ++ imem_meta:node_shard())), ?assertEqual([], imem_meta:physical_table_names(?TPTEST_1000@)), ?assertException(throw, {ClEr, {"Table to be purged does not exist", ?TPTEST_1000@}}, imem_meta:purge_table(?TPTEST_1000@)), ?assertException(throw, {UiEx, {"Purge not supported on this table type", not_existing_table}}, imem_meta:purge_table(not_existing_table)), ?assert(imem_meta:purge_table(?LOG_TABLE) >= 0), ?assertException(throw, {UiEx, {"Purge not supported on this table type", ddTable}}, imem_meta:purge_table(ddTable)), ?assertNot(lists:member({imem_meta:schema(), ?TPTEST_1000@}, [element(2, A) || A <- imem_meta:read(ddAlias)])), TimePartTable0 = imem_meta:physical_table_name(?TPTEST_1000@), ?CTPAL("TimePartTable ~p", [TimePartTable0]), ?assertEqual(TimePartTable0, imem_meta:physical_table_name(?TPTEST_1000@, ?TIMESTAMP)), ?assertMatch({ok, _}, imem_meta:create_check_table(?TPTEST_1000@, {record_info(fields, ddLog), ?ddLog, #ddLog{}}, [{record_name, ddLog}, {type, ordered_set}], system)), % ?CTPAL("Alias0 ~p", [[element(2, A) || A <- imem_meta:read(ddAlias)]]), ?CTPAL("Alias0~n~p", [imem_meta:read(ddAlias)]), ?assertEqual(ok, imem_meta:check_table(TimePartTable0)), ?assertEqual(0, imem_meta:table_size(TimePartTable0)), ?assertEqual([TimePartTable0], imem_meta:physical_table_names(?TPTEST_1000@)), ?assertMatch({ok, _}, imem_meta:create_check_table(?TPTEST_1000@, {record_info(fields, ddLog), ?ddLog, #ddLog{}}, [{record_name, ddLog}, {type, ordered_set}], system)), ct:sleep(1000), ?assert(lists:member({imem_meta:schema(), ?TPTEST_1000@}, [element(2, A) || A <- imem_meta:read(ddAlias)])), ?assertNot(lists:member({imem_meta:schema(), ?TPTEST_100@}, [element(2, A) || A <- imem_meta:read(ddAlias)])), ct:sleep(1000), ToDo : Check period mismatch also for existing tables ( accidentally matching a rolling valid period ) ? assertException(throw , { ' ClientError ' , { " Name conflict ( different rolling period ) in ddAlias " , ? TPTEST_100@ } } % , imem_meta:create_check_table(?TPTEST_100@ , { record_info(fields , ddLog ) , ? , # ddLog { } } % , [{record_name, ddLog}, {type, ordered_set}] % , system % ) % ), LogRec = #ddLog{logTime = ?TIME_UID, logLevel = info, pid = self() , module = ?MODULE, function = meta_partitions, node = node() , fields = [], message = <<"some log message">> }, ?assertEqual(ok, imem_meta:write(?TPTEST_1000@, LogRec)), ?assertEqual(1, imem_meta:table_size(TimePartTable0)), ?assertEqual(0, imem_meta:purge_table(?TPTEST_1000@)), {Secs, Mics, Node, _} = ?TIME_UID, LogRecF = LogRec#ddLog{logTime = {Secs + 2000, Mics, Node, ?INTEGER_UID}}, ?assertEqual(ok, imem_meta:write(?TPTEST_1000@, LogRecF)), ?CTPAL("physical_table_names ~p", [imem_meta:physical_table_names(?TPTEST_1000@)]), ?assertEqual(0, imem_meta:purge_table(?TPTEST_1000@, [{purge_delay, 10000}])), ?assertEqual(0, imem_meta:purge_table(?TPTEST_1000@)), PurgeResult = imem_meta:purge_table(?TPTEST_1000@, [{purge_delay, -3000}]), ?CTPAL("PurgeResult ~p", [PurgeResult]), ?assert(PurgeResult > 0), ?assertEqual(0, imem_meta:purge_table(?TPTEST_1000@)), ?assertEqual(ok, imem_meta:drop_table(?TPTEST_1000@)), ?assertEqual([], imem_meta:physical_table_names(?TPTEST_1000@)), Alias0a = imem_meta:read(ddAlias), ?assertEqual(false, lists:member({imem_meta:schema(), ?TPTEST_1000@}, [element(2, A) || A <- Alias0a])), TimePartTable1 = imem_meta:physical_table_name(?TPTEST_999999999@_), ?assertEqual(?TPTEST_1999999998@_, TimePartTable1), ?assertEqual(TimePartTable1, imem_meta:physical_table_name(?TPTEST_999999999@_, ?TIMESTAMP)), ?assertMatch({ok, _}, imem_meta:create_check_table(?TPTEST_999999999@_, {record_info(fields, ddLog), ?ddLog, #ddLog{}}, [{record_name, ddLog}, {type, ordered_set}], system)), ?assertEqual(ok, imem_meta:check_table(TimePartTable1)), ?assertEqual([TimePartTable1], imem_meta:physical_table_names(?TPTEST_999999999@_)), ?assertEqual(0, imem_meta:table_size(TimePartTable1)), ?assertMatch({ok, _}, imem_meta:create_check_table(?TPTEST_999999999@_, {record_info(fields, ddLog), ?ddLog, #ddLog{}}, [{record_name, ddLog}, {type, ordered_set}], system)), Alias1 = imem_meta:read(ddAlias), ?CTPAL("Alias1 ~p", [[element(2, A) || A <- Alias1]]), ?assert(lists:member({imem_meta:schema(), ?TPTEST_999999999@_}, [element(2, A) || A <- Alias1])), ?assertEqual(ok, imem_meta:write(?TPTEST_999999999@_, LogRec)), ?assertEqual(1, imem_meta:table_size(TimePartTable1)), ?assertEqual(0, imem_meta:purge_table(?TPTEST_999999999@_)), LogRecP = LogRec#ddLog{logTime = {900000000, 0, node(), ?INTEGER_UID}}, % ?TIME_UID format ?assertEqual(ok, imem_meta:write(?TPTEST_999999999@_, LogRecP)), ?CTPAL("Big Partition Tables after back-insert ~p", [imem_meta:physical_table_names(?TPTEST_999999999@_)]), using 2 - tuple ? TIMESTAMP format here for backward compatibility test ?assertEqual(ok, imem_meta:write(?TPTEST_999999999@_, LogRecFF)), ?CTPAL("Big Partition Tables after forward-insert ~p", [imem_meta:physical_table_names(?TPTEST_999999999@_)]), ?assertEqual(3, length(imem_meta:physical_table_names(?TPTEST_999999999@_))), % another partition created ?assert(imem_meta:purge_table(?TPTEST_999999999@_) > 0), ?assertEqual(ok, imem_meta:drop_table(?TPTEST_999999999@_)), Alias1a = imem_meta:read(ddAlias), ?assertEqual(false, lists:member({imem_meta:schema(), ?TPTEST_999999999@_}, [element(2, A) || A <- Alias1a])), ?assertEqual([], imem_meta:physical_table_names(?TPTEST_999999999@_)), ?CTPAL("dummy_table_name"), ?assertEqual({error, {"Table template not found in ddAlias", dummy_table_name}}, imem_meta:create_partitioned_table_sync(dummy_table_name, dummy_table_name)), ?CTPAL("physical_table_names"), ?assertEqual([], imem_meta:physical_table_names(?TPTEST_3@)), ?assertMatch({ok, _}, imem_meta:create_check_table(?TPTEST_3@, {record_info(fields, ddLog), ?ddLog, #ddLog{}}, ?LOG_TABLE_OPTS, system)), ?assertEqual(1, length(imem_meta:physical_table_names(?TPTEST_3@))), ?CTPAL("LogRec3"), LogRec3 = #ddLog{logTime = ?TIMESTAMP, logLevel = debug, pid = self() , module = ?MODULE, function = test, node = node() , fields = [], message = <<>>, stacktrace = [] using 2 - tuple ? TIMESTAMP format here for backward compatibility test ct:sleep(30), can write to first partition ?assertEqual(1, length(imem_meta:physical_table_names(?TPTEST_3@))), % one record in this partition now ct:sleep(4000), one partition at least created by partition rolling can write to second partition ( maybe third ) ct:sleep(4000), FL3Tables = imem_meta:physical_table_names(?TPTEST_3@), ?CTPAL("Tables written ~p ~p", [?TPTEST_3@, FL3Tables]), ?assert(length(FL3Tables) >= 3), ct:sleep(4000), ?assert(length(imem_meta:physical_table_names(?TPTEST_3@)) >= 4), _ = {timeout, 5, fun() -> ?assertEqual(ok, imem_meta:drop_table(?TPTEST_3@)) end}, ok. meta_preparations(_Config) -> ?CTPAL("Start"), ?assertEqual(["Schema", ".", "BaseName", "_", "01234", "@", "Node"], imem_meta:parse_table_name("Schema.BaseName_01234@Node")), ?assertEqual(["Schema", ".", "BaseName", "", "", "", ""], imem_meta:parse_table_name("Schema.BaseName")), ?assertEqual(["", "", "BaseName", "_", "01234", "@", "Node"], imem_meta:parse_table_name("BaseName_01234@Node")), ?assertEqual(["", "", "BaseName", "", "", "@", "Node"], imem_meta:parse_table_name("BaseName@Node")), ?assertEqual(["", "", "BaseName", "", "", "@", ""], imem_meta:parse_table_name("BaseName@")), ?assertEqual(["", "", "BaseName", "", "", "", ""], imem_meta:parse_table_name("BaseName")), ?assertEqual(["Schema", ".", "Name_Period", "", "", "@", "Node"], imem_meta:parse_table_name('Schema.Name_Period@Node')), ?assertEqual(["Schema", ".", "Name", "_", "12345", "@", "Node"], imem_meta:parse_table_name('Schema.Name_12345@Node')), ?assertEqual(["Schema", ".", "Name_Period", "", "", "@", "_"], imem_meta:parse_table_name('Schema.Name_Period@_')), ?assertEqual(["Schema", ".", "Name", "_", "12345", "@", "_"], imem_meta:parse_table_name('Schema.Name_12345@_')), ?assertEqual(["Schema", ".", "Name_Period", "", "", "@", ""], imem_meta:parse_table_name('Schema.Name_Period@')), ?assertEqual(["Sch_01", ".", "Name", "_", "12345", "@", ""], imem_meta:parse_table_name('Sch_01.Name_12345@')), ?assertEqual(["Sch_99", ".", "Name_Period", "", "", "", ""], imem_meta:parse_table_name('Sch_99.Name_Period')), ?assertEqual(["Sch_ma", ".", "Name_12345", "", "", "", ""], imem_meta:parse_table_name('Sch_ma.Name_12345')), ?assertEqual(["", "", "Name_Period", "", "", "@", "Node"], imem_meta:parse_table_name('Name_Period@Node')), ?assertEqual(["", "", "Name", "_", "12345", "@", "Node"], imem_meta:parse_table_name('Name_12345@Node')), ?assertEqual(["", "", "Name_Period", "", "", "@", "_"], imem_meta:parse_table_name('Name_Period@_')), ?assertEqual(["", "", "Name", "_", "12345", "@", "_"], imem_meta:parse_table_name('Name_12345@_')), ?assertEqual(["", "", "Name_Period", "", "", "@", ""], imem_meta:parse_table_name('Name_Period@')), ?assertEqual(["", "", "Name", "_", "12345", "@", ""], imem_meta:parse_table_name('Name_12345@')), ?assertEqual(["", "", "Name_Period", "", "", "", ""], imem_meta:parse_table_name('Name_Period')), ?assertEqual(["", "", "Name_12345", "", "", "", ""], imem_meta:parse_table_name('Name_12345')), ?assertEqual(true, imem_meta:is_time_partitioned_alias(?TPTEST_999999999@_)), ?assertEqual(true, imem_meta:is_time_partitioned_alias(?TPTEST_1000@)), ?assertEqual(true, imem_meta:is_time_partitioned_alias(tpTest_123@)), ?assertEqual(true, imem_meta:is_time_partitioned_alias(tpTest_123@_)), ?assertEqual(true, imem_meta:is_time_partitioned_alias(tpTest_123@local)), ?assertEqual(true, imem_meta:is_time_partitioned_alias(tpTest_123@testnode)), ?assertEqual(false, imem_meta:is_time_partitioned_alias(tpTest)), ?assertEqual(false, imem_meta:is_time_partitioned_alias(tpTest@)), ?assertEqual(false, imem_meta:is_time_partitioned_alias(tpTest@_)), ?assertEqual(false, imem_meta:is_time_partitioned_alias(tpTest123@_)), ?assertEqual(false, imem_meta:is_time_partitioned_alias(tpTest_12A@)), ?assertEqual(false, imem_meta:is_time_partitioned_alias(tpTest@local)), ?assertEqual(false, imem_meta:is_time_partitioned_alias(tpTest@testnode)), ?assertEqual(true, imem_meta:is_node_sharded_alias(?TPTEST_1000@)), ?assertEqual(true, imem_meta:is_node_sharded_alias(tpTest@)), ?assertEqual(true, imem_meta:is_node_sharded_alias(tpTest123@)), ?assertEqual(true, imem_meta:is_node_sharded_alias(tpTest_123@)), ?assertEqual(false, imem_meta:is_node_sharded_alias(?TPTEST_999999999@_)), ?assertEqual(false, imem_meta:is_node_sharded_alias(tpTest_1000)), ?assertEqual(false, imem_meta:is_node_sharded_alias(tpTest1000)), ?assertEqual(false, imem_meta:is_node_sharded_alias(tpTest123@_)), ?assertEqual(false, imem_meta:is_node_sharded_alias(tpTest_123@_)), ok. %%==================================================================== %% Helper functions. %%==================================================================== read_write_test(Tab, Key, N) -> Upd = fun() -> [{Tab, Key, Val}] = imem_meta:read(Tab, Key), imem_meta:write(Tab, {Tab, Key, Val + N}) end, imem_meta:transaction(Upd). receive_results(N, Acc) -> receive Result -> case N of 1 -> ?CTPAL("Result ~p", [Result]), [Result | Acc]; _ -> ?CTPAL("Result ~p", [Result]), receive_results(N - 1, [Result | Acc]) end after 1000 -> ?CTPAL("Result timeout"), Acc end.
null
https://raw.githubusercontent.com/K2InformaticsGmbH/imem/602b6cd31ea1af00041a9318119ab0c3e4d5b59a/test/imem_meta_ct.erl
erlang
------------------------------------------------------------------- File : imem_meta_ct.erl Description : Common testing imem_meta. Created : 09.11.2017 ------------------------------------------------------------------- -------------------------------------------------------------------- Test case related setup and teardown functions. -------------------------------------------------------------------- ==================================================================== Test cases. ==================================================================== ddCache@WKS018 key key value { "a": "Value-a", "b": "Value-b", "c": { "a": "Value-ca", "b": "Value-cb" } } Drop individual indices key update return last result only no trigger, no more log ?CTPAL("Alias0 ~p", [[element(2, A) || A <- imem_meta:read(ddAlias)]]), , imem_meta:create_check_table(?TPTEST_100@ , [{record_name, ddLog}, {type, ordered_set}] , system ) ), ?TIME_UID format another partition created one record in this partition now ==================================================================== Helper functions. ====================================================================
Copyright ( C ) 2017 K2 Informatics GmbH -module(imem_meta_ct). -include_lib("common_test/include/ct.hrl"). -include_lib("eunit/include/eunit.hrl"). -export([ end_per_testcase/2 , meta_concurrency/1 , meta_operations/1 , meta_partitions/1 , meta_preparations/1 , physical_table_names/1 ]). -define(LOG_TABLE_OPTS, [{record_name, ddLog} , {type, ordered_set} 430000 = 5 Days - 2000 sec ]). -define(TPTEST, tpTest). -define(TPTEST_1, tpTest_1). -define(TPTEST_2, tpTest_2). -define(TPTEST_3, tpTest_3). -define(TPTEST_3@, tpTest_3@). -define(TPTEST_100@, tpTest_100@). -define(TPTEST_1000@, tpTest_1000@). -define(TPTEST_999999999@_, tpTest_999999999@_). -define(TPTEST_1999999998@_, tpTest_1999999998@_). -define(TPTEST_1IDX, tpTest_1Idx). -define(NODEBUG, true). -define(TEST_SLAVE_IMEM_NODE_NAME, "metaslave"). -include_lib("imem.hrl"). -include_lib("imem_meta.hrl"). -include("imem_ct.hrl"). end_per_testcase(TestCase, _Config) -> ?CTPAL("End ~p",[TestCase]), catch imem_meta:drop_table(?TPTEST_1), catch imem_meta:drop_table(?TPTEST_2), catch imem_meta:drop_table(?TPTEST_3), catch imem_meta:drop_table(?TPTEST_1000@), catch imem_meta:drop_table(?TPTEST_999999999@_), catch imem_meta:drop_table(?TPTEST_100@), catch imem_meta:drop_table(?TPTEST_3@), catch imem_test_slave:stop(?TEST_SLAVE_IMEM_NODE_NAME), ok. physical_table_names(_Config) -> ?CTPAL("Start test single node"), LocalCacheStr = "ddCache@"++imem_meta:node_shard(), ?assertEqual([ddTable], imem_meta:physical_table_names(ddTable)), ?assertEqual([ddTable], imem_meta:physical_table_names("ddTable")), ?assertEqual([ddTable], imem_meta:physical_table_names(<<"ddTable">>)), ?assertEqual([ddTable], imem_meta:physical_table_names({imem_meta:schema(), ddTable})), [ ?assertEqual([Type], imem_meta:physical_table_names(atom_to_list(Type))) || Type <- ?DataTypes ], ?assertEqual([LocalCacheName], imem_meta:physical_table_names(ddCache@local)), ?assertEqual([LocalCacheName], imem_meta:physical_table_names(LocalCacheStr)), ?assertEqual([LocalCacheName], imem_meta:physical_table_names(LocalCacheName)), ?assertEqual([LocalCacheName], imem_meta:physical_table_names({imem_meta:schema(), LocalCacheName})), ?assertEqual([], imem_meta:physical_table_names("ddCache@123")), ?assertEqual([LocalCacheName], imem_meta:physical_table_names("ddCache@")), ?assertEqual([s_tab_1568764800@_], imem_meta:simple_or_local_node_sharded_tables(s_tab_1568764800@_)), Result1 = [{node(),imem_meta:schema(),ddTable}], ?assertEqual(Result1, imem_meta:cluster_table_names(ddTable)), ?assertEqual(Result1, imem_meta:cluster_table_names("ddTable")), ?assertEqual(Result1, imem_meta:cluster_table_names(<<"ddTable">>)), [ ?assertEqual([{node(),imem_meta:schema(),Type}], imem_meta:cluster_table_names(atom_to_list(Type))) || Type <- ?DataTypes ], ?assertEqual([{node(),imem_meta:schema(),LocalCacheName}], imem_meta:cluster_table_names(ddCache@local)), ?assertEqual([{node(),imem_meta:schema(),LocalCacheName}], imem_meta:cluster_table_names(LocalCacheStr)), ?assertEqual([{node(),imem_meta:schema(),LocalCacheName}], imem_meta:cluster_table_names(LocalCacheName)), ?assertEqual([], imem_meta:cluster_table_names("ddCache@123")), ?assertEqual([{node(),imem_meta:schema(),LocalCacheName}], imem_meta:cluster_table_names("ddCache@")), ?assertEqual([{node(),<<"csv$">>,<<"\"TestCsvFile.csv\"">>}], imem_meta:cluster_table_names(<<"csv$.\"TestCsvFile.csv\"">>)), ?CTPAL("Start test slave node"), ?assertNot(imem_test_slave:is_running(?TEST_SLAVE_IMEM_NODE_NAME)), Slave = imem_test_slave:start(?TEST_SLAVE_IMEM_NODE_NAME), ?CTPAL("Slave ~p", [Slave]), ct:sleep(5000), ?CTPAL("slave nodes ~p", [imem_meta:nodes()]), ?assert(imem_test_slave:is_running(?TEST_SLAVE_IMEM_NODE_NAME)), ?CTPAL("data_nodes ~p", [imem_meta:data_nodes()]), ?CTPAL("node_shards ~p", [imem_meta:node_shards()]), ?assert(lists:member({imem_meta:schema(),node()}, imem_meta:data_nodes())), ?assert(lists:member(imem_meta:node_shard(), imem_meta:node_shards())), ?assert(lists:member({imem_meta:schema(), Slave}, imem_meta:data_nodes())), ?assert(lists:member(?TEST_SLAVE_IMEM_NODE_NAME, imem_meta:node_shards())), DDCacheNames = imem_meta:physical_table_names("ddCache@"), SlaveCacheName = list_to_atom("ddCache@" ++ ?TEST_SLAVE_IMEM_NODE_NAME), ?CTPAL("ddCache@ -> ~p", [DDCacheNames]), ?assert(lists:member(LocalCacheName, DDCacheNames)), ?assert(lists:member(SlaveCacheName, DDCacheNames)), ?assertEqual([SlaveCacheName], imem_meta:physical_table_names("ddCache@" ++ ?TEST_SLAVE_IMEM_NODE_NAME)), LogNames = imem_meta:physical_table_names("ddLog_86400@"), LocalLogName = imem_meta:physical_table_name("ddLog_86400@"), [BaseName,_] = string:tokens(atom_to_list(LocalLogName),"@"), SlaveLogName = list_to_atom(BaseName ++ "@" ++ ?TEST_SLAVE_IMEM_NODE_NAME), ?CTPAL("ddLog_86400@ -> ~p", [LogNames]), ?assert(lists:member(LocalLogName, LogNames)), ?assert(lists:member(SlaveLogName, LogNames)), ?assertEqual([SlaveLogName], imem_meta:physical_table_names("ddLog_86400@" ++ ?TEST_SLAVE_IMEM_NODE_NAME)), ?assertEqual([], imem_meta:physical_table_names("ddAccount@" ++ ?TEST_SLAVE_IMEM_NODE_NAME)), ?assertEqual([{Slave,<<"csv$">>,<<"\"TestCsvFile.csv\"">>}], imem_meta:cluster_table_names("csv$.\"TestCsvFile.csv\"@"++?TEST_SLAVE_IMEM_NODE_NAME)), DDCacheClusterNames = imem_meta:cluster_table_names("ddCache@"), ?CTPAL("ddCache@ -> ~p", [DDCacheClusterNames]), ?assert(lists:member({node(),imem_meta:schema(),LocalCacheName}, DDCacheClusterNames)), ?assert(lists:member({Slave,imem_meta:schema(),SlaveCacheName}, DDCacheClusterNames)), ?assertEqual([{Slave,imem_meta:schema(),SlaveCacheName}], imem_meta:cluster_table_names("ddCache@" ++ ?TEST_SLAVE_IMEM_NODE_NAME)), LogClusterNames = imem_meta:cluster_table_names("ddLog_86400@"), ?CTPAL("ddLog_86400@ -> ~p", [LogClusterNames]), ?assert(lists:member({node(),imem_meta:schema(),LocalLogName}, LogClusterNames)), ?assert(lists:member({Slave,imem_meta:schema(),SlaveLogName}, LogClusterNames)), ?assertEqual([{Slave,imem_meta:schema(),SlaveLogName}], imem_meta:cluster_table_names("ddLog_86400@" ++ ?TEST_SLAVE_IMEM_NODE_NAME)), ?assertEqual([{Slave,imem_meta:schema(),ddAccount}], imem_meta:cluster_table_names("ddAccount@" ++ ?TEST_SLAVE_IMEM_NODE_NAME)), ?assertEqual([{Slave,imem_meta:schema(),integer}], imem_meta:cluster_table_names("integer@" ++ ?TEST_SLAVE_IMEM_NODE_NAME)), ?assertEqual(ok, imem_test_slave:stop(Slave)), ct:sleep(1000), ?assertNot(imem_test_slave:is_running(?TEST_SLAVE_IMEM_NODE_NAME)), ok. meta_concurrency(_Config) -> ?CTPAL("create_table"), ?assertMatch({ok, _}, imem_meta:create_table(?TPTEST_1, [hlk, val], [])), Self = self(), Key = [sum], ?CTPAL("write"), ?assertEqual(ok, imem_meta:write(?TPTEST_1, {?TPTEST_1, Key, 0})), [spawn(fun() -> Self ! {N, read_write_test(?TPTEST_1, Key, N)} end) || N <- lists:seq(1, 10)], ?CTPAL("ReadWriteResult"), ReadWriteResult = receive_results(10, []), ?assertEqual(10, length(ReadWriteResult)), ?assertEqual([{?TPTEST_1, Key, 55}], imem_meta:read(?TPTEST_1, Key)), ?assertEqual([{atomic, ok}], lists:usort([R || {_, R} <- ReadWriteResult])), ?assertEqual(ok, imem_meta:drop_table(?TPTEST_1)), ok. meta_operations(_Config) -> ?CTPAL("Start"), ClEr = 'ClientError', SyEx = 'SystemException', ?CTPAL("schema ~p",[imem_meta:schema()]), ?CTPAL("data nodes ~p", [imem_meta:data_nodes()]), ?assertEqual(true, is_atom(imem_meta:schema())), ?assertEqual(true, lists:member({imem_meta:schema(), node()}, imem_meta:data_nodes())), ?assertEqual([imem_meta:node_shard()], imem_meta:node_shards()), ?assertEqual(ok, imem_meta:check_table_meta(ddTable, record_info(fields, ddTable))), ?assertMatch({ok, _}, imem_meta:create_check_table(?LOG_TABLE, {record_info(fields, ddLog), ?ddLog, #ddLog{}}, ?LOG_TABLE_OPTS, system)), ?assertException(throw, {SyEx, {"Wrong table owner", {_, [system, admin]}}}, imem_meta:create_check_table(?LOG_TABLE, {record_info(fields, ddLog), ?ddLog, #ddLog{}}, [{record_name, ddLog}, {type, ordered_set}], admin)), ?assertException(throw, {SyEx, {"Wrong table options", {_, _}}}, imem_meta:create_check_table(?LOG_TABLE, {record_info(fields, ddLog), ?ddLog, #ddLog{}}, [{record_name, ddLog1}, {type, ordered_set}], system)), ?assertEqual(ok, imem_meta:check_table(?LOG_TABLE)), ?assertEqual(ok, imem_meta:check_table(?CACHE_TABLE)), Now = ?TIME_UID, LogCount1 = imem_meta:table_size(?LOG_TABLE), ?CTPAL("ddLog@ count ~p", [LogCount1]), Fields = [{test_criterium_1, value1}, {test_criterium_2, value2}], LogRec0 = #ddLog{logTime = Now, logLevel = info, pid = self() , module = ?MODULE, function = meta_operations, node = node() , fields = Fields, message = <<"some log message">>}, ?assertEqual(ok, imem_meta:write(?LOG_TABLE, LogRec0)), LogCount2 = imem_meta:table_size(?LOG_TABLE), ?CTPAL("ddLog@ count ~p", [LogCount2]), ?assert(LogCount2 > LogCount1), _Log1 = imem_meta:read(?LOG_TABLE, Now), ?CTPAL("ddLog@ count ~p", [_Log1]), ?assertEqual(ok, imem_meta:log_to_db(info, ?MODULE, test, [{test_3, value3}, {test_4, value4}], "Message")), ?assertEqual(ok, imem_meta:log_to_db(info, ?MODULE, test, [{test_3, value3}, {test_4, value4}], [])), ?assertEqual(ok, imem_meta:log_to_db(info, ?MODULE, test, [{test_3, value3}, {test_4, value4}], [stupid_error_message, 1])), ?assertEqual(ok, imem_meta:log_to_db(info, ?MODULE, test, [{test_3, value3}, {test_4, value4}], {stupid_error_message, 2})), LogCount2a = imem_meta:table_size(?LOG_TABLE), ?assert(LogCount2a >= LogCount2 + 4), ?CTPAL("test_database_operations"), value 1 value 2 ], ], BadTypes0 = [#ddColumn{name = 'a', type = integer, len = 10} ], BadTypes1 = [#ddColumn{name = 'a', type = integer, len = 10} , #ddColumn{name = 'a:b', type = integer, len = 10} ], BadTypes2 = [#ddColumn{name = 'a', type = integer, len = 10} , #ddColumn{name = current, type = integer, len = 10} ], BadTypes3 = [#ddColumn{name = 'a', type = integer, len = 10} , #ddColumn{name = b, type = iinteger, len = 10} ], BadNames1 = [#ddColumn{name = 'a', type = integer, len = 10} , #ddColumn{name = a, type = integer, len = 10} ], ?assertMatch({ok, _}, imem_meta:create_table(?TPTEST_1, Types1, [])), ?assertEqual(ok, imem_meta:create_index(?TPTEST_1, [])), ?assertMatch(ok, imem_meta:check_table(?TPTEST_1IDX)), ?CTPAL("ddTable for ?TPTEST_1 ~p", [imem_meta:read(ddTable, {imem_meta:schema(), ?TPTEST_1})]), ?assertEqual(ok, imem_meta:drop_index(?TPTEST_1)), ?assertException(throw, {'ClientError', {"Table does not exist", ?TPTEST_1IDX}}, imem_meta:check_table(?TPTEST_1IDX)), ?assertEqual(ok, imem_meta:create_index(?TPTEST_1, [])), ?assertException(throw, {'ClientError', {"Index already exists", {?TPTEST_1}}}, imem_meta:create_index(?TPTEST_1, [])), ?assertEqual([], imem_meta:read(?TPTEST_1IDX)), ?assertEqual(ok, imem_meta:write(?TPTEST_1IDX, #ddIndex{stu = {1, 2, 3}})), ?assertEqual([#ddIndex{stu = {1, 2, 3}}], imem_meta:read(?TPTEST_1IDX)), Idx1Def = #ddIdxDef{id = 1, name = <<"string index on b1">>, type = ivk, pl = [<<"b1">>]}, ?assertEqual(ok, imem_meta:create_or_replace_index(?TPTEST_1, [Idx1Def])), ?assertEqual([], imem_meta:read(?TPTEST_1IDX)), ?assertEqual([<<"table">>], imem_index:vnf_lcase_ascii_ne(<<"täble"/utf8>>)), ?assertEqual({?TPTEST_1, "meta", <<"täble"/utf8>>, "1"}, imem_meta:insert(?TPTEST_1, {?TPTEST_1, "meta", <<"täble"/utf8>>, "1"})), ?assertEqual([{?TPTEST_1, "meta", <<"täble"/utf8>>, "1"}], imem_meta:read(?TPTEST_1)), ?assertEqual([#ddIndex{stu = {1, <<"table">>, "meta"}}], imem_meta:read(?TPTEST_1IDX)), ?assertEqual([<<"tuble">>], imem_index:vnf_lcase_ascii_ne(<<"tüble"/utf8>>)), ?assertException(throw, {'ConcurrencyException', {"Data is modified by someone else", _}}, imem_meta:update(?TPTEST_1, {{?TPTEST_1, "meta", <<"tible"/utf8>>, "1"}, {?TPTEST_1, "meta", <<"tüble"/utf8>>, "1"}})), ?assertEqual({?TPTEST_1, "meta", <<"tüble"/utf8>>, "1"}, imem_meta:update(?TPTEST_1, {{?TPTEST_1, "meta", <<"täble"/utf8>>, "1"}, {?TPTEST_1, "meta", <<"tüble"/utf8>>, "1"}})), ?assertEqual([{?TPTEST_1, "meta", <<"tüble"/utf8>>, "1"}], imem_meta:read(?TPTEST_1)), ?assertEqual([#ddIndex{stu = {1, <<"tuble">>, "meta"}}], imem_meta:read(?TPTEST_1IDX)), ?assertEqual(ok, imem_meta:drop_index(?TPTEST_1)), ?assertEqual(ok, imem_meta:create_index(?TPTEST_1, [Idx1Def])), ?assertEqual([#ddIndex{stu = {1, <<"tuble">>, "meta"}}], imem_meta:read(?TPTEST_1IDX)), ?assertException(throw, {'ConcurrencyException', {"Data is modified by someone else", _}}, imem_meta:remove(?TPTEST_1, {?TPTEST_1, "meta", <<"tible"/utf8>>, "1"})), ?assertEqual({?TPTEST_1, "meta", <<"tüble"/utf8>>, "1"}, imem_meta:remove(?TPTEST_1, {?TPTEST_1, "meta", <<"tüble"/utf8>>, "1"})), ?assertEqual([], imem_meta:read(?TPTEST_1)), ?assertEqual([], imem_meta:read(?TPTEST_1IDX)), Idx2Def = #ddIdxDef{id = 2, name = <<"unique string index on b1">>, type = iv_k, pl = [<<"b1">>]}, ?assertEqual(ok, imem_meta:create_or_replace_index(?TPTEST_1, [Idx2Def])), ?assertEqual({?TPTEST_1, "meta", <<"täble"/utf8>>, "1"}, imem_meta:insert(?TPTEST_1, {?TPTEST_1, "meta", <<"täble"/utf8>>, "1"})), ?assertEqual(1, length(imem_meta:read(?TPTEST_1))), ?assertEqual(1, length(imem_meta:read(?TPTEST_1IDX))), ?assertEqual({?TPTEST_1, "meta1", <<"tüble"/utf8>>, "2"}, imem_meta:insert(?TPTEST_1, {?TPTEST_1, "meta1", <<"tüble"/utf8>>, "2"})), ?assertEqual(2, length(imem_meta:read(?TPTEST_1))), ?assertEqual(2, length(imem_meta:read(?TPTEST_1IDX))), ?assertException(throw, {'ClientError', {"Unique index violation", {?TPTEST_1IDX, 2, <<"table">>, "meta"}}}, imem_meta:insert(?TPTEST_1, {?TPTEST_1, "meta2", <<"table"/utf8>>, "2"})), ?assertEqual(2, length(imem_meta:read(?TPTEST_1))), ?assertEqual(2, length(imem_meta:read(?TPTEST_1IDX))), Idx3Def = #ddIdxDef{id = 3, name = <<"json index on b1:b">>, type = ivk, pl = [<<"b1:b">>, <<"b1:c:a">>]}, ?assertEqual(ok, imem_meta:create_or_replace_index(?TPTEST_1, [Idx3Def])), ?assertEqual(2, length(imem_meta:read(?TPTEST_1))), ?assertEqual(0, length(imem_meta:read(?TPTEST_1IDX))), JSON1 = << "{" "\"a\":\"Value-a\"," "\"b\":\"Value-b\"," "\"c\":{" "\"a\":\"Value-ca\"," "\"b\":\"Value-cb\"" "}" "}" >>, PROP1 = [{<<"a">>, <<"Value-a">>} , {<<"b">>, <<"Value-b">>} , {<<"c">>, [ {<<"a">>, <<"Value-ca">>} , {<<"b">>, <<"Value-cb">>} ] } ], ?assertEqual(PROP1, imem_json:decode(JSON1)), ?assertEqual({?TPTEST_1, "json1", JSON1, "3"}, imem_meta:insert(?TPTEST_1, {?TPTEST_1, "json1", JSON1, "3"})), ?assertEqual([#ddIndex{stu = {3, <<"value-b">>, "json1"}} , #ddIndex{stu = {3, <<"value-ca">>, "json1"}} ], imem_meta:read(?TPTEST_1IDX)), ?assertEqual(ok, imem_meta:drop_index(?TPTEST_1)), ?assertEqual(ok, imem_meta:create_index(?TPTEST_1, [Idx1Def, Idx2Def, Idx3Def])), ?assertEqual(ok, imem_meta:drop_index(?TPTEST_1, <<"json index on b1:b">>)), ?assertException(throw, {'ClientError', {"Index does not exist for" , ?TPTEST_1 , <<"non existent index">>}} , imem_meta:drop_index(?TPTEST_1, <<"non existent index">>)), ?assertException(throw, {'ClientError', {"Index does not exist for" , ?TPTEST_1 , 7}} , imem_meta:drop_index(?TPTEST_1, 7)), ?assertEqual(ok, imem_meta:drop_index(?TPTEST_1, 2)), ?assertEqual(ok, imem_meta:drop_index(?TPTEST_1, 1)), ?assertEqual({'ClientError', {"Table does not exist", ?TPTEST_1IDX}} , imem_meta:drop_index(?TPTEST_1)), ?CTPAL("?TPTEST_1 ~p", [imem_meta:read(?TPTEST_1)]), Idx4Def = #ddIdxDef{id = 4, name = <<"integer index on b1">>, type = ivk, pl = [<<"c1">>], vnf = <<"fun imem_index:vnf_integer/1">>}, ?assertEqual(ok, imem_meta:create_or_replace_index(?TPTEST_1, [Idx4Def])), ?assertEqual(3, length(imem_meta:read(?TPTEST_1IDX))), imem_meta:insert(?TPTEST_1, {?TPTEST_1, "11", <<"11">>, "11"}), ?assertEqual(4, length(imem_meta:read(?TPTEST_1IDX))), imem_meta:insert(?TPTEST_1, {?TPTEST_1, "12", <<"12">>, "c112"}), IdxExpect4 = [{ddIndex, {4, 1, "meta"}, 0} , {ddIndex, {4, 2, "meta1"}, 0} , {ddIndex, {4, 3, "json1"}, 0} , {ddIndex, {4, 11, "11"}, 0} ], ?assertEqual(IdxExpect4, imem_meta:read(?TPTEST_1IDX)), Vnf5 = <<"fun(__X) -> case imem_index:vnf_integer(__X) of ['$not_a_value'] -> ['$not_a_value']; [__V] -> [2*__V] end end">>, Idx5Def = #ddIdxDef{id = 5, name = <<"integer times 2 on b1">>, type = ivk, pl = [<<"c1">>], vnf = Vnf5}, ?assertEqual(ok, imem_meta:create_or_replace_index(?TPTEST_1, [Idx5Def])), ?CTPAL("?TPTEST_1IDX ~p", [imem_meta:read(?TPTEST_1IDX)]), IdxExpect5 = [{ddIndex, {5, 2, "meta"}, 0} , {ddIndex, {5, 4, "meta1"}, 0} , {ddIndex, {5, 6, "json1"}, 0} , {ddIndex, {5, 22, "11"}, 0} ], ?assertEqual(IdxExpect5, imem_meta:read(?TPTEST_1IDX)), ?assertMatch({ok, _}, imem_meta:create_table(?TPTEST_2, Types2, [])), ?assertMatch({ok, _}, imem_meta:create_table(?TPTEST_3, {[a, ?nav], [datetime, term], {?TPTEST_3, ?nav, undefined}}, [])), ?CTPAL("create_or_replace_trigger"), Trig = <<"fun(O,N,T,U,TO) -> imem_meta:log_to_db(debug,imem_meta,trigger,[{table,T},{old,O},{new,N},{user,U},{tropts,TO}],\"trigger\") end.">>, ?assertEqual(ok, imem_meta:create_or_replace_trigger(?TPTEST_3, Trig)), ?assertEqual(Trig, imem_meta:get_trigger(?TPTEST_3)), ?assertException(throw, {ClEr, {"No columns given in create table", bad_table_0}}, imem_meta:create_table('bad_table_0', [], [])), ?assertException(throw, {ClEr, {"No value column given in create table, add dummy value column", bad_table_0}}, imem_meta:create_table('bad_table_0', BadTypes0, [])), ?assertException(throw, {ClEr, {"Invalid character(s) in table name", 'bad_?table_1'}}, imem_meta:create_table('bad_?table_1', BadTypes1, [])), ?assertEqual({ok,{imem,select}}, imem_meta:create_table(select, BadTypes2, [])), ?assertException(throw, {ClEr, {"Invalid character(s) in column name", 'a:b'}}, imem_meta:create_table(bad_table_1, BadTypes1, [])), ?assertEqual({ok,{imem,bad_table_1}}, imem_meta:create_table(bad_table_1, BadTypes2, [])), ?assertException(throw, {ClEr, {"Invalid data type", iinteger}}, imem_meta:create_table(bad_table_1, BadTypes3, [])), ?assertException(throw, {ClEr, {"Duplicate column name",a}}, imem_meta:create_table(bad_table_1, BadNames1, [])), ?CTPAL("?TPTEST_3"), LogCount3 = imem_meta:table_size(?LOG_TABLE), ?assertEqual({?TPTEST_3, {{2000, 1, 1}, {12, 45, 55}}, undefined}, imem_meta:insert(?TPTEST_3, {?TPTEST_3, {{2000, 01, 01}, {12, 45, 55}}, ?nav})), ?assertEqual(1, imem_meta:table_size(?TPTEST_3)), trigger inserted one line ?assertException(throw, {ClEr, {"Not null constraint violation", {?TPTEST_3, _}}}, imem_meta:insert(?TPTEST_3, {?TPTEST_3, ?nav, undefined})), error inserted one line ?assertEqual({?TPTEST_3, {{2000, 1, 1}, {12, 45, 55}}, undefined}, imem_meta:update(?TPTEST_3, {{?TPTEST_3, {{2000, 1, 1}, {12, 45, 55}}, undefined}, {?TPTEST_3, {{2000, 01, 01}, {12, 45, 55}}, ?nav}})), ?assertEqual(1, imem_meta:table_size(?TPTEST_3)), trigger inserted one line ?assertEqual({?TPTEST_3, {{2000, 1, 1}, {12, 45, 56}}, undefined}, imem_meta:merge(?TPTEST_3, {?TPTEST_3, {{2000, 01, 01}, {12, 45, 56}}, ?nav})), ?assertEqual(2, imem_meta:table_size(?TPTEST_3)), trigger inserted one line ?assertEqual({?TPTEST_3, {{2000, 1, 1}, {12, 45, 56}}, undefined}, imem_meta:remove(?TPTEST_3, {?TPTEST_3, {{2000, 01, 01}, {12, 45, 56}}, undefined})), ?assertEqual(1, imem_meta:table_size(?TPTEST_3)), trigger inserted one line ?assertEqual(ok, imem_meta:drop_trigger(?TPTEST_3)), ?CTPAL("?TPTEST_3 before update ~p", [imem_meta:read(?TPTEST_3)]), Trans3 = fun() -> imem_meta:update(?TPTEST_3, {{?TPTEST_3, {{2000, 01, 01}, {12, 45, 55}}, undefined}, {?TPTEST_3, {{2000, 01, 01}, {12, 45, 56}}, "alternative"}}), end, ?assertEqual({?TPTEST_3, {{2000, 1, 1}, {12, 45, 57}}, undefined}, imem_meta:return_atomic(imem_meta:transaction(Trans3))), ?CTPAL("?TPTEST_3 after update ~p", [imem_meta:read(?TPTEST_3)]), ?assertEqual(2, imem_meta:table_size(?TPTEST_3)), Keys4 = [ {1, {?TPTEST_3, {{2000, 1, 1}, {12, 45, 59}}, undefined}} ], U = unknown, {_, _DefRec, TrigFun} = imem_meta:trigger_infos(?TPTEST_3), ?assertEqual(Keys4, imem_meta:update_tables([[{imem, ?TPTEST_3, set}, 1, {}, {?TPTEST_3, {{2000, 01, 01}, {12, 45, 59}}, undefined}, TrigFun, U, []]], optimistic)), ?assertException(throw, {ClEr, {"Not null constraint violation", {1, {?TPTEST_3, _}}}}, imem_meta:update_tables([[{imem, ?TPTEST_3, set}, 1, {}, {?TPTEST_3, ?nav, undefined}, TrigFun, U, []]], optimistic)), ?assertException(throw, {ClEr, {"Not null constraint violation", {1, {?TPTEST_3, _}}}}, imem_meta:update_tables([[{imem, ?TPTEST_3, set}, 1, {}, {?TPTEST_3, {{2000, 01, 01}, {12, 45, 59}}, ?nav}, TrigFun, U, []]], optimistic)), ?assertEqual([?TPTEST_1, ?TPTEST_1IDX, ?TPTEST_2, ?TPTEST_3], lists:sort(imem_meta:tables_starting_with(?TPTEST))), ?assertEqual([?TPTEST_1, ?TPTEST_1IDX, ?TPTEST_2, ?TPTEST_3], lists:sort(imem_meta:tables_starting_with(?TPTEST))), _DdNode0 = imem_meta:read(ddNode), ?CTPAL("ddNode0 ~p", [_DdNode0]), _DdNode1 = imem_meta:read(ddNode, node()), ?CTPAL("ddNode1 ~p", [_DdNode1]), _DdNode2 = imem_meta:select(ddNode, ?MatchAllRecords), ?CTPAL("ddNode2 ~p", [_DdNode2]), Schema0 = [{ddSchema, {imem_meta:schema(), node()}, []}], ?assertEqual(Schema0, imem_meta:read(ddSchema)), ?assertEqual({Schema0, true}, imem_meta:select(ddSchema, ?MatchAllRecords, 1000)), ?assertEqual(ok, imem_meta:drop_table(?TPTEST_3)), ?assertEqual(ok, imem_meta:drop_table(?TPTEST_2)), ?assertEqual(ok, imem_meta:drop_table(?TPTEST_1)), ok. meta_partitions(_Config) -> ?CTPAL("Start"), ClEr = 'ClientError', UiEx = 'UnimplementedException', LogTable = imem_meta:physical_table_name(?LOG_TABLE), ?assert(lists:member(LogTable, imem_meta:physical_table_names(?LOG_TABLE))), ?assertEqual(LogTable, imem_meta:physical_table_name(atom_to_list(?LOG_TABLE) ++ imem_meta:node_shard())), ?assertEqual([], imem_meta:physical_table_names(?TPTEST_1000@)), ?assertException(throw, {ClEr, {"Table to be purged does not exist", ?TPTEST_1000@}}, imem_meta:purge_table(?TPTEST_1000@)), ?assertException(throw, {UiEx, {"Purge not supported on this table type", not_existing_table}}, imem_meta:purge_table(not_existing_table)), ?assert(imem_meta:purge_table(?LOG_TABLE) >= 0), ?assertException(throw, {UiEx, {"Purge not supported on this table type", ddTable}}, imem_meta:purge_table(ddTable)), ?assertNot(lists:member({imem_meta:schema(), ?TPTEST_1000@}, [element(2, A) || A <- imem_meta:read(ddAlias)])), TimePartTable0 = imem_meta:physical_table_name(?TPTEST_1000@), ?CTPAL("TimePartTable ~p", [TimePartTable0]), ?assertEqual(TimePartTable0, imem_meta:physical_table_name(?TPTEST_1000@, ?TIMESTAMP)), ?assertMatch({ok, _}, imem_meta:create_check_table(?TPTEST_1000@, {record_info(fields, ddLog), ?ddLog, #ddLog{}}, [{record_name, ddLog}, {type, ordered_set}], system)), ?CTPAL("Alias0~n~p", [imem_meta:read(ddAlias)]), ?assertEqual(ok, imem_meta:check_table(TimePartTable0)), ?assertEqual(0, imem_meta:table_size(TimePartTable0)), ?assertEqual([TimePartTable0], imem_meta:physical_table_names(?TPTEST_1000@)), ?assertMatch({ok, _}, imem_meta:create_check_table(?TPTEST_1000@, {record_info(fields, ddLog), ?ddLog, #ddLog{}}, [{record_name, ddLog}, {type, ordered_set}], system)), ct:sleep(1000), ?assert(lists:member({imem_meta:schema(), ?TPTEST_1000@}, [element(2, A) || A <- imem_meta:read(ddAlias)])), ?assertNot(lists:member({imem_meta:schema(), ?TPTEST_100@}, [element(2, A) || A <- imem_meta:read(ddAlias)])), ct:sleep(1000), ToDo : Check period mismatch also for existing tables ( accidentally matching a rolling valid period ) ? assertException(throw , { ' ClientError ' , { " Name conflict ( different rolling period ) in ddAlias " , ? TPTEST_100@ } } , { record_info(fields , ddLog ) , ? , # ddLog { } } LogRec = #ddLog{logTime = ?TIME_UID, logLevel = info, pid = self() , module = ?MODULE, function = meta_partitions, node = node() , fields = [], message = <<"some log message">> }, ?assertEqual(ok, imem_meta:write(?TPTEST_1000@, LogRec)), ?assertEqual(1, imem_meta:table_size(TimePartTable0)), ?assertEqual(0, imem_meta:purge_table(?TPTEST_1000@)), {Secs, Mics, Node, _} = ?TIME_UID, LogRecF = LogRec#ddLog{logTime = {Secs + 2000, Mics, Node, ?INTEGER_UID}}, ?assertEqual(ok, imem_meta:write(?TPTEST_1000@, LogRecF)), ?CTPAL("physical_table_names ~p", [imem_meta:physical_table_names(?TPTEST_1000@)]), ?assertEqual(0, imem_meta:purge_table(?TPTEST_1000@, [{purge_delay, 10000}])), ?assertEqual(0, imem_meta:purge_table(?TPTEST_1000@)), PurgeResult = imem_meta:purge_table(?TPTEST_1000@, [{purge_delay, -3000}]), ?CTPAL("PurgeResult ~p", [PurgeResult]), ?assert(PurgeResult > 0), ?assertEqual(0, imem_meta:purge_table(?TPTEST_1000@)), ?assertEqual(ok, imem_meta:drop_table(?TPTEST_1000@)), ?assertEqual([], imem_meta:physical_table_names(?TPTEST_1000@)), Alias0a = imem_meta:read(ddAlias), ?assertEqual(false, lists:member({imem_meta:schema(), ?TPTEST_1000@}, [element(2, A) || A <- Alias0a])), TimePartTable1 = imem_meta:physical_table_name(?TPTEST_999999999@_), ?assertEqual(?TPTEST_1999999998@_, TimePartTable1), ?assertEqual(TimePartTable1, imem_meta:physical_table_name(?TPTEST_999999999@_, ?TIMESTAMP)), ?assertMatch({ok, _}, imem_meta:create_check_table(?TPTEST_999999999@_, {record_info(fields, ddLog), ?ddLog, #ddLog{}}, [{record_name, ddLog}, {type, ordered_set}], system)), ?assertEqual(ok, imem_meta:check_table(TimePartTable1)), ?assertEqual([TimePartTable1], imem_meta:physical_table_names(?TPTEST_999999999@_)), ?assertEqual(0, imem_meta:table_size(TimePartTable1)), ?assertMatch({ok, _}, imem_meta:create_check_table(?TPTEST_999999999@_, {record_info(fields, ddLog), ?ddLog, #ddLog{}}, [{record_name, ddLog}, {type, ordered_set}], system)), Alias1 = imem_meta:read(ddAlias), ?CTPAL("Alias1 ~p", [[element(2, A) || A <- Alias1]]), ?assert(lists:member({imem_meta:schema(), ?TPTEST_999999999@_}, [element(2, A) || A <- Alias1])), ?assertEqual(ok, imem_meta:write(?TPTEST_999999999@_, LogRec)), ?assertEqual(1, imem_meta:table_size(TimePartTable1)), ?assertEqual(0, imem_meta:purge_table(?TPTEST_999999999@_)), ?assertEqual(ok, imem_meta:write(?TPTEST_999999999@_, LogRecP)), ?CTPAL("Big Partition Tables after back-insert ~p", [imem_meta:physical_table_names(?TPTEST_999999999@_)]), using 2 - tuple ? TIMESTAMP format here for backward compatibility test ?assertEqual(ok, imem_meta:write(?TPTEST_999999999@_, LogRecFF)), ?CTPAL("Big Partition Tables after forward-insert ~p", [imem_meta:physical_table_names(?TPTEST_999999999@_)]), ?assert(imem_meta:purge_table(?TPTEST_999999999@_) > 0), ?assertEqual(ok, imem_meta:drop_table(?TPTEST_999999999@_)), Alias1a = imem_meta:read(ddAlias), ?assertEqual(false, lists:member({imem_meta:schema(), ?TPTEST_999999999@_}, [element(2, A) || A <- Alias1a])), ?assertEqual([], imem_meta:physical_table_names(?TPTEST_999999999@_)), ?CTPAL("dummy_table_name"), ?assertEqual({error, {"Table template not found in ddAlias", dummy_table_name}}, imem_meta:create_partitioned_table_sync(dummy_table_name, dummy_table_name)), ?CTPAL("physical_table_names"), ?assertEqual([], imem_meta:physical_table_names(?TPTEST_3@)), ?assertMatch({ok, _}, imem_meta:create_check_table(?TPTEST_3@, {record_info(fields, ddLog), ?ddLog, #ddLog{}}, ?LOG_TABLE_OPTS, system)), ?assertEqual(1, length(imem_meta:physical_table_names(?TPTEST_3@))), ?CTPAL("LogRec3"), LogRec3 = #ddLog{logTime = ?TIMESTAMP, logLevel = debug, pid = self() , module = ?MODULE, function = test, node = node() , fields = [], message = <<>>, stacktrace = [] using 2 - tuple ? TIMESTAMP format here for backward compatibility test ct:sleep(30), can write to first partition ct:sleep(4000), one partition at least created by partition rolling can write to second partition ( maybe third ) ct:sleep(4000), FL3Tables = imem_meta:physical_table_names(?TPTEST_3@), ?CTPAL("Tables written ~p ~p", [?TPTEST_3@, FL3Tables]), ?assert(length(FL3Tables) >= 3), ct:sleep(4000), ?assert(length(imem_meta:physical_table_names(?TPTEST_3@)) >= 4), _ = {timeout, 5, fun() -> ?assertEqual(ok, imem_meta:drop_table(?TPTEST_3@)) end}, ok. meta_preparations(_Config) -> ?CTPAL("Start"), ?assertEqual(["Schema", ".", "BaseName", "_", "01234", "@", "Node"], imem_meta:parse_table_name("Schema.BaseName_01234@Node")), ?assertEqual(["Schema", ".", "BaseName", "", "", "", ""], imem_meta:parse_table_name("Schema.BaseName")), ?assertEqual(["", "", "BaseName", "_", "01234", "@", "Node"], imem_meta:parse_table_name("BaseName_01234@Node")), ?assertEqual(["", "", "BaseName", "", "", "@", "Node"], imem_meta:parse_table_name("BaseName@Node")), ?assertEqual(["", "", "BaseName", "", "", "@", ""], imem_meta:parse_table_name("BaseName@")), ?assertEqual(["", "", "BaseName", "", "", "", ""], imem_meta:parse_table_name("BaseName")), ?assertEqual(["Schema", ".", "Name_Period", "", "", "@", "Node"], imem_meta:parse_table_name('Schema.Name_Period@Node')), ?assertEqual(["Schema", ".", "Name", "_", "12345", "@", "Node"], imem_meta:parse_table_name('Schema.Name_12345@Node')), ?assertEqual(["Schema", ".", "Name_Period", "", "", "@", "_"], imem_meta:parse_table_name('Schema.Name_Period@_')), ?assertEqual(["Schema", ".", "Name", "_", "12345", "@", "_"], imem_meta:parse_table_name('Schema.Name_12345@_')), ?assertEqual(["Schema", ".", "Name_Period", "", "", "@", ""], imem_meta:parse_table_name('Schema.Name_Period@')), ?assertEqual(["Sch_01", ".", "Name", "_", "12345", "@", ""], imem_meta:parse_table_name('Sch_01.Name_12345@')), ?assertEqual(["Sch_99", ".", "Name_Period", "", "", "", ""], imem_meta:parse_table_name('Sch_99.Name_Period')), ?assertEqual(["Sch_ma", ".", "Name_12345", "", "", "", ""], imem_meta:parse_table_name('Sch_ma.Name_12345')), ?assertEqual(["", "", "Name_Period", "", "", "@", "Node"], imem_meta:parse_table_name('Name_Period@Node')), ?assertEqual(["", "", "Name", "_", "12345", "@", "Node"], imem_meta:parse_table_name('Name_12345@Node')), ?assertEqual(["", "", "Name_Period", "", "", "@", "_"], imem_meta:parse_table_name('Name_Period@_')), ?assertEqual(["", "", "Name", "_", "12345", "@", "_"], imem_meta:parse_table_name('Name_12345@_')), ?assertEqual(["", "", "Name_Period", "", "", "@", ""], imem_meta:parse_table_name('Name_Period@')), ?assertEqual(["", "", "Name", "_", "12345", "@", ""], imem_meta:parse_table_name('Name_12345@')), ?assertEqual(["", "", "Name_Period", "", "", "", ""], imem_meta:parse_table_name('Name_Period')), ?assertEqual(["", "", "Name_12345", "", "", "", ""], imem_meta:parse_table_name('Name_12345')), ?assertEqual(true, imem_meta:is_time_partitioned_alias(?TPTEST_999999999@_)), ?assertEqual(true, imem_meta:is_time_partitioned_alias(?TPTEST_1000@)), ?assertEqual(true, imem_meta:is_time_partitioned_alias(tpTest_123@)), ?assertEqual(true, imem_meta:is_time_partitioned_alias(tpTest_123@_)), ?assertEqual(true, imem_meta:is_time_partitioned_alias(tpTest_123@local)), ?assertEqual(true, imem_meta:is_time_partitioned_alias(tpTest_123@testnode)), ?assertEqual(false, imem_meta:is_time_partitioned_alias(tpTest)), ?assertEqual(false, imem_meta:is_time_partitioned_alias(tpTest@)), ?assertEqual(false, imem_meta:is_time_partitioned_alias(tpTest@_)), ?assertEqual(false, imem_meta:is_time_partitioned_alias(tpTest123@_)), ?assertEqual(false, imem_meta:is_time_partitioned_alias(tpTest_12A@)), ?assertEqual(false, imem_meta:is_time_partitioned_alias(tpTest@local)), ?assertEqual(false, imem_meta:is_time_partitioned_alias(tpTest@testnode)), ?assertEqual(true, imem_meta:is_node_sharded_alias(?TPTEST_1000@)), ?assertEqual(true, imem_meta:is_node_sharded_alias(tpTest@)), ?assertEqual(true, imem_meta:is_node_sharded_alias(tpTest123@)), ?assertEqual(true, imem_meta:is_node_sharded_alias(tpTest_123@)), ?assertEqual(false, imem_meta:is_node_sharded_alias(?TPTEST_999999999@_)), ?assertEqual(false, imem_meta:is_node_sharded_alias(tpTest_1000)), ?assertEqual(false, imem_meta:is_node_sharded_alias(tpTest1000)), ?assertEqual(false, imem_meta:is_node_sharded_alias(tpTest123@_)), ?assertEqual(false, imem_meta:is_node_sharded_alias(tpTest_123@_)), ok. read_write_test(Tab, Key, N) -> Upd = fun() -> [{Tab, Key, Val}] = imem_meta:read(Tab, Key), imem_meta:write(Tab, {Tab, Key, Val + N}) end, imem_meta:transaction(Upd). receive_results(N, Acc) -> receive Result -> case N of 1 -> ?CTPAL("Result ~p", [Result]), [Result | Acc]; _ -> ?CTPAL("Result ~p", [Result]), receive_results(N - 1, [Result | Acc]) end after 1000 -> ?CTPAL("Result timeout"), Acc end.
3d9bed3e8dda7e07426a859d148db7bf4db61a3f81d77faa0d158a47ec18c7af
proof-ninja/ocaml-blake3
blake3.ml
external rust_hash : bytes -> bytes -> unit = "blake3_hash" [@@noalloc] external rust_hash_mc : bytes -> bytes -> unit = "blake3_hash_multicore" [@@noalloc] let hash size s = let bytes = Bytes.create size in rust_hash s bytes; bytes let hash_multicore size s = let bytes = Bytes.create size in rust_hash_mc s bytes; bytes
null
https://raw.githubusercontent.com/proof-ninja/ocaml-blake3/b83e491d2b71712c237264ec118b318e14176069/src/blake3.ml
ocaml
external rust_hash : bytes -> bytes -> unit = "blake3_hash" [@@noalloc] external rust_hash_mc : bytes -> bytes -> unit = "blake3_hash_multicore" [@@noalloc] let hash size s = let bytes = Bytes.create size in rust_hash s bytes; bytes let hash_multicore size s = let bytes = Bytes.create size in rust_hash_mc s bytes; bytes
8f909ec68a43d73dbcaa30fe516cc2c60f1536612c34e46f1470f5162ad890a4
sunshineclt/Racket-Helper
homework1-g2.rkt
#lang racket (define (dowork n m i) (define (print j) (display j) (display ",") (if (= j m) (display #\newline) (print (+ j 1)))) (print 1) (if (= i n) (void) (dowork n m (+ i 1)))) (define (loop) (let ((n (read)) (m (read))) (if (eq? n eof) (void) (begin (dowork n m 1) (loop))))) (loop)
null
https://raw.githubusercontent.com/sunshineclt/Racket-Helper/bf85f38dd8d084db68265bb98d8c38bada6494ec/%E9%99%88%E4%B9%90%E5%A4%A9/Week1/homework1-g2.rkt
racket
#lang racket (define (dowork n m i) (define (print j) (display j) (display ",") (if (= j m) (display #\newline) (print (+ j 1)))) (print 1) (if (= i n) (void) (dowork n m (+ i 1)))) (define (loop) (let ((n (read)) (m (read))) (if (eq? n eof) (void) (begin (dowork n m 1) (loop))))) (loop)
84734f494baa1fe0c1e69234f84a6518563883f80cdb407e31d4c5b7f18a858f
Deducteam/Dedukti
basic.ml
* Basic * { 2 Identifiers ( hashconsed strings ) } type ident = string let string_of_ident s = s let ident_eq s1 s2 = s1 == s2 || s1 = s2 type mident = string let string_of_mident s = s let mident_eq = ident_eq type name = mident * ident let mk_name md id = (md, id) let name_eq (m, s) (m', s') = mident_eq m m' && ident_eq s s' let md = fst let id = snd module WS = Weak.Make (struct type t = ident let equal = ident_eq let hash = Hashtbl.hash end) let hash_ident = WS.create 251 let mk_ident = WS.merge hash_ident let hash_mident = WS.create 251 let mk_mident md = WS.merge hash_mident md let dmark = mk_ident "$" module IdentSet = Set.Make (struct type t = ident let compare = compare end) module MidentSet = Set.Make (struct type t = mident let compare = compare end) module NameSet = Set.Make (struct type t = name let compare = compare end) * { 2 Lists with Length } module LList = struct type 'a t = {len : int; lst : 'a list} let nil = {len = 0; lst = []} let cons x {len; lst} = {len = len + 1; lst = x :: lst} let len x = x.len let lst x = x.lst let is_empty x = x.len = 0 let of_list lst = {len = List.length lst; lst} let of_array arr = {len = Array.length arr; lst = Array.to_list arr} let map f {len; lst} = {len; lst = List.map f lst} let mapi f {len; lst} = {len; lst = List.mapi f lst} let nth l i = assert (i < l.len); List.nth l.lst i end * { 2 Localization } type loc = int * int let dloc = (-1, -1) let mk_loc l c = (l, c) let of_loc l = l * { 2 Debugging } module Debug = struct type flag = string * bool ref let new_flag v m = (m, ref v) let set value (_, fl) = fl := value let register_flag = new_flag false let enable_flag = set true let disable_flag = set false let do_debug fmt = Format.( kfprintf (fun _ -> pp_print_newline err_formatter (); pp_print_flush err_formatter ()) err_formatter fmt) let ignore_debug fmt = Format.(ifprintf err_formatter) fmt let debug (msg, fl) = if !fl then fun fmt -> do_debug ("[%s] " ^^ fmt) msg else ignore_debug [@@inline] let debug_eval (_, fl) clos = if !fl then clos () let d_warn = new_flag true "Warning" let d_notice = new_flag false "Notice" end * { 2 Misc functions } let bind_opt f = function None -> None | Some x -> f x let map_opt f = function None -> None | Some x -> Some (f x) let fold_map (f : 'b -> 'a -> 'c * 'b) (b0 : 'b) (alst : 'a list) : 'c list * 'b = let clst, b2 = List.fold_left (fun (accu, b1) a -> let c, b2 = f b1 a in (c :: accu, b2)) ([], b0) alst in (List.rev clst, b2) let split x = let rec aux acc n l = if n <= 0 then (List.rev acc, l) else aux (List.hd l :: acc) (n - 1) (List.tl l) in aux [] x let rev_mapi f l = let rec rmap_f i accu = function | [] -> accu | a :: l -> rmap_f (i + 1) (f i a :: accu) l in rmap_f 0 [] l let concat l1 = function [] -> l1 | l2 -> l1 @ l2 * { 2 Printing functions } type 'a printer = Format.formatter -> 'a -> unit let string_of fp = Format.asprintf "%a" fp let pp_ident fmt id = Format.fprintf fmt "%s" id let pp_mident fmt md = Format.fprintf fmt "%s" md let pp_name fmt (md, id) = Format.fprintf fmt "%a.%a" pp_mident md pp_ident id let pp_loc fmt = function | -1, -1 -> Format.fprintf fmt "unspecified location" | l, -1 -> Format.fprintf fmt "line:%i" l | l, c -> Format.fprintf fmt "line:%i column:%i" l c let format_of_sep str fmt () : unit = Format.fprintf fmt "%s" str let pp_list sep pp fmt l = Format.pp_print_list ~pp_sep:(format_of_sep sep) pp fmt l let pp_llist sep pp fmt l = pp_list sep pp fmt (LList.lst l) let pp_arr sep pp fmt a = pp_list sep pp fmt (Array.to_list a) let pp_lazy pp fmt l = Format.fprintf fmt "%a" pp (Lazy.force l) let pp_option def pp fmt = function | None -> Format.fprintf fmt "%s" def | Some a -> Format.fprintf fmt "%a" pp a let pp_pair pp_fst pp_snd fmt x = Format.fprintf fmt "(%a, %a)" pp_fst (fst x) pp_snd (snd x) let pp_triple pp_fst pp_snd pp_thd fmt (x, y, z) = Format.fprintf fmt "(%a, %a, %a)" pp_fst x pp_snd y pp_thd z
null
https://raw.githubusercontent.com/Deducteam/Dedukti/7124a3edbaecf2d8a9046272cbc4d0d09cc3fad0/kernel/basic.ml
ocaml
* Basic * { 2 Identifiers ( hashconsed strings ) } type ident = string let string_of_ident s = s let ident_eq s1 s2 = s1 == s2 || s1 = s2 type mident = string let string_of_mident s = s let mident_eq = ident_eq type name = mident * ident let mk_name md id = (md, id) let name_eq (m, s) (m', s') = mident_eq m m' && ident_eq s s' let md = fst let id = snd module WS = Weak.Make (struct type t = ident let equal = ident_eq let hash = Hashtbl.hash end) let hash_ident = WS.create 251 let mk_ident = WS.merge hash_ident let hash_mident = WS.create 251 let mk_mident md = WS.merge hash_mident md let dmark = mk_ident "$" module IdentSet = Set.Make (struct type t = ident let compare = compare end) module MidentSet = Set.Make (struct type t = mident let compare = compare end) module NameSet = Set.Make (struct type t = name let compare = compare end) * { 2 Lists with Length } module LList = struct type 'a t = {len : int; lst : 'a list} let nil = {len = 0; lst = []} let cons x {len; lst} = {len = len + 1; lst = x :: lst} let len x = x.len let lst x = x.lst let is_empty x = x.len = 0 let of_list lst = {len = List.length lst; lst} let of_array arr = {len = Array.length arr; lst = Array.to_list arr} let map f {len; lst} = {len; lst = List.map f lst} let mapi f {len; lst} = {len; lst = List.mapi f lst} let nth l i = assert (i < l.len); List.nth l.lst i end * { 2 Localization } type loc = int * int let dloc = (-1, -1) let mk_loc l c = (l, c) let of_loc l = l * { 2 Debugging } module Debug = struct type flag = string * bool ref let new_flag v m = (m, ref v) let set value (_, fl) = fl := value let register_flag = new_flag false let enable_flag = set true let disable_flag = set false let do_debug fmt = Format.( kfprintf (fun _ -> pp_print_newline err_formatter (); pp_print_flush err_formatter ()) err_formatter fmt) let ignore_debug fmt = Format.(ifprintf err_formatter) fmt let debug (msg, fl) = if !fl then fun fmt -> do_debug ("[%s] " ^^ fmt) msg else ignore_debug [@@inline] let debug_eval (_, fl) clos = if !fl then clos () let d_warn = new_flag true "Warning" let d_notice = new_flag false "Notice" end * { 2 Misc functions } let bind_opt f = function None -> None | Some x -> f x let map_opt f = function None -> None | Some x -> Some (f x) let fold_map (f : 'b -> 'a -> 'c * 'b) (b0 : 'b) (alst : 'a list) : 'c list * 'b = let clst, b2 = List.fold_left (fun (accu, b1) a -> let c, b2 = f b1 a in (c :: accu, b2)) ([], b0) alst in (List.rev clst, b2) let split x = let rec aux acc n l = if n <= 0 then (List.rev acc, l) else aux (List.hd l :: acc) (n - 1) (List.tl l) in aux [] x let rev_mapi f l = let rec rmap_f i accu = function | [] -> accu | a :: l -> rmap_f (i + 1) (f i a :: accu) l in rmap_f 0 [] l let concat l1 = function [] -> l1 | l2 -> l1 @ l2 * { 2 Printing functions } type 'a printer = Format.formatter -> 'a -> unit let string_of fp = Format.asprintf "%a" fp let pp_ident fmt id = Format.fprintf fmt "%s" id let pp_mident fmt md = Format.fprintf fmt "%s" md let pp_name fmt (md, id) = Format.fprintf fmt "%a.%a" pp_mident md pp_ident id let pp_loc fmt = function | -1, -1 -> Format.fprintf fmt "unspecified location" | l, -1 -> Format.fprintf fmt "line:%i" l | l, c -> Format.fprintf fmt "line:%i column:%i" l c let format_of_sep str fmt () : unit = Format.fprintf fmt "%s" str let pp_list sep pp fmt l = Format.pp_print_list ~pp_sep:(format_of_sep sep) pp fmt l let pp_llist sep pp fmt l = pp_list sep pp fmt (LList.lst l) let pp_arr sep pp fmt a = pp_list sep pp fmt (Array.to_list a) let pp_lazy pp fmt l = Format.fprintf fmt "%a" pp (Lazy.force l) let pp_option def pp fmt = function | None -> Format.fprintf fmt "%s" def | Some a -> Format.fprintf fmt "%a" pp a let pp_pair pp_fst pp_snd fmt x = Format.fprintf fmt "(%a, %a)" pp_fst (fst x) pp_snd (snd x) let pp_triple pp_fst pp_snd pp_thd fmt (x, y, z) = Format.fprintf fmt "(%a, %a, %a)" pp_fst x pp_snd y pp_thd z
fe1967cf3e8c40efa318ad1dcf5b1259f336d2968fa7ba1bfce730151c78dd97
mbj/stratosphere
Application.hs
module Stratosphere.KinesisAnalyticsV2.Application ( module Exports, Application(..), mkApplication ) where import qualified Data.Aeson as JSON import qualified Stratosphere.Prelude as Prelude import Stratosphere.Property import {-# SOURCE #-} Stratosphere.KinesisAnalyticsV2.Application.ApplicationConfigurationProperty as Exports import {-# SOURCE #-} Stratosphere.KinesisAnalyticsV2.Application.ApplicationMaintenanceConfigurationProperty as Exports import {-# SOURCE #-} Stratosphere.KinesisAnalyticsV2.Application.RunConfigurationProperty as Exports import Stratosphere.ResourceProperties import Stratosphere.Tag import Stratosphere.Value data Application = Application {applicationConfiguration :: (Prelude.Maybe ApplicationConfigurationProperty), applicationDescription :: (Prelude.Maybe (Value Prelude.Text)), applicationMaintenanceConfiguration :: (Prelude.Maybe ApplicationMaintenanceConfigurationProperty), applicationMode :: (Prelude.Maybe (Value Prelude.Text)), applicationName :: (Prelude.Maybe (Value Prelude.Text)), runConfiguration :: (Prelude.Maybe RunConfigurationProperty), runtimeEnvironment :: (Value Prelude.Text), serviceExecutionRole :: (Value Prelude.Text), tags :: (Prelude.Maybe [Tag])} mkApplication :: Value Prelude.Text -> Value Prelude.Text -> Application mkApplication runtimeEnvironment serviceExecutionRole = Application {runtimeEnvironment = runtimeEnvironment, serviceExecutionRole = serviceExecutionRole, applicationConfiguration = Prelude.Nothing, applicationDescription = Prelude.Nothing, applicationMaintenanceConfiguration = Prelude.Nothing, applicationMode = Prelude.Nothing, applicationName = Prelude.Nothing, runConfiguration = Prelude.Nothing, tags = Prelude.Nothing} instance ToResourceProperties Application where toResourceProperties Application {..} = ResourceProperties {awsType = "AWS::KinesisAnalyticsV2::Application", supportsTags = Prelude.True, properties = Prelude.fromList ((Prelude.<>) ["RuntimeEnvironment" JSON..= runtimeEnvironment, "ServiceExecutionRole" JSON..= serviceExecutionRole] (Prelude.catMaybes [(JSON..=) "ApplicationConfiguration" Prelude.<$> applicationConfiguration, (JSON..=) "ApplicationDescription" Prelude.<$> applicationDescription, (JSON..=) "ApplicationMaintenanceConfiguration" Prelude.<$> applicationMaintenanceConfiguration, (JSON..=) "ApplicationMode" Prelude.<$> applicationMode, (JSON..=) "ApplicationName" Prelude.<$> applicationName, (JSON..=) "RunConfiguration" Prelude.<$> runConfiguration, (JSON..=) "Tags" Prelude.<$> tags]))} instance JSON.ToJSON Application where toJSON Application {..} = JSON.object (Prelude.fromList ((Prelude.<>) ["RuntimeEnvironment" JSON..= runtimeEnvironment, "ServiceExecutionRole" JSON..= serviceExecutionRole] (Prelude.catMaybes [(JSON..=) "ApplicationConfiguration" Prelude.<$> applicationConfiguration, (JSON..=) "ApplicationDescription" Prelude.<$> applicationDescription, (JSON..=) "ApplicationMaintenanceConfiguration" Prelude.<$> applicationMaintenanceConfiguration, (JSON..=) "ApplicationMode" Prelude.<$> applicationMode, (JSON..=) "ApplicationName" Prelude.<$> applicationName, (JSON..=) "RunConfiguration" Prelude.<$> runConfiguration, (JSON..=) "Tags" Prelude.<$> tags]))) instance Property "ApplicationConfiguration" Application where type PropertyType "ApplicationConfiguration" Application = ApplicationConfigurationProperty set newValue Application {..} = Application {applicationConfiguration = Prelude.pure newValue, ..} instance Property "ApplicationDescription" Application where type PropertyType "ApplicationDescription" Application = Value Prelude.Text set newValue Application {..} = Application {applicationDescription = Prelude.pure newValue, ..} instance Property "ApplicationMaintenanceConfiguration" Application where type PropertyType "ApplicationMaintenanceConfiguration" Application = ApplicationMaintenanceConfigurationProperty set newValue Application {..} = Application {applicationMaintenanceConfiguration = Prelude.pure newValue, ..} instance Property "ApplicationMode" Application where type PropertyType "ApplicationMode" Application = Value Prelude.Text set newValue Application {..} = Application {applicationMode = Prelude.pure newValue, ..} instance Property "ApplicationName" Application where type PropertyType "ApplicationName" Application = Value Prelude.Text set newValue Application {..} = Application {applicationName = Prelude.pure newValue, ..} instance Property "RunConfiguration" Application where type PropertyType "RunConfiguration" Application = RunConfigurationProperty set newValue Application {..} = Application {runConfiguration = Prelude.pure newValue, ..} instance Property "RuntimeEnvironment" Application where type PropertyType "RuntimeEnvironment" Application = Value Prelude.Text set newValue Application {..} = Application {runtimeEnvironment = newValue, ..} instance Property "ServiceExecutionRole" Application where type PropertyType "ServiceExecutionRole" Application = Value Prelude.Text set newValue Application {..} = Application {serviceExecutionRole = newValue, ..} instance Property "Tags" Application where type PropertyType "Tags" Application = [Tag] set newValue Application {..} = Application {tags = Prelude.pure newValue, ..}
null
https://raw.githubusercontent.com/mbj/stratosphere/c70f301715425247efcda29af4f3fcf7ec04aa2f/services/kinesisanalyticsv2/gen/Stratosphere/KinesisAnalyticsV2/Application.hs
haskell
# SOURCE # # SOURCE # # SOURCE #
module Stratosphere.KinesisAnalyticsV2.Application ( module Exports, Application(..), mkApplication ) where import qualified Data.Aeson as JSON import qualified Stratosphere.Prelude as Prelude import Stratosphere.Property import Stratosphere.ResourceProperties import Stratosphere.Tag import Stratosphere.Value data Application = Application {applicationConfiguration :: (Prelude.Maybe ApplicationConfigurationProperty), applicationDescription :: (Prelude.Maybe (Value Prelude.Text)), applicationMaintenanceConfiguration :: (Prelude.Maybe ApplicationMaintenanceConfigurationProperty), applicationMode :: (Prelude.Maybe (Value Prelude.Text)), applicationName :: (Prelude.Maybe (Value Prelude.Text)), runConfiguration :: (Prelude.Maybe RunConfigurationProperty), runtimeEnvironment :: (Value Prelude.Text), serviceExecutionRole :: (Value Prelude.Text), tags :: (Prelude.Maybe [Tag])} mkApplication :: Value Prelude.Text -> Value Prelude.Text -> Application mkApplication runtimeEnvironment serviceExecutionRole = Application {runtimeEnvironment = runtimeEnvironment, serviceExecutionRole = serviceExecutionRole, applicationConfiguration = Prelude.Nothing, applicationDescription = Prelude.Nothing, applicationMaintenanceConfiguration = Prelude.Nothing, applicationMode = Prelude.Nothing, applicationName = Prelude.Nothing, runConfiguration = Prelude.Nothing, tags = Prelude.Nothing} instance ToResourceProperties Application where toResourceProperties Application {..} = ResourceProperties {awsType = "AWS::KinesisAnalyticsV2::Application", supportsTags = Prelude.True, properties = Prelude.fromList ((Prelude.<>) ["RuntimeEnvironment" JSON..= runtimeEnvironment, "ServiceExecutionRole" JSON..= serviceExecutionRole] (Prelude.catMaybes [(JSON..=) "ApplicationConfiguration" Prelude.<$> applicationConfiguration, (JSON..=) "ApplicationDescription" Prelude.<$> applicationDescription, (JSON..=) "ApplicationMaintenanceConfiguration" Prelude.<$> applicationMaintenanceConfiguration, (JSON..=) "ApplicationMode" Prelude.<$> applicationMode, (JSON..=) "ApplicationName" Prelude.<$> applicationName, (JSON..=) "RunConfiguration" Prelude.<$> runConfiguration, (JSON..=) "Tags" Prelude.<$> tags]))} instance JSON.ToJSON Application where toJSON Application {..} = JSON.object (Prelude.fromList ((Prelude.<>) ["RuntimeEnvironment" JSON..= runtimeEnvironment, "ServiceExecutionRole" JSON..= serviceExecutionRole] (Prelude.catMaybes [(JSON..=) "ApplicationConfiguration" Prelude.<$> applicationConfiguration, (JSON..=) "ApplicationDescription" Prelude.<$> applicationDescription, (JSON..=) "ApplicationMaintenanceConfiguration" Prelude.<$> applicationMaintenanceConfiguration, (JSON..=) "ApplicationMode" Prelude.<$> applicationMode, (JSON..=) "ApplicationName" Prelude.<$> applicationName, (JSON..=) "RunConfiguration" Prelude.<$> runConfiguration, (JSON..=) "Tags" Prelude.<$> tags]))) instance Property "ApplicationConfiguration" Application where type PropertyType "ApplicationConfiguration" Application = ApplicationConfigurationProperty set newValue Application {..} = Application {applicationConfiguration = Prelude.pure newValue, ..} instance Property "ApplicationDescription" Application where type PropertyType "ApplicationDescription" Application = Value Prelude.Text set newValue Application {..} = Application {applicationDescription = Prelude.pure newValue, ..} instance Property "ApplicationMaintenanceConfiguration" Application where type PropertyType "ApplicationMaintenanceConfiguration" Application = ApplicationMaintenanceConfigurationProperty set newValue Application {..} = Application {applicationMaintenanceConfiguration = Prelude.pure newValue, ..} instance Property "ApplicationMode" Application where type PropertyType "ApplicationMode" Application = Value Prelude.Text set newValue Application {..} = Application {applicationMode = Prelude.pure newValue, ..} instance Property "ApplicationName" Application where type PropertyType "ApplicationName" Application = Value Prelude.Text set newValue Application {..} = Application {applicationName = Prelude.pure newValue, ..} instance Property "RunConfiguration" Application where type PropertyType "RunConfiguration" Application = RunConfigurationProperty set newValue Application {..} = Application {runConfiguration = Prelude.pure newValue, ..} instance Property "RuntimeEnvironment" Application where type PropertyType "RuntimeEnvironment" Application = Value Prelude.Text set newValue Application {..} = Application {runtimeEnvironment = newValue, ..} instance Property "ServiceExecutionRole" Application where type PropertyType "ServiceExecutionRole" Application = Value Prelude.Text set newValue Application {..} = Application {serviceExecutionRole = newValue, ..} instance Property "Tags" Application where type PropertyType "Tags" Application = [Tag] set newValue Application {..} = Application {tags = Prelude.pure newValue, ..}
8a2008a86f5e943be46596a49479d1942a4fe994448ee899983afb32cd3bc638
roburio/albatross
vmm_ring.mli
( c ) 2018 , all rights reserved type 'a t val create : ?size:int -> 'a -> unit -> 'a t val write : 'a t -> Ptime.t * 'a -> unit val read_last : 'a t -> ?tst:('a -> bool) -> int -> (Ptime.t * 'a) list val read_history : 'a t -> ?tst:('a -> bool) -> Ptime.t -> (Ptime.t * 'a) list
null
https://raw.githubusercontent.com/roburio/albatross/3cf3d6dc56868a800967cbca2b29e743e7b2d487/src/vmm_ring.mli
ocaml
( c ) 2018 , all rights reserved type 'a t val create : ?size:int -> 'a -> unit -> 'a t val write : 'a t -> Ptime.t * 'a -> unit val read_last : 'a t -> ?tst:('a -> bool) -> int -> (Ptime.t * 'a) list val read_history : 'a t -> ?tst:('a -> bool) -> Ptime.t -> (Ptime.t * 'a) list
d467ab9c1a6e790e96305c688f85bdb7d5cdd4f0bee25323ff704347bd2c6fd2
roehst/tapl-implementations
syntax.ml
open Format open Support.Error open Support.Pervasive (* ---------------------------------------------------------------------- *) type ty = TyTop | TyArr of ty * ty | TyRecord of (string * ty) list | TyBool type term = TmVar of info * int * int | TmAbs of info * string * ty * term | TmApp of info * term * term | TmRecord of info * (string * term) list | TmProj of info * term * string | TmTrue of info | TmFalse of info | TmIf of info * term * term * term type binding = NameBind | VarBind of ty type context = (string * binding) list type command = | Eval of info * term | Bind of info * string * binding (* ---------------------------------------------------------------------- *) (* Context management *) let emptycontext = [] let ctxlength ctx = List.length ctx let addbinding ctx x bind = (x,bind)::ctx let addname ctx x = addbinding ctx x NameBind let rec isnamebound ctx x = match ctx with [] -> false | (y,_)::rest -> if y=x then true else isnamebound rest x let rec pickfreshname ctx x = if isnamebound ctx x then pickfreshname ctx (x^"'") else ((x,NameBind)::ctx), x let index2name fi ctx x = try let (xn,_) = List.nth ctx x in xn with Failure _ -> let msg = Printf.sprintf "Variable lookup failure: offset: %d, ctx size: %d" in error fi (msg x (List.length ctx)) let rec name2index fi ctx x = match ctx with [] -> error fi ("Identifier " ^ x ^ " is unbound") | (y,_)::rest -> if y=x then 0 else 1 + (name2index fi rest x) (* ---------------------------------------------------------------------- *) (* Shifting *) let tmmap onvar c t = let rec walk c t = match t with TmVar(fi,x,n) -> onvar fi c x n | TmAbs(fi,x,tyT1,t2) -> TmAbs(fi,x,tyT1,walk (c+1) t2) | TmApp(fi,t1,t2) -> TmApp(fi,walk c t1,walk c t2) | TmProj(fi,t1,l) -> TmProj(fi,walk c t1,l) | TmRecord(fi,fields) -> TmRecord(fi,List.map (fun (li,ti) -> (li,walk c ti)) fields) | TmTrue(fi) as t -> t | TmFalse(fi) as t -> t | TmIf(fi,t1,t2,t3) -> TmIf(fi,walk c t1,walk c t2,walk c t3) in walk c t let termShiftAbove d c t = tmmap (fun fi c x n -> if x>=c then TmVar(fi,x+d,n+d) else TmVar(fi,x,n+d)) c t let termShift d t = termShiftAbove d 0 t (* ---------------------------------------------------------------------- *) (* Substitution *) let termSubst j s t = tmmap (fun fi j x n -> if x=j then termShift j s else TmVar(fi,x,n)) j t let termSubstTop s t = termShift (-1) (termSubst 0 (termShift 1 s) t) (* ---------------------------------------------------------------------- *) (* Context management (continued) *) let rec getbinding fi ctx i = try let (_,bind) = List.nth ctx i in bind with Failure _ -> let msg = Printf.sprintf "Variable lookup failure: offset: %d, ctx size: %d" in error fi (msg i (List.length ctx)) let getTypeFromContext fi ctx i = match getbinding fi ctx i with VarBind(tyT) -> tyT | _ -> error fi ("getTypeFromContext: Wrong kind of binding for variable " ^ (index2name fi ctx i)) (* ---------------------------------------------------------------------- *) (* Extracting file info *) let tmInfo t = match t with TmVar(fi,_,_) -> fi | TmAbs(fi,_,_,_) -> fi | TmApp(fi, _, _) -> fi | TmProj(fi,_,_) -> fi | TmRecord(fi,_) -> fi | TmTrue(fi) -> fi | TmFalse(fi) -> fi | TmIf(fi,_,_,_) -> fi (* ---------------------------------------------------------------------- *) (* Printing *) The printing functions call these utility functions to insert grouping information and line - breaking hints for the pretty - printing library : obox Open a " box " whose contents will be indented by two spaces if the whole box can not fit on the current line obox0 Same but indent continuation lines to the same column as the beginning of the box rather than 2 more columns to the right cbox Close the current box break Insert a breakpoint indicating where the line maybe broken if necessary . See the documentation for the Format module in the OCaml library for more details . information and line-breaking hints for the pretty-printing library: obox Open a "box" whose contents will be indented by two spaces if the whole box cannot fit on the current line obox0 Same but indent continuation lines to the same column as the beginning of the box rather than 2 more columns to the right cbox Close the current box break Insert a breakpoint indicating where the line maybe broken if necessary. See the documentation for the Format module in the OCaml library for more details. *) let obox0() = open_hvbox 0 let obox() = open_hvbox 2 let cbox() = close_box() let break() = print_break 0 0 let small t = match t with TmVar(_,_,_) -> true | _ -> false let rec printty_Type outer tyT = match tyT with tyT -> printty_ArrowType outer tyT and printty_ArrowType outer tyT = match tyT with TyArr(tyT1,tyT2) -> obox0(); printty_AType false tyT1; if outer then pr " "; pr "->"; if outer then print_space() else break(); printty_ArrowType outer tyT2; cbox() | tyT -> printty_AType outer tyT and printty_AType outer tyT = match tyT with TyTop -> pr "Top" | TyRecord(fields) -> let pf i (li,tyTi) = if (li <> ((string_of_int i))) then (pr li; pr ":"); printty_Type false tyTi in let rec p i l = match l with [] -> () | [f] -> pf i f | f::rest -> pf i f; pr","; if outer then print_space() else break(); p (i+1) rest in pr "{"; open_hovbox 0; p 1 fields; pr "}"; cbox() | TyBool -> pr "Bool" | tyT -> pr "("; printty_Type outer tyT; pr ")" let printty tyT = printty_Type true tyT let rec printtm_Term outer ctx t = match t with TmAbs(fi,x,tyT1,t2) -> (let (ctx',x') = (pickfreshname ctx x) in obox(); pr "lambda "; pr x'; pr ":"; printty_Type false tyT1; pr "."; if (small t2) && not outer then break() else print_space(); printtm_Term outer ctx' t2; cbox()) | TmIf(fi, t1, t2, t3) -> obox0(); pr "if "; printtm_Term false ctx t1; print_space(); pr "then "; printtm_Term false ctx t2; print_space(); pr "else "; printtm_Term false ctx t3; cbox() | t -> printtm_AppTerm outer ctx t and printtm_AppTerm outer ctx t = match t with TmApp(fi, t1, t2) -> obox0(); printtm_AppTerm false ctx t1; print_space(); printtm_ATerm false ctx t2; cbox() | t -> printtm_PathTerm outer ctx t and printtm_PathTerm outer ctx t = match t with TmProj(_, t1, l) -> printtm_ATerm false ctx t1; pr "."; pr l | t -> printtm_ATerm outer ctx t and printtm_ATerm outer ctx t = match t with TmVar(fi,x,n) -> if ctxlength ctx = n then pr (index2name fi ctx x) else pr ("[bad index: " ^ (string_of_int x) ^ "/" ^ (string_of_int n) ^ " in {" ^ (List.fold_left (fun s (x,_) -> s ^ " " ^ x) "" ctx) ^ " }]") | TmRecord(fi, fields) -> let pf i (li,ti) = if (li <> ((string_of_int i))) then (pr li; pr "="); printtm_Term false ctx ti in let rec p i l = match l with [] -> () | [f] -> pf i f | f::rest -> pf i f; pr","; if outer then print_space() else break(); p (i+1) rest in pr "{"; open_hovbox 0; p 1 fields; pr "}"; cbox() | TmTrue(_) -> pr "true" | TmFalse(_) -> pr "false" | t -> pr "("; printtm_Term outer ctx t; pr ")" let printtm ctx t = printtm_Term true ctx t let prbinding ctx b = match b with NameBind -> () | VarBind(tyT) -> pr ": "; printty tyT
null
https://raw.githubusercontent.com/roehst/tapl-implementations/23c0dc505a8c0b0a797201a7e4e3e5b939dd8fdb/joinexercise/syntax.ml
ocaml
---------------------------------------------------------------------- ---------------------------------------------------------------------- Context management ---------------------------------------------------------------------- Shifting ---------------------------------------------------------------------- Substitution ---------------------------------------------------------------------- Context management (continued) ---------------------------------------------------------------------- Extracting file info ---------------------------------------------------------------------- Printing
open Format open Support.Error open Support.Pervasive type ty = TyTop | TyArr of ty * ty | TyRecord of (string * ty) list | TyBool type term = TmVar of info * int * int | TmAbs of info * string * ty * term | TmApp of info * term * term | TmRecord of info * (string * term) list | TmProj of info * term * string | TmTrue of info | TmFalse of info | TmIf of info * term * term * term type binding = NameBind | VarBind of ty type context = (string * binding) list type command = | Eval of info * term | Bind of info * string * binding let emptycontext = [] let ctxlength ctx = List.length ctx let addbinding ctx x bind = (x,bind)::ctx let addname ctx x = addbinding ctx x NameBind let rec isnamebound ctx x = match ctx with [] -> false | (y,_)::rest -> if y=x then true else isnamebound rest x let rec pickfreshname ctx x = if isnamebound ctx x then pickfreshname ctx (x^"'") else ((x,NameBind)::ctx), x let index2name fi ctx x = try let (xn,_) = List.nth ctx x in xn with Failure _ -> let msg = Printf.sprintf "Variable lookup failure: offset: %d, ctx size: %d" in error fi (msg x (List.length ctx)) let rec name2index fi ctx x = match ctx with [] -> error fi ("Identifier " ^ x ^ " is unbound") | (y,_)::rest -> if y=x then 0 else 1 + (name2index fi rest x) let tmmap onvar c t = let rec walk c t = match t with TmVar(fi,x,n) -> onvar fi c x n | TmAbs(fi,x,tyT1,t2) -> TmAbs(fi,x,tyT1,walk (c+1) t2) | TmApp(fi,t1,t2) -> TmApp(fi,walk c t1,walk c t2) | TmProj(fi,t1,l) -> TmProj(fi,walk c t1,l) | TmRecord(fi,fields) -> TmRecord(fi,List.map (fun (li,ti) -> (li,walk c ti)) fields) | TmTrue(fi) as t -> t | TmFalse(fi) as t -> t | TmIf(fi,t1,t2,t3) -> TmIf(fi,walk c t1,walk c t2,walk c t3) in walk c t let termShiftAbove d c t = tmmap (fun fi c x n -> if x>=c then TmVar(fi,x+d,n+d) else TmVar(fi,x,n+d)) c t let termShift d t = termShiftAbove d 0 t let termSubst j s t = tmmap (fun fi j x n -> if x=j then termShift j s else TmVar(fi,x,n)) j t let termSubstTop s t = termShift (-1) (termSubst 0 (termShift 1 s) t) let rec getbinding fi ctx i = try let (_,bind) = List.nth ctx i in bind with Failure _ -> let msg = Printf.sprintf "Variable lookup failure: offset: %d, ctx size: %d" in error fi (msg i (List.length ctx)) let getTypeFromContext fi ctx i = match getbinding fi ctx i with VarBind(tyT) -> tyT | _ -> error fi ("getTypeFromContext: Wrong kind of binding for variable " ^ (index2name fi ctx i)) let tmInfo t = match t with TmVar(fi,_,_) -> fi | TmAbs(fi,_,_,_) -> fi | TmApp(fi, _, _) -> fi | TmProj(fi,_,_) -> fi | TmRecord(fi,_) -> fi | TmTrue(fi) -> fi | TmFalse(fi) -> fi | TmIf(fi,_,_,_) -> fi The printing functions call these utility functions to insert grouping information and line - breaking hints for the pretty - printing library : obox Open a " box " whose contents will be indented by two spaces if the whole box can not fit on the current line obox0 Same but indent continuation lines to the same column as the beginning of the box rather than 2 more columns to the right cbox Close the current box break Insert a breakpoint indicating where the line maybe broken if necessary . See the documentation for the Format module in the OCaml library for more details . information and line-breaking hints for the pretty-printing library: obox Open a "box" whose contents will be indented by two spaces if the whole box cannot fit on the current line obox0 Same but indent continuation lines to the same column as the beginning of the box rather than 2 more columns to the right cbox Close the current box break Insert a breakpoint indicating where the line maybe broken if necessary. See the documentation for the Format module in the OCaml library for more details. *) let obox0() = open_hvbox 0 let obox() = open_hvbox 2 let cbox() = close_box() let break() = print_break 0 0 let small t = match t with TmVar(_,_,_) -> true | _ -> false let rec printty_Type outer tyT = match tyT with tyT -> printty_ArrowType outer tyT and printty_ArrowType outer tyT = match tyT with TyArr(tyT1,tyT2) -> obox0(); printty_AType false tyT1; if outer then pr " "; pr "->"; if outer then print_space() else break(); printty_ArrowType outer tyT2; cbox() | tyT -> printty_AType outer tyT and printty_AType outer tyT = match tyT with TyTop -> pr "Top" | TyRecord(fields) -> let pf i (li,tyTi) = if (li <> ((string_of_int i))) then (pr li; pr ":"); printty_Type false tyTi in let rec p i l = match l with [] -> () | [f] -> pf i f | f::rest -> pf i f; pr","; if outer then print_space() else break(); p (i+1) rest in pr "{"; open_hovbox 0; p 1 fields; pr "}"; cbox() | TyBool -> pr "Bool" | tyT -> pr "("; printty_Type outer tyT; pr ")" let printty tyT = printty_Type true tyT let rec printtm_Term outer ctx t = match t with TmAbs(fi,x,tyT1,t2) -> (let (ctx',x') = (pickfreshname ctx x) in obox(); pr "lambda "; pr x'; pr ":"; printty_Type false tyT1; pr "."; if (small t2) && not outer then break() else print_space(); printtm_Term outer ctx' t2; cbox()) | TmIf(fi, t1, t2, t3) -> obox0(); pr "if "; printtm_Term false ctx t1; print_space(); pr "then "; printtm_Term false ctx t2; print_space(); pr "else "; printtm_Term false ctx t3; cbox() | t -> printtm_AppTerm outer ctx t and printtm_AppTerm outer ctx t = match t with TmApp(fi, t1, t2) -> obox0(); printtm_AppTerm false ctx t1; print_space(); printtm_ATerm false ctx t2; cbox() | t -> printtm_PathTerm outer ctx t and printtm_PathTerm outer ctx t = match t with TmProj(_, t1, l) -> printtm_ATerm false ctx t1; pr "."; pr l | t -> printtm_ATerm outer ctx t and printtm_ATerm outer ctx t = match t with TmVar(fi,x,n) -> if ctxlength ctx = n then pr (index2name fi ctx x) else pr ("[bad index: " ^ (string_of_int x) ^ "/" ^ (string_of_int n) ^ " in {" ^ (List.fold_left (fun s (x,_) -> s ^ " " ^ x) "" ctx) ^ " }]") | TmRecord(fi, fields) -> let pf i (li,ti) = if (li <> ((string_of_int i))) then (pr li; pr "="); printtm_Term false ctx ti in let rec p i l = match l with [] -> () | [f] -> pf i f | f::rest -> pf i f; pr","; if outer then print_space() else break(); p (i+1) rest in pr "{"; open_hovbox 0; p 1 fields; pr "}"; cbox() | TmTrue(_) -> pr "true" | TmFalse(_) -> pr "false" | t -> pr "("; printtm_Term outer ctx t; pr ")" let printtm ctx t = printtm_Term true ctx t let prbinding ctx b = match b with NameBind -> () | VarBind(tyT) -> pr ": "; printty tyT
e3239bd15bae69c4e64bd4d5553ac5e4c8d96c1583f1b25354c90bd9a5adca20
fujita-y/ypsilon
procedural.scm
#!nobacktrace (library (rnrs records procedural (6)) (export make-record-type-descriptor record-type-descriptor? make-record-constructor-descriptor record-constructor record-predicate record-accessor record-mutator) (import (core records)))
null
https://raw.githubusercontent.com/fujita-y/ypsilon/f742470e2810aabb7a7c898fd6c07227c14a725f/sitelib/rnrs/records/procedural.scm
scheme
#!nobacktrace (library (rnrs records procedural (6)) (export make-record-type-descriptor record-type-descriptor? make-record-constructor-descriptor record-constructor record-predicate record-accessor record-mutator) (import (core records)))
ea6b0b063751e6c60141ef29a1478fc737c11fd16fc3fe42696c69e42b35ace7
jaspervdj/advent-of-code
IntCode.hs
-- | 2019's virtual machine, IntCode. # LANGUAGE DeriveFoldable # {-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE DeriveTraversable #-} # LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE LambdaCase # # LANGUAGE RecordWildCards # module AdventOfCode.IntCode ( Interrupt (..) , Program , parseProgram , makeProgram , Machine (..) , initMachine , stepMachine , runMachine , evalMachine , runAsciiMachine , runAsciiMachineIO , test ) where import qualified AdventOfCode.NanoParser as NP import qualified AdventOfCode.NanoTest as NT import Data.Char (chr, ord) import qualified Data.IntMap as IM import Data.Maybe (fromMaybe, maybeToList) import qualified System.IO as IO data Interrupt = HaltSuccess | OutOfBounds String Int | InsufficientInput | UnknownOpcode Int | IllegalParams String deriving (Show) newtype Program = Program (IM.IntMap Int) deriving (Semigroup, Show) parseProgram :: NP.Parser Char Program parseProgram = makeProgram <$> NP.sepBy1 (NP.signedDecimal) (NP.char ',') makeProgram :: [Int] -> Program makeProgram = Program . IM.fromList . zip [0 ..] newtype Memory = Memory (IM.IntMap Int) instance Show Memory where show (Memory s) = unwords $ map (\(x, y) -> show x ++ ":" ++ show y) $ IM.toList s load :: Int -> Memory -> Either Interrupt Int load n (Memory mem) | n < 0 = Left $ OutOfBounds "load" n | otherwise = Right . fromMaybe 0 $ IM.lookup n mem store :: Int -> Int -> Memory -> Either Interrupt Memory store n x (Memory mem) | n < 0 = Left $ OutOfBounds "store" n | otherwise = Right $ Memory $ IM.insert n x mem -- | Points to a memory location. data Pointer = Absolute !Int | Relative !Int deriving (Show) -- | Can be read but not always written to. data Param = Position !Pointer | Immediate !Int deriving (Show) data Instr p = Add p p Pointer | Multiply p p Pointer | Input Pointer | Output p | JumpIfTrue p p | JumpIfFalse p p | LessThan p p Pointer | Equals p p Pointer | RelativeBaseOffset p | Halt deriving (Foldable, Functor, Show, Traversable) instrSize :: Instr p -> Int instrSize = \case Add _ _ _ -> 4 Multiply _ _ _ -> 4 Input _ -> 2 Output _ -> 2 JumpIfTrue _ _ -> 3 JumpIfFalse _ _ -> 3 LessThan _ _ _ -> 4 Equals _ _ _ -> 4 RelativeBaseOffset _ -> 2 Halt -> 1 loadInstr :: Int -> Memory -> Either Interrupt (Instr Param) loadInstr ip mem = fmap parseInstr (load ip mem) >>= \case (1, pmodes) -> parseBinop Add pmodes (2, pmodes) -> parseBinop Multiply pmodes (7, pmodes) -> parseBinop LessThan pmodes (8, pmodes) -> parseBinop Equals pmodes (3, p1 : _) -> Input <$> parsePointer p1 (ip + 1) (4, p1 : _) -> Output <$> parseParam p1 (ip + 1) (5, p1 : p2 : _) -> JumpIfTrue <$> parseParam p1 (ip + 1) <*> parseParam p2 (ip + 2) (6, p1 : p2 : _) -> JumpIfFalse <$> parseParam p1 (ip + 1) <*> parseParam p2 (ip + 2) (9, p1 : _) -> RelativeBaseOffset <$> parseParam p1 (ip + 1) (99, _) -> pure Halt (op, _) -> Left $ UnknownOpcode op where parseInstr encoded = let (leading, op) = encoded `divMod` 100 params l = let (l', p) = l `divMod` 10 in p : params l' in (op, params leading) parseParam 0 n = Position . Absolute <$> load n mem parseParam 1 n = Immediate <$> load n mem parseParam 2 n = Position . Relative <$> load n mem parseParam m _ = Left $ IllegalParams $ "Invalid param mode: " ++ show m parsePointer m n = parseParam m n >>= \case Position p -> pure p Immediate _ -> Left $ IllegalParams $ "Unexpected immediate param mode" parseBinop c (p1 : p2 : p3 : _) = c <$> parseParam p1 (ip + 1) <*> parseParam p2 (ip + 2) <*> parsePointer p3 (ip + 3) parseBinop _ _ = Left $ IllegalParams $ "Missing parameter modes for binop" data Machine = Machine { mInputs :: [Int] , mRelBase :: Int , mIp :: Int , mMem :: Memory } deriving (Show) initMachine :: [Int] -> Program -> Machine initMachine inputs (Program mem) = Machine inputs 0 0 (Memory mem) stepMachine :: Machine -> Either Interrupt (Machine, Maybe Int) stepMachine machine@Machine {..} = do let resolvePointer (Absolute p) = p resolvePointer (Relative p) = mRelBase + p loadParam (Immediate n) = pure n loadParam (Position p) = load (resolvePointer p) mMem instr <- loadInstr mIp mMem >>= traverse loadParam let machine' = machine {mIp = mIp + instrSize instr} binop f x y p = do mem <- store (resolvePointer p) (f x y) mMem pure (machine' {mMem = mem}, Nothing) case instr of Add x y p -> binop (+) x y p Multiply x y p -> binop (*) x y p LessThan x y p -> binop (\l r -> if l < r then 1 else 0) x y p Equals x y p -> binop (\l r -> if l == r then 1 else 0) x y p Output o -> pure (machine', Just o) Input p -> case mInputs of [] -> Left InsufficientInput i : is -> do m <- store (resolvePointer p) i mMem pure (machine' {mMem = m, mInputs = is}, Nothing) JumpIfTrue x dst -> pure (if x /= 0 then machine {mIp = dst} else machine', Nothing) JumpIfFalse x dst -> pure (if x == 0 then machine {mIp = dst} else machine', Nothing) RelativeBaseOffset o -> pure (machine' {mRelBase = mRelBase + o}, Nothing) Halt -> Left HaltSuccess runMachine :: Machine -> ([Int], Interrupt, Machine) runMachine machine = case stepMachine machine of Left err -> ([], err, machine) Right (machine', out) -> -- Set up recursion in a way that preserves laziness. let (output, err, machine'') = runMachine machine' in (maybeToList out ++ output, err, machine'') evalMachine :: Machine -> [Int] evalMachine = (\(o, _, _) -> o) . runMachine runAsciiMachine :: String -> Program -> String runAsciiMachine input prog = let (outputs, _, _) = runMachine $ initMachine (map ord input) prog in concatMap renderAsciiOrNumber outputs -- | Run a machine that reads and prints ASCII interactively. Mostly useful for -- debugging. runAsciiMachineIO :: (IO.Handle, IO.Handle) -> Program -> IO () runAsciiMachineIO (inh, outh) prog = do IO.hSetBuffering inh IO.NoBuffering input <- IO.hGetContents inh IO.hPutStrLn outh $ runAsciiMachine input prog renderAsciiOrNumber :: Int -> String renderAsciiOrNumber i = if i <= 0xff then [chr i] else show i test :: IO () test = do let quine = [109,1,204,-1,1001,100,1,100,1008,100,16,101,1006,101,0,99] evalMachine (initMachine [] (makeProgram quine)) NT.@?= quine evalMachine (initMachine [] $ makeProgram [1102,34915192,34915192,7,4,7,99,0]) NT.@?= [1219070632396864]
null
https://raw.githubusercontent.com/jaspervdj/advent-of-code/bdc9628d1495d4e7fdbd9cea2739b929f733e751/lib/hs/AdventOfCode/IntCode.hs
haskell
| 2019's virtual machine, IntCode. # LANGUAGE DeriveFunctor # # LANGUAGE DeriveTraversable # | Points to a memory location. | Can be read but not always written to. Set up recursion in a way that preserves laziness. | Run a machine that reads and prints ASCII interactively. Mostly useful for debugging.
# LANGUAGE DeriveFoldable # # LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE LambdaCase # # LANGUAGE RecordWildCards # module AdventOfCode.IntCode ( Interrupt (..) , Program , parseProgram , makeProgram , Machine (..) , initMachine , stepMachine , runMachine , evalMachine , runAsciiMachine , runAsciiMachineIO , test ) where import qualified AdventOfCode.NanoParser as NP import qualified AdventOfCode.NanoTest as NT import Data.Char (chr, ord) import qualified Data.IntMap as IM import Data.Maybe (fromMaybe, maybeToList) import qualified System.IO as IO data Interrupt = HaltSuccess | OutOfBounds String Int | InsufficientInput | UnknownOpcode Int | IllegalParams String deriving (Show) newtype Program = Program (IM.IntMap Int) deriving (Semigroup, Show) parseProgram :: NP.Parser Char Program parseProgram = makeProgram <$> NP.sepBy1 (NP.signedDecimal) (NP.char ',') makeProgram :: [Int] -> Program makeProgram = Program . IM.fromList . zip [0 ..] newtype Memory = Memory (IM.IntMap Int) instance Show Memory where show (Memory s) = unwords $ map (\(x, y) -> show x ++ ":" ++ show y) $ IM.toList s load :: Int -> Memory -> Either Interrupt Int load n (Memory mem) | n < 0 = Left $ OutOfBounds "load" n | otherwise = Right . fromMaybe 0 $ IM.lookup n mem store :: Int -> Int -> Memory -> Either Interrupt Memory store n x (Memory mem) | n < 0 = Left $ OutOfBounds "store" n | otherwise = Right $ Memory $ IM.insert n x mem data Pointer = Absolute !Int | Relative !Int deriving (Show) data Param = Position !Pointer | Immediate !Int deriving (Show) data Instr p = Add p p Pointer | Multiply p p Pointer | Input Pointer | Output p | JumpIfTrue p p | JumpIfFalse p p | LessThan p p Pointer | Equals p p Pointer | RelativeBaseOffset p | Halt deriving (Foldable, Functor, Show, Traversable) instrSize :: Instr p -> Int instrSize = \case Add _ _ _ -> 4 Multiply _ _ _ -> 4 Input _ -> 2 Output _ -> 2 JumpIfTrue _ _ -> 3 JumpIfFalse _ _ -> 3 LessThan _ _ _ -> 4 Equals _ _ _ -> 4 RelativeBaseOffset _ -> 2 Halt -> 1 loadInstr :: Int -> Memory -> Either Interrupt (Instr Param) loadInstr ip mem = fmap parseInstr (load ip mem) >>= \case (1, pmodes) -> parseBinop Add pmodes (2, pmodes) -> parseBinop Multiply pmodes (7, pmodes) -> parseBinop LessThan pmodes (8, pmodes) -> parseBinop Equals pmodes (3, p1 : _) -> Input <$> parsePointer p1 (ip + 1) (4, p1 : _) -> Output <$> parseParam p1 (ip + 1) (5, p1 : p2 : _) -> JumpIfTrue <$> parseParam p1 (ip + 1) <*> parseParam p2 (ip + 2) (6, p1 : p2 : _) -> JumpIfFalse <$> parseParam p1 (ip + 1) <*> parseParam p2 (ip + 2) (9, p1 : _) -> RelativeBaseOffset <$> parseParam p1 (ip + 1) (99, _) -> pure Halt (op, _) -> Left $ UnknownOpcode op where parseInstr encoded = let (leading, op) = encoded `divMod` 100 params l = let (l', p) = l `divMod` 10 in p : params l' in (op, params leading) parseParam 0 n = Position . Absolute <$> load n mem parseParam 1 n = Immediate <$> load n mem parseParam 2 n = Position . Relative <$> load n mem parseParam m _ = Left $ IllegalParams $ "Invalid param mode: " ++ show m parsePointer m n = parseParam m n >>= \case Position p -> pure p Immediate _ -> Left $ IllegalParams $ "Unexpected immediate param mode" parseBinop c (p1 : p2 : p3 : _) = c <$> parseParam p1 (ip + 1) <*> parseParam p2 (ip + 2) <*> parsePointer p3 (ip + 3) parseBinop _ _ = Left $ IllegalParams $ "Missing parameter modes for binop" data Machine = Machine { mInputs :: [Int] , mRelBase :: Int , mIp :: Int , mMem :: Memory } deriving (Show) initMachine :: [Int] -> Program -> Machine initMachine inputs (Program mem) = Machine inputs 0 0 (Memory mem) stepMachine :: Machine -> Either Interrupt (Machine, Maybe Int) stepMachine machine@Machine {..} = do let resolvePointer (Absolute p) = p resolvePointer (Relative p) = mRelBase + p loadParam (Immediate n) = pure n loadParam (Position p) = load (resolvePointer p) mMem instr <- loadInstr mIp mMem >>= traverse loadParam let machine' = machine {mIp = mIp + instrSize instr} binop f x y p = do mem <- store (resolvePointer p) (f x y) mMem pure (machine' {mMem = mem}, Nothing) case instr of Add x y p -> binop (+) x y p Multiply x y p -> binop (*) x y p LessThan x y p -> binop (\l r -> if l < r then 1 else 0) x y p Equals x y p -> binop (\l r -> if l == r then 1 else 0) x y p Output o -> pure (machine', Just o) Input p -> case mInputs of [] -> Left InsufficientInput i : is -> do m <- store (resolvePointer p) i mMem pure (machine' {mMem = m, mInputs = is}, Nothing) JumpIfTrue x dst -> pure (if x /= 0 then machine {mIp = dst} else machine', Nothing) JumpIfFalse x dst -> pure (if x == 0 then machine {mIp = dst} else machine', Nothing) RelativeBaseOffset o -> pure (machine' {mRelBase = mRelBase + o}, Nothing) Halt -> Left HaltSuccess runMachine :: Machine -> ([Int], Interrupt, Machine) runMachine machine = case stepMachine machine of Left err -> ([], err, machine) Right (machine', out) -> let (output, err, machine'') = runMachine machine' in (maybeToList out ++ output, err, machine'') evalMachine :: Machine -> [Int] evalMachine = (\(o, _, _) -> o) . runMachine runAsciiMachine :: String -> Program -> String runAsciiMachine input prog = let (outputs, _, _) = runMachine $ initMachine (map ord input) prog in concatMap renderAsciiOrNumber outputs runAsciiMachineIO :: (IO.Handle, IO.Handle) -> Program -> IO () runAsciiMachineIO (inh, outh) prog = do IO.hSetBuffering inh IO.NoBuffering input <- IO.hGetContents inh IO.hPutStrLn outh $ runAsciiMachine input prog renderAsciiOrNumber :: Int -> String renderAsciiOrNumber i = if i <= 0xff then [chr i] else show i test :: IO () test = do let quine = [109,1,204,-1,1001,100,1,100,1008,100,16,101,1006,101,0,99] evalMachine (initMachine [] (makeProgram quine)) NT.@?= quine evalMachine (initMachine [] $ makeProgram [1102,34915192,34915192,7,4,7,99,0]) NT.@?= [1219070632396864]
dd51e1260fa15643f7dc96ef4b614f244464214910d67882e5302b68baa5685f
svenpanne/EOPL3
exercise-2-12.rkt
#lang eopl ; ------------------------------------------------------------------------------ Exercise 2.12 ; A variant using a triple of functions. (define make-stack (lambda (pop-func top-func empty-stack?-func) (list pop-func top-func empty-stack?-func))) (define pop-func car) (define top-func cadr) (define empty-stack?-func caddr) (define empty-stack (lambda () (make-stack (lambda () (report-empty-stack 'pop)) (lambda () (report-empty-stack 'top)) (lambda () #t)))) (define push (lambda (stack value) (make-stack (lambda () stack) (lambda () value) (lambda () #f)))) (define pop (lambda (stack) ((pop-func stack)))) (define top (lambda (stack) ((top-func stack)))) (define empty-stack? (lambda (stack) ((empty-stack?-func stack)))) (define report-empty-stack (lambda (func) (eopl:error func "Empty stack"))) ; A variant using a more "OO"-like interface. (define empty-stack-oo (lambda () (letrec ((this (lambda (message . args) (case message ((push) (push-oo this (car args))) ((pop) (report-empty-stack 'pop)) ((top) (report-empty-stack 'top)) ((empty-stack?) #t))))) this))) (define push-oo (lambda (stack value) (letrec ((this (lambda (message . args) (case message ((push) (push-oo this (car args))) ((pop) stack) ((top) value) ((empty-stack?) #f))))) this)))
null
https://raw.githubusercontent.com/svenpanne/EOPL3/3fc14c4dbb1c53a37bd67399eba34cea8f8234cc/chapter2/exercise-2-12.rkt
racket
------------------------------------------------------------------------------ A variant using a triple of functions. A variant using a more "OO"-like interface.
#lang eopl Exercise 2.12 (define make-stack (lambda (pop-func top-func empty-stack?-func) (list pop-func top-func empty-stack?-func))) (define pop-func car) (define top-func cadr) (define empty-stack?-func caddr) (define empty-stack (lambda () (make-stack (lambda () (report-empty-stack 'pop)) (lambda () (report-empty-stack 'top)) (lambda () #t)))) (define push (lambda (stack value) (make-stack (lambda () stack) (lambda () value) (lambda () #f)))) (define pop (lambda (stack) ((pop-func stack)))) (define top (lambda (stack) ((top-func stack)))) (define empty-stack? (lambda (stack) ((empty-stack?-func stack)))) (define report-empty-stack (lambda (func) (eopl:error func "Empty stack"))) (define empty-stack-oo (lambda () (letrec ((this (lambda (message . args) (case message ((push) (push-oo this (car args))) ((pop) (report-empty-stack 'pop)) ((top) (report-empty-stack 'top)) ((empty-stack?) #t))))) this))) (define push-oo (lambda (stack value) (letrec ((this (lambda (message . args) (case message ((push) (push-oo this (car args))) ((pop) stack) ((top) value) ((empty-stack?) #f))))) this)))
0abb72fb61841e49cd601b13247eee8f9d05ca88436753609a000be41221803a
cblp/crdt
GCounter.hs
module CRDT.Cv.GCounter ( GCounter (..) , initial , query -- * Operation , increment ) where import Data.IntMap.Strict (IntMap) import qualified Data.IntMap.Strict as IntMap import Data.Semilattice (Semilattice) -- | Grow-only counter. newtype GCounter a = GCounter (IntMap a) deriving (Eq, Show) instance Ord a => Semigroup (GCounter a) where GCounter x <> GCounter y = GCounter $ IntMap.unionWith max x y | See ' CvRDT ' instance Ord a => Semilattice (GCounter a) -- | Increment counter increment :: Num a => Word -- ^ replica id -> GCounter a -> GCounter a increment replicaId (GCounter imap) = GCounter (IntMap.insertWith (+) i 1 imap) where i = fromIntegral replicaId -- | Initial state initial :: GCounter a initial = GCounter IntMap.empty -- | Get value from the state query :: Num a => GCounter a -> a query (GCounter v) = sum v
null
https://raw.githubusercontent.com/cblp/crdt/175d7ee7df66de1f013ee167ac31719752e0c20b/crdt/lib/CRDT/Cv/GCounter.hs
haskell
* Operation | Grow-only counter. | Increment counter ^ replica id | Initial state | Get value from the state
module CRDT.Cv.GCounter ( GCounter (..) , initial , query , increment ) where import Data.IntMap.Strict (IntMap) import qualified Data.IntMap.Strict as IntMap import Data.Semilattice (Semilattice) newtype GCounter a = GCounter (IntMap a) deriving (Eq, Show) instance Ord a => Semigroup (GCounter a) where GCounter x <> GCounter y = GCounter $ IntMap.unionWith max x y | See ' CvRDT ' instance Ord a => Semilattice (GCounter a) increment :: Num a -> GCounter a -> GCounter a increment replicaId (GCounter imap) = GCounter (IntMap.insertWith (+) i 1 imap) where i = fromIntegral replicaId initial :: GCounter a initial = GCounter IntMap.empty query :: Num a => GCounter a -> a query (GCounter v) = sum v
dca10da26fe0a623c5c734aab96530243993f6bfa2d718b5c152586642e63347
parsonsmatt/unification
Unification.hs
# LANGUAGE GeneralizedNewtypeDeriving # module Unification where import Control.Monad.State import Control.Monad.Except import Data.Map (Map) import qualified Data.Map.Strict as Map data Expr = Lit String | Var String | List [Expr] | Expr :=> Expr deriving (Eq, Ord, Show) infixr 4 :=> newtype Unification a = Unification { unUnification :: ExceptT UnificationError (State Theta) a } deriving (Functor, Applicative, Monad, MonadState Theta, MonadError UnificationError) data UnificationError = VariableOccursCheck | IncompatibleUnification Expr Expr | InexplicableFailure | OccursCheckWithNotVar | UnifyVarWithNotVar deriving Show type Theta = Map Expr Expr runUnify :: Expr -> Expr -> Either UnificationError Theta runUnify a b = evalState (runExceptT (unUnification (unify a b))) mempty unify :: Expr -> Expr -> Unification Theta unify a b | a == b = get unify (Var a) b = unifyVar (Var a) b unify a (Var b) = unifyVar (Var b) a unify (opX :=> argsX) (opY :=> argsY) = do unify opX opY unify argsX argsY unify (List as) (List bs) = last <$> zipWithM unify as bs unify (Lit _) (Lit _) = get unify a b = throwError $ IncompatibleUnification a b unifyVar :: Expr -> Expr -> Unification Theta unifyVar var@(Var _) x = do theta <- get case Map.lookup var theta of Just val -> unify val x Nothing -> case Map.lookup x theta of Just val -> unify var val Nothing -> do occursCheck var x let x' = Map.foldrWithKey replace x theta modify (Map.insert var x') updateVariables var x' get unifyVar _ _ = throwError UnifyVarWithNotVar occursCheck :: Expr -> Expr -> Unification () occursCheck var@(Var a) expr = do theta <- get case expr of Var b -> do when (a == b) throwOccurs gets (Map.lookup expr) >>= mapM_ (occursCheck var) Lit _ -> return () List xs -> mapM_ (occursCheck var) xs op :=> arg -> do occursCheck var op occursCheck var arg where throwOccurs = throwError VariableOccursCheck occursCheck _ _ = throwError OccursCheckWithNotVar replace :: Expr -> Expr -> Expr -> Expr replace source replacement target | source == target = replacement | otherwise = case target of List xs -> List $ map (replace source replacement) xs op :=> arg -> replace source replacement op :=> replace source replacement arg a -> a updateVariables :: Expr -> Expr -> Unification () updateVariables var@(Var a) replacement = modify (Map.map (replace var replacement)) ex :: Int -> (Expr, Expr) ex 1 = ( Var "P" :=> Var "X" , Var "P" :=> Lit "a" ) ex 2 = ( Var "P" :=> Lit "f" :=> List [ Var "Y", Lit "g" :=> Var "Y"] , Var "P" :=> Lit "f" :=> List [ Lit "a", Var "X" ] ) ex 3 = ( Var "P" :=> List [ Var "Y", Var "Y" ] , Var "P" :=> List [ Lit "f" :=> Lit "a", Lit "a" ] ) ex 4 = ( Var "P" :=> List [ Var "Y", Lit "f" :=> Var "Y" ] , Var "P" :=> List [ Var "X", Var "X" ] ) main :: IO () main = forM_ [1..4] (print . uncurry runUnify . ex)
null
https://raw.githubusercontent.com/parsonsmatt/unification/04093a013705d793d4d239bd9e1d5a492687306a/src/Unification.hs
haskell
# LANGUAGE GeneralizedNewtypeDeriving # module Unification where import Control.Monad.State import Control.Monad.Except import Data.Map (Map) import qualified Data.Map.Strict as Map data Expr = Lit String | Var String | List [Expr] | Expr :=> Expr deriving (Eq, Ord, Show) infixr 4 :=> newtype Unification a = Unification { unUnification :: ExceptT UnificationError (State Theta) a } deriving (Functor, Applicative, Monad, MonadState Theta, MonadError UnificationError) data UnificationError = VariableOccursCheck | IncompatibleUnification Expr Expr | InexplicableFailure | OccursCheckWithNotVar | UnifyVarWithNotVar deriving Show type Theta = Map Expr Expr runUnify :: Expr -> Expr -> Either UnificationError Theta runUnify a b = evalState (runExceptT (unUnification (unify a b))) mempty unify :: Expr -> Expr -> Unification Theta unify a b | a == b = get unify (Var a) b = unifyVar (Var a) b unify a (Var b) = unifyVar (Var b) a unify (opX :=> argsX) (opY :=> argsY) = do unify opX opY unify argsX argsY unify (List as) (List bs) = last <$> zipWithM unify as bs unify (Lit _) (Lit _) = get unify a b = throwError $ IncompatibleUnification a b unifyVar :: Expr -> Expr -> Unification Theta unifyVar var@(Var _) x = do theta <- get case Map.lookup var theta of Just val -> unify val x Nothing -> case Map.lookup x theta of Just val -> unify var val Nothing -> do occursCheck var x let x' = Map.foldrWithKey replace x theta modify (Map.insert var x') updateVariables var x' get unifyVar _ _ = throwError UnifyVarWithNotVar occursCheck :: Expr -> Expr -> Unification () occursCheck var@(Var a) expr = do theta <- get case expr of Var b -> do when (a == b) throwOccurs gets (Map.lookup expr) >>= mapM_ (occursCheck var) Lit _ -> return () List xs -> mapM_ (occursCheck var) xs op :=> arg -> do occursCheck var op occursCheck var arg where throwOccurs = throwError VariableOccursCheck occursCheck _ _ = throwError OccursCheckWithNotVar replace :: Expr -> Expr -> Expr -> Expr replace source replacement target | source == target = replacement | otherwise = case target of List xs -> List $ map (replace source replacement) xs op :=> arg -> replace source replacement op :=> replace source replacement arg a -> a updateVariables :: Expr -> Expr -> Unification () updateVariables var@(Var a) replacement = modify (Map.map (replace var replacement)) ex :: Int -> (Expr, Expr) ex 1 = ( Var "P" :=> Var "X" , Var "P" :=> Lit "a" ) ex 2 = ( Var "P" :=> Lit "f" :=> List [ Var "Y", Lit "g" :=> Var "Y"] , Var "P" :=> Lit "f" :=> List [ Lit "a", Var "X" ] ) ex 3 = ( Var "P" :=> List [ Var "Y", Var "Y" ] , Var "P" :=> List [ Lit "f" :=> Lit "a", Lit "a" ] ) ex 4 = ( Var "P" :=> List [ Var "Y", Lit "f" :=> Var "Y" ] , Var "P" :=> List [ Var "X", Var "X" ] ) main :: IO () main = forM_ [1..4] (print . uncurry runUnify . ex)
d807f3ef0267f5c9bee8ad44044eb13d84b7db604475c2725eee804783eab8d7
monadbobo/ocaml-core
extended_unix.mli
open Core.Std (** Extensions to [Core.Unix]. *) val fork_exec : ?stdin:Unix.File_descr.t -> ?stdout:Unix.File_descr.t -> ?stderr:Unix.File_descr.t -> ?path_lookup:bool -> ?env:[ `Extend of (string * string) list | `Replace of (string * string) list ] -> ?working_dir:string -> ?setuid:int -> ?setgid:int -> string -> string list -> Pid.t * [ fork_exec prog args ~stdin ~stdout ~stderr ~setuid ~setgid ] forks a new process that executes the program in file [ prog ] , with arguments [ args ] . The pid of the new process is returned immediately ; the new process executes concurrently with the current process . The function raises EPERM if when using [ set{gid , uid } ] and the user i d is not 0 . The standard input and outputs of the new process are connected to the descriptors [ stdin ] , [ stdout ] and [ stderr ] . The close_on_exec flag is cleared from [ stderr ] [ stdout ] and [ stdin ] so it 's safe to pass in fds with [ close_on_exec ] set . @param path_lookup if [ true ] than we use PATH to find the process to exec . @env specifies the environment the process runs in ERRORS : Unix.unix_error . This function should not raise EINTR ; it will restart itself automatically . RATIONAL : [ setuid ] and [ setgid ] do not do a full i d drop ( e.g. : they save the i d in saved i d ) when the user does not have the privileges required to setuid to anyone . By default all file descriptors should be set_closexec ASAP after being open to avoid being captured in parallel execution of fork_exec ; resetting the closexec flag on the forked flag is a cleaner and more thread safe approach . BUGS : The capabilities for setuid in linux are not tied to the uid 0 ( man 7 capabilities ) . It is still fair to assume that under most system this capability is there IFF uid = = 0 . A more fine grain permissionning approach would make this function non - portable and be hard to implement in an async - signal - way . Because this function keeps the lock for most of its lifespan and restarts automatically on EINTR it might prevent the OCaml signal handlers to run in that thread . forks a new process that executes the program in file [prog], with arguments [args]. The pid of the new process is returned immediately; the new process executes concurrently with the current process. The function raises EPERM if when using [set{gid,uid}] and the user id is not 0. The standard input and outputs of the new process are connected to the descriptors [stdin], [stdout] and [stderr]. The close_on_exec flag is cleared from [stderr] [stdout] and [stdin] so it's safe to pass in fds with [close_on_exec] set. @param path_lookup if [true] than we use PATH to find the process to exec. @env specifies the environment the process runs in ERRORS: Unix.unix_error. This function should not raise EINTR; it will restart itself automatically. RATIONAL: [setuid] and [setgid] do not do a full id drop (e.g.: they save the id in saved id) when the user does not have the privileges required to setuid to anyone. By default all file descriptors should be set_closexec ASAP after being open to avoid being captured in parallel execution of fork_exec; resetting the closexec flag on the forked flag is a cleaner and more thread safe approach. BUGS: The capabilities for setuid in linux are not tied to the uid 0 (man 7 capabilities). It is still fair to assume that under most system this capability is there IFF uid == 0. A more fine grain permissionning approach would make this function non-portable and be hard to implement in an async-signal-way. Because this function keeps the lock for most of its lifespan and restarts automatically on EINTR it might prevent the OCaml signal handlers to run in that thread. *) val seteuid : int -> unit val setreuid : uid:int -> euid:int -> unit val gettid : unit -> int type statvfs = { bsize: int; (** file system block size *) frsize: int; (** fragment size *) blocks: int; (** size of fs in frsize units *) bfree: int; (** # free blocks *) bavail: int; (** # free blocks for non-root *) files: int; (** # inodes *) ffree: int; (** # free inodes *) favail: int; (** # free inodes for non-root *) fsid: int; (** file system ID *) flag: int; (** mount flags *) namemax: int; (** maximum filename length *) } with sexp, bin_io (** get file system statistics *) external statvfs : string -> statvfs = "statvfs_stub" (** get load averages *) external getloadavg : unit -> float * float * float = "getloadavg_stub" module Extended_passwd : sig open Unix.Passwd (** [of_passwd_line] parse a passwd-like line *) val of_passwd_line : string -> t option (** [of_passwd_line_exn] parse a passwd-like line *) val of_passwd_line_exn : string -> t (** [of_passwd_file] parse a passwd-like file *) val of_passwd_file : string -> t list option (** [of_passwd_file_exn] parse a passwd-like file *) val of_passwd_file_exn : string -> t list end
null
https://raw.githubusercontent.com/monadbobo/ocaml-core/9c1c06e7a1af7e15b6019a325d7dbdbd4cdb4020/base/core/extended/lib/extended_unix.mli
ocaml
* Extensions to [Core.Unix]. * file system block size * fragment size * size of fs in frsize units * # free blocks * # free blocks for non-root * # inodes * # free inodes * # free inodes for non-root * file system ID * mount flags * maximum filename length * get file system statistics * get load averages * [of_passwd_line] parse a passwd-like line * [of_passwd_line_exn] parse a passwd-like line * [of_passwd_file] parse a passwd-like file * [of_passwd_file_exn] parse a passwd-like file
open Core.Std val fork_exec : ?stdin:Unix.File_descr.t -> ?stdout:Unix.File_descr.t -> ?stderr:Unix.File_descr.t -> ?path_lookup:bool -> ?env:[ `Extend of (string * string) list | `Replace of (string * string) list ] -> ?working_dir:string -> ?setuid:int -> ?setgid:int -> string -> string list -> Pid.t * [ fork_exec prog args ~stdin ~stdout ~stderr ~setuid ~setgid ] forks a new process that executes the program in file [ prog ] , with arguments [ args ] . The pid of the new process is returned immediately ; the new process executes concurrently with the current process . The function raises EPERM if when using [ set{gid , uid } ] and the user i d is not 0 . The standard input and outputs of the new process are connected to the descriptors [ stdin ] , [ stdout ] and [ stderr ] . The close_on_exec flag is cleared from [ stderr ] [ stdout ] and [ stdin ] so it 's safe to pass in fds with [ close_on_exec ] set . @param path_lookup if [ true ] than we use PATH to find the process to exec . @env specifies the environment the process runs in ERRORS : Unix.unix_error . This function should not raise EINTR ; it will restart itself automatically . RATIONAL : [ setuid ] and [ setgid ] do not do a full i d drop ( e.g. : they save the i d in saved i d ) when the user does not have the privileges required to setuid to anyone . By default all file descriptors should be set_closexec ASAP after being open to avoid being captured in parallel execution of fork_exec ; resetting the closexec flag on the forked flag is a cleaner and more thread safe approach . BUGS : The capabilities for setuid in linux are not tied to the uid 0 ( man 7 capabilities ) . It is still fair to assume that under most system this capability is there IFF uid = = 0 . A more fine grain permissionning approach would make this function non - portable and be hard to implement in an async - signal - way . Because this function keeps the lock for most of its lifespan and restarts automatically on EINTR it might prevent the OCaml signal handlers to run in that thread . forks a new process that executes the program in file [prog], with arguments [args]. The pid of the new process is returned immediately; the new process executes concurrently with the current process. The function raises EPERM if when using [set{gid,uid}] and the user id is not 0. The standard input and outputs of the new process are connected to the descriptors [stdin], [stdout] and [stderr]. The close_on_exec flag is cleared from [stderr] [stdout] and [stdin] so it's safe to pass in fds with [close_on_exec] set. @param path_lookup if [true] than we use PATH to find the process to exec. @env specifies the environment the process runs in ERRORS: Unix.unix_error. This function should not raise EINTR; it will restart itself automatically. RATIONAL: [setuid] and [setgid] do not do a full id drop (e.g.: they save the id in saved id) when the user does not have the privileges required to setuid to anyone. By default all file descriptors should be set_closexec ASAP after being open to avoid being captured in parallel execution of fork_exec; resetting the closexec flag on the forked flag is a cleaner and more thread safe approach. BUGS: The capabilities for setuid in linux are not tied to the uid 0 (man 7 capabilities). It is still fair to assume that under most system this capability is there IFF uid == 0. A more fine grain permissionning approach would make this function non-portable and be hard to implement in an async-signal-way. Because this function keeps the lock for most of its lifespan and restarts automatically on EINTR it might prevent the OCaml signal handlers to run in that thread. *) val seteuid : int -> unit val setreuid : uid:int -> euid:int -> unit val gettid : unit -> int type statvfs = { } with sexp, bin_io external statvfs : string -> statvfs = "statvfs_stub" external getloadavg : unit -> float * float * float = "getloadavg_stub" module Extended_passwd : sig open Unix.Passwd val of_passwd_line : string -> t option val of_passwd_line_exn : string -> t val of_passwd_file : string -> t list option val of_passwd_file_exn : string -> t list end
157bb7498aceae6e1578427db430d48bbc5d0fcf0ddde8680424b6cefa779f47
hjcapple/reading-sicp
tree_op_map.scm
#lang racket P72 - [ 树操作和树映射 ] (define (count-leaves x) (cond ((null? x) 0) ((not (pair? x)) 1) (else (+ (count-leaves (car x)) (count-leaves (cdr x)))))) (define (scale-tree tree factor) (cond ((null? tree) null) ((not (pair? tree)) (* tree factor)) (else (cons (scale-tree (car tree) factor) (scale-tree (cdr tree) factor))))) (define (scale-tree-2 tree factor) (map (lambda (sub-tree) (if (pair? sub-tree) (scale-tree sub-tree factor) (* sub-tree factor))) tree)) ;;;;;;;;;;;;;;;;;;;;;;;; (define x (cons (list 1 2) (list 3 4))) (length x) (count-leaves x) (list x x) (length (list x x)) (count-leaves (list x x)) (scale-tree (list 1 (list 2 (list 3 4 5) (list 6 7))) 10) (scale-tree-2 (list 1 (list 2 (list 3 4 5) (list 6 7))) 10)
null
https://raw.githubusercontent.com/hjcapple/reading-sicp/7051d55dde841c06cf9326dc865d33d656702ecc/chapter_2/tree_op_map.scm
scheme
#lang racket P72 - [ 树操作和树映射 ] (define (count-leaves x) (cond ((null? x) 0) ((not (pair? x)) 1) (else (+ (count-leaves (car x)) (count-leaves (cdr x)))))) (define (scale-tree tree factor) (cond ((null? tree) null) ((not (pair? tree)) (* tree factor)) (else (cons (scale-tree (car tree) factor) (scale-tree (cdr tree) factor))))) (define (scale-tree-2 tree factor) (map (lambda (sub-tree) (if (pair? sub-tree) (scale-tree sub-tree factor) (* sub-tree factor))) tree)) (define x (cons (list 1 2) (list 3 4))) (length x) (count-leaves x) (list x x) (length (list x x)) (count-leaves (list x x)) (scale-tree (list 1 (list 2 (list 3 4 5) (list 6 7))) 10) (scale-tree-2 (list 1 (list 2 (list 3 4 5) (list 6 7))) 10)
5d474c13aa9149fec0734bfd50d64fe7beea6d3c38b1568ceeabac22ce1ad3a7
Eduap-com/WordMat
dstoka.lisp
;;; Compiled by f2cl version: ( " f2cl1.l , v 95098eb54f13 2013/04/01 00:45:16 toy $ " " f2cl2.l , v 95098eb54f13 2013/04/01 00:45:16 toy $ " " f2cl3.l , v 96616d88fb7e 2008/02/22 22:19:34 rtoy $ " " f2cl4.l , v 96616d88fb7e 2008/02/22 22:19:34 rtoy $ " " f2cl5.l , v 95098eb54f13 2013/04/01 00:45:16 toy $ " " f2cl6.l , v 1d5cbacbb977 2008/08/24 00:56:27 rtoy $ " " macros.l , v 1409c1352feb 2013/03/24 20:44:50 toy $ " ) ;;; Using Lisp CMU Common Lisp snapshot-2013-11 (20E Unicode) ;;; ;;; Options: ((:prune-labels nil) (:auto-save t) (:relaxed-array-decls t) ;;; (:coerce-assigns :as-needed) (:array-type ':array) ;;; (:array-slicing t) (:declare-common nil) ;;; (:float-format single-float)) (in-package "ODEPACK") (defun dstoka (neq y yh nyh yh1 ewt savf savx acor wm iwm f jac psol) (declare (type (f2cl-lib:integer4) nyh) (type (array double-float (*)) wm acor savx savf ewt yh1 yh y) (type (array f2cl-lib:integer4 (*)) iwm neq)) (let ((dls001-el (make-array 13 :element-type 'double-float :displaced-to (dls001-part-0 *dls001-common-block*) :displaced-index-offset 2)) (dls001-elco (make-array 156 :element-type 'double-float :displaced-to (dls001-part-0 *dls001-common-block*) :displaced-index-offset 15)) (dls001-tesco (make-array 36 :element-type 'double-float :displaced-to (dls001-part-0 *dls001-common-block*) :displaced-index-offset 173))) (symbol-macrolet ((conit (aref (dls001-part-0 *dls001-common-block*) 0)) (crate (aref (dls001-part-0 *dls001-common-block*) 1)) (el dls001-el) (elco dls001-elco) (hold (aref (dls001-part-0 *dls001-common-block*) 171)) (rmax (aref (dls001-part-0 *dls001-common-block*) 172)) (tesco dls001-tesco) (ccmax (aref (dls001-part-0 *dls001-common-block*) 209)) (el0 (aref (dls001-part-0 *dls001-common-block*) 210)) (h (aref (dls001-part-0 *dls001-common-block*) 211)) (hmin (aref (dls001-part-0 *dls001-common-block*) 212)) (hmxi (aref (dls001-part-0 *dls001-common-block*) 213)) (hu (aref (dls001-part-0 *dls001-common-block*) 214)) (rc (aref (dls001-part-0 *dls001-common-block*) 215)) (tn (aref (dls001-part-0 *dls001-common-block*) 216)) (ialth (aref (dls001-part-1 *dls001-common-block*) 6)) (ipup (aref (dls001-part-1 *dls001-common-block*) 7)) (lmax (aref (dls001-part-1 *dls001-common-block*) 8)) (meo (aref (dls001-part-1 *dls001-common-block*) 9)) (nqnyh (aref (dls001-part-1 *dls001-common-block*) 10)) (nslp (aref (dls001-part-1 *dls001-common-block*) 11)) (icf (aref (dls001-part-1 *dls001-common-block*) 12)) (ierpj (aref (dls001-part-1 *dls001-common-block*) 13)) (iersl (aref (dls001-part-1 *dls001-common-block*) 14)) (jcur (aref (dls001-part-1 *dls001-common-block*) 15)) (jstart (aref (dls001-part-1 *dls001-common-block*) 16)) (kflag (aref (dls001-part-1 *dls001-common-block*) 17)) (l (aref (dls001-part-1 *dls001-common-block*) 18)) (meth (aref (dls001-part-1 *dls001-common-block*) 25)) (miter (aref (dls001-part-1 *dls001-common-block*) 26)) (maxord (aref (dls001-part-1 *dls001-common-block*) 27)) (maxcor (aref (dls001-part-1 *dls001-common-block*) 28)) (msbp (aref (dls001-part-1 *dls001-common-block*) 29)) (mxncf (aref (dls001-part-1 *dls001-common-block*) 30)) (n (aref (dls001-part-1 *dls001-common-block*) 31)) (nq (aref (dls001-part-1 *dls001-common-block*) 32)) (nst (aref (dls001-part-1 *dls001-common-block*) 33)) (nfe (aref (dls001-part-1 *dls001-common-block*) 34)) (nqu (aref (dls001-part-1 *dls001-common-block*) 36)) (stifr (aref (dls002-part-0 *dls002-common-block*) 0)) (newt (aref (dls002-part-1 *dls002-common-block*) 0)) (nsfi (aref (dls002-part-1 *dls002-common-block*) 1)) (nslj (aref (dls002-part-1 *dls002-common-block*) 2)) (njev (aref (dls002-part-1 *dls002-common-block*) 3)) (epcon (aref (dlpk01-part-0 *dlpk01-common-block*) 1)) (jacflg (aref (dlpk01-part-1 *dlpk01-common-block*) 1)) (mnewt (aref (dlpk01-part-1 *dlpk01-common-block*) 7)) (ncfn (aref (dlpk01-part-1 *dlpk01-common-block*) 11))) (f2cl-lib:with-multi-array-data ((neq f2cl-lib:integer4 neq-%data% neq-%offset%) (iwm f2cl-lib:integer4 iwm-%data% iwm-%offset%) (y double-float y-%data% y-%offset%) (yh double-float yh-%data% yh-%offset%) (yh1 double-float yh1-%data% yh1-%offset%) (ewt double-float ewt-%data% ewt-%offset%) (savf double-float savf-%data% savf-%offset%) (savx double-float savx-%data% savx-%offset%) (acor double-float acor-%data% acor-%offset%) (wm double-float wm-%data% wm-%offset%)) (prog ((nslow 0) (newq 0) (ncf 0) (m 0) (jok 0) (jb 0) (j 0) (iret 0) (iredo 0) (i1 0) (i 0) (told 0.0d0) (stiff 0.0d0) (roc 0.0d0) (rhup 0.0d0) (rhsm 0.0d0) (rhdn 0.0d0) (rh 0.0d0) (r 0.0d0) (dfnorm 0.0d0) (exup 0.0d0) (exsm 0.0d0) (exdn 0.0d0) (dup 0.0d0) (dsm 0.0d0) (drc 0.0d0) (delp 0.0d0) (del 0.0d0) (ddn 0.0d0) (dcon 0.0d0)) (declare (type (double-float) dcon ddn del delp drc dsm dup exdn exsm exup dfnorm r rh rhdn rhsm rhup roc stiff told) (type (f2cl-lib:integer4) i i1 iredo iret j jb jok m ncf newq nslow)) (setf kflag 0) (setf told tn) (setf ncf 0) (setf ierpj 0) (setf iersl 0) (setf jcur 0) (setf icf 0) (setf delp 0.0d0) (if (> jstart 0) (go label200)) (if (= jstart -1) (go label100)) (if (= jstart -2) (go label160)) (setf lmax (f2cl-lib:int-add maxord 1)) (setf nq 1) (setf l 2) (setf ialth 2) (setf rmax 10000.0d0) (setf rc 0.0d0) (setf el0 1.0d0) (setf crate 0.7d0) (setf hold h) (setf meo meth) (setf nslp 0) (setf nslj 0) (setf ipup 0) (setf iret 3) (setf newt 0) (setf stifr 0.0d0) (go label140) label100 (setf ipup miter) (setf lmax (f2cl-lib:int-add maxord 1)) (if (= ialth 1) (setf ialth 2)) (if (= meth meo) (go label110)) (dcfode meth elco tesco) (setf meo meth) (if (> nq maxord) (go label120)) (setf ialth l) (setf iret 1) (go label150) label110 (if (<= nq maxord) (go label160)) label120 (setf nq maxord) (setf l lmax) (f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1)) ((> i l) nil) (tagbody label125 (setf (f2cl-lib:fref el (i) ((1 13))) (f2cl-lib:fref elco (i nq) ((1 13) (1 12)))))) (setf nqnyh (f2cl-lib:int-mul nq nyh)) (setf rc (/ (* rc (f2cl-lib:fref el (1) ((1 13)))) el0)) (setf el0 (f2cl-lib:fref el (1) ((1 13)))) (setf conit (/ 0.5d0 (f2cl-lib:int-add nq 2))) (setf epcon (* conit (f2cl-lib:fref tesco (2 nq) ((1 3) (1 12))))) (setf ddn (/ (dvnorm n savf ewt) (f2cl-lib:fref tesco (1 l) ((1 3) (1 12))))) (setf exdn (/ 1.0d0 l)) (setf rhdn (/ 1.0d0 (+ (* 1.3d0 (expt ddn exdn)) 1.3d-6))) (setf rh (min rhdn 1.0d0)) (setf iredo 3) (if (= h hold) (go label170)) (setf rh (min rh (abs (/ h hold)))) (setf h hold) (go label175) label140 (dcfode meth elco tesco) label150 (f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1)) ((> i l) nil) (tagbody label155 (setf (f2cl-lib:fref el (i) ((1 13))) (f2cl-lib:fref elco (i nq) ((1 13) (1 12)))))) (setf nqnyh (f2cl-lib:int-mul nq nyh)) (setf rc (/ (* rc (f2cl-lib:fref el (1) ((1 13)))) el0)) (setf el0 (f2cl-lib:fref el (1) ((1 13)))) (setf conit (/ 0.5d0 (f2cl-lib:int-add nq 2))) (setf epcon (* conit (f2cl-lib:fref tesco (2 nq) ((1 3) (1 12))))) (f2cl-lib:computed-goto (label160 label170 label200) iret) label160 (if (= h hold) (go label200)) (setf rh (/ h hold)) (setf h hold) (setf iredo 3) (go label175) label170 (setf rh (max rh (/ hmin (abs h)))) label175 (setf rh (min rh rmax)) (setf rh (/ rh (max 1.0d0 (* (abs h) hmxi rh)))) (setf r 1.0d0) (f2cl-lib:fdo (j 2 (f2cl-lib:int-add j 1)) ((> j l) nil) (tagbody (setf r (* r rh)) (f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1)) ((> i n) nil) (tagbody (setf (f2cl-lib:fref yh-%data% (i j) ((1 nyh) (1 *)) yh-%offset%) (* (f2cl-lib:fref yh-%data% (i j) ((1 nyh) (1 *)) yh-%offset%) r)))))) label180 (setf h (* h rh)) (setf rc (* rc rh)) (setf ialth l) (if (= iredo 0) (go label690)) label200 (cond ((or (= newt 0) (= jacflg 0)) (setf drc 0.0d0) (setf ipup 0) (setf crate 0.7d0)) (t (setf drc (abs (- rc 1.0d0))) (if (> drc ccmax) (setf ipup miter)) (if (>= nst (f2cl-lib:int-add nslp msbp)) (setf ipup miter)))) (setf tn (+ tn h)) (setf i1 (f2cl-lib:int-add nqnyh 1)) (f2cl-lib:fdo (jb 1 (f2cl-lib:int-add jb 1)) ((> jb nq) nil) (tagbody (setf i1 (f2cl-lib:int-sub i1 nyh)) (f2cl-lib:fdo (i i1 (f2cl-lib:int-add i 1)) ((> i nqnyh) nil) (tagbody label210 (setf (f2cl-lib:fref yh1-%data% (i) ((1 *)) yh1-%offset%) (+ (f2cl-lib:fref yh1-%data% (i) ((1 *)) yh1-%offset%) (f2cl-lib:fref yh1-%data% ((f2cl-lib:int-add i nyh)) ((1 *)) yh1-%offset%))))) label215)) label220 (setf m 0) (setf mnewt 0) (setf stiff 0.0d0) (setf roc 0.05d0) (setf nslow 0) (f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1)) ((> i n) nil) (tagbody label230 (setf (f2cl-lib:fref y-%data% (i) ((1 *)) y-%offset%) (f2cl-lib:fref yh-%data% (i 1) ((1 nyh) (1 *)) yh-%offset%)))) (multiple-value-bind (var-0 var-1 var-2 var-3) (funcall f neq tn y savf) (declare (ignore var-0 var-2 var-3)) (when var-1 (setf tn var-1))) (setf nfe (f2cl-lib:int-add nfe 1)) (if (or (= newt 0) (<= ipup 0)) (go label250)) (setf jok 1) (if (or (= nst 0) (> nst (f2cl-lib:int-add nslj 50))) (setf jok -1)) (if (and (= icf 1) (< drc 0.2d0)) (setf jok -1)) (if (= icf 2) (setf jok -1)) (cond ((= jok (f2cl-lib:int-sub 1)) (setf nslj nst) (setf njev (f2cl-lib:int-add njev 1)))) (multiple-value-bind (var-0 var-1 var-2 var-3 var-4 var-5 var-6 var-7 var-8 var-9 var-10) (dsetpk neq y yh1 ewt acor savf jok wm iwm f jac) (declare (ignore var-0 var-1 var-2 var-3 var-4 var-5 var-7 var-8 var-9 var-10)) (setf jok var-6)) (setf ipup 0) (setf rc 1.0d0) (setf drc 0.0d0) (setf nslp nst) (setf crate 0.7d0) (if (/= ierpj 0) (go label430)) label250 (f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1)) ((> i n) nil) (tagbody label260 (setf (f2cl-lib:fref acor-%data% (i) ((1 *)) acor-%offset%) 0.0d0))) label270 (if (/= newt 0) (go label350)) (f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1)) ((> i n) nil) (tagbody (setf (f2cl-lib:fref savf-%data% (i) ((1 *)) savf-%offset%) (- (* h (f2cl-lib:fref savf-%data% (i) ((1 *)) savf-%offset%)) (f2cl-lib:fref yh-%data% (i 2) ((1 nyh) (1 *)) yh-%offset%))) label290 (setf (f2cl-lib:fref y-%data% (i) ((1 *)) y-%offset%) (- (f2cl-lib:fref savf-%data% (i) ((1 *)) savf-%offset%) (f2cl-lib:fref acor-%data% (i) ((1 *)) acor-%offset%))))) (setf del (dvnorm n y ewt)) (f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1)) ((> i n) nil) (tagbody (setf (f2cl-lib:fref y-%data% (i) ((1 *)) y-%offset%) (+ (f2cl-lib:fref yh-%data% (i 1) ((1 nyh) (1 *)) yh-%offset%) (* (f2cl-lib:fref el (1) ((1 13))) (f2cl-lib:fref savf-%data% (i) ((1 *)) savf-%offset%)))) label300 (setf (f2cl-lib:fref acor-%data% (i) ((1 *)) acor-%offset%) (f2cl-lib:fref savf-%data% (i) ((1 *)) savf-%offset%)))) (setf stiff 1.0d0) (go label400) label350 (f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1)) ((> i n) nil) (tagbody label360 (setf (f2cl-lib:fref savx-%data% (i) ((1 *)) savx-%offset%) (- (* h (f2cl-lib:fref savf-%data% (i) ((1 *)) savf-%offset%)) (+ (f2cl-lib:fref yh-%data% (i 2) ((1 nyh) (1 *)) yh-%offset%) (f2cl-lib:fref acor-%data% (i) ((1 *)) acor-%offset%)))))) (setf dfnorm (dvnorm n savx ewt)) (dsolpk neq y savf savx ewt wm iwm f psol) (if (< iersl 0) (go label430)) (if (> iersl 0) (go label410)) (setf del (dvnorm n savx ewt)) (if (> del 1.0d-8) (setf stiff (max stiff (/ dfnorm del)))) (f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1)) ((> i n) nil) (tagbody (setf (f2cl-lib:fref acor-%data% (i) ((1 *)) acor-%offset%) (+ (f2cl-lib:fref acor-%data% (i) ((1 *)) acor-%offset%) (f2cl-lib:fref savx-%data% (i) ((1 *)) savx-%offset%))) label380 (setf (f2cl-lib:fref y-%data% (i) ((1 *)) y-%offset%) (+ (f2cl-lib:fref yh-%data% (i 1) ((1 nyh) (1 *)) yh-%offset%) (* (f2cl-lib:fref el (1) ((1 13))) (f2cl-lib:fref acor-%data% (i) ((1 *)) acor-%offset%)))))) label400 (cond ((/= m 0) (setf roc (max 0.05d0 (/ del delp))) (setf crate (max (* 0.2d0 crate) roc)))) (setf dcon (/ (* del (min 1.0d0 (* 1.5d0 crate))) epcon)) (if (<= dcon 1.0d0) (go label450)) (setf m (f2cl-lib:int-add m 1)) (if (= m maxcor) (go label410)) (if (and (>= m 2) (> del (* 2.0d0 delp))) (go label410)) (if (> roc 10.0d0) (go label410)) (if (> roc 0.8d0) (setf nslow (f2cl-lib:int-add nslow 1))) (if (>= nslow 2) (go label410)) (setf mnewt m) (setf delp del) (multiple-value-bind (var-0 var-1 var-2 var-3) (funcall f neq tn y savf) (declare (ignore var-0 var-2 var-3)) (when var-1 (setf tn var-1))) (setf nfe (f2cl-lib:int-add nfe 1)) (go label270) label410 (setf icf 1) (cond ((= newt 0) (if (= nst 0) (go label430)) (if (= miter 0) (go label430)) (setf newt miter) (setf stifr 1023.0d0) (setf ipup miter) (go label220))) (if (or (= jcur 1) (= jacflg 0)) (go label430)) (setf ipup miter) (go label220) label430 (setf icf 2) (setf ncf (f2cl-lib:int-add ncf 1)) (setf ncfn (f2cl-lib:int-add ncfn 1)) (setf rmax 2.0d0) (setf tn told) (setf i1 (f2cl-lib:int-add nqnyh 1)) (f2cl-lib:fdo (jb 1 (f2cl-lib:int-add jb 1)) ((> jb nq) nil) (tagbody (setf i1 (f2cl-lib:int-sub i1 nyh)) (f2cl-lib:fdo (i i1 (f2cl-lib:int-add i 1)) ((> i nqnyh) nil) (tagbody label440 (setf (f2cl-lib:fref yh1-%data% (i) ((1 *)) yh1-%offset%) (- (f2cl-lib:fref yh1-%data% (i) ((1 *)) yh1-%offset%) (f2cl-lib:fref yh1-%data% ((f2cl-lib:int-add i nyh)) ((1 *)) yh1-%offset%))))) label445)) (if (or (< ierpj 0) (< iersl 0)) (go label680)) (if (<= (abs h) (* hmin 1.00001d0)) (go label670)) (if (= ncf mxncf) (go label670)) (setf rh 0.5d0) (setf ipup miter) (setf iredo 1) (go label170) label450 (setf jcur 0) (if (> newt 0) (setf stifr (* 0.5d0 (+ stifr stiff)))) (if (= m 0) (setf dsm (/ del (f2cl-lib:fref tesco (2 nq) ((1 3) (1 12)))))) (if (> m 0) (setf dsm (/ (dvnorm n acor ewt) (f2cl-lib:fref tesco (2 nq) ((1 3) (1 12)))))) (if (> dsm 1.0d0) (go label500)) (setf kflag 0) (setf iredo 0) (setf nst (f2cl-lib:int-add nst 1)) (if (= newt 0) (setf nsfi (f2cl-lib:int-add nsfi 1))) (if (and (> newt 0) (< stifr 1.5d0)) (setf newt 0)) (setf hu h) (setf nqu nq) (f2cl-lib:fdo (j 1 (f2cl-lib:int-add j 1)) ((> j l) nil) (tagbody (f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1)) ((> i n) nil) (tagbody (setf (f2cl-lib:fref yh-%data% (i j) ((1 nyh) (1 *)) yh-%offset%) (+ (f2cl-lib:fref yh-%data% (i j) ((1 nyh) (1 *)) yh-%offset%) (* (f2cl-lib:fref el (j) ((1 13))) (f2cl-lib:fref acor-%data% (i) ((1 *)) acor-%offset%)))))))) label470 (setf ialth (f2cl-lib:int-sub ialth 1)) (if (= ialth 0) (go label520)) (if (> ialth 1) (go label700)) (if (= l lmax) (go label700)) (f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1)) ((> i n) nil) (tagbody label490 (setf (f2cl-lib:fref yh-%data% (i lmax) ((1 nyh) (1 *)) yh-%offset%) (f2cl-lib:fref acor-%data% (i) ((1 *)) acor-%offset%)))) (go label700) label500 (setf kflag (f2cl-lib:int-sub kflag 1)) (setf tn told) (setf i1 (f2cl-lib:int-add nqnyh 1)) (f2cl-lib:fdo (jb 1 (f2cl-lib:int-add jb 1)) ((> jb nq) nil) (tagbody (setf i1 (f2cl-lib:int-sub i1 nyh)) (f2cl-lib:fdo (i i1 (f2cl-lib:int-add i 1)) ((> i nqnyh) nil) (tagbody label510 (setf (f2cl-lib:fref yh1-%data% (i) ((1 *)) yh1-%offset%) (- (f2cl-lib:fref yh1-%data% (i) ((1 *)) yh1-%offset%) (f2cl-lib:fref yh1-%data% ((f2cl-lib:int-add i nyh)) ((1 *)) yh1-%offset%))))) label515)) (setf rmax 2.0d0) (if (<= (abs h) (* hmin 1.00001d0)) (go label660)) (if (<= kflag -3) (go label640)) (setf iredo 2) (setf rhup 0.0d0) (go label540) label520 (setf rhup 0.0d0) (if (= l lmax) (go label540)) (f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1)) ((> i n) nil) (tagbody label530 (setf (f2cl-lib:fref savf-%data% (i) ((1 *)) savf-%offset%) (- (f2cl-lib:fref acor-%data% (i) ((1 *)) acor-%offset%) (f2cl-lib:fref yh-%data% (i lmax) ((1 nyh) (1 *)) yh-%offset%))))) (setf dup (/ (dvnorm n savf ewt) (f2cl-lib:fref tesco (3 nq) ((1 3) (1 12))))) (setf exup (/ 1.0d0 (f2cl-lib:int-add l 1))) (setf rhup (/ 1.0d0 (+ (* 1.4d0 (expt dup exup)) 1.4d-6))) label540 (setf exsm (/ 1.0d0 l)) (setf rhsm (/ 1.0d0 (+ (* 1.2d0 (expt dsm exsm)) 1.2d-6))) (setf rhdn 0.0d0) (if (= nq 1) (go label560)) (setf ddn (/ (dvnorm n (f2cl-lib:array-slice yh-%data% double-float (1 l) ((1 nyh) (1 *)) yh-%offset%) ewt) (f2cl-lib:fref tesco (1 nq) ((1 3) (1 12))))) (setf exdn (/ 1.0d0 nq)) (setf rhdn (/ 1.0d0 (+ (* 1.3d0 (expt ddn exdn)) 1.3d-6))) label560 (if (>= rhsm rhup) (go label570)) (if (> rhup rhdn) (go label590)) (go label580) label570 (if (< rhsm rhdn) (go label580)) (setf newq nq) (setf rh rhsm) (go label620) label580 (setf newq (f2cl-lib:int-sub nq 1)) (setf rh rhdn) (if (and (< kflag 0) (> rh 1.0d0)) (setf rh 1.0d0)) (go label620) label590 (setf newq l) (setf rh rhup) (if (< rh 1.1d0) (go label610)) (setf r (/ (f2cl-lib:fref el (l) ((1 13))) l)) (f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1)) ((> i n) nil) (tagbody label600 (setf (f2cl-lib:fref yh-%data% (i (f2cl-lib:int-add newq 1)) ((1 nyh) (1 *)) yh-%offset%) (* (f2cl-lib:fref acor-%data% (i) ((1 *)) acor-%offset%) r)))) (go label630) label610 (setf ialth 3) (go label700) label620 (if (and (= kflag 0) (< rh 1.1d0)) (go label610)) (if (<= kflag -2) (setf rh (min rh 0.2d0))) (if (= newq nq) (go label170)) label630 (setf nq newq) (setf l (f2cl-lib:int-add nq 1)) (setf iret 2) (go label150) label640 (if (= kflag -10) (go label660)) (setf rh 0.1d0) (setf rh (max (/ hmin (abs h)) rh)) (setf h (* h rh)) (f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1)) ((> i n) nil) (tagbody label645 (setf (f2cl-lib:fref y-%data% (i) ((1 *)) y-%offset%) (f2cl-lib:fref yh-%data% (i 1) ((1 nyh) (1 *)) yh-%offset%)))) (multiple-value-bind (var-0 var-1 var-2 var-3) (funcall f neq tn y savf) (declare (ignore var-0 var-2 var-3)) (when var-1 (setf tn var-1))) (setf nfe (f2cl-lib:int-add nfe 1)) (f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1)) ((> i n) nil) (tagbody label650 (setf (f2cl-lib:fref yh-%data% (i 2) ((1 nyh) (1 *)) yh-%offset%) (* h (f2cl-lib:fref savf-%data% (i) ((1 *)) savf-%offset%))))) (setf ipup miter) (setf ialth 5) (if (= nq 1) (go label200)) (setf nq 1) (setf l 2) (setf iret 3) (go label150) label660 (setf kflag -1) (go label720) label670 (setf kflag -2) (go label720) label680 (setf kflag -3) (go label720) label690 (setf rmax 10.0d0) label700 (setf r (/ 1.0d0 (f2cl-lib:fref tesco (2 nqu) ((1 3) (1 12))))) (f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1)) ((> i n) nil) (tagbody label710 (setf (f2cl-lib:fref acor-%data% (i) ((1 *)) acor-%offset%) (* (f2cl-lib:fref acor-%data% (i) ((1 *)) acor-%offset%) r)))) label720 (setf hold h) (setf jstart 1) (go end_label) end_label (return (values nil nil nil nil nil nil nil nil nil nil nil nil nil nil))))))) (in-package #-gcl #:cl-user #+gcl "CL-USER") #+#.(cl:if (cl:find-package '#:f2cl) '(and) '(or)) (eval-when (:load-toplevel :compile-toplevel :execute) (setf (gethash 'fortran-to-lisp::dstoka fortran-to-lisp::*f2cl-function-info*) (fortran-to-lisp::make-f2cl-finfo :arg-types '((array fortran-to-lisp::integer4 (*)) (array double-float (*)) (array double-float (*)) (fortran-to-lisp::integer4) (array double-float (*)) (array double-float (*)) (array double-float (*)) (array double-float (*)) (array double-float (*)) (array double-float (*)) (array fortran-to-lisp::integer4 (*)) t t t) :return-values '(nil nil nil nil nil nil nil nil nil nil nil nil nil nil) :calls '(fortran-to-lisp::dsolpk fortran-to-lisp::dsetpk fortran-to-lisp::dvnorm fortran-to-lisp::dcfode))))
null
https://raw.githubusercontent.com/Eduap-com/WordMat/83c9336770067f54431cc42c7147dc6ed640a339/Windows/ExternalPrograms/maxima-5.45.1/share/maxima/5.45.1/share/odepack/src/dstoka.lisp
lisp
Compiled by f2cl version: Using Lisp CMU Common Lisp snapshot-2013-11 (20E Unicode) Options: ((:prune-labels nil) (:auto-save t) (:relaxed-array-decls t) (:coerce-assigns :as-needed) (:array-type ':array) (:array-slicing t) (:declare-common nil) (:float-format single-float))
( " f2cl1.l , v 95098eb54f13 2013/04/01 00:45:16 toy $ " " f2cl2.l , v 95098eb54f13 2013/04/01 00:45:16 toy $ " " f2cl3.l , v 96616d88fb7e 2008/02/22 22:19:34 rtoy $ " " f2cl4.l , v 96616d88fb7e 2008/02/22 22:19:34 rtoy $ " " f2cl5.l , v 95098eb54f13 2013/04/01 00:45:16 toy $ " " f2cl6.l , v 1d5cbacbb977 2008/08/24 00:56:27 rtoy $ " " macros.l , v 1409c1352feb 2013/03/24 20:44:50 toy $ " ) (in-package "ODEPACK") (defun dstoka (neq y yh nyh yh1 ewt savf savx acor wm iwm f jac psol) (declare (type (f2cl-lib:integer4) nyh) (type (array double-float (*)) wm acor savx savf ewt yh1 yh y) (type (array f2cl-lib:integer4 (*)) iwm neq)) (let ((dls001-el (make-array 13 :element-type 'double-float :displaced-to (dls001-part-0 *dls001-common-block*) :displaced-index-offset 2)) (dls001-elco (make-array 156 :element-type 'double-float :displaced-to (dls001-part-0 *dls001-common-block*) :displaced-index-offset 15)) (dls001-tesco (make-array 36 :element-type 'double-float :displaced-to (dls001-part-0 *dls001-common-block*) :displaced-index-offset 173))) (symbol-macrolet ((conit (aref (dls001-part-0 *dls001-common-block*) 0)) (crate (aref (dls001-part-0 *dls001-common-block*) 1)) (el dls001-el) (elco dls001-elco) (hold (aref (dls001-part-0 *dls001-common-block*) 171)) (rmax (aref (dls001-part-0 *dls001-common-block*) 172)) (tesco dls001-tesco) (ccmax (aref (dls001-part-0 *dls001-common-block*) 209)) (el0 (aref (dls001-part-0 *dls001-common-block*) 210)) (h (aref (dls001-part-0 *dls001-common-block*) 211)) (hmin (aref (dls001-part-0 *dls001-common-block*) 212)) (hmxi (aref (dls001-part-0 *dls001-common-block*) 213)) (hu (aref (dls001-part-0 *dls001-common-block*) 214)) (rc (aref (dls001-part-0 *dls001-common-block*) 215)) (tn (aref (dls001-part-0 *dls001-common-block*) 216)) (ialth (aref (dls001-part-1 *dls001-common-block*) 6)) (ipup (aref (dls001-part-1 *dls001-common-block*) 7)) (lmax (aref (dls001-part-1 *dls001-common-block*) 8)) (meo (aref (dls001-part-1 *dls001-common-block*) 9)) (nqnyh (aref (dls001-part-1 *dls001-common-block*) 10)) (nslp (aref (dls001-part-1 *dls001-common-block*) 11)) (icf (aref (dls001-part-1 *dls001-common-block*) 12)) (ierpj (aref (dls001-part-1 *dls001-common-block*) 13)) (iersl (aref (dls001-part-1 *dls001-common-block*) 14)) (jcur (aref (dls001-part-1 *dls001-common-block*) 15)) (jstart (aref (dls001-part-1 *dls001-common-block*) 16)) (kflag (aref (dls001-part-1 *dls001-common-block*) 17)) (l (aref (dls001-part-1 *dls001-common-block*) 18)) (meth (aref (dls001-part-1 *dls001-common-block*) 25)) (miter (aref (dls001-part-1 *dls001-common-block*) 26)) (maxord (aref (dls001-part-1 *dls001-common-block*) 27)) (maxcor (aref (dls001-part-1 *dls001-common-block*) 28)) (msbp (aref (dls001-part-1 *dls001-common-block*) 29)) (mxncf (aref (dls001-part-1 *dls001-common-block*) 30)) (n (aref (dls001-part-1 *dls001-common-block*) 31)) (nq (aref (dls001-part-1 *dls001-common-block*) 32)) (nst (aref (dls001-part-1 *dls001-common-block*) 33)) (nfe (aref (dls001-part-1 *dls001-common-block*) 34)) (nqu (aref (dls001-part-1 *dls001-common-block*) 36)) (stifr (aref (dls002-part-0 *dls002-common-block*) 0)) (newt (aref (dls002-part-1 *dls002-common-block*) 0)) (nsfi (aref (dls002-part-1 *dls002-common-block*) 1)) (nslj (aref (dls002-part-1 *dls002-common-block*) 2)) (njev (aref (dls002-part-1 *dls002-common-block*) 3)) (epcon (aref (dlpk01-part-0 *dlpk01-common-block*) 1)) (jacflg (aref (dlpk01-part-1 *dlpk01-common-block*) 1)) (mnewt (aref (dlpk01-part-1 *dlpk01-common-block*) 7)) (ncfn (aref (dlpk01-part-1 *dlpk01-common-block*) 11))) (f2cl-lib:with-multi-array-data ((neq f2cl-lib:integer4 neq-%data% neq-%offset%) (iwm f2cl-lib:integer4 iwm-%data% iwm-%offset%) (y double-float y-%data% y-%offset%) (yh double-float yh-%data% yh-%offset%) (yh1 double-float yh1-%data% yh1-%offset%) (ewt double-float ewt-%data% ewt-%offset%) (savf double-float savf-%data% savf-%offset%) (savx double-float savx-%data% savx-%offset%) (acor double-float acor-%data% acor-%offset%) (wm double-float wm-%data% wm-%offset%)) (prog ((nslow 0) (newq 0) (ncf 0) (m 0) (jok 0) (jb 0) (j 0) (iret 0) (iredo 0) (i1 0) (i 0) (told 0.0d0) (stiff 0.0d0) (roc 0.0d0) (rhup 0.0d0) (rhsm 0.0d0) (rhdn 0.0d0) (rh 0.0d0) (r 0.0d0) (dfnorm 0.0d0) (exup 0.0d0) (exsm 0.0d0) (exdn 0.0d0) (dup 0.0d0) (dsm 0.0d0) (drc 0.0d0) (delp 0.0d0) (del 0.0d0) (ddn 0.0d0) (dcon 0.0d0)) (declare (type (double-float) dcon ddn del delp drc dsm dup exdn exsm exup dfnorm r rh rhdn rhsm rhup roc stiff told) (type (f2cl-lib:integer4) i i1 iredo iret j jb jok m ncf newq nslow)) (setf kflag 0) (setf told tn) (setf ncf 0) (setf ierpj 0) (setf iersl 0) (setf jcur 0) (setf icf 0) (setf delp 0.0d0) (if (> jstart 0) (go label200)) (if (= jstart -1) (go label100)) (if (= jstart -2) (go label160)) (setf lmax (f2cl-lib:int-add maxord 1)) (setf nq 1) (setf l 2) (setf ialth 2) (setf rmax 10000.0d0) (setf rc 0.0d0) (setf el0 1.0d0) (setf crate 0.7d0) (setf hold h) (setf meo meth) (setf nslp 0) (setf nslj 0) (setf ipup 0) (setf iret 3) (setf newt 0) (setf stifr 0.0d0) (go label140) label100 (setf ipup miter) (setf lmax (f2cl-lib:int-add maxord 1)) (if (= ialth 1) (setf ialth 2)) (if (= meth meo) (go label110)) (dcfode meth elco tesco) (setf meo meth) (if (> nq maxord) (go label120)) (setf ialth l) (setf iret 1) (go label150) label110 (if (<= nq maxord) (go label160)) label120 (setf nq maxord) (setf l lmax) (f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1)) ((> i l) nil) (tagbody label125 (setf (f2cl-lib:fref el (i) ((1 13))) (f2cl-lib:fref elco (i nq) ((1 13) (1 12)))))) (setf nqnyh (f2cl-lib:int-mul nq nyh)) (setf rc (/ (* rc (f2cl-lib:fref el (1) ((1 13)))) el0)) (setf el0 (f2cl-lib:fref el (1) ((1 13)))) (setf conit (/ 0.5d0 (f2cl-lib:int-add nq 2))) (setf epcon (* conit (f2cl-lib:fref tesco (2 nq) ((1 3) (1 12))))) (setf ddn (/ (dvnorm n savf ewt) (f2cl-lib:fref tesco (1 l) ((1 3) (1 12))))) (setf exdn (/ 1.0d0 l)) (setf rhdn (/ 1.0d0 (+ (* 1.3d0 (expt ddn exdn)) 1.3d-6))) (setf rh (min rhdn 1.0d0)) (setf iredo 3) (if (= h hold) (go label170)) (setf rh (min rh (abs (/ h hold)))) (setf h hold) (go label175) label140 (dcfode meth elco tesco) label150 (f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1)) ((> i l) nil) (tagbody label155 (setf (f2cl-lib:fref el (i) ((1 13))) (f2cl-lib:fref elco (i nq) ((1 13) (1 12)))))) (setf nqnyh (f2cl-lib:int-mul nq nyh)) (setf rc (/ (* rc (f2cl-lib:fref el (1) ((1 13)))) el0)) (setf el0 (f2cl-lib:fref el (1) ((1 13)))) (setf conit (/ 0.5d0 (f2cl-lib:int-add nq 2))) (setf epcon (* conit (f2cl-lib:fref tesco (2 nq) ((1 3) (1 12))))) (f2cl-lib:computed-goto (label160 label170 label200) iret) label160 (if (= h hold) (go label200)) (setf rh (/ h hold)) (setf h hold) (setf iredo 3) (go label175) label170 (setf rh (max rh (/ hmin (abs h)))) label175 (setf rh (min rh rmax)) (setf rh (/ rh (max 1.0d0 (* (abs h) hmxi rh)))) (setf r 1.0d0) (f2cl-lib:fdo (j 2 (f2cl-lib:int-add j 1)) ((> j l) nil) (tagbody (setf r (* r rh)) (f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1)) ((> i n) nil) (tagbody (setf (f2cl-lib:fref yh-%data% (i j) ((1 nyh) (1 *)) yh-%offset%) (* (f2cl-lib:fref yh-%data% (i j) ((1 nyh) (1 *)) yh-%offset%) r)))))) label180 (setf h (* h rh)) (setf rc (* rc rh)) (setf ialth l) (if (= iredo 0) (go label690)) label200 (cond ((or (= newt 0) (= jacflg 0)) (setf drc 0.0d0) (setf ipup 0) (setf crate 0.7d0)) (t (setf drc (abs (- rc 1.0d0))) (if (> drc ccmax) (setf ipup miter)) (if (>= nst (f2cl-lib:int-add nslp msbp)) (setf ipup miter)))) (setf tn (+ tn h)) (setf i1 (f2cl-lib:int-add nqnyh 1)) (f2cl-lib:fdo (jb 1 (f2cl-lib:int-add jb 1)) ((> jb nq) nil) (tagbody (setf i1 (f2cl-lib:int-sub i1 nyh)) (f2cl-lib:fdo (i i1 (f2cl-lib:int-add i 1)) ((> i nqnyh) nil) (tagbody label210 (setf (f2cl-lib:fref yh1-%data% (i) ((1 *)) yh1-%offset%) (+ (f2cl-lib:fref yh1-%data% (i) ((1 *)) yh1-%offset%) (f2cl-lib:fref yh1-%data% ((f2cl-lib:int-add i nyh)) ((1 *)) yh1-%offset%))))) label215)) label220 (setf m 0) (setf mnewt 0) (setf stiff 0.0d0) (setf roc 0.05d0) (setf nslow 0) (f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1)) ((> i n) nil) (tagbody label230 (setf (f2cl-lib:fref y-%data% (i) ((1 *)) y-%offset%) (f2cl-lib:fref yh-%data% (i 1) ((1 nyh) (1 *)) yh-%offset%)))) (multiple-value-bind (var-0 var-1 var-2 var-3) (funcall f neq tn y savf) (declare (ignore var-0 var-2 var-3)) (when var-1 (setf tn var-1))) (setf nfe (f2cl-lib:int-add nfe 1)) (if (or (= newt 0) (<= ipup 0)) (go label250)) (setf jok 1) (if (or (= nst 0) (> nst (f2cl-lib:int-add nslj 50))) (setf jok -1)) (if (and (= icf 1) (< drc 0.2d0)) (setf jok -1)) (if (= icf 2) (setf jok -1)) (cond ((= jok (f2cl-lib:int-sub 1)) (setf nslj nst) (setf njev (f2cl-lib:int-add njev 1)))) (multiple-value-bind (var-0 var-1 var-2 var-3 var-4 var-5 var-6 var-7 var-8 var-9 var-10) (dsetpk neq y yh1 ewt acor savf jok wm iwm f jac) (declare (ignore var-0 var-1 var-2 var-3 var-4 var-5 var-7 var-8 var-9 var-10)) (setf jok var-6)) (setf ipup 0) (setf rc 1.0d0) (setf drc 0.0d0) (setf nslp nst) (setf crate 0.7d0) (if (/= ierpj 0) (go label430)) label250 (f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1)) ((> i n) nil) (tagbody label260 (setf (f2cl-lib:fref acor-%data% (i) ((1 *)) acor-%offset%) 0.0d0))) label270 (if (/= newt 0) (go label350)) (f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1)) ((> i n) nil) (tagbody (setf (f2cl-lib:fref savf-%data% (i) ((1 *)) savf-%offset%) (- (* h (f2cl-lib:fref savf-%data% (i) ((1 *)) savf-%offset%)) (f2cl-lib:fref yh-%data% (i 2) ((1 nyh) (1 *)) yh-%offset%))) label290 (setf (f2cl-lib:fref y-%data% (i) ((1 *)) y-%offset%) (- (f2cl-lib:fref savf-%data% (i) ((1 *)) savf-%offset%) (f2cl-lib:fref acor-%data% (i) ((1 *)) acor-%offset%))))) (setf del (dvnorm n y ewt)) (f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1)) ((> i n) nil) (tagbody (setf (f2cl-lib:fref y-%data% (i) ((1 *)) y-%offset%) (+ (f2cl-lib:fref yh-%data% (i 1) ((1 nyh) (1 *)) yh-%offset%) (* (f2cl-lib:fref el (1) ((1 13))) (f2cl-lib:fref savf-%data% (i) ((1 *)) savf-%offset%)))) label300 (setf (f2cl-lib:fref acor-%data% (i) ((1 *)) acor-%offset%) (f2cl-lib:fref savf-%data% (i) ((1 *)) savf-%offset%)))) (setf stiff 1.0d0) (go label400) label350 (f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1)) ((> i n) nil) (tagbody label360 (setf (f2cl-lib:fref savx-%data% (i) ((1 *)) savx-%offset%) (- (* h (f2cl-lib:fref savf-%data% (i) ((1 *)) savf-%offset%)) (+ (f2cl-lib:fref yh-%data% (i 2) ((1 nyh) (1 *)) yh-%offset%) (f2cl-lib:fref acor-%data% (i) ((1 *)) acor-%offset%)))))) (setf dfnorm (dvnorm n savx ewt)) (dsolpk neq y savf savx ewt wm iwm f psol) (if (< iersl 0) (go label430)) (if (> iersl 0) (go label410)) (setf del (dvnorm n savx ewt)) (if (> del 1.0d-8) (setf stiff (max stiff (/ dfnorm del)))) (f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1)) ((> i n) nil) (tagbody (setf (f2cl-lib:fref acor-%data% (i) ((1 *)) acor-%offset%) (+ (f2cl-lib:fref acor-%data% (i) ((1 *)) acor-%offset%) (f2cl-lib:fref savx-%data% (i) ((1 *)) savx-%offset%))) label380 (setf (f2cl-lib:fref y-%data% (i) ((1 *)) y-%offset%) (+ (f2cl-lib:fref yh-%data% (i 1) ((1 nyh) (1 *)) yh-%offset%) (* (f2cl-lib:fref el (1) ((1 13))) (f2cl-lib:fref acor-%data% (i) ((1 *)) acor-%offset%)))))) label400 (cond ((/= m 0) (setf roc (max 0.05d0 (/ del delp))) (setf crate (max (* 0.2d0 crate) roc)))) (setf dcon (/ (* del (min 1.0d0 (* 1.5d0 crate))) epcon)) (if (<= dcon 1.0d0) (go label450)) (setf m (f2cl-lib:int-add m 1)) (if (= m maxcor) (go label410)) (if (and (>= m 2) (> del (* 2.0d0 delp))) (go label410)) (if (> roc 10.0d0) (go label410)) (if (> roc 0.8d0) (setf nslow (f2cl-lib:int-add nslow 1))) (if (>= nslow 2) (go label410)) (setf mnewt m) (setf delp del) (multiple-value-bind (var-0 var-1 var-2 var-3) (funcall f neq tn y savf) (declare (ignore var-0 var-2 var-3)) (when var-1 (setf tn var-1))) (setf nfe (f2cl-lib:int-add nfe 1)) (go label270) label410 (setf icf 1) (cond ((= newt 0) (if (= nst 0) (go label430)) (if (= miter 0) (go label430)) (setf newt miter) (setf stifr 1023.0d0) (setf ipup miter) (go label220))) (if (or (= jcur 1) (= jacflg 0)) (go label430)) (setf ipup miter) (go label220) label430 (setf icf 2) (setf ncf (f2cl-lib:int-add ncf 1)) (setf ncfn (f2cl-lib:int-add ncfn 1)) (setf rmax 2.0d0) (setf tn told) (setf i1 (f2cl-lib:int-add nqnyh 1)) (f2cl-lib:fdo (jb 1 (f2cl-lib:int-add jb 1)) ((> jb nq) nil) (tagbody (setf i1 (f2cl-lib:int-sub i1 nyh)) (f2cl-lib:fdo (i i1 (f2cl-lib:int-add i 1)) ((> i nqnyh) nil) (tagbody label440 (setf (f2cl-lib:fref yh1-%data% (i) ((1 *)) yh1-%offset%) (- (f2cl-lib:fref yh1-%data% (i) ((1 *)) yh1-%offset%) (f2cl-lib:fref yh1-%data% ((f2cl-lib:int-add i nyh)) ((1 *)) yh1-%offset%))))) label445)) (if (or (< ierpj 0) (< iersl 0)) (go label680)) (if (<= (abs h) (* hmin 1.00001d0)) (go label670)) (if (= ncf mxncf) (go label670)) (setf rh 0.5d0) (setf ipup miter) (setf iredo 1) (go label170) label450 (setf jcur 0) (if (> newt 0) (setf stifr (* 0.5d0 (+ stifr stiff)))) (if (= m 0) (setf dsm (/ del (f2cl-lib:fref tesco (2 nq) ((1 3) (1 12)))))) (if (> m 0) (setf dsm (/ (dvnorm n acor ewt) (f2cl-lib:fref tesco (2 nq) ((1 3) (1 12)))))) (if (> dsm 1.0d0) (go label500)) (setf kflag 0) (setf iredo 0) (setf nst (f2cl-lib:int-add nst 1)) (if (= newt 0) (setf nsfi (f2cl-lib:int-add nsfi 1))) (if (and (> newt 0) (< stifr 1.5d0)) (setf newt 0)) (setf hu h) (setf nqu nq) (f2cl-lib:fdo (j 1 (f2cl-lib:int-add j 1)) ((> j l) nil) (tagbody (f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1)) ((> i n) nil) (tagbody (setf (f2cl-lib:fref yh-%data% (i j) ((1 nyh) (1 *)) yh-%offset%) (+ (f2cl-lib:fref yh-%data% (i j) ((1 nyh) (1 *)) yh-%offset%) (* (f2cl-lib:fref el (j) ((1 13))) (f2cl-lib:fref acor-%data% (i) ((1 *)) acor-%offset%)))))))) label470 (setf ialth (f2cl-lib:int-sub ialth 1)) (if (= ialth 0) (go label520)) (if (> ialth 1) (go label700)) (if (= l lmax) (go label700)) (f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1)) ((> i n) nil) (tagbody label490 (setf (f2cl-lib:fref yh-%data% (i lmax) ((1 nyh) (1 *)) yh-%offset%) (f2cl-lib:fref acor-%data% (i) ((1 *)) acor-%offset%)))) (go label700) label500 (setf kflag (f2cl-lib:int-sub kflag 1)) (setf tn told) (setf i1 (f2cl-lib:int-add nqnyh 1)) (f2cl-lib:fdo (jb 1 (f2cl-lib:int-add jb 1)) ((> jb nq) nil) (tagbody (setf i1 (f2cl-lib:int-sub i1 nyh)) (f2cl-lib:fdo (i i1 (f2cl-lib:int-add i 1)) ((> i nqnyh) nil) (tagbody label510 (setf (f2cl-lib:fref yh1-%data% (i) ((1 *)) yh1-%offset%) (- (f2cl-lib:fref yh1-%data% (i) ((1 *)) yh1-%offset%) (f2cl-lib:fref yh1-%data% ((f2cl-lib:int-add i nyh)) ((1 *)) yh1-%offset%))))) label515)) (setf rmax 2.0d0) (if (<= (abs h) (* hmin 1.00001d0)) (go label660)) (if (<= kflag -3) (go label640)) (setf iredo 2) (setf rhup 0.0d0) (go label540) label520 (setf rhup 0.0d0) (if (= l lmax) (go label540)) (f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1)) ((> i n) nil) (tagbody label530 (setf (f2cl-lib:fref savf-%data% (i) ((1 *)) savf-%offset%) (- (f2cl-lib:fref acor-%data% (i) ((1 *)) acor-%offset%) (f2cl-lib:fref yh-%data% (i lmax) ((1 nyh) (1 *)) yh-%offset%))))) (setf dup (/ (dvnorm n savf ewt) (f2cl-lib:fref tesco (3 nq) ((1 3) (1 12))))) (setf exup (/ 1.0d0 (f2cl-lib:int-add l 1))) (setf rhup (/ 1.0d0 (+ (* 1.4d0 (expt dup exup)) 1.4d-6))) label540 (setf exsm (/ 1.0d0 l)) (setf rhsm (/ 1.0d0 (+ (* 1.2d0 (expt dsm exsm)) 1.2d-6))) (setf rhdn 0.0d0) (if (= nq 1) (go label560)) (setf ddn (/ (dvnorm n (f2cl-lib:array-slice yh-%data% double-float (1 l) ((1 nyh) (1 *)) yh-%offset%) ewt) (f2cl-lib:fref tesco (1 nq) ((1 3) (1 12))))) (setf exdn (/ 1.0d0 nq)) (setf rhdn (/ 1.0d0 (+ (* 1.3d0 (expt ddn exdn)) 1.3d-6))) label560 (if (>= rhsm rhup) (go label570)) (if (> rhup rhdn) (go label590)) (go label580) label570 (if (< rhsm rhdn) (go label580)) (setf newq nq) (setf rh rhsm) (go label620) label580 (setf newq (f2cl-lib:int-sub nq 1)) (setf rh rhdn) (if (and (< kflag 0) (> rh 1.0d0)) (setf rh 1.0d0)) (go label620) label590 (setf newq l) (setf rh rhup) (if (< rh 1.1d0) (go label610)) (setf r (/ (f2cl-lib:fref el (l) ((1 13))) l)) (f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1)) ((> i n) nil) (tagbody label600 (setf (f2cl-lib:fref yh-%data% (i (f2cl-lib:int-add newq 1)) ((1 nyh) (1 *)) yh-%offset%) (* (f2cl-lib:fref acor-%data% (i) ((1 *)) acor-%offset%) r)))) (go label630) label610 (setf ialth 3) (go label700) label620 (if (and (= kflag 0) (< rh 1.1d0)) (go label610)) (if (<= kflag -2) (setf rh (min rh 0.2d0))) (if (= newq nq) (go label170)) label630 (setf nq newq) (setf l (f2cl-lib:int-add nq 1)) (setf iret 2) (go label150) label640 (if (= kflag -10) (go label660)) (setf rh 0.1d0) (setf rh (max (/ hmin (abs h)) rh)) (setf h (* h rh)) (f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1)) ((> i n) nil) (tagbody label645 (setf (f2cl-lib:fref y-%data% (i) ((1 *)) y-%offset%) (f2cl-lib:fref yh-%data% (i 1) ((1 nyh) (1 *)) yh-%offset%)))) (multiple-value-bind (var-0 var-1 var-2 var-3) (funcall f neq tn y savf) (declare (ignore var-0 var-2 var-3)) (when var-1 (setf tn var-1))) (setf nfe (f2cl-lib:int-add nfe 1)) (f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1)) ((> i n) nil) (tagbody label650 (setf (f2cl-lib:fref yh-%data% (i 2) ((1 nyh) (1 *)) yh-%offset%) (* h (f2cl-lib:fref savf-%data% (i) ((1 *)) savf-%offset%))))) (setf ipup miter) (setf ialth 5) (if (= nq 1) (go label200)) (setf nq 1) (setf l 2) (setf iret 3) (go label150) label660 (setf kflag -1) (go label720) label670 (setf kflag -2) (go label720) label680 (setf kflag -3) (go label720) label690 (setf rmax 10.0d0) label700 (setf r (/ 1.0d0 (f2cl-lib:fref tesco (2 nqu) ((1 3) (1 12))))) (f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1)) ((> i n) nil) (tagbody label710 (setf (f2cl-lib:fref acor-%data% (i) ((1 *)) acor-%offset%) (* (f2cl-lib:fref acor-%data% (i) ((1 *)) acor-%offset%) r)))) label720 (setf hold h) (setf jstart 1) (go end_label) end_label (return (values nil nil nil nil nil nil nil nil nil nil nil nil nil nil))))))) (in-package #-gcl #:cl-user #+gcl "CL-USER") #+#.(cl:if (cl:find-package '#:f2cl) '(and) '(or)) (eval-when (:load-toplevel :compile-toplevel :execute) (setf (gethash 'fortran-to-lisp::dstoka fortran-to-lisp::*f2cl-function-info*) (fortran-to-lisp::make-f2cl-finfo :arg-types '((array fortran-to-lisp::integer4 (*)) (array double-float (*)) (array double-float (*)) (fortran-to-lisp::integer4) (array double-float (*)) (array double-float (*)) (array double-float (*)) (array double-float (*)) (array double-float (*)) (array double-float (*)) (array fortran-to-lisp::integer4 (*)) t t t) :return-values '(nil nil nil nil nil nil nil nil nil nil nil nil nil nil) :calls '(fortran-to-lisp::dsolpk fortran-to-lisp::dsetpk fortran-to-lisp::dvnorm fortran-to-lisp::dcfode))))
d022cbc9c68856efd2994b44077e5e6acf121fef3dede4426dafa455dfe1d941
ndmitchell/catch
Req.hs
module Req(module Req, module Val) where import Val import Yhc.Core import General import Data.Proposition -- DATA DEFINITIONS type Scopes = [Scope] data Scope = Scope CoreFuncName Vals type Reqs = PropSimple Req data Req = Req {reqExpr :: CoreExpr, reqVals :: Vals} | Demonic | Angelic deriving (Ord, Eq) type ReqCall = (CoreFuncName, Vals) ReqCall ( name , vals ) = Req ( CoreApp ( CoreFun name ) [ " ? " ] ) vals instance Show Scope where show (Scope name reqs) = "(\\forall " ++ name ++ ", " ++ show reqs ++ ")" instance Show Req where show (Req expr x) = showCoreExprGroup expr ++ show x show Demonic = "?Demonic" show Angelic = "?Angelic" instance PropLit Req where -- do not define anything, its a pretty bad PropLit! precondition : all the Req 's must be the same collapse :: Core -> Reqs -> Vals collapse core reqs | any (head lits /=) lits = error "Collapse, precondition violated" | otherwise = propFold fold reqs where fold = PropFold {foldOr = valsOrs core, foldAnd = valsAnds core ,foldNot = error "collapse.foldNot", foldLit = reqVals} lits = map reqExpr $ propAll reqs
null
https://raw.githubusercontent.com/ndmitchell/catch/5d834416a27b4df3f7ce7830c4757d4505aaf96e/inspect/Req.hs
haskell
DATA DEFINITIONS do not define anything, its a pretty bad PropLit!
module Req(module Req, module Val) where import Val import Yhc.Core import General import Data.Proposition type Scopes = [Scope] data Scope = Scope CoreFuncName Vals type Reqs = PropSimple Req data Req = Req {reqExpr :: CoreExpr, reqVals :: Vals} | Demonic | Angelic deriving (Ord, Eq) type ReqCall = (CoreFuncName, Vals) ReqCall ( name , vals ) = Req ( CoreApp ( CoreFun name ) [ " ? " ] ) vals instance Show Scope where show (Scope name reqs) = "(\\forall " ++ name ++ ", " ++ show reqs ++ ")" instance Show Req where show (Req expr x) = showCoreExprGroup expr ++ show x show Demonic = "?Demonic" show Angelic = "?Angelic" instance PropLit Req where precondition : all the Req 's must be the same collapse :: Core -> Reqs -> Vals collapse core reqs | any (head lits /=) lits = error "Collapse, precondition violated" | otherwise = propFold fold reqs where fold = PropFold {foldOr = valsOrs core, foldAnd = valsAnds core ,foldNot = error "collapse.foldNot", foldLit = reqVals} lits = map reqExpr $ propAll reqs
016194e118eb65ecbd75e489714d32f6bad1a75d8ce068aa84493a6845bde2bf
serokell/ariadne
Tx.hs
-- | Part of the backend which deals with transactions. module Ariadne.Wallet.Backend.Tx ( sendTx ) where import Prelude hiding (list) import qualified Data.Text.Buildable import Control.Exception (Exception(displayException)) import Control.Lens (at, ix) import Control.Natural ((:~>)(..)) import Formatting (bprint, build, formatToString, (%)) import Text.PrettyPrint.ANSI.Leijen (Doc, list, softline, string) import Pos.Client.Txp.Network (prepareMTx, submitTxRaw) import Pos.Core.Txp (Tx(..), TxAux(..), TxOutAux(..)) import Pos.Crypto (EncryptedSecretKey, PassPhrase, SafeSigner(..), checkPassMatches, hash) import Pos.Crypto.HD (ShouldCheckPassphrase(..)) import Pos.Infra.Diffusion.Types (Diffusion) import Pos.Launcher (HasConfigurations) import Pos.Util (maybeThrow) import Ariadne.Cardano.Face import Ariadne.Cardano.Knit (showCoin) import Ariadne.Wallet.Backend.Mode () import Ariadne.Wallet.Backend.Util (accountsToUse) import Ariadne.Wallet.Cardano.Kernel.Bip32 (DerivationPath(..), deriveHDSecretKeyByPath) import Ariadne.Wallet.Cardano.Kernel.Bip44 import Ariadne.Wallet.Cardano.Kernel.DB.AcidState import Ariadne.Wallet.Cardano.Kernel.DB.HdWallet import Ariadne.Wallet.Cardano.Kernel.DB.HdWallet.Read import Ariadne.Wallet.Cardano.Kernel.DB.InDb import Ariadne.Wallet.Cardano.Kernel.DB.Util.IxSet (IxSet) import Ariadne.Wallet.Cardano.WalletLayer (ActiveWalletLayer(..), PassiveWalletLayer(..)) import Ariadne.Wallet.Face data SendTxException = SendTxNoAddresses !HdRootId | SendTxNoAccounts !HdRootId | SendTxIncorrectPassPhrase | SendTxNotConfirmed deriving (Show) instance Buildable SendTxException where build = \case SendTxNoAccounts walletIdx -> bprint ("Wallet "%build%" does not have any accounts") walletIdx SendTxNoAddresses walletIdx -> bprint ("Wallet "%build%" does not have any addresses") walletIdx SendTxIncorrectPassPhrase -> "Incorrect passphrase" SendTxNotConfirmed -> "Not confirmed by User" instance Exception SendTxException where toException e = case e of SendTxIncorrectPassPhrase -> walletPassExceptionToException e _ -> SomeException e fromException = walletPassExceptionFromException displayException = toString . prettyL -- | Send a transaction from selected to wallet to the list of ' TxOut 's . If list of accounts is not empty , only those accounts -- may be used as inputs. If this list is empty and an account from -- the input wallet is selected, this account will be used as input. -- Otherwise inputs will be selected from all accounts in the wallet. sendTx :: HasConfigurations => ActiveWalletLayer IO -> WalletFace -> CardanoFace -> IORef (Maybe WalletSelection) -> (Doc -> IO ()) -> (WalletReference -> IO PassPhrase) -> (WalletReference -> IO TxId -> IO TxId) -> (ConfirmationType -> IO Bool) -> Bool -> WalletReference -> [LocalAccountReference] -> InputSelectionPolicy -> NonEmpty TxOut -> IO TxId sendTx awl WalletFace {..} CardanoFace {..} walletSelRef printAction getPassPhrase voidWrongPass waitUiConfirm noConfirm walletRef accRefs isp outs = do let NT runCardanoMode = cardanoRunCardanoMode walletDb <- pwlGetDBSnapshot pwl let wallets = walletDb ^. dbHdWallets (walletRootId, accountsToUse') <- accountsToUse pwl walletSelRef walletRef accRefs unless noConfirm $ unlessM (waitUiConfirm . ConfirmSend . map txOutToInfo $ toList outs) $ throwM SendTxNotConfirmed pp <- getPassPhrase $ WalletRefByHdRootId walletRootId voidWrongPass walletRef . runCardanoMode $ sendTxDo wallets walletRootId pp accountsToUse' =<< cardanoGetDiffusion where pwl :: PassiveWalletLayer IO pwl = walletPassiveLayer awl sendTxDo :: HdWallets -> HdRootId -> PassPhrase -> IxSet HdAccount -> Diffusion CardanoMode -> CardanoMode TxId sendTxDo wallets walletRootId pp accountsToUse' diffusion = do -- Wallet creation and deletion is organized in such way that -- the absence of a key is not possible. esk <- liftIO $ fromMaybe (error "Bug: Keystore has no such key.") <$> pwlLookupKeystore pwl walletRootId maybeThrow SendTxIncorrectPassPhrase $ checkPassMatches pp esk let signersMap :: HashMap Address SafeSigner -- safe due to passphrase check above signersMap = walletSigners esk wallets pp accountsToUse' let getSigner :: Address -> Maybe SafeSigner getSigner addr = signersMap ^. at addr ourAddresses <- maybeThrow (SendTxNoAddresses walletRootId) (nonEmpty $ keys signersMap) changeAccountId <- changeAccountIdFromAccounts let newChangeAddress = walletNewAddress (AccountRefByHdAccountId changeAccountId) HdChainInternal (txAux, _) <- prepareMTx cardanoProtocolMagic getSigner mempty isp ourAddresses (map TxOutAux outs) (const newChangeAddress) [ AD-518 ] TODO : call even when inputs are selected from multiple accounts . when (length accountsToUse' == 1) $ liftIO $ whenLeftM (awlNewPending awl changeAccountId txAux) throwM let tx = taTx txAux let txId = hash tx liftIO $ printAction $ formatSubmitTxMsg tx txId <$ submitTxRaw diffusion txAux where | Used for sending tx with existing accountsToUse changeAccountIdFromAccounts :: MonadThrow m => m HdAccountId changeAccountIdFromAccounts = do We pick one of the accounts to generate change address in it . changeAccount <- maybeThrow (SendTxNoAccounts walletRootId) (toList accountsToUse' ^? ix 0) return $ changeAccount ^. hdAccountId formatToDoc :: forall a. Buildable a => a -> Doc formatToDoc = string . formatToString build formatSubmitTxMsg :: Tx -> Doc formatSubmitTxMsg UnsafeTx {..} = mconcat [ "Submitting Tx with inputs: " , list . toList $ map formatToDoc _txInputs , "," , softline , "outputs: " , list . toList $ map formatToDoc _txOutputs , "…" ] txOutToInfo :: TxOut -> ConfirmSendInfo txOutToInfo TxOut{..} = ConfirmSendInfo {..} where confirmSendAddress = show $ formatToDoc txOutAddress (confirmSendAmount, outCoin) = showCoin $ txOutValue confirmSendCoin = show outCoin -- Assumes the passphrase is correct! walletSigners :: EncryptedSecretKey -> HdWallets -> PassPhrase -> IxSet HdAccount -> HashMap Address SafeSigner walletSigners rootSK wallets pp = foldMap accountSigners where -- See the contract of this function shouldNotCheck = ShouldCheckPassphrase False invalidPassphrase :: a invalidPassphrase = error "walletSigners: passphrase is invalid and why was it checked at all??!!?" deriveAccountKey :: HdAccountIx -> EncryptedSecretKey deriveAccountKey accIdx = let derPath = DerivationPath $ encodeBip44DerivationPathToAccount accIdx in case deriveHDSecretKeyByPath shouldNotCheck pp rootSK derPath of Nothing -> invalidPassphrase Just key -> key deriveAddressKey :: EncryptedSecretKey -> HdAddressChain -> HdAddressIx -> EncryptedSecretKey deriveAddressKey accKey addrChain addrIx = let derPath = DerivationPath $ encodeBip44DerivationPathFromAccount addrChain addrIx in case deriveHDSecretKeyByPath shouldNotCheck pp accKey derPath of Nothing -> invalidPassphrase Just key -> key accountSigners :: HdAccount -> HashMap Address SafeSigner accountSigners hdAcc = let accId = hdAcc ^. hdAccountId accIx = accId ^. hdAccountIdIx accountKey :: EncryptedSecretKey accountKey = deriveAccountKey accIx toAddrTuple :: HdAddress -> (HdAddressChain, HdAddressIx, Address) toAddrTuple hdAddr = let addrId = hdAddr ^. hdAddressId addrChain = addrId ^. hdAddressIdChain addrIx = addrId ^. hdAddressIdIx in ( addrChain , addrIx , _fromDb (hdAddr ^. hdAddressAddress) ) accountAddresses :: [(HdAddressChain, HdAddressIx, Address)] accountAddresses = map toAddrTuple $ toList addressesSet addressesSet :: IxSet HdAddress addressesSet = fromRight (error "Bug: Unknown accountId") (readAddressesByAccountId accId wallets) step :: HashMap Address SafeSigner -> (HdAddressChain, HdAddressIx, Address) -> HashMap Address SafeSigner step m (addrChain, addrIx, addr) = m & at addr .~ Just (SafeSigner (deriveAddressKey accountKey addrChain addrIx) pp) in foldl' step mempty accountAddresses
null
https://raw.githubusercontent.com/serokell/ariadne/5f49ee53b6bbaf332cb6f110c75f7b971acdd452/ariadne/cardano/src/Ariadne/Wallet/Backend/Tx.hs
haskell
| Part of the backend which deals with transactions. | Send a transaction from selected to wallet to the list of may be used as inputs. If this list is empty and an account from the input wallet is selected, this account will be used as input. Otherwise inputs will be selected from all accounts in the wallet. Wallet creation and deletion is organized in such way that the absence of a key is not possible. safe due to passphrase check above Assumes the passphrase is correct! See the contract of this function
module Ariadne.Wallet.Backend.Tx ( sendTx ) where import Prelude hiding (list) import qualified Data.Text.Buildable import Control.Exception (Exception(displayException)) import Control.Lens (at, ix) import Control.Natural ((:~>)(..)) import Formatting (bprint, build, formatToString, (%)) import Text.PrettyPrint.ANSI.Leijen (Doc, list, softline, string) import Pos.Client.Txp.Network (prepareMTx, submitTxRaw) import Pos.Core.Txp (Tx(..), TxAux(..), TxOutAux(..)) import Pos.Crypto (EncryptedSecretKey, PassPhrase, SafeSigner(..), checkPassMatches, hash) import Pos.Crypto.HD (ShouldCheckPassphrase(..)) import Pos.Infra.Diffusion.Types (Diffusion) import Pos.Launcher (HasConfigurations) import Pos.Util (maybeThrow) import Ariadne.Cardano.Face import Ariadne.Cardano.Knit (showCoin) import Ariadne.Wallet.Backend.Mode () import Ariadne.Wallet.Backend.Util (accountsToUse) import Ariadne.Wallet.Cardano.Kernel.Bip32 (DerivationPath(..), deriveHDSecretKeyByPath) import Ariadne.Wallet.Cardano.Kernel.Bip44 import Ariadne.Wallet.Cardano.Kernel.DB.AcidState import Ariadne.Wallet.Cardano.Kernel.DB.HdWallet import Ariadne.Wallet.Cardano.Kernel.DB.HdWallet.Read import Ariadne.Wallet.Cardano.Kernel.DB.InDb import Ariadne.Wallet.Cardano.Kernel.DB.Util.IxSet (IxSet) import Ariadne.Wallet.Cardano.WalletLayer (ActiveWalletLayer(..), PassiveWalletLayer(..)) import Ariadne.Wallet.Face data SendTxException = SendTxNoAddresses !HdRootId | SendTxNoAccounts !HdRootId | SendTxIncorrectPassPhrase | SendTxNotConfirmed deriving (Show) instance Buildable SendTxException where build = \case SendTxNoAccounts walletIdx -> bprint ("Wallet "%build%" does not have any accounts") walletIdx SendTxNoAddresses walletIdx -> bprint ("Wallet "%build%" does not have any addresses") walletIdx SendTxIncorrectPassPhrase -> "Incorrect passphrase" SendTxNotConfirmed -> "Not confirmed by User" instance Exception SendTxException where toException e = case e of SendTxIncorrectPassPhrase -> walletPassExceptionToException e _ -> SomeException e fromException = walletPassExceptionFromException displayException = toString . prettyL ' TxOut 's . If list of accounts is not empty , only those accounts sendTx :: HasConfigurations => ActiveWalletLayer IO -> WalletFace -> CardanoFace -> IORef (Maybe WalletSelection) -> (Doc -> IO ()) -> (WalletReference -> IO PassPhrase) -> (WalletReference -> IO TxId -> IO TxId) -> (ConfirmationType -> IO Bool) -> Bool -> WalletReference -> [LocalAccountReference] -> InputSelectionPolicy -> NonEmpty TxOut -> IO TxId sendTx awl WalletFace {..} CardanoFace {..} walletSelRef printAction getPassPhrase voidWrongPass waitUiConfirm noConfirm walletRef accRefs isp outs = do let NT runCardanoMode = cardanoRunCardanoMode walletDb <- pwlGetDBSnapshot pwl let wallets = walletDb ^. dbHdWallets (walletRootId, accountsToUse') <- accountsToUse pwl walletSelRef walletRef accRefs unless noConfirm $ unlessM (waitUiConfirm . ConfirmSend . map txOutToInfo $ toList outs) $ throwM SendTxNotConfirmed pp <- getPassPhrase $ WalletRefByHdRootId walletRootId voidWrongPass walletRef . runCardanoMode $ sendTxDo wallets walletRootId pp accountsToUse' =<< cardanoGetDiffusion where pwl :: PassiveWalletLayer IO pwl = walletPassiveLayer awl sendTxDo :: HdWallets -> HdRootId -> PassPhrase -> IxSet HdAccount -> Diffusion CardanoMode -> CardanoMode TxId sendTxDo wallets walletRootId pp accountsToUse' diffusion = do esk <- liftIO $ fromMaybe (error "Bug: Keystore has no such key.") <$> pwlLookupKeystore pwl walletRootId maybeThrow SendTxIncorrectPassPhrase $ checkPassMatches pp esk let signersMap :: HashMap Address SafeSigner signersMap = walletSigners esk wallets pp accountsToUse' let getSigner :: Address -> Maybe SafeSigner getSigner addr = signersMap ^. at addr ourAddresses <- maybeThrow (SendTxNoAddresses walletRootId) (nonEmpty $ keys signersMap) changeAccountId <- changeAccountIdFromAccounts let newChangeAddress = walletNewAddress (AccountRefByHdAccountId changeAccountId) HdChainInternal (txAux, _) <- prepareMTx cardanoProtocolMagic getSigner mempty isp ourAddresses (map TxOutAux outs) (const newChangeAddress) [ AD-518 ] TODO : call even when inputs are selected from multiple accounts . when (length accountsToUse' == 1) $ liftIO $ whenLeftM (awlNewPending awl changeAccountId txAux) throwM let tx = taTx txAux let txId = hash tx liftIO $ printAction $ formatSubmitTxMsg tx txId <$ submitTxRaw diffusion txAux where | Used for sending tx with existing accountsToUse changeAccountIdFromAccounts :: MonadThrow m => m HdAccountId changeAccountIdFromAccounts = do We pick one of the accounts to generate change address in it . changeAccount <- maybeThrow (SendTxNoAccounts walletRootId) (toList accountsToUse' ^? ix 0) return $ changeAccount ^. hdAccountId formatToDoc :: forall a. Buildable a => a -> Doc formatToDoc = string . formatToString build formatSubmitTxMsg :: Tx -> Doc formatSubmitTxMsg UnsafeTx {..} = mconcat [ "Submitting Tx with inputs: " , list . toList $ map formatToDoc _txInputs , "," , softline , "outputs: " , list . toList $ map formatToDoc _txOutputs , "…" ] txOutToInfo :: TxOut -> ConfirmSendInfo txOutToInfo TxOut{..} = ConfirmSendInfo {..} where confirmSendAddress = show $ formatToDoc txOutAddress (confirmSendAmount, outCoin) = showCoin $ txOutValue confirmSendCoin = show outCoin walletSigners :: EncryptedSecretKey -> HdWallets -> PassPhrase -> IxSet HdAccount -> HashMap Address SafeSigner walletSigners rootSK wallets pp = foldMap accountSigners where shouldNotCheck = ShouldCheckPassphrase False invalidPassphrase :: a invalidPassphrase = error "walletSigners: passphrase is invalid and why was it checked at all??!!?" deriveAccountKey :: HdAccountIx -> EncryptedSecretKey deriveAccountKey accIdx = let derPath = DerivationPath $ encodeBip44DerivationPathToAccount accIdx in case deriveHDSecretKeyByPath shouldNotCheck pp rootSK derPath of Nothing -> invalidPassphrase Just key -> key deriveAddressKey :: EncryptedSecretKey -> HdAddressChain -> HdAddressIx -> EncryptedSecretKey deriveAddressKey accKey addrChain addrIx = let derPath = DerivationPath $ encodeBip44DerivationPathFromAccount addrChain addrIx in case deriveHDSecretKeyByPath shouldNotCheck pp accKey derPath of Nothing -> invalidPassphrase Just key -> key accountSigners :: HdAccount -> HashMap Address SafeSigner accountSigners hdAcc = let accId = hdAcc ^. hdAccountId accIx = accId ^. hdAccountIdIx accountKey :: EncryptedSecretKey accountKey = deriveAccountKey accIx toAddrTuple :: HdAddress -> (HdAddressChain, HdAddressIx, Address) toAddrTuple hdAddr = let addrId = hdAddr ^. hdAddressId addrChain = addrId ^. hdAddressIdChain addrIx = addrId ^. hdAddressIdIx in ( addrChain , addrIx , _fromDb (hdAddr ^. hdAddressAddress) ) accountAddresses :: [(HdAddressChain, HdAddressIx, Address)] accountAddresses = map toAddrTuple $ toList addressesSet addressesSet :: IxSet HdAddress addressesSet = fromRight (error "Bug: Unknown accountId") (readAddressesByAccountId accId wallets) step :: HashMap Address SafeSigner -> (HdAddressChain, HdAddressIx, Address) -> HashMap Address SafeSigner step m (addrChain, addrIx, addr) = m & at addr .~ Just (SafeSigner (deriveAddressKey accountKey addrChain addrIx) pp) in foldl' step mempty accountAddresses
ebfafa71779861077bdd7f8aef897588d5cd4160f7800205823f0171d67ff4d6
zenspider/schemers
exercise.2.18.scm
#lang racket/base Exercise 2.18 : ;; Define a procedure `reverse' that takes a list as argument and ;; returns a list of the same elements in reverse order: ;; ;; (reverse (list 1 4 9 16 25)) ;; (25 16 9 4 1) (require "../lib/test.rkt") (define (reverse l) (define (iterate l r) (if (null? l) r (iterate (cdr l) (cons (car l) r)))) (iterate l null)) (assert-equal '(3 2 1) (reverse '(1 2 3))) (done)
null
https://raw.githubusercontent.com/zenspider/schemers/2939ca553ac79013a4c3aaaec812c1bad3933b16/sicp/ch_2/exercise.2.18.scm
scheme
Define a procedure `reverse' that takes a list as argument and returns a list of the same elements in reverse order: (reverse (list 1 4 9 16 25)) (25 16 9 4 1)
#lang racket/base Exercise 2.18 : (require "../lib/test.rkt") (define (reverse l) (define (iterate l r) (if (null? l) r (iterate (cdr l) (cons (car l) r)))) (iterate l null)) (assert-equal '(3 2 1) (reverse '(1 2 3))) (done)
8eca30ff42e9938d7ac6a98f3cfae949afdeaea5ae25c2d6dad7a5d7a5eb7054
altsun/My-Lisps
od_oc_oca.lsp
;;;********************************************** CHUONG TRINH DANH SO THU TU VA COPY TANG DAN 1 . Lenh OD : , so bat ( begin ) va so ( increment ) tuy y 2 . Lenh OC : copy so co san 3 . Lenh OCA : copy chap dinh dang bang so , , so : 1 , 2 ... A , B ... , A1 , A2 ... , AB-01 , ... , AB-01 - C1 , AB-01 - C2 ... gioi A den Z. Cac so Copyright by ssg - www.cadviet.com - December 2008 ;;;********************************************** ;;;------------------------------------------------- (defun etype (e) ;;;Entity Type (cdr (assoc 0 (entget e))) ) ;;;------------------------------------------------- (defun wtxt (txt p / sty d h) ;;;Write txt on graphic screen, defaul setting (setq sty (getvar "textstyle") d (tblsearch "style" sty) h (cdr (assoc 40 d)) ) (if (= h 0) (setq h (cdr (assoc 42 d)))) (entmake (list (cons 0 "TEXT") (cons 7 sty) (cons 1 txt) (cons 10 p) (cons 40 h) (assoc 41 d)) ) ) ;;;------------------------------------------------- (defun incN (n dn / n2 i n1) ;;;Increase number n (setq n2 (itoa (+ dn (atoi n))) i (- (strlen n) (strlen n2)) ) (if (> i 0) (setq n1 (substr n 1 i)) (setq n1 "")) (strcat n1 n2) ) ;;;------------------------------------------------- (defun incC (c / i c1 c2) ;;;Increase character c (setq i (strlen c) c1 (substr c 1 (- i 1)) c2 (chr (1+ (ascii (substr c i 1)))) ) (if (or (= c2 "{") (= c2 "[")) (progn (command "erase" (entlast) "") (alert "Over character!") (exit)) (strcat c1 c2) ) ) ;;;============================ (defun C:OD( / cn dn c n p) ;;;Make OrDinal number with any format (setq cn (getstring "\nBegin at <1>: " T) dn (getint "\nIncrement <1>: ") ) (if (not dn) (setq dn 1)) (if (= cn "") (setq cn "1")) (setq c (vl-string-right-trim "0 1 2 3 4 5 6 7 8 9" cn)) (setq n (vl-string-subst "" c cn)) (if (/= n "") (setq mode 1) (setq mode 0)) (while (setq p (getpoint "\nBase point : ")) (wtxt cn p) (if (= n "") (setq cn (incC cn)) (setq cn (strcat c (incN (vl-string-subst "" c cn) dn))) ) ) (princ) ) ;;;============================ (defun C:OC( / e dn p1 cn c n p2 dat) ;;;Make Ordinal number. Copy from template (setq e (car (entsel "\nSelect template text:")) dn (getint "\nIncrement <1>: ") p1 (getpoint "\nBase point:") cn (cdr (assoc 1 (entget e))) ) (if (not dn) (setq dn 1)) (if (= cn "") (setq cn "1")) (setq c (vl-string-right-trim "0 1 2 3 4 5 6 7 8 9" cn) n (vl-string-subst "" c cn) ) (while (setq p2 (getpoint p1 "\nNew point : ")) (command "copy" e "" p1 p2) (if (= n "") (setq cn (incC cn)) (setq cn (strcat c (incN (vl-string-subst "" c cn) dn))) ) (setq dat (entget (entlast)) dat (subst (cons 1 cn) (assoc 1 dat) dat) ) (entmod dat) ) (princ) ) ;;;============================ (defun C:OCA( / e e0 dn p1 cn c n p2 dat) ;;;Make Ordinal number. Copy from Atttribute block (setq e0 (car (entsel "\nSelect attribute block:")) e (entnext e0) ) (if (/= (etype e) "ATTRIB") (progn (alert "Object is not a Attribute Block!") (exit))) (setq dn (getint "\nIncrement <1>: ") p1 (getpoint "\nBase point:") cn (cdr (assoc 1 (entget e))) ) (if (not dn) (setq dn 1)) (if (= cn "") (setq cn "1")) (setq c (vl-string-right-trim "0 1 2 3 4 5 6 7 8 9" cn) n (vl-string-subst "" c cn) ) (while (setq p2 (getpoint p1 "\nNew point : ")) (command "copy" e0 "" p1 p2) (if (= n "") (setq cn (incC cn)) (setq cn (strcat c (incN (vl-string-subst "" c cn) dn))) ) (setq dat (entget (entnext (entlast))) dat (subst (cons 1 cn) (assoc 1 dat) dat) ) (entmod dat) (command "regen") ) (princ) ) ;;;============================
null
https://raw.githubusercontent.com/altsun/My-Lisps/85476bb09b79ef5e966402cc5158978d1cebd7eb/Common/od_oc_oca.lsp
lisp
********************************************** ********************************************** ------------------------------------------------- Entity Type ------------------------------------------------- Write txt on graphic screen, defaul setting ------------------------------------------------- Increase number n ------------------------------------------------- Increase character c ============================ Make OrDinal number with any format ============================ Make Ordinal number. Copy from template ============================ Make Ordinal number. Copy from Atttribute block ============================
CHUONG TRINH DANH SO THU TU VA COPY TANG DAN 1 . Lenh OD : , so bat ( begin ) va so ( increment ) tuy y 2 . Lenh OC : copy so co san 3 . Lenh OCA : copy chap dinh dang bang so , , so : 1 , 2 ... A , B ... , A1 , A2 ... , AB-01 , ... , AB-01 - C1 , AB-01 - C2 ... gioi A den Z. Cac so Copyright by ssg - www.cadviet.com - December 2008 (cdr (assoc 0 (entget e))) ) (setq sty (getvar "textstyle") d (tblsearch "style" sty) h (cdr (assoc 40 d)) ) (if (= h 0) (setq h (cdr (assoc 42 d)))) (entmake (list (cons 0 "TEXT") (cons 7 sty) (cons 1 txt) (cons 10 p) (cons 40 h) (assoc 41 d)) ) ) (setq n2 (itoa (+ dn (atoi n))) i (- (strlen n) (strlen n2)) ) (if (> i 0) (setq n1 (substr n 1 i)) (setq n1 "")) (strcat n1 n2) ) (setq i (strlen c) c1 (substr c 1 (- i 1)) c2 (chr (1+ (ascii (substr c i 1)))) ) (if (or (= c2 "{") (= c2 "[")) (progn (command "erase" (entlast) "") (alert "Over character!") (exit)) (strcat c1 c2) ) ) (setq cn (getstring "\nBegin at <1>: " T) dn (getint "\nIncrement <1>: ") ) (if (not dn) (setq dn 1)) (if (= cn "") (setq cn "1")) (setq c (vl-string-right-trim "0 1 2 3 4 5 6 7 8 9" cn)) (setq n (vl-string-subst "" c cn)) (if (/= n "") (setq mode 1) (setq mode 0)) (while (setq p (getpoint "\nBase point : ")) (wtxt cn p) (if (= n "") (setq cn (incC cn)) (setq cn (strcat c (incN (vl-string-subst "" c cn) dn))) ) ) (princ) ) (setq e (car (entsel "\nSelect template text:")) dn (getint "\nIncrement <1>: ") p1 (getpoint "\nBase point:") cn (cdr (assoc 1 (entget e))) ) (if (not dn) (setq dn 1)) (if (= cn "") (setq cn "1")) (setq c (vl-string-right-trim "0 1 2 3 4 5 6 7 8 9" cn) n (vl-string-subst "" c cn) ) (while (setq p2 (getpoint p1 "\nNew point : ")) (command "copy" e "" p1 p2) (if (= n "") (setq cn (incC cn)) (setq cn (strcat c (incN (vl-string-subst "" c cn) dn))) ) (setq dat (entget (entlast)) dat (subst (cons 1 cn) (assoc 1 dat) dat) ) (entmod dat) ) (princ) ) (setq e0 (car (entsel "\nSelect attribute block:")) e (entnext e0) ) (if (/= (etype e) "ATTRIB") (progn (alert "Object is not a Attribute Block!") (exit))) (setq dn (getint "\nIncrement <1>: ") p1 (getpoint "\nBase point:") cn (cdr (assoc 1 (entget e))) ) (if (not dn) (setq dn 1)) (if (= cn "") (setq cn "1")) (setq c (vl-string-right-trim "0 1 2 3 4 5 6 7 8 9" cn) n (vl-string-subst "" c cn) ) (while (setq p2 (getpoint p1 "\nNew point : ")) (command "copy" e0 "" p1 p2) (if (= n "") (setq cn (incC cn)) (setq cn (strcat c (incN (vl-string-subst "" c cn) dn))) ) (setq dat (entget (entnext (entlast))) dat (subst (cons 1 cn) (assoc 1 dat) dat) ) (entmod dat) (command "regen") ) (princ) )
c77fd821309bec3626eb58553f940751124f52405d5fcae2930f04f4a6fc3fd2
dreyk/zraft_lib
zraft_lib_sup.erl
%% ------------------------------------------------------------------- @author < > Copyright ( c ) 2015 . All Rights Reserved . %% This file is provided to you under the Apache License , %% Version 2.0 (the "License"); you may not use this file except in compliance with the License . You may obtain %% a copy of the License at %% %% -2.0 %% %% Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY %% KIND, either express or implied. See the License for the %% specific language governing permissions and limitations %% under the License. %% %% ------------------------------------------------------------------- -module(zraft_lib_sup). -author("dreyk"). -behaviour(supervisor). -export([start_link/0]). -export([init/1,start_consensus/2,start_consensus/1]). -include("zraft.hrl"). -spec(start_link() -> {ok, Pid :: pid()} | ignore | {error, Reason :: term()}). start_link() -> supervisor:start_link({local, ?MODULE}, ?MODULE, []). -spec(init(Args :: term()) -> {ok, {SupFlags :: {RestartStrategy :: supervisor:strategy(), MaxR :: non_neg_integer(), MaxT :: non_neg_integer()}, [ChildSpec :: supervisor:child_spec()] }}). init([]) -> Timeout = max(1,round(zraft_consensus:get_election_timeout()*4/1000)), SupFlags = {one_for_one,2,Timeout}, Peers = read_peers(), {ok, {SupFlags, Peers}}. -spec start_consensus(zraft_consensus:peer_id(),module()) -> supervisor:startchild_ret(). start_consensus(PeerID,BackEnd)-> Spec = consensus_spec([PeerID,BackEnd]), start_result(supervisor:start_child(?MODULE, Spec)). -spec start_consensus(zraft_consensus:peer_id()) -> supervisor:startchild_ret(). start_consensus(PeerID)-> Spec = consensus_spec([PeerID]), start_result(supervisor:start_child(?MODULE, Spec)). start_result({ok,P})-> {ok,P}; start_result({error,{already_started,_}})-> {error,already_created}; start_result({error,already_present})-> {error,already_created}; start_result(Err)-> Err. @private consensus_spec([{PeerName,_}|_]=Args) -> { PeerName, {zraft_consensus, start_link,Args}, permanent, 5000, worker, [zraft_consensus] }. %%@private read_peers()-> DataDir = zraft_util:get_env(log_dir, "data"), case file:list_dir(DataDir) of {ok,Dirs}-> read_peers(DataDir,Dirs,[]); _-> [] end. read_peers(DataDir,[Dir|T],Acc)-> RaftDir = filename:join(DataDir,Dir), case zraft_fs_log:load_raft_meta(RaftDir) of {ok,#raft_meta{id = Peer,back_end = BackEnd}}-> Spec = consensus_spec([Peer,BackEnd]), read_peers(DataDir,T,[Spec|Acc]); _-> lager:warning("~p does't contain peer meta",[RaftDir]), read_peers(DataDir,T,Acc) end; read_peers(_DataDir,[],Acc)-> Acc.
null
https://raw.githubusercontent.com/dreyk/zraft_lib/ead65c45df576be3758639e3fe3a46edefdeae1d/src/zraft_lib_sup.erl
erlang
------------------------------------------------------------------- Version 2.0 (the "License"); you may not use this file a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ------------------------------------------------------------------- @private
@author < > Copyright ( c ) 2015 . All Rights Reserved . This file is provided to you under the Apache License , except in compliance with the License . You may obtain software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY -module(zraft_lib_sup). -author("dreyk"). -behaviour(supervisor). -export([start_link/0]). -export([init/1,start_consensus/2,start_consensus/1]). -include("zraft.hrl"). -spec(start_link() -> {ok, Pid :: pid()} | ignore | {error, Reason :: term()}). start_link() -> supervisor:start_link({local, ?MODULE}, ?MODULE, []). -spec(init(Args :: term()) -> {ok, {SupFlags :: {RestartStrategy :: supervisor:strategy(), MaxR :: non_neg_integer(), MaxT :: non_neg_integer()}, [ChildSpec :: supervisor:child_spec()] }}). init([]) -> Timeout = max(1,round(zraft_consensus:get_election_timeout()*4/1000)), SupFlags = {one_for_one,2,Timeout}, Peers = read_peers(), {ok, {SupFlags, Peers}}. -spec start_consensus(zraft_consensus:peer_id(),module()) -> supervisor:startchild_ret(). start_consensus(PeerID,BackEnd)-> Spec = consensus_spec([PeerID,BackEnd]), start_result(supervisor:start_child(?MODULE, Spec)). -spec start_consensus(zraft_consensus:peer_id()) -> supervisor:startchild_ret(). start_consensus(PeerID)-> Spec = consensus_spec([PeerID]), start_result(supervisor:start_child(?MODULE, Spec)). start_result({ok,P})-> {ok,P}; start_result({error,{already_started,_}})-> {error,already_created}; start_result({error,already_present})-> {error,already_created}; start_result(Err)-> Err. @private consensus_spec([{PeerName,_}|_]=Args) -> { PeerName, {zraft_consensus, start_link,Args}, permanent, 5000, worker, [zraft_consensus] }. read_peers()-> DataDir = zraft_util:get_env(log_dir, "data"), case file:list_dir(DataDir) of {ok,Dirs}-> read_peers(DataDir,Dirs,[]); _-> [] end. read_peers(DataDir,[Dir|T],Acc)-> RaftDir = filename:join(DataDir,Dir), case zraft_fs_log:load_raft_meta(RaftDir) of {ok,#raft_meta{id = Peer,back_end = BackEnd}}-> Spec = consensus_spec([Peer,BackEnd]), read_peers(DataDir,T,[Spec|Acc]); _-> lager:warning("~p does't contain peer meta",[RaftDir]), read_peers(DataDir,T,Acc) end; read_peers(_DataDir,[],Acc)-> Acc.
06ac85ecd93fd56c4466918a7b6eff3ec516236055ec47d6dab8dfabce956e50
haskell/happy
ParseMonad.hs
module Happy.Frontend.ParseMonad (module X) where -- We use the bootstrapped version if it is available #ifdef HAPPY_BOOTSTRAP import Happy.Frontend.ParseMonad.Bootstrapped as X #else import Happy.Frontend.ParseMonad.Oracle as X #endif
null
https://raw.githubusercontent.com/haskell/happy/934763408f8df29180c63d7a2c69be0b84030967/packages/frontend/src/Happy/Frontend/ParseMonad.hs
haskell
We use the bootstrapped version if it is available
module Happy.Frontend.ParseMonad (module X) where #ifdef HAPPY_BOOTSTRAP import Happy.Frontend.ParseMonad.Bootstrapped as X #else import Happy.Frontend.ParseMonad.Oracle as X #endif
abdf7b3ea84a441d8e20a30dcd23405d30e1f90647b61fd922eada316e593f29
potatosalad/erlang-jose
jose_json_jason.erl
-*- mode : erlang ; tab - width : 4 ; indent - tabs - mode : 1 ; st - rulers : [ 70 ] -*- %% vim: ts=4 sw=4 ft=erlang noet -module(jose_json_jason). -behaviour(jose_json). %% jose_json callbacks -export([decode/1]). -export([encode/1]). %%==================================================================== %% jose_json callbacks %%==================================================================== decode(Binary) -> 'Elixir.Jason':'decode!'(Binary). encode(Term) -> 'Elixir.Jason':'encode!'(Term). %%%------------------------------------------------------------------- Internal functions %%%-------------------------------------------------------------------
null
https://raw.githubusercontent.com/potatosalad/erlang-jose/43d3db467f909bbc932bd663ddcb1af93180dfd3/src/json/jose_json_jason.erl
erlang
vim: ts=4 sw=4 ft=erlang noet jose_json callbacks ==================================================================== jose_json callbacks ==================================================================== ------------------------------------------------------------------- -------------------------------------------------------------------
-*- mode : erlang ; tab - width : 4 ; indent - tabs - mode : 1 ; st - rulers : [ 70 ] -*- -module(jose_json_jason). -behaviour(jose_json). -export([decode/1]). -export([encode/1]). decode(Binary) -> 'Elixir.Jason':'decode!'(Binary). encode(Term) -> 'Elixir.Jason':'encode!'(Term). Internal functions
f68873a65ea50f8871cd22b8f342968329bd9a6122f4a2ea0e5a127d3a717a3b
valerauko/gitegylet-electron
menu.cljs
(ns gitegylet.menu) (defonce remote (.-remote (js/require "electron"))) (defn build [template] (.buildFromTemplate (.-Menu remote) (clj->js template)))
null
https://raw.githubusercontent.com/valerauko/gitegylet-electron/bee01d4e70f3f1e8636bf82c0d1a78c3d640c1b7/src/cljs/gitegylet/menu.cljs
clojure
(ns gitegylet.menu) (defonce remote (.-remote (js/require "electron"))) (defn build [template] (.buildFromTemplate (.-Menu remote) (clj->js template)))
d1dfd3799ae6a7bab4f483e19214751d9c258d1e3b188508634f54880ba7c8bd
nextjournal/ssh-auth-github
ssh-auth-github.clj
#! /usr/bin/env bb (require '[babashka.curl :as curl]) (require '[cheshire.core :as json]) (require '[clojure.tools.cli :as tools.cli]) (require '[clojure.string :as str]) (require '[babashka.fs :as fs]) (defn print-usage [summary] (println (->> ["Usage: " "ssh-auth-github.clj [options]" "" "Options:" summary] (str/join \newline)))) (defn read-config [] (let [{:keys [options _arguments errors summary] :as _cli-options} (tools.cli/parse-opts *command-line-args* [["-h" "--help"] ["-t" "--token TOKEN" "Github token"] ["-o" "--organization ORGANIZATION" "Github organization"] ["-e" "--team TEAM" "Github team"] ["-c" "--config PATH" "Path to configuration file" :default "config.edn"]])] (when (:help options) (print-usage summary) (System/exit 1)) (when errors (println errors) (print-usage summary) (System/exit 1)) (cond-> {} (fs/exists? (:config options)) (merge (read-string (slurp (:config options)))) true (merge (dissoc options :config))))) (defn query [organization team] (format "{organization(login: \"%s\") { team(slug: \"%s\") { members { nodes { login publicKeys(first: 100) { nodes { key } } } } } } }" organization team)) (defn retrieve-keys [config] (let [resp (curl/post "" {:body (json/generate-string {"query" (query (:organization config) (:team config))}) :throw false :headers {"Authorization" (format "bearer %s" (:token config))}}) body (-> resp (:body) (json/parse-string true))] (cond (not= 200 (:status resp)) (do (clojure.pprint/pprint body) (System/exit 1)) (:errors body) (do (clojure.pprint/pprint (:errors body)) (System/exit 1)) :else body))) (defn parse-response [data] (when-not (seq (get-in data [:data :organization :team])) (println "Error: Team is empty!") (System/exit 1)) (->> (get-in data [:data :organization :team :members :nodes]) (mapcat (fn [n] (map #(str (:key %) " " (:login n)) (get-in n [:publicKeys :nodes])))))) (doseq [l (->> (read-config) (retrieve-keys) (parse-response))] (println l))
null
https://raw.githubusercontent.com/nextjournal/ssh-auth-github/bf20e56eeea1cddeeefa71b5195c121d84f34c42/ssh-auth-github.clj
clojure
#! /usr/bin/env bb (require '[babashka.curl :as curl]) (require '[cheshire.core :as json]) (require '[clojure.tools.cli :as tools.cli]) (require '[clojure.string :as str]) (require '[babashka.fs :as fs]) (defn print-usage [summary] (println (->> ["Usage: " "ssh-auth-github.clj [options]" "" "Options:" summary] (str/join \newline)))) (defn read-config [] (let [{:keys [options _arguments errors summary] :as _cli-options} (tools.cli/parse-opts *command-line-args* [["-h" "--help"] ["-t" "--token TOKEN" "Github token"] ["-o" "--organization ORGANIZATION" "Github organization"] ["-e" "--team TEAM" "Github team"] ["-c" "--config PATH" "Path to configuration file" :default "config.edn"]])] (when (:help options) (print-usage summary) (System/exit 1)) (when errors (println errors) (print-usage summary) (System/exit 1)) (cond-> {} (fs/exists? (:config options)) (merge (read-string (slurp (:config options)))) true (merge (dissoc options :config))))) (defn query [organization team] (format "{organization(login: \"%s\") { team(slug: \"%s\") { members { nodes { login publicKeys(first: 100) { nodes { key } } } } } } }" organization team)) (defn retrieve-keys [config] (let [resp (curl/post "" {:body (json/generate-string {"query" (query (:organization config) (:team config))}) :throw false :headers {"Authorization" (format "bearer %s" (:token config))}}) body (-> resp (:body) (json/parse-string true))] (cond (not= 200 (:status resp)) (do (clojure.pprint/pprint body) (System/exit 1)) (:errors body) (do (clojure.pprint/pprint (:errors body)) (System/exit 1)) :else body))) (defn parse-response [data] (when-not (seq (get-in data [:data :organization :team])) (println "Error: Team is empty!") (System/exit 1)) (->> (get-in data [:data :organization :team :members :nodes]) (mapcat (fn [n] (map #(str (:key %) " " (:login n)) (get-in n [:publicKeys :nodes])))))) (doseq [l (->> (read-config) (retrieve-keys) (parse-response))] (println l))
31b4f6c496b20a9aa247435be769c3290fffd8c5ac2a4adfd73f294e556d4050
peruukki/nhl-score-api
core_test.clj
(ns nhl-score-api.core-test (:require [clojure.test :refer :all] [nhl-score-api.core :refer :all] [nhl-score-api.cache :refer [get-cached-fn]] [clojure.data.json :as json])) (def latest-scores-fetched (atom false)) (def scores-in-date-range-fetched (atom false)) (def latest-scores {:teams {} :scores {} :goals []}) (def scores-in-date-range [{:teams {} :scores {} :goals []}]) (declare assert-status assert-json-content-type assert-cors-enabled assert-browser-caching-disabled assert-body) (declare latest-scores-api-fn) (declare scores-in-date-range-api-fn) (deftest api-routing (testing "Root path returns project version" (let [version (System/getProperty "nhl-score-api.version") response (app {:uri "/"})] (is (not (nil? version)) "Project version number is valid") (assert-status response 200) (assert-json-content-type response) (assert-cors-enabled response) (assert-body response {:version version} "Response contains version number"))) (testing "Unknown path returns 404 Not Found" (let [response (app {:uri "/this-path-does-not-exist"})] (assert-status response 404) (assert-json-content-type response) (assert-body response {} "Response contains empty body")))) (deftest latest-scores-route (testing "Returns success response" (let [path "/api/scores/latest" response (get-response path {} latest-scores-api-fn scores-in-date-range-api-fn)] (is (= 200 (:status response)) "Response status is 200")))) (deftest scores-in-date-range-route (testing "Returns success response with :start-date parameter" (let [path "/api/scores" response (get-response path {:start-date "2021-10-03"} latest-scores-api-fn scores-in-date-range-api-fn)] (is (= 200 (:status response)) "Response status is 200"))) (testing "Returns success response with :start-date and :end-date parameters" (let [path "/api/scores" response (get-response path {:start-date "2021-10-03" :end-date "2021-10-04"} latest-scores-api-fn scores-in-date-range-api-fn)] (is (= 200 (:status response)) "Response status is 200"))) (testing "Returns failure response without parameters" (let [path "/api/scores" response (get-response path {} latest-scores-api-fn scores-in-date-range-api-fn)] (is (= 400 (:status response)) "Response status is 400") (is (= {:errors ["Missing required parameter startDate"]} (:body response)) "Response body contains errors"))) (testing "Returns failure response with invalid date range parameters" (let [path "/api/scores" response (get-response path {:start-date "2021-10-01" :end-date "2021-10-17"} latest-scores-api-fn scores-in-date-range-api-fn)] (is (= 400 (:status response)) "Response status is 400") (is (= {:errors ["Date range exceeds maximum limit of 16 days"]} (:body response)) "Response body contains errors")))) (deftest json-key-transforming (testing "Response JSON keyword key is transformed to camel case" (is (= "goalCount" (json-key-transformer :goal-count)) "JSON key is in camel case")) (testing "Response JSON string key is not transformed" (is (= "goal-count" (json-key-transformer "goal-count")) "Key is not transformed"))) (deftest browser-caching (testing "Browser caching is disabled by response headers") (let [response (app {:uri "/"})] (assert-browser-caching-disabled response))) (defn- assert-status [response expected-status] (is (= expected-status (:status response)) (str "Status code is " expected-status))) (defn- assert-json-content-type [response] (is (= "application/json; charset=utf-8" (get (:headers response) "Content-Type")) "Content type is JSON")) (defn- assert-cors-enabled [response] (is (= "*" (get (:headers response) "Access-Control-Allow-Origin")) "Access-Control-Allow-Origin allows all sites") (is (= "Content-Type" (get (:headers response) "Access-Control-Allow-Headers")) "Access-Control-Allow-Headers allows Content-Type header")) (defn- assert-browser-caching-disabled [response] (is (= "0" (get (:headers response) "Expires")) "Expires header disables browser caching")) (defn- assert-body [response expected-body message] (is (= (json/write-str expected-body) (:body response)) message)) (defn- latest-scores-api-fn [] (reset! latest-scores-fetched true) latest-scores) (defn- scores-in-date-range-api-fn [start-date end-date] (reset! scores-in-date-range-fetched true) scores-in-date-range)
null
https://raw.githubusercontent.com/peruukki/nhl-score-api/3564975b35091c044f975cb6563fcac48ede12cc/test/nhl_score_api/core_test.clj
clojure
(ns nhl-score-api.core-test (:require [clojure.test :refer :all] [nhl-score-api.core :refer :all] [nhl-score-api.cache :refer [get-cached-fn]] [clojure.data.json :as json])) (def latest-scores-fetched (atom false)) (def scores-in-date-range-fetched (atom false)) (def latest-scores {:teams {} :scores {} :goals []}) (def scores-in-date-range [{:teams {} :scores {} :goals []}]) (declare assert-status assert-json-content-type assert-cors-enabled assert-browser-caching-disabled assert-body) (declare latest-scores-api-fn) (declare scores-in-date-range-api-fn) (deftest api-routing (testing "Root path returns project version" (let [version (System/getProperty "nhl-score-api.version") response (app {:uri "/"})] (is (not (nil? version)) "Project version number is valid") (assert-status response 200) (assert-json-content-type response) (assert-cors-enabled response) (assert-body response {:version version} "Response contains version number"))) (testing "Unknown path returns 404 Not Found" (let [response (app {:uri "/this-path-does-not-exist"})] (assert-status response 404) (assert-json-content-type response) (assert-body response {} "Response contains empty body")))) (deftest latest-scores-route (testing "Returns success response" (let [path "/api/scores/latest" response (get-response path {} latest-scores-api-fn scores-in-date-range-api-fn)] (is (= 200 (:status response)) "Response status is 200")))) (deftest scores-in-date-range-route (testing "Returns success response with :start-date parameter" (let [path "/api/scores" response (get-response path {:start-date "2021-10-03"} latest-scores-api-fn scores-in-date-range-api-fn)] (is (= 200 (:status response)) "Response status is 200"))) (testing "Returns success response with :start-date and :end-date parameters" (let [path "/api/scores" response (get-response path {:start-date "2021-10-03" :end-date "2021-10-04"} latest-scores-api-fn scores-in-date-range-api-fn)] (is (= 200 (:status response)) "Response status is 200"))) (testing "Returns failure response without parameters" (let [path "/api/scores" response (get-response path {} latest-scores-api-fn scores-in-date-range-api-fn)] (is (= 400 (:status response)) "Response status is 400") (is (= {:errors ["Missing required parameter startDate"]} (:body response)) "Response body contains errors"))) (testing "Returns failure response with invalid date range parameters" (let [path "/api/scores" response (get-response path {:start-date "2021-10-01" :end-date "2021-10-17"} latest-scores-api-fn scores-in-date-range-api-fn)] (is (= 400 (:status response)) "Response status is 400") (is (= {:errors ["Date range exceeds maximum limit of 16 days"]} (:body response)) "Response body contains errors")))) (deftest json-key-transforming (testing "Response JSON keyword key is transformed to camel case" (is (= "goalCount" (json-key-transformer :goal-count)) "JSON key is in camel case")) (testing "Response JSON string key is not transformed" (is (= "goal-count" (json-key-transformer "goal-count")) "Key is not transformed"))) (deftest browser-caching (testing "Browser caching is disabled by response headers") (let [response (app {:uri "/"})] (assert-browser-caching-disabled response))) (defn- assert-status [response expected-status] (is (= expected-status (:status response)) (str "Status code is " expected-status))) (defn- assert-json-content-type [response] (is (= "application/json; charset=utf-8" (get (:headers response) "Content-Type")) "Content type is JSON")) (defn- assert-cors-enabled [response] (is (= "*" (get (:headers response) "Access-Control-Allow-Origin")) "Access-Control-Allow-Origin allows all sites") (is (= "Content-Type" (get (:headers response) "Access-Control-Allow-Headers")) "Access-Control-Allow-Headers allows Content-Type header")) (defn- assert-browser-caching-disabled [response] (is (= "0" (get (:headers response) "Expires")) "Expires header disables browser caching")) (defn- assert-body [response expected-body message] (is (= (json/write-str expected-body) (:body response)) message)) (defn- latest-scores-api-fn [] (reset! latest-scores-fetched true) latest-scores) (defn- scores-in-date-range-api-fn [start-date end-date] (reset! scores-in-date-range-fetched true) scores-in-date-range)
35942705962a8eae8dd580999226f1fae6fe822d4bb17cd0ef869de5b8936504
pfdietz/ansi-test
upgraded-complex-part-type.lsp
;-*- Mode: Lisp -*- Author : Created : Sat Nov 27 21:15:46 2004 ;;;; Contains: Tests of UPGRADE-COMPLEX-PART-TYPE (defmacro def-ucpt-test (name types) `(deftest ,name (loop for type in (remove-duplicates ,types) for upgraded-type = (upgraded-complex-part-type type) for result = (append (check-all-subtypep type upgraded-type) (check-all-subtypep type 'real) (check-all-subtypep `(complex ,type) 'complex) (check-all-subtypep `(complex ,upgraded-type) 'complex) (check-all-subtypep `(complex ,type) `(complex ,upgraded-type))) when result collect result) nil)) (def-ucpt-test upgraded-complex-part-type.1 '(real integer rational ratio float short-float single-float double-float long-float fixnum bignum bit unsigned-byte signed-byte)) (def-ucpt-test upgraded-complex-part-type.2 (mapcar #'find-class '(real float integer rational ratio))) (def-ucpt-test upgraded-complex-part-type.3 (mapcar #'class-of '(1.0s0 1.0f0 1.0d0 1.0l0))) (def-ucpt-test upgraded-complex-part-type.4 (loop for i from 1 to 100 collect `(unsigned-byte ,i))) (def-ucpt-test upgraded-complex-part-type.5 (loop for i from 1 to 100 collect `(signed-byte ,i))) (def-ucpt-test upgraded-complex-part-type.6 (loop for i = 1 then (* i 2) repeat 100 collect (class-of i))) ;;; environment argument (deftest upgraded-complex-part-type.7 (loop for type in '(real integer rational float short-float single-float double-float long-float fixnum bignum bit unsigned-byte signed-byte) for ut1 = (upgraded-complex-part-type type) for ut2 = (upgraded-complex-part-type type nil) unless (equal ut1 ut2) collect (list type ut1 ut2)) nil) (deftest upgraded-complex-part-type.8 (loop for type in '(real integer rational float short-float single-float double-float long-float fixnum bignum bit unsigned-byte signed-byte) for ut1 = (upgraded-complex-part-type type) for ut2 = (eval `(macrolet ((%m (&environment env) (list 'quote (upgraded-complex-part-type ',type env)))) (%m))) unless (equal ut1 ut2) collect (list type ut1 ut2)) nil) Subtype constraint (deftest upgraded-complex-part-type.9 (let* ((types `(nil integer fixnum bignum float short-float single-float double-float long-float rational #-sbcl ratio real ,@(remove-duplicates (mapcar #'class-of '(0.0s0 0.0f0 0.0d0 0.0l0 0 100000000000000000))) ,@(mapcar #'(lambda (x) `(eql ,x)) (remove-duplicates '(0.0s0 0.0f0 0.0d0 0.0l0 0 1.0s0 1.0f0 1.0d0 1.0l0 1 100000000000000000))))) (utypes (mapcar #'upgraded-complex-part-type types))) (loop for sublist on types for usublist on utypes for tp1 = (car sublist) for utp1 = (car usublist) nconc (loop for tp2 in (cdr sublist) for utp2 in (cdr usublist) nconc (and (subtypep tp1 tp2) (let ((result (check-all-subtypep utp1 utp2))) (and result (list (list tp1 tp2 result)))))))) nil) ;;; Error tests (deftest upgraded-complex-part-type.error.1 (signals-error (upgraded-complex-part-type) program-error) t) (deftest upgraded-complex-part-type.error.2 (signals-error (upgraded-complex-part-type 'real nil nil) program-error) t)
null
https://raw.githubusercontent.com/pfdietz/ansi-test/3f4b9d31c3408114f0467eaeca4fd13b28e2ce31/numbers/upgraded-complex-part-type.lsp
lisp
-*- Mode: Lisp -*- Contains: Tests of UPGRADE-COMPLEX-PART-TYPE environment argument Error tests
Author : Created : Sat Nov 27 21:15:46 2004 (defmacro def-ucpt-test (name types) `(deftest ,name (loop for type in (remove-duplicates ,types) for upgraded-type = (upgraded-complex-part-type type) for result = (append (check-all-subtypep type upgraded-type) (check-all-subtypep type 'real) (check-all-subtypep `(complex ,type) 'complex) (check-all-subtypep `(complex ,upgraded-type) 'complex) (check-all-subtypep `(complex ,type) `(complex ,upgraded-type))) when result collect result) nil)) (def-ucpt-test upgraded-complex-part-type.1 '(real integer rational ratio float short-float single-float double-float long-float fixnum bignum bit unsigned-byte signed-byte)) (def-ucpt-test upgraded-complex-part-type.2 (mapcar #'find-class '(real float integer rational ratio))) (def-ucpt-test upgraded-complex-part-type.3 (mapcar #'class-of '(1.0s0 1.0f0 1.0d0 1.0l0))) (def-ucpt-test upgraded-complex-part-type.4 (loop for i from 1 to 100 collect `(unsigned-byte ,i))) (def-ucpt-test upgraded-complex-part-type.5 (loop for i from 1 to 100 collect `(signed-byte ,i))) (def-ucpt-test upgraded-complex-part-type.6 (loop for i = 1 then (* i 2) repeat 100 collect (class-of i))) (deftest upgraded-complex-part-type.7 (loop for type in '(real integer rational float short-float single-float double-float long-float fixnum bignum bit unsigned-byte signed-byte) for ut1 = (upgraded-complex-part-type type) for ut2 = (upgraded-complex-part-type type nil) unless (equal ut1 ut2) collect (list type ut1 ut2)) nil) (deftest upgraded-complex-part-type.8 (loop for type in '(real integer rational float short-float single-float double-float long-float fixnum bignum bit unsigned-byte signed-byte) for ut1 = (upgraded-complex-part-type type) for ut2 = (eval `(macrolet ((%m (&environment env) (list 'quote (upgraded-complex-part-type ',type env)))) (%m))) unless (equal ut1 ut2) collect (list type ut1 ut2)) nil) Subtype constraint (deftest upgraded-complex-part-type.9 (let* ((types `(nil integer fixnum bignum float short-float single-float double-float long-float rational #-sbcl ratio real ,@(remove-duplicates (mapcar #'class-of '(0.0s0 0.0f0 0.0d0 0.0l0 0 100000000000000000))) ,@(mapcar #'(lambda (x) `(eql ,x)) (remove-duplicates '(0.0s0 0.0f0 0.0d0 0.0l0 0 1.0s0 1.0f0 1.0d0 1.0l0 1 100000000000000000))))) (utypes (mapcar #'upgraded-complex-part-type types))) (loop for sublist on types for usublist on utypes for tp1 = (car sublist) for utp1 = (car usublist) nconc (loop for tp2 in (cdr sublist) for utp2 in (cdr usublist) nconc (and (subtypep tp1 tp2) (let ((result (check-all-subtypep utp1 utp2))) (and result (list (list tp1 tp2 result)))))))) nil) (deftest upgraded-complex-part-type.error.1 (signals-error (upgraded-complex-part-type) program-error) t) (deftest upgraded-complex-part-type.error.2 (signals-error (upgraded-complex-part-type 'real nil nil) program-error) t)
18ac5d6bd1d2e7ac78fee36a8b2e31e77645937866df56a2bf162b9a930760d4
mirage/ocaml-openflow
lldp.ml
* Copyright ( c ) 2011 < > * * Permission to use , copy , modify , and distribute this software for any * purpose with or without fee is hereby granted , provided that the above * copyright notice and this permission notice appear in all copies . * * THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN * ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE . * Copyright (c) 2011 Charalampos Rotsos <> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. *) open Cstruct open Printf open Net open Net.Nettypes exception Unparsable of Cstruct.t cenum lldp_tlv_types { LLDP_TYPE_END = 0 ; LLDP_TYPE_CHASSIS_ID = 1 ; LLDP_TYPE_PORT_ID = 2 ; LLDP_TYPE_TTL = 3 ; LLDP_TYPE_PORT_DESCR = 4 ; LLDP_TYPE_SYSTEM_NAME = 5 ; = 6 ; LLDP_TYPE_SYSTEM_CAP = 7 ; LLDP_TYPE_MGMT_ADDR = 8 } as uint8_t cenum lldp_chassis_id_subtype { LLDP_CHASSIS_CHASSIS_COMP_SUBTYPE = 1 ; LLDP_CHASSIS_INTF_ALIAS_SUBTYPE = 2 ; LLDP_CHASSIS_PORT_COMP_SUBTYPE = 3 ; LLDP_CHASSIS_MAC_ADDR_SUBTYPE = 4 ; LLDP_CHASSIS_NETWORK_ADDR_SUBTYPE = 5 ; LLDP_CHASSIS_INTF_NAME_SUBTYPE = 6 ; LLDP_CHASSIS_LOCAL_SUBTYPE = 8 } as uint8_t cenum lldp_port_id_subtype { LLDP_PORT_INTF_ALIAS_SUBTYPE = 1 ; LLDP_PORT_PORT_COMP_SUBTYPE = 2 ; LLDP_PORT_MAC_ADDR_SUBTYPE = 3 ; LLDP_PORT_NETWORK_ADDR_SUBTYPE = 4 ; LLDP_PORT_INTF_NAME_SUBTYPE = 5 ; LLDP_PORT_AGENT_CIRC_ID_SUBTYPE = 6 ; LLDP_PORT_LOCAL_SUBTYPE = 7 } as uint8_t LLDP_TYPE_END = 0; LLDP_TYPE_CHASSIS_ID = 1; LLDP_TYPE_PORT_ID = 2; LLDP_TYPE_TTL = 3; LLDP_TYPE_PORT_DESCR = 4; LLDP_TYPE_SYSTEM_NAME = 5; LLDP_TYPE_SYSTEM_DESCR = 6; LLDP_TYPE_SYSTEM_CAP = 7; LLDP_TYPE_MGMT_ADDR = 8 } as uint8_t cenum lldp_chassis_id_subtype { LLDP_CHASSIS_CHASSIS_COMP_SUBTYPE = 1; LLDP_CHASSIS_INTF_ALIAS_SUBTYPE = 2; LLDP_CHASSIS_PORT_COMP_SUBTYPE = 3; LLDP_CHASSIS_MAC_ADDR_SUBTYPE = 4; LLDP_CHASSIS_NETWORK_ADDR_SUBTYPE = 5; LLDP_CHASSIS_INTF_NAME_SUBTYPE = 6; LLDP_CHASSIS_LOCAL_SUBTYPE = 8 } as uint8_t cenum lldp_port_id_subtype { LLDP_PORT_INTF_ALIAS_SUBTYPE = 1; LLDP_PORT_PORT_COMP_SUBTYPE = 2; LLDP_PORT_MAC_ADDR_SUBTYPE = 3; LLDP_PORT_NETWORK_ADDR_SUBTYPE = 4; LLDP_PORT_INTF_NAME_SUBTYPE = 5; LLDP_PORT_AGENT_CIRC_ID_SUBTYPE = 6; LLDP_PORT_LOCAL_SUBTYPE = 7 } as uint8_t*) cstruct ethernet { uint8_t dst[6]; uint8_t src[6]; uint16_t ethertype } as big_endian type lldp_tlv_types = LLDP_TYPE_END | LLDP_TYPE_CHASSIS_ID | LLDP_TYPE_PORT_ID | LLDP_TYPE_TTL | LLDP_TYPE_PORT_DESCR | LLDP_TYPE_SYSTEM_NAME | LLDP_TYPE_SYSTEM_DESCR | LLDP_TYPE_SYSTEM_CAP | LLDP_TYPE_MGMT_ADDR let lldp_tlv_types_of_int = function | 0 -> Some LLDP_TYPE_END | 1 -> Some LLDP_TYPE_CHASSIS_ID | 2 -> Some LLDP_TYPE_PORT_ID | 3 -> Some LLDP_TYPE_TTL | 4 -> Some LLDP_TYPE_PORT_DESCR | 5 -> Some LLDP_TYPE_SYSTEM_NAME | 6 -> Some LLDP_TYPE_SYSTEM_DESCR | 7 -> Some LLDP_TYPE_SYSTEM_CAP | 8 -> Some LLDP_TYPE_MGMT_ADDR | _ -> None let lldp_tlv_types_to_int = function | LLDP_TYPE_END -> 0 | LLDP_TYPE_CHASSIS_ID -> 1 | LLDP_TYPE_PORT_ID -> 2 | LLDP_TYPE_TTL -> 3 | LLDP_TYPE_PORT_DESCR -> 4 | LLDP_TYPE_SYSTEM_NAME -> 5 | LLDP_TYPE_SYSTEM_DESCR -> 6 | LLDP_TYPE_SYSTEM_CAP -> 7 | LLDP_TYPE_MGMT_ADDR -> 8 let lldp_tlv_types_to_string = function | LLDP_TYPE_END -> "LLDP_TYPE_END" | LLDP_TYPE_CHASSIS_ID -> "LLDP_TYPE_CHASSIS_ID" | LLDP_TYPE_PORT_ID -> "LLDP_TYPE_PORT_ID" | LLDP_TYPE_TTL -> "LLDP_TYPE_TTL" | LLDP_TYPE_PORT_DESCR -> "LLDP_TYPE_PORT_DESCR" | LLDP_TYPE_SYSTEM_NAME -> "LLDP_TYPE_SYSTEM_NAME" | LLDP_TYPE_SYSTEM_DESCR -> "LLDP_TYPE_SYSTEM_DESCR" | LLDP_TYPE_SYSTEM_CAP -> "LLDP_TYPE_SYSTEM_CAP" | LLDP_TYPE_MGMT_ADDR -> "LLDP_TYPE_MGMT_ADDR" type lldp_chassis_id_subtype = LLDP_CHASSIS_CHASSIS_COMP_SUBTYPE | LLDP_CHASSIS_INTF_ALIAS_SUBTYPE | LLDP_CHASSIS_PORT_COMP_SUBTYPE | LLDP_CHASSIS_MAC_ADDR_SUBTYPE | LLDP_CHASSIS_NETWORK_ADDR_SUBTYPE | LLDP_CHASSIS_INTF_NAME_SUBTYPE | LLDP_CHASSIS_LOCAL_SUBTYPE let lldp_chassis_id_subtype_of_int = function | 1 -> Some LLDP_CHASSIS_CHASSIS_COMP_SUBTYPE | 2 -> Some LLDP_CHASSIS_INTF_ALIAS_SUBTYPE | 3 -> Some LLDP_CHASSIS_PORT_COMP_SUBTYPE | 4 -> Some LLDP_CHASSIS_MAC_ADDR_SUBTYPE | 5 -> Some LLDP_CHASSIS_NETWORK_ADDR_SUBTYPE | 6 -> Some LLDP_CHASSIS_INTF_NAME_SUBTYPE | 8 -> Some LLDP_CHASSIS_LOCAL_SUBTYPE | _ -> None let lldp_chassis_id_subtype_to_int = function | LLDP_CHASSIS_CHASSIS_COMP_SUBTYPE -> 1 | LLDP_CHASSIS_INTF_ALIAS_SUBTYPE -> 2 | LLDP_CHASSIS_PORT_COMP_SUBTYPE -> 3 | LLDP_CHASSIS_MAC_ADDR_SUBTYPE -> 4 | LLDP_CHASSIS_NETWORK_ADDR_SUBTYPE -> 5 | LLDP_CHASSIS_INTF_NAME_SUBTYPE -> 6 | LLDP_CHASSIS_LOCAL_SUBTYPE -> 8 let lldp_chassis_id_subtype_to_string = function | LLDP_CHASSIS_CHASSIS_COMP_SUBTYPE -> "LLDP_CHASSIS_CHASSIS_COMP_SUBTYPE" | LLDP_CHASSIS_INTF_ALIAS_SUBTYPE -> "LLDP_CHASSIS_INTF_ALIAS_SUBTYPE" | LLDP_CHASSIS_PORT_COMP_SUBTYPE -> "LLDP_CHASSIS_PORT_COMP_SUBTYPE" | LLDP_CHASSIS_MAC_ADDR_SUBTYPE -> "LLDP_CHASSIS_MAC_ADDR_SUBTYPE" | LLDP_CHASSIS_NETWORK_ADDR_SUBTYPE -> "LLDP_CHASSIS_NETWORK_ADDR_SUBTYPE" | LLDP_CHASSIS_INTF_NAME_SUBTYPE -> "LLDP_CHASSIS_INTF_NAME_SUBTYPE" | LLDP_CHASSIS_LOCAL_SUBTYPE -> "LLDP_CHASSIS_LOCAL_SUBTYPE" type lldp_port_id_subtype = LLDP_PORT_INTF_ALIAS_SUBTYPE | LLDP_PORT_PORT_COMP_SUBTYPE | LLDP_PORT_MAC_ADDR_SUBTYPE | LLDP_PORT_NETWORK_ADDR_SUBTYPE | LLDP_PORT_INTF_NAME_SUBTYPE | LLDP_PORT_AGENT_CIRC_ID_SUBTYPE | LLDP_PORT_LOCAL_SUBTYPE let lldp_port_id_subtype_of_int = function | 1 -> Some LLDP_PORT_INTF_ALIAS_SUBTYPE | 2 -> Some LLDP_PORT_PORT_COMP_SUBTYPE | 3 -> Some LLDP_PORT_MAC_ADDR_SUBTYPE | 4 -> Some LLDP_PORT_NETWORK_ADDR_SUBTYPE | 5 -> Some LLDP_PORT_INTF_NAME_SUBTYPE | 6 -> Some LLDP_PORT_AGENT_CIRC_ID_SUBTYPE | 7 -> Some LLDP_PORT_LOCAL_SUBTYPE | _ -> None let lldp_port_id_subtype_to_int = function | LLDP_PORT_INTF_ALIAS_SUBTYPE -> 1 | LLDP_PORT_PORT_COMP_SUBTYPE -> 2 | LLDP_PORT_MAC_ADDR_SUBTYPE -> 3 | LLDP_PORT_NETWORK_ADDR_SUBTYPE -> 4 | LLDP_PORT_INTF_NAME_SUBTYPE -> 5 | LLDP_PORT_AGENT_CIRC_ID_SUBTYPE -> 6 | LLDP_PORT_LOCAL_SUBTYPE -> 7 let lldp_port_id_subtype_to_string = function | LLDP_PORT_INTF_ALIAS_SUBTYPE -> "LLDP_PORT_INTF_ALIAS_SUBTYPE" | LLDP_PORT_PORT_COMP_SUBTYPE -> "LLDP_PORT_PORT_COMP_SUBTYPE" | LLDP_PORT_MAC_ADDR_SUBTYPE -> "LLDP_PORT_MAC_ADDR_SUBTYPE" | LLDP_PORT_NETWORK_ADDR_SUBTYPE -> "LLDP_PORT_NETWORK_ADDR_SUBTYPE" | LLDP_PORT_INTF_NAME_SUBTYPE -> "LLDP_PORT_INTF_NAME_SUBTYPE" | LLDP_PORT_AGENT_CIRC_ID_SUBTYPE -> "LLDP_PORT_AGENT_CIRC_ID_SUBTYPE" | LLDP_PORT_LOCAL_SUBTYPE -> "LLDP_PORT_LOCAL_SUBTYPE" type lldp_tvl = | Tlv_chassis_id_chassis_comp of string | Tlv_chassis_id_intf_alias of string | Tlv_chassis_id_port_comp of string | Tlv_chassis_id_mac of Macaddr.t | Tlv_chassis_id_net of Ipaddr.V4.t | Tlv_chassis_id_intf_name of string | Tlv_chassis_id_local of string | Tlv_port_id_intf_alias of string | Tlv_port_id_port_comp of string | Tlv_port_id_mac of Macaddr.t | Tlv_port_id_net of Ipaddr.V4.t | Tlv_port_id_intf_name of string | Tlv_port_id_circ_id of string | Tlv_port_id_local of string | Tlv_ttl of int | Tlv_end | Tlv of lldp_tlv_types * string | Tlv_unk of int * string let parse_lldp_tlv bits = let tlv_type_len = Cstruct.BE.get_uint16 bits 0 in let tlv_type = tlv_type_len lsr 9 in let tlv_len = tlv_type_len land 0x01FF in let tlv = match (lldp_tlv_types_of_int tlv_type) with | Some(LLDP_TYPE_END) -> Tlv_end | Some(LLDP_TYPE_CHASSIS_ID) -> begin let data = Cstruct.to_string (Cstruct.sub bits 3 (tlv_len - 1)) in let chassis_id_subtype = Cstruct.get_uint8 bits 2 in match (lldp_chassis_id_subtype_of_int chassis_id_subtype) with | Some(LLDP_CHASSIS_CHASSIS_COMP_SUBTYPE)-> Tlv_chassis_id_chassis_comp(data) | Some(LLDP_CHASSIS_INTF_ALIAS_SUBTYPE) -> Tlv_chassis_id_intf_alias(data) | Some(LLDP_CHASSIS_PORT_COMP_SUBTYPE) -> Tlv_chassis_id_port_comp(data) | Some(LLDP_CHASSIS_MAC_ADDR_SUBTYPE) -> begin match (Macaddr.of_bytes data) with | None -> raise (Unparsable bits) | Some addr -> (Tlv_chassis_id_mac addr) end | Some(LLDP_CHASSIS_NETWORK_ADDR_SUBTYPE)-> let ip = Ipaddr.V4.of_int32 (Cstruct.BE.get_uint32 bits 3) in Tlv_chassis_id_net(ip) | Some(LLDP_CHASSIS_INTF_NAME_SUBTYPE) -> Tlv_chassis_id_intf_name(data) | Some(LLDP_CHASSIS_LOCAL_SUBTYPE) -> Tlv_chassis_id_local(data) | None -> raise (Unparsable(bits)) end | Some(LLDP_TYPE_PORT_ID) -> begin let data = Cstruct.to_string (Cstruct.sub bits 3 (tlv_len - 1)) in let port_id_subtype = Cstruct.get_uint8 bits 2 in match (lldp_port_id_subtype_of_int port_id_subtype) with | Some(LLDP_PORT_INTF_ALIAS_SUBTYPE) -> Tlv_port_id_intf_alias(data) | Some(LLDP_PORT_PORT_COMP_SUBTYPE) -> Tlv_port_id_port_comp(data) | Some(LLDP_PORT_MAC_ADDR_SUBTYPE) -> begin match (Macaddr.of_bytes data) with | None -> raise (Unparsable(bits)) | Some addr -> Tlv_port_id_mac(addr) end | Some(LLDP_PORT_NETWORK_ADDR_SUBTYPE) -> let ip = Ipaddr.V4.of_int32 (Cstruct.BE.get_uint32 bits 3) in Tlv_port_id_net(ip) | Some(LLDP_PORT_INTF_NAME_SUBTYPE) -> Tlv_port_id_intf_name(data) | Some(LLDP_PORT_AGENT_CIRC_ID_SUBTYPE)-> Tlv_port_id_circ_id(data) | Some(LLDP_PORT_LOCAL_SUBTYPE) -> Tlv_port_id_local(data) | None -> raise (Unparsable(bits)) end | Some(LLDP_TYPE_TTL) -> let ttl = Cstruct.BE.get_uint16 bits 3 in Tlv_ttl(ttl) | Some(typ) -> let data = Cstruct.to_string (Cstruct.sub bits 3 (tlv_len - 1)) in Tlv(typ, data) | None -> let data = Cstruct.to_string (Cstruct.sub bits 2 tlv_len) in Tlv_unk(tlv_type, data) in (tlv_len + 2, tlv) let parse_lldp_tlvs bits = (* Ignore ethernet headers for now *) let bits = Cstruct.shift bits sizeof_ethernet in let rec parse_lldp_tlvs_inner bits = match (Cstruct.len bits) with | 0 -> [] | _ -> let (len, tlv) = parse_lldp_tlv bits in if(tlv = Tlv_end) then [tlv] else let bits = Cstruct.shift bits len in [tlv] @ (parse_lldp_tlvs_inner bits) in parse_lldp_tlvs_inner bits let set_lldp_tlv_typ_subtyp_data bits typ subtyp data = let typ = typ lsl 9 in let len = ((String.length data) + 1) land 0x1ff in let typ_len = typ + len in let _ = Cstruct.BE.set_uint16 bits 0 typ_len in let _ = Cstruct.set_uint8 bits 2 subtyp in let _ = Cstruct.blit_from_string data 0 bits 3 (String.length data) in len + 2 let set_lldp_tlv_typ_data bits typ data = let typ = typ lsl 9 in let len = (String.length data) land 0x1ff in let typ_len = typ + len in let _ = Cstruct.BE.set_uint16 bits 0 typ_len in let _ = Cstruct.blit_from_string data 0 bits 2 (String.length data) in len + 2 let marsal_lldp_tlv tlv bits = match tlv with (* chassis id *) | Tlv_chassis_id_chassis_comp(data) -> set_lldp_tlv_typ_subtyp_data bits 1 1 data | Tlv_chassis_id_intf_alias(data) -> set_lldp_tlv_typ_subtyp_data bits 1 2 data | Tlv_chassis_id_port_comp(data) -> set_lldp_tlv_typ_subtyp_data bits 1 3 data | Tlv_chassis_id_mac(mac) -> set_lldp_tlv_typ_subtyp_data bits 1 4 (Macaddr.to_bytes mac) | Tlv_chassis_id_net(ip) -> let _ = Cstruct.BE.set_uint16 bits 0 0x205 in let _ = Cstruct.set_uint8 bits 2 5 in let _ = Cstruct.BE.set_uint32 bits 3 (Ipaddr.V4.to_int32 ip) in 7 | Tlv_chassis_id_intf_name(data) -> set_lldp_tlv_typ_subtyp_data bits 1 6 data | Tlv_chassis_id_local(data) -> set_lldp_tlv_typ_subtyp_data bits 1 8 data (* Port id *) | Tlv_port_id_intf_alias(data) -> set_lldp_tlv_typ_subtyp_data bits 2 1 data | Tlv_port_id_port_comp(data) -> set_lldp_tlv_typ_subtyp_data bits 2 2 data | Tlv_port_id_mac(mac) -> set_lldp_tlv_typ_subtyp_data bits 2 3 (Macaddr.to_bytes mac) | Tlv_port_id_net(ip) -> let _ = Cstruct.BE.set_uint16 bits 0 0x405 in let _ = Cstruct.set_uint8 bits 2 4 in let _ = Cstruct.BE.set_uint32 bits 3 (Ipaddr.V4.to_int32 ip) in 7 | Tlv_port_id_intf_name(data) -> set_lldp_tlv_typ_subtyp_data bits 2 5 data | Tlv_port_id_circ_id(data) -> set_lldp_tlv_typ_subtyp_data bits 2 6 data | Tlv_port_id_local(data) -> set_lldp_tlv_typ_subtyp_data bits 2 7 data | Tlv_ttl(ttl) -> let _ = Cstruct.BE.set_uint16 bits 0 0x602 in let _ = Cstruct.BE.set_uint16 bits 2 ttl in 4 | Tlv_end -> let _ = Cstruct.BE.set_uint16 bits 0 0x000 in 2 | Tlv(typ, data) -> set_lldp_tlv_typ_data bits (lldp_tlv_types_to_int typ) data | Tlv_unk (typ, data) -> set_lldp_tlv_typ_data bits typ data let marsal_lldp_tlvs mac tlvs bits = let _ = set_ethernet_dst "\x01\x80\xc2\x00\x00\x0e" 0 bits in let _ = set_ethernet_src (Macaddr.to_bytes mac) 0 bits in let _ = set_ethernet_ethertype bits 0x88cc in let bits = Cstruct.shift bits sizeof_ethernet in let rec marsal_lldp_tlvs_inner tlvs bits = match tlvs with | [] -> 0 | h::t -> let len = marsal_lldp_tlv h bits in let bits = Cstruct.shift bits len in let rest = marsal_lldp_tlvs_inner t bits in len + rest in sizeof_ethernet + marsal_lldp_tlvs_inner tlvs bits
null
https://raw.githubusercontent.com/mirage/ocaml-openflow/dcda113745e8edc61b5508eb8ac2d1e864e1a2df/lib/lldp.ml
ocaml
Ignore ethernet headers for now chassis id Port id
* Copyright ( c ) 2011 < > * * Permission to use , copy , modify , and distribute this software for any * purpose with or without fee is hereby granted , provided that the above * copyright notice and this permission notice appear in all copies . * * THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN * ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE . * Copyright (c) 2011 Charalampos Rotsos <> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. *) open Cstruct open Printf open Net open Net.Nettypes exception Unparsable of Cstruct.t cenum lldp_tlv_types { LLDP_TYPE_END = 0 ; LLDP_TYPE_CHASSIS_ID = 1 ; LLDP_TYPE_PORT_ID = 2 ; LLDP_TYPE_TTL = 3 ; LLDP_TYPE_PORT_DESCR = 4 ; LLDP_TYPE_SYSTEM_NAME = 5 ; = 6 ; LLDP_TYPE_SYSTEM_CAP = 7 ; LLDP_TYPE_MGMT_ADDR = 8 } as uint8_t cenum lldp_chassis_id_subtype { LLDP_CHASSIS_CHASSIS_COMP_SUBTYPE = 1 ; LLDP_CHASSIS_INTF_ALIAS_SUBTYPE = 2 ; LLDP_CHASSIS_PORT_COMP_SUBTYPE = 3 ; LLDP_CHASSIS_MAC_ADDR_SUBTYPE = 4 ; LLDP_CHASSIS_NETWORK_ADDR_SUBTYPE = 5 ; LLDP_CHASSIS_INTF_NAME_SUBTYPE = 6 ; LLDP_CHASSIS_LOCAL_SUBTYPE = 8 } as uint8_t cenum lldp_port_id_subtype { LLDP_PORT_INTF_ALIAS_SUBTYPE = 1 ; LLDP_PORT_PORT_COMP_SUBTYPE = 2 ; LLDP_PORT_MAC_ADDR_SUBTYPE = 3 ; LLDP_PORT_NETWORK_ADDR_SUBTYPE = 4 ; LLDP_PORT_INTF_NAME_SUBTYPE = 5 ; LLDP_PORT_AGENT_CIRC_ID_SUBTYPE = 6 ; LLDP_PORT_LOCAL_SUBTYPE = 7 } as uint8_t LLDP_TYPE_END = 0; LLDP_TYPE_CHASSIS_ID = 1; LLDP_TYPE_PORT_ID = 2; LLDP_TYPE_TTL = 3; LLDP_TYPE_PORT_DESCR = 4; LLDP_TYPE_SYSTEM_NAME = 5; LLDP_TYPE_SYSTEM_DESCR = 6; LLDP_TYPE_SYSTEM_CAP = 7; LLDP_TYPE_MGMT_ADDR = 8 } as uint8_t cenum lldp_chassis_id_subtype { LLDP_CHASSIS_CHASSIS_COMP_SUBTYPE = 1; LLDP_CHASSIS_INTF_ALIAS_SUBTYPE = 2; LLDP_CHASSIS_PORT_COMP_SUBTYPE = 3; LLDP_CHASSIS_MAC_ADDR_SUBTYPE = 4; LLDP_CHASSIS_NETWORK_ADDR_SUBTYPE = 5; LLDP_CHASSIS_INTF_NAME_SUBTYPE = 6; LLDP_CHASSIS_LOCAL_SUBTYPE = 8 } as uint8_t cenum lldp_port_id_subtype { LLDP_PORT_INTF_ALIAS_SUBTYPE = 1; LLDP_PORT_PORT_COMP_SUBTYPE = 2; LLDP_PORT_MAC_ADDR_SUBTYPE = 3; LLDP_PORT_NETWORK_ADDR_SUBTYPE = 4; LLDP_PORT_INTF_NAME_SUBTYPE = 5; LLDP_PORT_AGENT_CIRC_ID_SUBTYPE = 6; LLDP_PORT_LOCAL_SUBTYPE = 7 } as uint8_t*) cstruct ethernet { uint8_t dst[6]; uint8_t src[6]; uint16_t ethertype } as big_endian type lldp_tlv_types = LLDP_TYPE_END | LLDP_TYPE_CHASSIS_ID | LLDP_TYPE_PORT_ID | LLDP_TYPE_TTL | LLDP_TYPE_PORT_DESCR | LLDP_TYPE_SYSTEM_NAME | LLDP_TYPE_SYSTEM_DESCR | LLDP_TYPE_SYSTEM_CAP | LLDP_TYPE_MGMT_ADDR let lldp_tlv_types_of_int = function | 0 -> Some LLDP_TYPE_END | 1 -> Some LLDP_TYPE_CHASSIS_ID | 2 -> Some LLDP_TYPE_PORT_ID | 3 -> Some LLDP_TYPE_TTL | 4 -> Some LLDP_TYPE_PORT_DESCR | 5 -> Some LLDP_TYPE_SYSTEM_NAME | 6 -> Some LLDP_TYPE_SYSTEM_DESCR | 7 -> Some LLDP_TYPE_SYSTEM_CAP | 8 -> Some LLDP_TYPE_MGMT_ADDR | _ -> None let lldp_tlv_types_to_int = function | LLDP_TYPE_END -> 0 | LLDP_TYPE_CHASSIS_ID -> 1 | LLDP_TYPE_PORT_ID -> 2 | LLDP_TYPE_TTL -> 3 | LLDP_TYPE_PORT_DESCR -> 4 | LLDP_TYPE_SYSTEM_NAME -> 5 | LLDP_TYPE_SYSTEM_DESCR -> 6 | LLDP_TYPE_SYSTEM_CAP -> 7 | LLDP_TYPE_MGMT_ADDR -> 8 let lldp_tlv_types_to_string = function | LLDP_TYPE_END -> "LLDP_TYPE_END" | LLDP_TYPE_CHASSIS_ID -> "LLDP_TYPE_CHASSIS_ID" | LLDP_TYPE_PORT_ID -> "LLDP_TYPE_PORT_ID" | LLDP_TYPE_TTL -> "LLDP_TYPE_TTL" | LLDP_TYPE_PORT_DESCR -> "LLDP_TYPE_PORT_DESCR" | LLDP_TYPE_SYSTEM_NAME -> "LLDP_TYPE_SYSTEM_NAME" | LLDP_TYPE_SYSTEM_DESCR -> "LLDP_TYPE_SYSTEM_DESCR" | LLDP_TYPE_SYSTEM_CAP -> "LLDP_TYPE_SYSTEM_CAP" | LLDP_TYPE_MGMT_ADDR -> "LLDP_TYPE_MGMT_ADDR" type lldp_chassis_id_subtype = LLDP_CHASSIS_CHASSIS_COMP_SUBTYPE | LLDP_CHASSIS_INTF_ALIAS_SUBTYPE | LLDP_CHASSIS_PORT_COMP_SUBTYPE | LLDP_CHASSIS_MAC_ADDR_SUBTYPE | LLDP_CHASSIS_NETWORK_ADDR_SUBTYPE | LLDP_CHASSIS_INTF_NAME_SUBTYPE | LLDP_CHASSIS_LOCAL_SUBTYPE let lldp_chassis_id_subtype_of_int = function | 1 -> Some LLDP_CHASSIS_CHASSIS_COMP_SUBTYPE | 2 -> Some LLDP_CHASSIS_INTF_ALIAS_SUBTYPE | 3 -> Some LLDP_CHASSIS_PORT_COMP_SUBTYPE | 4 -> Some LLDP_CHASSIS_MAC_ADDR_SUBTYPE | 5 -> Some LLDP_CHASSIS_NETWORK_ADDR_SUBTYPE | 6 -> Some LLDP_CHASSIS_INTF_NAME_SUBTYPE | 8 -> Some LLDP_CHASSIS_LOCAL_SUBTYPE | _ -> None let lldp_chassis_id_subtype_to_int = function | LLDP_CHASSIS_CHASSIS_COMP_SUBTYPE -> 1 | LLDP_CHASSIS_INTF_ALIAS_SUBTYPE -> 2 | LLDP_CHASSIS_PORT_COMP_SUBTYPE -> 3 | LLDP_CHASSIS_MAC_ADDR_SUBTYPE -> 4 | LLDP_CHASSIS_NETWORK_ADDR_SUBTYPE -> 5 | LLDP_CHASSIS_INTF_NAME_SUBTYPE -> 6 | LLDP_CHASSIS_LOCAL_SUBTYPE -> 8 let lldp_chassis_id_subtype_to_string = function | LLDP_CHASSIS_CHASSIS_COMP_SUBTYPE -> "LLDP_CHASSIS_CHASSIS_COMP_SUBTYPE" | LLDP_CHASSIS_INTF_ALIAS_SUBTYPE -> "LLDP_CHASSIS_INTF_ALIAS_SUBTYPE" | LLDP_CHASSIS_PORT_COMP_SUBTYPE -> "LLDP_CHASSIS_PORT_COMP_SUBTYPE" | LLDP_CHASSIS_MAC_ADDR_SUBTYPE -> "LLDP_CHASSIS_MAC_ADDR_SUBTYPE" | LLDP_CHASSIS_NETWORK_ADDR_SUBTYPE -> "LLDP_CHASSIS_NETWORK_ADDR_SUBTYPE" | LLDP_CHASSIS_INTF_NAME_SUBTYPE -> "LLDP_CHASSIS_INTF_NAME_SUBTYPE" | LLDP_CHASSIS_LOCAL_SUBTYPE -> "LLDP_CHASSIS_LOCAL_SUBTYPE" type lldp_port_id_subtype = LLDP_PORT_INTF_ALIAS_SUBTYPE | LLDP_PORT_PORT_COMP_SUBTYPE | LLDP_PORT_MAC_ADDR_SUBTYPE | LLDP_PORT_NETWORK_ADDR_SUBTYPE | LLDP_PORT_INTF_NAME_SUBTYPE | LLDP_PORT_AGENT_CIRC_ID_SUBTYPE | LLDP_PORT_LOCAL_SUBTYPE let lldp_port_id_subtype_of_int = function | 1 -> Some LLDP_PORT_INTF_ALIAS_SUBTYPE | 2 -> Some LLDP_PORT_PORT_COMP_SUBTYPE | 3 -> Some LLDP_PORT_MAC_ADDR_SUBTYPE | 4 -> Some LLDP_PORT_NETWORK_ADDR_SUBTYPE | 5 -> Some LLDP_PORT_INTF_NAME_SUBTYPE | 6 -> Some LLDP_PORT_AGENT_CIRC_ID_SUBTYPE | 7 -> Some LLDP_PORT_LOCAL_SUBTYPE | _ -> None let lldp_port_id_subtype_to_int = function | LLDP_PORT_INTF_ALIAS_SUBTYPE -> 1 | LLDP_PORT_PORT_COMP_SUBTYPE -> 2 | LLDP_PORT_MAC_ADDR_SUBTYPE -> 3 | LLDP_PORT_NETWORK_ADDR_SUBTYPE -> 4 | LLDP_PORT_INTF_NAME_SUBTYPE -> 5 | LLDP_PORT_AGENT_CIRC_ID_SUBTYPE -> 6 | LLDP_PORT_LOCAL_SUBTYPE -> 7 let lldp_port_id_subtype_to_string = function | LLDP_PORT_INTF_ALIAS_SUBTYPE -> "LLDP_PORT_INTF_ALIAS_SUBTYPE" | LLDP_PORT_PORT_COMP_SUBTYPE -> "LLDP_PORT_PORT_COMP_SUBTYPE" | LLDP_PORT_MAC_ADDR_SUBTYPE -> "LLDP_PORT_MAC_ADDR_SUBTYPE" | LLDP_PORT_NETWORK_ADDR_SUBTYPE -> "LLDP_PORT_NETWORK_ADDR_SUBTYPE" | LLDP_PORT_INTF_NAME_SUBTYPE -> "LLDP_PORT_INTF_NAME_SUBTYPE" | LLDP_PORT_AGENT_CIRC_ID_SUBTYPE -> "LLDP_PORT_AGENT_CIRC_ID_SUBTYPE" | LLDP_PORT_LOCAL_SUBTYPE -> "LLDP_PORT_LOCAL_SUBTYPE" type lldp_tvl = | Tlv_chassis_id_chassis_comp of string | Tlv_chassis_id_intf_alias of string | Tlv_chassis_id_port_comp of string | Tlv_chassis_id_mac of Macaddr.t | Tlv_chassis_id_net of Ipaddr.V4.t | Tlv_chassis_id_intf_name of string | Tlv_chassis_id_local of string | Tlv_port_id_intf_alias of string | Tlv_port_id_port_comp of string | Tlv_port_id_mac of Macaddr.t | Tlv_port_id_net of Ipaddr.V4.t | Tlv_port_id_intf_name of string | Tlv_port_id_circ_id of string | Tlv_port_id_local of string | Tlv_ttl of int | Tlv_end | Tlv of lldp_tlv_types * string | Tlv_unk of int * string let parse_lldp_tlv bits = let tlv_type_len = Cstruct.BE.get_uint16 bits 0 in let tlv_type = tlv_type_len lsr 9 in let tlv_len = tlv_type_len land 0x01FF in let tlv = match (lldp_tlv_types_of_int tlv_type) with | Some(LLDP_TYPE_END) -> Tlv_end | Some(LLDP_TYPE_CHASSIS_ID) -> begin let data = Cstruct.to_string (Cstruct.sub bits 3 (tlv_len - 1)) in let chassis_id_subtype = Cstruct.get_uint8 bits 2 in match (lldp_chassis_id_subtype_of_int chassis_id_subtype) with | Some(LLDP_CHASSIS_CHASSIS_COMP_SUBTYPE)-> Tlv_chassis_id_chassis_comp(data) | Some(LLDP_CHASSIS_INTF_ALIAS_SUBTYPE) -> Tlv_chassis_id_intf_alias(data) | Some(LLDP_CHASSIS_PORT_COMP_SUBTYPE) -> Tlv_chassis_id_port_comp(data) | Some(LLDP_CHASSIS_MAC_ADDR_SUBTYPE) -> begin match (Macaddr.of_bytes data) with | None -> raise (Unparsable bits) | Some addr -> (Tlv_chassis_id_mac addr) end | Some(LLDP_CHASSIS_NETWORK_ADDR_SUBTYPE)-> let ip = Ipaddr.V4.of_int32 (Cstruct.BE.get_uint32 bits 3) in Tlv_chassis_id_net(ip) | Some(LLDP_CHASSIS_INTF_NAME_SUBTYPE) -> Tlv_chassis_id_intf_name(data) | Some(LLDP_CHASSIS_LOCAL_SUBTYPE) -> Tlv_chassis_id_local(data) | None -> raise (Unparsable(bits)) end | Some(LLDP_TYPE_PORT_ID) -> begin let data = Cstruct.to_string (Cstruct.sub bits 3 (tlv_len - 1)) in let port_id_subtype = Cstruct.get_uint8 bits 2 in match (lldp_port_id_subtype_of_int port_id_subtype) with | Some(LLDP_PORT_INTF_ALIAS_SUBTYPE) -> Tlv_port_id_intf_alias(data) | Some(LLDP_PORT_PORT_COMP_SUBTYPE) -> Tlv_port_id_port_comp(data) | Some(LLDP_PORT_MAC_ADDR_SUBTYPE) -> begin match (Macaddr.of_bytes data) with | None -> raise (Unparsable(bits)) | Some addr -> Tlv_port_id_mac(addr) end | Some(LLDP_PORT_NETWORK_ADDR_SUBTYPE) -> let ip = Ipaddr.V4.of_int32 (Cstruct.BE.get_uint32 bits 3) in Tlv_port_id_net(ip) | Some(LLDP_PORT_INTF_NAME_SUBTYPE) -> Tlv_port_id_intf_name(data) | Some(LLDP_PORT_AGENT_CIRC_ID_SUBTYPE)-> Tlv_port_id_circ_id(data) | Some(LLDP_PORT_LOCAL_SUBTYPE) -> Tlv_port_id_local(data) | None -> raise (Unparsable(bits)) end | Some(LLDP_TYPE_TTL) -> let ttl = Cstruct.BE.get_uint16 bits 3 in Tlv_ttl(ttl) | Some(typ) -> let data = Cstruct.to_string (Cstruct.sub bits 3 (tlv_len - 1)) in Tlv(typ, data) | None -> let data = Cstruct.to_string (Cstruct.sub bits 2 tlv_len) in Tlv_unk(tlv_type, data) in (tlv_len + 2, tlv) let parse_lldp_tlvs bits = let bits = Cstruct.shift bits sizeof_ethernet in let rec parse_lldp_tlvs_inner bits = match (Cstruct.len bits) with | 0 -> [] | _ -> let (len, tlv) = parse_lldp_tlv bits in if(tlv = Tlv_end) then [tlv] else let bits = Cstruct.shift bits len in [tlv] @ (parse_lldp_tlvs_inner bits) in parse_lldp_tlvs_inner bits let set_lldp_tlv_typ_subtyp_data bits typ subtyp data = let typ = typ lsl 9 in let len = ((String.length data) + 1) land 0x1ff in let typ_len = typ + len in let _ = Cstruct.BE.set_uint16 bits 0 typ_len in let _ = Cstruct.set_uint8 bits 2 subtyp in let _ = Cstruct.blit_from_string data 0 bits 3 (String.length data) in len + 2 let set_lldp_tlv_typ_data bits typ data = let typ = typ lsl 9 in let len = (String.length data) land 0x1ff in let typ_len = typ + len in let _ = Cstruct.BE.set_uint16 bits 0 typ_len in let _ = Cstruct.blit_from_string data 0 bits 2 (String.length data) in len + 2 let marsal_lldp_tlv tlv bits = match tlv with | Tlv_chassis_id_chassis_comp(data) -> set_lldp_tlv_typ_subtyp_data bits 1 1 data | Tlv_chassis_id_intf_alias(data) -> set_lldp_tlv_typ_subtyp_data bits 1 2 data | Tlv_chassis_id_port_comp(data) -> set_lldp_tlv_typ_subtyp_data bits 1 3 data | Tlv_chassis_id_mac(mac) -> set_lldp_tlv_typ_subtyp_data bits 1 4 (Macaddr.to_bytes mac) | Tlv_chassis_id_net(ip) -> let _ = Cstruct.BE.set_uint16 bits 0 0x205 in let _ = Cstruct.set_uint8 bits 2 5 in let _ = Cstruct.BE.set_uint32 bits 3 (Ipaddr.V4.to_int32 ip) in 7 | Tlv_chassis_id_intf_name(data) -> set_lldp_tlv_typ_subtyp_data bits 1 6 data | Tlv_chassis_id_local(data) -> set_lldp_tlv_typ_subtyp_data bits 1 8 data | Tlv_port_id_intf_alias(data) -> set_lldp_tlv_typ_subtyp_data bits 2 1 data | Tlv_port_id_port_comp(data) -> set_lldp_tlv_typ_subtyp_data bits 2 2 data | Tlv_port_id_mac(mac) -> set_lldp_tlv_typ_subtyp_data bits 2 3 (Macaddr.to_bytes mac) | Tlv_port_id_net(ip) -> let _ = Cstruct.BE.set_uint16 bits 0 0x405 in let _ = Cstruct.set_uint8 bits 2 4 in let _ = Cstruct.BE.set_uint32 bits 3 (Ipaddr.V4.to_int32 ip) in 7 | Tlv_port_id_intf_name(data) -> set_lldp_tlv_typ_subtyp_data bits 2 5 data | Tlv_port_id_circ_id(data) -> set_lldp_tlv_typ_subtyp_data bits 2 6 data | Tlv_port_id_local(data) -> set_lldp_tlv_typ_subtyp_data bits 2 7 data | Tlv_ttl(ttl) -> let _ = Cstruct.BE.set_uint16 bits 0 0x602 in let _ = Cstruct.BE.set_uint16 bits 2 ttl in 4 | Tlv_end -> let _ = Cstruct.BE.set_uint16 bits 0 0x000 in 2 | Tlv(typ, data) -> set_lldp_tlv_typ_data bits (lldp_tlv_types_to_int typ) data | Tlv_unk (typ, data) -> set_lldp_tlv_typ_data bits typ data let marsal_lldp_tlvs mac tlvs bits = let _ = set_ethernet_dst "\x01\x80\xc2\x00\x00\x0e" 0 bits in let _ = set_ethernet_src (Macaddr.to_bytes mac) 0 bits in let _ = set_ethernet_ethertype bits 0x88cc in let bits = Cstruct.shift bits sizeof_ethernet in let rec marsal_lldp_tlvs_inner tlvs bits = match tlvs with | [] -> 0 | h::t -> let len = marsal_lldp_tlv h bits in let bits = Cstruct.shift bits len in let rest = marsal_lldp_tlvs_inner t bits in len + rest in sizeof_ethernet + marsal_lldp_tlvs_inner tlvs bits
68424858c92f9b9513e7d8ea4f1fbb68e2b8b5cccbf81413a6fc3a53e4621a62
gsakkas/rite
3565.ml
let rec clone x n = if n > 0 then x :: ((clone x n) - 1) else [];; (* fix let rec clone x n = if n > 0 then x :: (clone x (n - 1)) else [];; *) changed spans ( 2,40)-(2,57 ) clone x ( n - 1 ) AppG [ VarG , BopG EmptyG EmptyG ] (2,40)-(2,57) clone x (n - 1) AppG [VarG,BopG EmptyG EmptyG] *) type error slice ( 2,4)-(2,67 ) ( 2,15)-(2,65 ) ( 2,17)-(2,65 ) ( 2,21)-(2,65 ) ( 2,35)-(2,57 ) ( ) ( 2,41)-(2,52 ) ( 2,42)-(2,47 ) ( 2,63)-(2,65 ) (2,4)-(2,67) (2,15)-(2,65) (2,17)-(2,65) (2,21)-(2,65) (2,35)-(2,57) (2,40)-(2,57) (2,41)-(2,52) (2,42)-(2,47) (2,63)-(2,65) *)
null
https://raw.githubusercontent.com/gsakkas/rite/958a0ad2460e15734447bc07bd181f5d35956d3b/data/sp14/3565.ml
ocaml
fix let rec clone x n = if n > 0 then x :: (clone x (n - 1)) else [];;
let rec clone x n = if n > 0 then x :: ((clone x n) - 1) else [];; changed spans ( 2,40)-(2,57 ) clone x ( n - 1 ) AppG [ VarG , BopG EmptyG EmptyG ] (2,40)-(2,57) clone x (n - 1) AppG [VarG,BopG EmptyG EmptyG] *) type error slice ( 2,4)-(2,67 ) ( 2,15)-(2,65 ) ( 2,17)-(2,65 ) ( 2,21)-(2,65 ) ( 2,35)-(2,57 ) ( ) ( 2,41)-(2,52 ) ( 2,42)-(2,47 ) ( 2,63)-(2,65 ) (2,4)-(2,67) (2,15)-(2,65) (2,17)-(2,65) (2,21)-(2,65) (2,35)-(2,57) (2,40)-(2,57) (2,41)-(2,52) (2,42)-(2,47) (2,63)-(2,65) *)
71f631326869dc92536279a1e3767231dce0920b746e46b3b90eeba0434d2e8c
toolslive/ordma
rsocket.ml
type rsocket = int type ba = (char, Bigarray.int8_unsigned_elt, Bigarray.c_layout) Bigarray.Array1.t external rsocket : Unix.socket_domain -> Unix.socket_type -> int -> rsocket = "ordma_rsocket" let show rsocket = string_of_int rsocket external rconnect : rsocket -> Unix.sockaddr -> unit = "ordma_rconnect" external rsend : rsocket -> bytes -> int -> int -> Unix.msg_flag list -> int = "ordma_rsend" external rrecv : rsocket -> bytes -> int -> int -> Unix.msg_flag list -> int = "ordma_rrecv" external rsend_ba : rsocket -> ba -> int -> int -> Unix.msg_flag list -> int = "ordma_rsend_ba" external rrecv_ba : rsocket -> ba -> int -> int -> Unix.msg_flag list -> int = "ordma_rrecv_ba" external rclose : rsocket -> unit = "ordma_rclose" external rbind : rsocket -> Unix.sockaddr -> unit = "ordma_rbind" external raccept : rsocket -> rsocket * Unix.sockaddr = "ordma_raccept" external rlisten : rsocket -> int -> unit = "ordma_rlisten" type socket_error_option = SO_ERROR module SO: sig type ('opt, 'v) t val bool: (Unix.socket_bool_option, bool) t val int: (Unix.socket_int_option, int) t val optint: (Unix.socket_optint_option, int option) t val float: (Unix.socket_float_option, float) t val error: (socket_error_option, Unix.error option) t val get: ('opt, 'v) t -> rsocket -> 'opt -> 'v val set: ('opt, 'v) t -> rsocket -> 'opt -> 'v -> unit end = struct type ('opt, 'v) t = int let bool = 0 let int = 1 let optint = 2 let float = 3 let error = 4 external get: ('opt, 'v) t -> rsocket -> 'opt -> 'v = "ordma_rgetsockopt" external set: ('opt, 'v) t -> rsocket -> 'opt -> 'v -> unit = "ordma_rsetsockopt" end let rgetsockopt fd opt = SO.get SO.bool fd opt let rsetsockopt fd opt v = SO.set SO.bool fd opt v let rgetsockopt_error fd = SO.get SO.error fd SO_ERROR external set_nonblock : rsocket -> unit = "ordma_set_nonblock" module Version = struct include Ordma_version end
null
https://raw.githubusercontent.com/toolslive/ordma/e430cb48677a6c0c7847c00118c5eb4ebedebe2c/rsocket.ml
ocaml
type rsocket = int type ba = (char, Bigarray.int8_unsigned_elt, Bigarray.c_layout) Bigarray.Array1.t external rsocket : Unix.socket_domain -> Unix.socket_type -> int -> rsocket = "ordma_rsocket" let show rsocket = string_of_int rsocket external rconnect : rsocket -> Unix.sockaddr -> unit = "ordma_rconnect" external rsend : rsocket -> bytes -> int -> int -> Unix.msg_flag list -> int = "ordma_rsend" external rrecv : rsocket -> bytes -> int -> int -> Unix.msg_flag list -> int = "ordma_rrecv" external rsend_ba : rsocket -> ba -> int -> int -> Unix.msg_flag list -> int = "ordma_rsend_ba" external rrecv_ba : rsocket -> ba -> int -> int -> Unix.msg_flag list -> int = "ordma_rrecv_ba" external rclose : rsocket -> unit = "ordma_rclose" external rbind : rsocket -> Unix.sockaddr -> unit = "ordma_rbind" external raccept : rsocket -> rsocket * Unix.sockaddr = "ordma_raccept" external rlisten : rsocket -> int -> unit = "ordma_rlisten" type socket_error_option = SO_ERROR module SO: sig type ('opt, 'v) t val bool: (Unix.socket_bool_option, bool) t val int: (Unix.socket_int_option, int) t val optint: (Unix.socket_optint_option, int option) t val float: (Unix.socket_float_option, float) t val error: (socket_error_option, Unix.error option) t val get: ('opt, 'v) t -> rsocket -> 'opt -> 'v val set: ('opt, 'v) t -> rsocket -> 'opt -> 'v -> unit end = struct type ('opt, 'v) t = int let bool = 0 let int = 1 let optint = 2 let float = 3 let error = 4 external get: ('opt, 'v) t -> rsocket -> 'opt -> 'v = "ordma_rgetsockopt" external set: ('opt, 'v) t -> rsocket -> 'opt -> 'v -> unit = "ordma_rsetsockopt" end let rgetsockopt fd opt = SO.get SO.bool fd opt let rsetsockopt fd opt v = SO.set SO.bool fd opt v let rgetsockopt_error fd = SO.get SO.error fd SO_ERROR external set_nonblock : rsocket -> unit = "ordma_set_nonblock" module Version = struct include Ordma_version end
bf354d0cc9011a8dbe0e3715cbe127826f0eed3ea9ad936532783a86e44d1a19
chef/chef-server
chef_wm_enforce_tests.erl
-module(chef_wm_enforce_tests). -include_lib("eunit/include/eunit.hrl"). max_size_test_() -> DefaultMaxSize = 1000000, TunedValue = 5, [ {"Default tests", {foreach, fun() -> meck:new(wrq), application:unset_env(oc_chef_wm, max_request_size) end, fun(_) -> meck:unload(wrq) end, [ ?_test(max_size_success('POST', DefaultMaxSize)), ?_test(max_size_success('PUT', DefaultMaxSize)), ?_test(max_size_error('POST', DefaultMaxSize)), ?_test(max_size_error('PUT', DefaultMaxSize)) ] } }, {"Tuned tests", {foreach, fun() -> meck:new(wrq), application:set_env(oc_chef_wm, max_request_size, TunedValue) end, fun(_) -> meck:unload(wrq), application:unset_env(oc_chef_wm, max_request_size) end, [ ?_test(max_size_success('POST', TunedValue)), ?_test(max_size_success('PUT', TunedValue)), ?_test(max_size_error('POST', TunedValue)), ?_test(max_size_error('PUT', TunedValue)) ] } }, {"Disabled tests", {foreach, fun() -> application:set_env(oc_chef_wm, max_request_size, disabled) end, fun(_) -> application:unset_env(oc_chef_wm, max_request_size) end, [ fun(_) -> ?_test(disabled_max_size()) end ] } }, {"Incorrect configuration tests", {foreach, fun() -> application:unset_env(oc_chef_wm, max_request_size) end, fun(_) -> application:unset_env(oc_chef_wm, max_request_size) end, [ ?_test(config_error(0)), ?_test(config_error(-1)), ?_test(config_error(not_disabled)) ] } } ]. max_size_success(Method, MaxSize) -> meck:expect(wrq, method, 1, Method), meck:expect(wrq, set_max_recv_body, 2, req), meck:expect(wrq, req_body, 1, ignored), ?assertEqual(req, chef_wm_enforce:max_size(req)), ?assert(meck:called(wrq, set_max_recv_body, [MaxSize, req])). max_size_error(Method, MaxSize) -> meck:expect(wrq, method, 1, Method), meck:expect(wrq, set_max_recv_body, 2, req), meck:expect(wrq, req_body, fun(_) -> exit("request body too large") end), ErrorMessage = list_to_binary("JSON must be no more than " ++ integer_to_list(MaxSize) ++ " bytes."), ?assertThrow({too_big, ErrorMessage }, chef_wm_enforce:max_size(req)), ?assert(meck:called(wrq, set_max_recv_body, [MaxSize, req])). disabled_max_size() -> ?assertEqual(req, chef_wm_enforce:max_size(req)). config_error(Val) -> application:set_env(oc_chef_wm, max_request_size, Val), ?assertError(config_bad_type, chef_wm_enforce:max_size(req)). max_size_when_get_should_return_req_test() -> meck:new(wrq), try meck:expect(wrq, method, 1, 'GET'), ?assertEqual(req, chef_wm_enforce:max_size(req)), ?assert(meck:called(wrq, method, [req])) after meck:unload(wrq) end.
null
https://raw.githubusercontent.com/chef/chef-server/6d31841ecd73d984d819244add7ad6ebac284323/src/oc_erchef/apps/oc_chef_wm/test/chef_wm_enforce_tests.erl
erlang
-module(chef_wm_enforce_tests). -include_lib("eunit/include/eunit.hrl"). max_size_test_() -> DefaultMaxSize = 1000000, TunedValue = 5, [ {"Default tests", {foreach, fun() -> meck:new(wrq), application:unset_env(oc_chef_wm, max_request_size) end, fun(_) -> meck:unload(wrq) end, [ ?_test(max_size_success('POST', DefaultMaxSize)), ?_test(max_size_success('PUT', DefaultMaxSize)), ?_test(max_size_error('POST', DefaultMaxSize)), ?_test(max_size_error('PUT', DefaultMaxSize)) ] } }, {"Tuned tests", {foreach, fun() -> meck:new(wrq), application:set_env(oc_chef_wm, max_request_size, TunedValue) end, fun(_) -> meck:unload(wrq), application:unset_env(oc_chef_wm, max_request_size) end, [ ?_test(max_size_success('POST', TunedValue)), ?_test(max_size_success('PUT', TunedValue)), ?_test(max_size_error('POST', TunedValue)), ?_test(max_size_error('PUT', TunedValue)) ] } }, {"Disabled tests", {foreach, fun() -> application:set_env(oc_chef_wm, max_request_size, disabled) end, fun(_) -> application:unset_env(oc_chef_wm, max_request_size) end, [ fun(_) -> ?_test(disabled_max_size()) end ] } }, {"Incorrect configuration tests", {foreach, fun() -> application:unset_env(oc_chef_wm, max_request_size) end, fun(_) -> application:unset_env(oc_chef_wm, max_request_size) end, [ ?_test(config_error(0)), ?_test(config_error(-1)), ?_test(config_error(not_disabled)) ] } } ]. max_size_success(Method, MaxSize) -> meck:expect(wrq, method, 1, Method), meck:expect(wrq, set_max_recv_body, 2, req), meck:expect(wrq, req_body, 1, ignored), ?assertEqual(req, chef_wm_enforce:max_size(req)), ?assert(meck:called(wrq, set_max_recv_body, [MaxSize, req])). max_size_error(Method, MaxSize) -> meck:expect(wrq, method, 1, Method), meck:expect(wrq, set_max_recv_body, 2, req), meck:expect(wrq, req_body, fun(_) -> exit("request body too large") end), ErrorMessage = list_to_binary("JSON must be no more than " ++ integer_to_list(MaxSize) ++ " bytes."), ?assertThrow({too_big, ErrorMessage }, chef_wm_enforce:max_size(req)), ?assert(meck:called(wrq, set_max_recv_body, [MaxSize, req])). disabled_max_size() -> ?assertEqual(req, chef_wm_enforce:max_size(req)). config_error(Val) -> application:set_env(oc_chef_wm, max_request_size, Val), ?assertError(config_bad_type, chef_wm_enforce:max_size(req)). max_size_when_get_should_return_req_test() -> meck:new(wrq), try meck:expect(wrq, method, 1, 'GET'), ?assertEqual(req, chef_wm_enforce:max_size(req)), ?assert(meck:called(wrq, method, [req])) after meck:unload(wrq) end.
797436a7424329e0b98bf04a504625e81c11609e369465ca4b0c03ce41a8c5ba
webyrd/miniKanren-hangout-summaries
intro-hangout-4.scm
(load "pmatch.scm") (define-syntax test (syntax-rules () [(test name expr expected-val) (let ((v expr)) (if (equal? v expected-val) (begin (display "passed test ") (write name) (newline)) (error 'name (format "\nTest ~s failed!!\nExpected ~s, but got ~s" name expected-val v))))])) (define empty-env '()) (define lookup (lambda (x env) (cond ((null? env) (error 'lookup (format "unbound variable ~s" x))) ((eq? (caar env) x) (cdar env)) (else (lookup x (cdr env)))))) ;; lambda calculus ;; ;; x variable ;; (lambda (x) expr) lambda expression (abstract) ;; (e e) application (define eval-expr (lambda (expr env) (pmatch expr [,n (guard (number? n)) n] [(zero? ,e) (zero? (eval-expr e env))] [(add1 ,e) (add1 (eval-expr e env))] [(sub1 ,e) (sub1 (eval-expr e env))] [(* ,e1 ,e2) (* (eval-expr e1 env) (eval-expr e2 env))] [(if ,e1 ,e2 ,e3) (if (eval-expr e1 env) (eval-expr e2 env) (eval-expr e3 env))] [,x (guard (symbol? x)) ; variable (lookup x env)] [(lambda (,x) ,body) (guard (symbol? x)) ; lambda/abstraction `(closure ,x ,body ,env)] [(,rator ,rand) ;application (apply-proc (eval-expr rator env) (eval-expr rand env))]))) ; ; rator rand ( ( lambda ( y ) ( * y y ) ) ( add1 5 ) ) ;; => ;; (closure y (* y y) ()) ; value of the rator (proc) 6 ; value of the rand ( ) ( * y y ) ( ( y . 6 ) ) ;; (((lambda (y) ;; (lambda (z) ;; (* y z))) ( add1 4 ) ) ;; (sub1 7)) ;; ((lambda (y) ;; (lambda (z) ;; (* y z))) ( add1 4 ) ) ;; ((lambda (y) ;; => (closure y (lambda (z) (* y z)) ()) ;; (lambda (z) ;; (* y z))) ( add1 4 ) ; ; = > 5 ;; ) ;; (closure y (lambda (z) (* y z)) ()) proc ;; 5 val ( lambda ( z ) ( * y z ) ) in ( ( y . 5 ) ) ( closure z ( * y z ) ( ( y . 5 ) ) ) proc ;; 6 val ( * y z ) in ( ( z . 6 ) ( y . 5 ) ) (define apply-proc (lambda (proc val) (pmatch proc [(closure ,x ,body ,env) (eval-expr body `((,x . ,val) . ,env))]))) (test "! 5" (eval-expr '(((lambda (!) (lambda (n) ((! !) n))) (lambda (!) (lambda (n) (if (zero? n) 1 (* n ((! !) (sub1 n))))))) 5) empty-env) 120) (test "eval-expr lambda" (eval-expr '(lambda (y) (* y y)) '((z . 17))) '(closure y (* y y) ((z . 17)))) (test "eval-expr app 1" (eval-expr '((lambda (y) (* y y)) (add1 5)) '((z . 17))) 36) (test "eval-expr app 2" (eval-expr '(((lambda (y) (lambda (z) (* y z))) (add1 4)) (sub1 7)) empty-env) 30) (test "eval-expr var" (eval-expr 'y '((y . 5))) 5) (test "eval-expr var/add1" (eval-expr '(add1 y) '((y . 5))) 6) (test "eval-expr num" (eval-expr '5 empty-env) 5) (test "eval-expr bignum" (eval-expr '5983724897985749873827589372589732985798237598273598 empty-env) 5983724897985749873827589372589732985798237598273598) (test "eval-expr zero? 1" (eval-expr '(zero? 0) empty-env) #t) (test "eval-expr zero? 2" (eval-expr '(zero? 1) empty-env) #f) (test "eval-expr zero? 3" (eval-expr '(zero? (add1 0)) empty-env) #f) (test "eval-expr zero? 4" (eval-expr '(zero? (sub1 1)) empty-env) #t) (test "eval-expr add1" (eval-expr '(add1 (add1 5)) empty-env) 7) (test "eval-expr sub1" (eval-expr '(sub1 (sub1 5)) empty-env) 3) (test "eval-expr * 1" (eval-expr '(* 3 4) empty-env) 12) (test "eval-expr * 2" (eval-expr '(* (* 3 4) 5) empty-env) 60) (test "eval-expr * 3" (eval-expr '(* 5 (* 3 4)) empty-env) 60) (test "eval-expr if 1" (eval-expr '(if (zero? 0) 5 6) empty-env) 5) (test "eval-expr if 2" (eval-expr '(if (zero? 1) 5 6) empty-env) 6) (test "eval-expr if 3" (eval-expr '(if (zero? (* 3 4)) (add1 6) (sub1 6)) empty-env) 5) #!eof (let ((x (+ 2 3))) x - > 5 (+ (let ((y (* x x))) y - > 25 (let ((x 7)) x - > 7 (+ x y))) x)) ;; environment ;; association-list (alist) represention of environments ;; () empty environment (let ((x (+ 2 3))) ( ( x . 5 ) ) (let ((y (* x x))) ( ( y . 25 ) ( x . 5 ) ) (let ((x 7)) ( ( x . 7 ) ( y . 25 ) ( x . 5 ) ) (+ x y)))) ;; tagged-list representation of environments ;; (empty-env) ( ext - env x 5 ( empty - env ) ) ( ext - env y 25 ( ext - env x 5 ( empty - env ) ) ) ( ext - env x 7 ( ext - env y 25 ( ext - env x 5 ( empty - env ) ) ) ) (define lookup (lambda (x env) (cond ((null? env) (error 'lookup (format "unbound variable ~s" x))) ((eq? (car (car env)) x) (cdr (car env))) (else (lookup x (cdr env)))))) (lookup 'y '((y . 25) (x . 5))) (lookup 'x '((y . 25) (x . 5))) (lookup 'z '((y . 25) (x . 5))) ;; (lookup 'y '()) (define lookup (lambda (x env) (cond ((null? env) (error 'lookup (format "unbound variable ~s" x))) ((eq? (caar env) x) (cdar env)) (else (lookup x (cdr env)))))) (lookup 'y '((y . 25) (x . 5))) (lookup 'x '((y . 25) (x . 5))) (lookup 'z '((y . 25) (x . 5))) (define lookup (lambda (x env) (pmatch env (() (error 'lookup (format "unbound variable ~s" x))) (((,y . ,v) . ,rest-env) (if (eq? y x) v (lookup x rest-env)))))) (lookup 'y '((y . 25) (x . 5))) (lookup 'x '((y . 25) (x . 5))) (lookup 'z '((y . 25) (x . 5))) ;; tagged-list representation of environments ;; (empty-env) ( ext - env x 5 ( empty - env ) ) ( ext - env y 25 ( ext - env x 5 ( empty - env ) ) ) (define lookup (lambda (x env) (pmatch env ((empty-env) (error 'lookup (format "unbound variable ~s" x))) ((ext-env ,y ,v ,rest-env) (if (eq? y x) v (lookup x rest-env)))))) (lookup 'y '(ext-env x 7 (ext-env y 25 (ext-env x 5 (empty-env)))))
null
https://raw.githubusercontent.com/webyrd/miniKanren-hangout-summaries/06b33ba37e298c14babb7c6c0f63fe01bc65d547/code/intro-hangouts/intro-hangout-4/intro-hangout-4.scm
scheme
lambda calculus x variable (lambda (x) expr) lambda expression (abstract) (e e) application variable lambda/abstraction application ; rator rand => (closure y (* y y) ()) ; value of the rator (proc) value of the rand ( ) (((lambda (y) (lambda (z) (* y z))) (sub1 7)) ((lambda (y) (lambda (z) (* y z))) ((lambda (y) ;; => (closure y (lambda (z) (* y z)) ()) (lambda (z) (* y z))) ; = > 5 ) (closure y (lambda (z) (* y z)) ()) proc 5 val 6 val environment association-list (alist) represention of environments () empty environment tagged-list representation of environments (empty-env) (lookup 'y '()) tagged-list representation of environments (empty-env)
(load "pmatch.scm") (define-syntax test (syntax-rules () [(test name expr expected-val) (let ((v expr)) (if (equal? v expected-val) (begin (display "passed test ") (write name) (newline)) (error 'name (format "\nTest ~s failed!!\nExpected ~s, but got ~s" name expected-val v))))])) (define empty-env '()) (define lookup (lambda (x env) (cond ((null? env) (error 'lookup (format "unbound variable ~s" x))) ((eq? (caar env) x) (cdar env)) (else (lookup x (cdr env)))))) (define eval-expr (lambda (expr env) (pmatch expr [,n (guard (number? n)) n] [(zero? ,e) (zero? (eval-expr e env))] [(add1 ,e) (add1 (eval-expr e env))] [(sub1 ,e) (sub1 (eval-expr e env))] [(* ,e1 ,e2) (* (eval-expr e1 env) (eval-expr e2 env))] [(if ,e1 ,e2 ,e3) (if (eval-expr e1 env) (eval-expr e2 env) (eval-expr e3 env))] (lookup x env)] `(closure ,x ,body ,env)] (apply-proc (eval-expr rator env) (eval-expr rand env))]))) ( ( lambda ( y ) ( * y y ) ) ( add1 5 ) ) ( * y y ) ( ( y . 6 ) ) ( add1 4 ) ) ( add1 4 ) ) ( lambda ( z ) ( * y z ) ) in ( ( y . 5 ) ) ( closure z ( * y z ) ( ( y . 5 ) ) ) proc ( * y z ) in ( ( z . 6 ) ( y . 5 ) ) (define apply-proc (lambda (proc val) (pmatch proc [(closure ,x ,body ,env) (eval-expr body `((,x . ,val) . ,env))]))) (test "! 5" (eval-expr '(((lambda (!) (lambda (n) ((! !) n))) (lambda (!) (lambda (n) (if (zero? n) 1 (* n ((! !) (sub1 n))))))) 5) empty-env) 120) (test "eval-expr lambda" (eval-expr '(lambda (y) (* y y)) '((z . 17))) '(closure y (* y y) ((z . 17)))) (test "eval-expr app 1" (eval-expr '((lambda (y) (* y y)) (add1 5)) '((z . 17))) 36) (test "eval-expr app 2" (eval-expr '(((lambda (y) (lambda (z) (* y z))) (add1 4)) (sub1 7)) empty-env) 30) (test "eval-expr var" (eval-expr 'y '((y . 5))) 5) (test "eval-expr var/add1" (eval-expr '(add1 y) '((y . 5))) 6) (test "eval-expr num" (eval-expr '5 empty-env) 5) (test "eval-expr bignum" (eval-expr '5983724897985749873827589372589732985798237598273598 empty-env) 5983724897985749873827589372589732985798237598273598) (test "eval-expr zero? 1" (eval-expr '(zero? 0) empty-env) #t) (test "eval-expr zero? 2" (eval-expr '(zero? 1) empty-env) #f) (test "eval-expr zero? 3" (eval-expr '(zero? (add1 0)) empty-env) #f) (test "eval-expr zero? 4" (eval-expr '(zero? (sub1 1)) empty-env) #t) (test "eval-expr add1" (eval-expr '(add1 (add1 5)) empty-env) 7) (test "eval-expr sub1" (eval-expr '(sub1 (sub1 5)) empty-env) 3) (test "eval-expr * 1" (eval-expr '(* 3 4) empty-env) 12) (test "eval-expr * 2" (eval-expr '(* (* 3 4) 5) empty-env) 60) (test "eval-expr * 3" (eval-expr '(* 5 (* 3 4)) empty-env) 60) (test "eval-expr if 1" (eval-expr '(if (zero? 0) 5 6) empty-env) 5) (test "eval-expr if 2" (eval-expr '(if (zero? 1) 5 6) empty-env) 6) (test "eval-expr if 3" (eval-expr '(if (zero? (* 3 4)) (add1 6) (sub1 6)) empty-env) 5) #!eof (let ((x (+ 2 3))) x - > 5 (+ (let ((y (* x x))) y - > 25 (let ((x 7)) x - > 7 (+ x y))) x)) (let ((x (+ 2 3))) ( ( x . 5 ) ) (let ((y (* x x))) ( ( y . 25 ) ( x . 5 ) ) (let ((x 7)) ( ( x . 7 ) ( y . 25 ) ( x . 5 ) ) (+ x y)))) ( ext - env x 5 ( empty - env ) ) ( ext - env y 25 ( ext - env x 5 ( empty - env ) ) ) ( ext - env x 7 ( ext - env y 25 ( ext - env x 5 ( empty - env ) ) ) ) (define lookup (lambda (x env) (cond ((null? env) (error 'lookup (format "unbound variable ~s" x))) ((eq? (car (car env)) x) (cdr (car env))) (else (lookup x (cdr env)))))) (lookup 'y '((y . 25) (x . 5))) (lookup 'x '((y . 25) (x . 5))) (lookup 'z '((y . 25) (x . 5))) (define lookup (lambda (x env) (cond ((null? env) (error 'lookup (format "unbound variable ~s" x))) ((eq? (caar env) x) (cdar env)) (else (lookup x (cdr env)))))) (lookup 'y '((y . 25) (x . 5))) (lookup 'x '((y . 25) (x . 5))) (lookup 'z '((y . 25) (x . 5))) (define lookup (lambda (x env) (pmatch env (() (error 'lookup (format "unbound variable ~s" x))) (((,y . ,v) . ,rest-env) (if (eq? y x) v (lookup x rest-env)))))) (lookup 'y '((y . 25) (x . 5))) (lookup 'x '((y . 25) (x . 5))) (lookup 'z '((y . 25) (x . 5))) ( ext - env x 5 ( empty - env ) ) ( ext - env y 25 ( ext - env x 5 ( empty - env ) ) ) (define lookup (lambda (x env) (pmatch env ((empty-env) (error 'lookup (format "unbound variable ~s" x))) ((ext-env ,y ,v ,rest-env) (if (eq? y x) v (lookup x rest-env)))))) (lookup 'y '(ext-env x 7 (ext-env y 25 (ext-env x 5 (empty-env)))))
3dd4ff21ee151ea357986fd73157937b8acb38338fab1685ad668d781d6d329b
dvcrn/proton
core.cljs
(ns proton.core (:require-macros [cljs.core.async.macros :refer [go go-loop]]) (:require [proton.lib.helpers :as helpers] [proton.lib.atom :as atom-env] [proton.lib.package_manager :as pm] [proton.lib.proton :as proton] [proton.lib.mode :as mode-manager] [proton.lib.keymap :as keymap-manager] [cljs.nodejs :as node] [clojure.string :as string :refer [join lower-case upper-case]] [proton.layers.base :as layerbase] [proton.layers.core.core :as core-layer] ;; tools [proton.layers.tools.minimap.core] [proton.layers.tools.expose.core] [proton.layers.tools.git.core] [proton.layers.tools.linter.core] [proton.layers.tools.build.core] [proton.layers.tools.bookmarks.core] [proton.layers.tools.todo.core] [proton.layers.tools.terminal.core] ;; etc [proton.layers.fun.power_mode.core] ;; langs [proton.layers.lang.clojure.core] [proton.layers.lang.swift.core] [proton.layers.lang.csharp.core] [proton.layers.lang.python.core] [proton.layers.lang.julia.core] [proton.layers.lang.latex.core] [proton.layers.lang.markdown.core] [proton.layers.lang.elixir.core] [proton.layers.lang.elm.core] [proton.layers.lang.javascript.core] [proton.layers.lang.rust.core] [proton.layers.lang.html.core] [proton.layers.lang.go.core] [proton.layers.lang.ruby.core] [proton.layers.lang.json.core] [proton.layers.lang.css.core] [proton.layers.lang.sass.core] [proton.layers.lang.stylus.core] [proton.layers.lang.less.core] [proton.layers.lang.haml.core] [proton.layers.lang.slim.core] [proton.layers.lang.jade.core] [proton.layers.lang.handlebars.core] [proton.layers.lang.mustache.core] [proton.layers.lang.typescript.core] [proton.layers.lang.haskell.core] ;; config-files [proton.layers.config-files.docker.core] ;; frameworks [proton.layers.frameworks.django.core] [proton.layers.frameworks.react.core] ;; apps [proton.layers.apps.notes.core] [proton.config.editor :as editor-config] [proton.config.proton :as proton-config] [cljs.core.async :as async :refer [chan put! pub sub unsub >! <!]])) ;; Atom for holding all disposables objects (def disposables (atom [])) (swap! disposables conj atom-env/subscriptions) (defonce current-chain (atom [])) ;; Atom that holds chain timeout id (def chain-timer (atom nil)) (def mode-keys [:m (keyword ",")]) (defn is-mode-key? [chain-key] (not (nil? (some #{(first chain-key)} mode-keys)))) (defn- chain-delay [f] (reset! chain-timer (js/setTimeout f (* 1000 (atom-env/get-config "proton.core.whichKeyDelay"))))) (defn chain [e] (let [keystroke (helpers/extract-keystroke-from-event e)] check for ESC key (when-not (nil? @chain-timer) (js/clearTimeout @chain-timer)) (if (= keystroke "escape") (atom-env/deactivate-proton-mode!) (do ;; append new key to chain (swap! current-chain conj (keyword (helpers/keystroke->keybinding keystroke))) ;; check if the current character sequence is a action (let [keymaps (keymap-manager/find-keybindings @current-chain)] (if (or (nil? keymaps) (empty? keymaps)) (atom-env/deactivate-proton-mode!) (if (keymap-manager/is-action? keymaps) (do (atom-env/deactivate-proton-mode!) (reset! current-chain []) (keymap-manager/exec-binding keymaps)) (when-not (atom-env/get-config "proton.core.whichKeyDisabled") (if (and (atom-env/get-config "proton.core.whichKeyDelayOnInit") (atom-env/bottom-panel-visible?)) (atom-env/update-bottom-panel (helpers/tree->html keymaps @current-chain)) (chain-delay #(atom-env/update-bottom-panel (helpers/tree->html keymaps @current-chain)))))))))))) (defn init [] (go (proton/init-proton-mode-keymaps!) (atom-env/insert-process-step! "Initialising proton... Just a moment!" "") (let [{:keys [additional-packages layers configuration disabled-packages keybindings keymaps]} (proton/load-config) editor-default editor-config/default proton-default proton-config/default] (let [all-layers (into [] (distinct (concat (:layers proton-default) layers))) all-configuration (reduce helpers/config-reducer [] (distinct (concat (:settings editor-default) (proton/configs-for-layers all-layers) configuration))) config-map (into (hash-map) all-configuration)] (atom-env/insert-process-step! "Initialising layers") (proton/init-layers! all-layers all-configuration) (atom-env/mark-last-step-as-completed!) (let [layer-packages (into [] (distinct (concat (proton/packages-for-layers all-layers) additional-packages))) selected-packages (into [] (distinct (concat layer-packages (:core-packages editor-default)))) all-keymaps (into [] (distinct (concat keymaps (:keymaps editor-default) (proton/keymaps-for-layers all-layers)))) all-keybindings (helpers/deep-merge (proton/keybindings-for-layers all-layers) keybindings) wipe-configs? (true? (config-map "proton.core.wipeUserConfigs")) all-packages (pm/register-packages (into (hash-map) (concat (map pm/register-installable selected-packages) (map pm/register-removable disabled-packages)))) to-install (pm/get-to-install all-packages) to-remove (pm/get-to-remove (filter (comp not pm/is-bundled?) all-packages))] ;; Show welcome screen if there are packages to install/remove or the option to always show is enabled (if (or (config-map "proton.core.alwaysShowWelcomeScreen") (> (count to-install) 0) (> (count to-remove) 0) ) (atom-env/show-modal-panel)) ;; wipe existing config (when wipe-configs? (do (atom-env/insert-process-step! "Wiping existing configuration") (doall (map atom-env/unset-config! (filter #(not (or (= "core.themes" %) (= "core.disabledPackages" %))) (atom-env/get-all-settings)))) (atom-env/mark-last-step-as-completed!))) (atom-env/set-config! "proton.core.selectedLayers" (clj->js (map #(subs (str %) 1) all-layers))) ; avoid duplicates (atom-env/set-config! "core.disabledPackages" (distinct (array-seq (atom-env/get-config "core.disabledPackages")))) ;; save commands into command tree (atom-env/insert-process-step! "Initialising keybinding tree") (atom-env/mark-last-step-as-completed!) ;; set all custom keybindings from layers + user config (atom-env/insert-process-step! "Applying layer keymaps") (doall (map #(atom-env/set-keymap! (:selector %) (:keymap %)) all-keymaps)) (atom-env/mark-last-step-as-completed!) ;; Install all necessary packages (if (> (count to-install) 0) (do (atom-env/insert-process-step! (str "Installing <span class='proton-status-package-count'>" (count to-install) "</span> new package(s)") "") (doseq [package to-install] (atom-env/insert-process-step! (str "Installing <span class='proton-status-package'>" (name package) "</span>")) (<! (pm/install-package (name package))) (atom-env/mark-last-step-as-completed!)))) ;; Remove deleted packages (if (> (count to-remove) 0) (do (atom-env/insert-process-step! (str "Removing <span class='proton-status-package-count'>" (count to-remove) "</span> orphaned package(s)") "") (doseq [package to-remove] (atom-env/insert-process-step! (str "Removing <span class='proton-status-package'>" (name package) "</span>")) (<! (pm/remove-package (name package))) (atom-env/mark-last-step-as-completed!)))) ;; set the user config (atom-env/insert-process-step! "Applying user configuration") (doall (map #(apply atom-env/set-config! %) all-configuration)) (proton/show-deprecated-configs all-configuration) (atom-env/mark-last-step-as-completed!) ;; Make sure all collected packages are definitely enabled (atom-env/insert-process-step! "Verifying package state") (proton/init-modes-for-layers all-layers) (pm/activate-packages!) (atom-env/mark-last-step-as-completed!) (atom-env/insert-process-step! "All done!" "") (mode-manager/activate-mode (atom-env/get-active-editor)) (keymap-manager/set-proton-leader-keys all-keybindings) (proton/init-proton-leader-keys! all-configuration) ;; Hide the welcome screen after a timeout if we showed it earlier (if (or (config-map "proton.core.alwaysShowWelcomeScreen") (> (count to-install) 0) (> (count to-remove) 0) ) (.setTimeout js/window #(atom-env/hide-modal-panel) (config-map "proton.core.post-init-timeout")))))))) (defn on-space [] (reset! current-chain []) (atom-env/activate-proton-mode!) (when-not (atom-env/get-config "proton.core.whichKeyDisabled") (chain-delay #(atom-env/update-bottom-panel (helpers/tree->html (keymap-manager/find-keybindings []) @current-chain))))) (defn on-mode-key [] (reset! current-chain []) (if-let [mode-keymap (keymap-manager/get-mode-keybindings (keymap-manager/get-current-editor-mode))] (let [core-mode-key (first mode-keys)] (swap! current-chain conj core-mode-key) (atom-env/activate-proton-mode!) (when-not (atom-env/get-config "proton.core.whichKeyDisabled") (chain-delay #(atom-env/update-bottom-panel (helpers/tree->html (keymap-manager/find-keybindings @current-chain) @current-chain))))))) (defn toggle [e] (if (helpers/is-proton-target? e) (if (atom-env/is-proton-mode-active?) (atom-env/deactivate-proton-mode!) (on-space)) (.abortKeyBinding e))) (defn toggle-mode [e] (if (helpers/is-proton-target? e) (if (atom-env/is-proton-mode-active?) (atom-env/deactivate-proton-mode!) (on-mode-key)) (.abortKeyBinding e))) (defn activate [state] (helpers/sync-env-path!) (.setTimeout js/window #(init) 2000) (pm/init-subscriptions!) (swap! disposables conj (proton/panel-item-subscription)) (.add atom-env/subscriptions (.add atom-env/commands "atom-workspace.proton-mode" "proton:chain" chain)) (.add atom-env/subscriptions (.add atom-env/commands "atom-workspace" "proton:toggle" toggle)) (.add atom-env/subscriptions (.add atom-env/commands "atom-workspace" "proton:toggleMode" toggle-mode))) (defn deactivate [] (.log js/console "deactivating...") (doseq [disposable @disposables] (.log js/console disposable) (.dispose disposable)) (keymap-manager/cleanup!) (mode-manager/cleanup!) (atom-env/clear-keymap!) (pm/cleanup!) (atom-env/reset-process-steps!)) (defn serialize [] nil) ;; live-reload ;; calls stop before hotswapping code ;; then start after all code is loaded ;; the return value of stop will be the argument to start (defn stop [] (let [state (serialize)] (deactivate) state)) (defn start [state] (activate state))
null
https://raw.githubusercontent.com/dvcrn/proton/427d83ffdb61d84a04e3d30032b792a9cfbfc53f/src/cljs/proton/core.cljs
clojure
tools etc langs config-files frameworks apps Atom for holding all disposables objects Atom that holds chain timeout id append new key to chain check if the current character sequence is a action Show welcome screen if there are packages to install/remove or the option to always show is enabled wipe existing config avoid duplicates save commands into command tree set all custom keybindings from layers + user config Install all necessary packages Remove deleted packages set the user config Make sure all collected packages are definitely enabled Hide the welcome screen after a timeout if we showed it earlier live-reload calls stop before hotswapping code then start after all code is loaded the return value of stop will be the argument to start
(ns proton.core (:require-macros [cljs.core.async.macros :refer [go go-loop]]) (:require [proton.lib.helpers :as helpers] [proton.lib.atom :as atom-env] [proton.lib.package_manager :as pm] [proton.lib.proton :as proton] [proton.lib.mode :as mode-manager] [proton.lib.keymap :as keymap-manager] [cljs.nodejs :as node] [clojure.string :as string :refer [join lower-case upper-case]] [proton.layers.base :as layerbase] [proton.layers.core.core :as core-layer] [proton.layers.tools.minimap.core] [proton.layers.tools.expose.core] [proton.layers.tools.git.core] [proton.layers.tools.linter.core] [proton.layers.tools.build.core] [proton.layers.tools.bookmarks.core] [proton.layers.tools.todo.core] [proton.layers.tools.terminal.core] [proton.layers.fun.power_mode.core] [proton.layers.lang.clojure.core] [proton.layers.lang.swift.core] [proton.layers.lang.csharp.core] [proton.layers.lang.python.core] [proton.layers.lang.julia.core] [proton.layers.lang.latex.core] [proton.layers.lang.markdown.core] [proton.layers.lang.elixir.core] [proton.layers.lang.elm.core] [proton.layers.lang.javascript.core] [proton.layers.lang.rust.core] [proton.layers.lang.html.core] [proton.layers.lang.go.core] [proton.layers.lang.ruby.core] [proton.layers.lang.json.core] [proton.layers.lang.css.core] [proton.layers.lang.sass.core] [proton.layers.lang.stylus.core] [proton.layers.lang.less.core] [proton.layers.lang.haml.core] [proton.layers.lang.slim.core] [proton.layers.lang.jade.core] [proton.layers.lang.handlebars.core] [proton.layers.lang.mustache.core] [proton.layers.lang.typescript.core] [proton.layers.lang.haskell.core] [proton.layers.config-files.docker.core] [proton.layers.frameworks.django.core] [proton.layers.frameworks.react.core] [proton.layers.apps.notes.core] [proton.config.editor :as editor-config] [proton.config.proton :as proton-config] [cljs.core.async :as async :refer [chan put! pub sub unsub >! <!]])) (def disposables (atom [])) (swap! disposables conj atom-env/subscriptions) (defonce current-chain (atom [])) (def chain-timer (atom nil)) (def mode-keys [:m (keyword ",")]) (defn is-mode-key? [chain-key] (not (nil? (some #{(first chain-key)} mode-keys)))) (defn- chain-delay [f] (reset! chain-timer (js/setTimeout f (* 1000 (atom-env/get-config "proton.core.whichKeyDelay"))))) (defn chain [e] (let [keystroke (helpers/extract-keystroke-from-event e)] check for ESC key (when-not (nil? @chain-timer) (js/clearTimeout @chain-timer)) (if (= keystroke "escape") (atom-env/deactivate-proton-mode!) (do (swap! current-chain conj (keyword (helpers/keystroke->keybinding keystroke))) (let [keymaps (keymap-manager/find-keybindings @current-chain)] (if (or (nil? keymaps) (empty? keymaps)) (atom-env/deactivate-proton-mode!) (if (keymap-manager/is-action? keymaps) (do (atom-env/deactivate-proton-mode!) (reset! current-chain []) (keymap-manager/exec-binding keymaps)) (when-not (atom-env/get-config "proton.core.whichKeyDisabled") (if (and (atom-env/get-config "proton.core.whichKeyDelayOnInit") (atom-env/bottom-panel-visible?)) (atom-env/update-bottom-panel (helpers/tree->html keymaps @current-chain)) (chain-delay #(atom-env/update-bottom-panel (helpers/tree->html keymaps @current-chain)))))))))))) (defn init [] (go (proton/init-proton-mode-keymaps!) (atom-env/insert-process-step! "Initialising proton... Just a moment!" "") (let [{:keys [additional-packages layers configuration disabled-packages keybindings keymaps]} (proton/load-config) editor-default editor-config/default proton-default proton-config/default] (let [all-layers (into [] (distinct (concat (:layers proton-default) layers))) all-configuration (reduce helpers/config-reducer [] (distinct (concat (:settings editor-default) (proton/configs-for-layers all-layers) configuration))) config-map (into (hash-map) all-configuration)] (atom-env/insert-process-step! "Initialising layers") (proton/init-layers! all-layers all-configuration) (atom-env/mark-last-step-as-completed!) (let [layer-packages (into [] (distinct (concat (proton/packages-for-layers all-layers) additional-packages))) selected-packages (into [] (distinct (concat layer-packages (:core-packages editor-default)))) all-keymaps (into [] (distinct (concat keymaps (:keymaps editor-default) (proton/keymaps-for-layers all-layers)))) all-keybindings (helpers/deep-merge (proton/keybindings-for-layers all-layers) keybindings) wipe-configs? (true? (config-map "proton.core.wipeUserConfigs")) all-packages (pm/register-packages (into (hash-map) (concat (map pm/register-installable selected-packages) (map pm/register-removable disabled-packages)))) to-install (pm/get-to-install all-packages) to-remove (pm/get-to-remove (filter (comp not pm/is-bundled?) all-packages))] (if (or (config-map "proton.core.alwaysShowWelcomeScreen") (> (count to-install) 0) (> (count to-remove) 0) ) (atom-env/show-modal-panel)) (when wipe-configs? (do (atom-env/insert-process-step! "Wiping existing configuration") (doall (map atom-env/unset-config! (filter #(not (or (= "core.themes" %) (= "core.disabledPackages" %))) (atom-env/get-all-settings)))) (atom-env/mark-last-step-as-completed!))) (atom-env/set-config! "proton.core.selectedLayers" (clj->js (map #(subs (str %) 1) all-layers))) (atom-env/set-config! "core.disabledPackages" (distinct (array-seq (atom-env/get-config "core.disabledPackages")))) (atom-env/insert-process-step! "Initialising keybinding tree") (atom-env/mark-last-step-as-completed!) (atom-env/insert-process-step! "Applying layer keymaps") (doall (map #(atom-env/set-keymap! (:selector %) (:keymap %)) all-keymaps)) (atom-env/mark-last-step-as-completed!) (if (> (count to-install) 0) (do (atom-env/insert-process-step! (str "Installing <span class='proton-status-package-count'>" (count to-install) "</span> new package(s)") "") (doseq [package to-install] (atom-env/insert-process-step! (str "Installing <span class='proton-status-package'>" (name package) "</span>")) (<! (pm/install-package (name package))) (atom-env/mark-last-step-as-completed!)))) (if (> (count to-remove) 0) (do (atom-env/insert-process-step! (str "Removing <span class='proton-status-package-count'>" (count to-remove) "</span> orphaned package(s)") "") (doseq [package to-remove] (atom-env/insert-process-step! (str "Removing <span class='proton-status-package'>" (name package) "</span>")) (<! (pm/remove-package (name package))) (atom-env/mark-last-step-as-completed!)))) (atom-env/insert-process-step! "Applying user configuration") (doall (map #(apply atom-env/set-config! %) all-configuration)) (proton/show-deprecated-configs all-configuration) (atom-env/mark-last-step-as-completed!) (atom-env/insert-process-step! "Verifying package state") (proton/init-modes-for-layers all-layers) (pm/activate-packages!) (atom-env/mark-last-step-as-completed!) (atom-env/insert-process-step! "All done!" "") (mode-manager/activate-mode (atom-env/get-active-editor)) (keymap-manager/set-proton-leader-keys all-keybindings) (proton/init-proton-leader-keys! all-configuration) (if (or (config-map "proton.core.alwaysShowWelcomeScreen") (> (count to-install) 0) (> (count to-remove) 0) ) (.setTimeout js/window #(atom-env/hide-modal-panel) (config-map "proton.core.post-init-timeout")))))))) (defn on-space [] (reset! current-chain []) (atom-env/activate-proton-mode!) (when-not (atom-env/get-config "proton.core.whichKeyDisabled") (chain-delay #(atom-env/update-bottom-panel (helpers/tree->html (keymap-manager/find-keybindings []) @current-chain))))) (defn on-mode-key [] (reset! current-chain []) (if-let [mode-keymap (keymap-manager/get-mode-keybindings (keymap-manager/get-current-editor-mode))] (let [core-mode-key (first mode-keys)] (swap! current-chain conj core-mode-key) (atom-env/activate-proton-mode!) (when-not (atom-env/get-config "proton.core.whichKeyDisabled") (chain-delay #(atom-env/update-bottom-panel (helpers/tree->html (keymap-manager/find-keybindings @current-chain) @current-chain))))))) (defn toggle [e] (if (helpers/is-proton-target? e) (if (atom-env/is-proton-mode-active?) (atom-env/deactivate-proton-mode!) (on-space)) (.abortKeyBinding e))) (defn toggle-mode [e] (if (helpers/is-proton-target? e) (if (atom-env/is-proton-mode-active?) (atom-env/deactivate-proton-mode!) (on-mode-key)) (.abortKeyBinding e))) (defn activate [state] (helpers/sync-env-path!) (.setTimeout js/window #(init) 2000) (pm/init-subscriptions!) (swap! disposables conj (proton/panel-item-subscription)) (.add atom-env/subscriptions (.add atom-env/commands "atom-workspace.proton-mode" "proton:chain" chain)) (.add atom-env/subscriptions (.add atom-env/commands "atom-workspace" "proton:toggle" toggle)) (.add atom-env/subscriptions (.add atom-env/commands "atom-workspace" "proton:toggleMode" toggle-mode))) (defn deactivate [] (.log js/console "deactivating...") (doseq [disposable @disposables] (.log js/console disposable) (.dispose disposable)) (keymap-manager/cleanup!) (mode-manager/cleanup!) (atom-env/clear-keymap!) (pm/cleanup!) (atom-env/reset-process-steps!)) (defn serialize [] nil) (defn stop [] (let [state (serialize)] (deactivate) state)) (defn start [state] (activate state))
14804998230dab824953b969650ee0ea982db5201b2b62e06f0756a21f548eb1
clj-kondo/clj-kondo
core.clj
(ns clj-kondo.impl.types.clojure.core {:no-doc true} (:require [clj-kondo.impl.types.utils :as tu])) ;; sorted in order of appearance in ;; a lot of this work was already figured out here: ;; (def seqable->seq {:arities {1 {:args [:seqable] :ret :seq}}}) (def seqable->boolean {:arities {1 {:args [:seqable] :ret :boolean}}}) (def seqable->any {:arities {1 {:args [:seqable] :ret :any}}}) (def any->boolean {:arities {1 {:ret :boolean}}}) ;; arity-1 function that returns the same type (def a->a {:arities {1 {:args [:any]}} :fn #(:tag (first %))}) (def number->number {:arities {1 {:args [:number] :ret :number}}}) (def number->number->number {:arities {2 {:args [:number :number] :ret :number}}}) (def number*->number {:arities {:varargs {:args [{:op :rest :spec :number}] :ret :number}}}) (def number+->number {:arities {:varargs {:args [:number {:op :rest :spec :number}] :ret :number}}}) (def number->boolean {:arities {:varargs {:args [:number] :ret :boolean}}}) (def compare-numbers {:arities {:varargs {:args [{:op :rest :spec :number}] :ret :boolean}}}) (def int->int {:arities {1 {:args [:int] :ret :int}}}) (def int->int->int {:arities {2 {:args [:int :int] :ret :int}}}) (def clojure-core {'if {:fn (fn [[_ then else]] (tu/union-type then else))} 'let {:fn last} 16 'list {:arities {:varargs {:ret :list}}} 22 'cons {:arities {2 {:args [:any :seqable]}}} 49 'first seqable->any 57 'next seqable->seq 66 'rest seqable->seq 75 'conj {:arities {0 {:args [:nilable/coll] :ret :coll} :varargs {:args [:nilable/coll {:op :rest :spec :any}] :ret :coll}}} 91 'second seqable->any 98 'ffirst seqable->any 105 'nfirst seqable->seq 112 'fnext seqable->any 119 'nnext seqable->seq 126 'seq {:arities {1 {:args [:seqable] :ret :seq}}} 139 'instance? any->boolean 146 'seq? any->boolean 153 'char? any->boolean 160 'string? any->boolean 167 'map? any->boolean 181 'assoc {:arities {3 {:args [:nilable/associative :any :any]} :varargs {:min-arity 3 :args '[:nilable/associative :any :any {:op :rest :spec [:any :any]}]}} :fn (fn [args] (let [farg (first args)] (if-let [t (:tag farg)] (case t :map :map :vector :vector (if (and (map? t) (identical? :map (:type t))) t :associative)) :associative)))} 202 'meta {:arities {1 {:ret :nilable/map}}} 211 'with-meta a->a 262 'last seqable->any 272 'butlast seqable->seq 283 ' defn 338 ' to - array 346 ' cast 353 'vector {:arities {:varargs {:ret :vector}}} 367 'vec {:arities {1 {:ret :vector}}} 379 'hash-map {:arities {:varargs {:args [{:op :rest :spec [:any :any]}] :ret :map}}} 389 'hash-set {:arities {:varargs {:ret :set}}} 398 'sorted-map {:arities {:varargs {:ret :sorted-map}}} ;; 407 'sorted-map-by 417 ' sorted - set 425 ' sorted - set - by 436 'nil? any->boolean 444 ' defmacro 493 ' when 'when {:fn (fn [args] (tu/union-type :nil (last args)))} 499 ' when - not 'when-not {:fn (fn [args] (tu/union-type :nil (last args)))} 505 'false? any->boolean 512 'true? any->boolean 519 'boolean? any->boolean 524 'not any->boolean 531 'some? any->boolean 538 'any? any->boolean 544 'str {:arities {:varargs {:args [{:op :rest :spec :any}] :ret :string}}} 562 'symbol? any->boolean 568 'keyword? any->boolean 574 ' cond 'cond {:fn (fn [args] (loop [args (seq args) last-cond nil rets []] (if args (let [next-cond (first args) args (rest args) next-ret (first args) args (next args)] (recur args next-cond (conj rets next-ret))) (if (identical? :keyword (:tag last-cond)) (reduce tu/union-type #{} rets) (reduce tu/union-type :nil rets)))))} 589 'symbol {:arities {1 {:args [#{:symbol :string :keyword}] :ret :symbol} 2 {:args [:nilable/string :string] :ret :symbol}}} 604 ' 614 ' keyword 'keyword {:arities {1 {:args [#{:symbol :string :keyword}] :ret :keyword} 2 {:args [:nilable/string :string] :ret :keyword}}} 625 ' find - keyword 648 'list* {:arities {:varargs {:args [{:op :rest :spec :any :last :seqable}] :ret :list}}} 660 'apply {:arities {:varargs {:args [:ifn {:op :rest :spec :any :last :seqable}] :ret :any}}} 675 ' vary - meta 'lazy-seq {:arities {:varargs {:ret :seq}}} 692 ' chunk - buffer ;; 695 'chunk-append 698 ' chunk 701 ' chunk - first 704 ' chunk - rest 707 ' chunk - next ;; 710 'chunk-cons 715 'chunked-seq? any->boolean 718 'concat {:arities {:varargs {:args [{:op :rest :spec :seqable}] :ret :seq}}} 746 ' delay 755 'delay? any->boolean 761 ' force ;; 767 'if-not 775 'identical? {:arities {2 {:ret :boolean}}} 783 '= {:arities {:varargs {:ret :boolean}}} 819 'not= {:arities {:varargs {:ret :boolean}}} 831 ' compare 'compare {:arities {2 {:ret :number}}} 842 ' and 'and {:fn (fn [args] (reduce tu/union-type :nil args))} 854 ' or 'or {:fn (fn [args] (reduce tu/union-type #{} args))} 867 'zero? any->boolean 874 'count {:arities {1 {:args [:seqable] :ret :number}}} 882 'int {:arities {1 {:args [#{:number :char}] :ret :int}}} 889 'nth {:arities {2 {:args [:seqable :int] :ret :any} 3 {:args [:seqable :int :any] :ret :any}}} 900 '< compare-numbers 915 'inc' number->number 922 'inc number->number 947 'reverse {:arities {1 {:args [:seqable]}} :ret :seq} 972 '+' number*->number 984 '+ number*->number 996 '*' number*->number 1008 '* number*->number 1020 '/ number+->number ;; 1031 '-' number+->number ;; 1043 '- number+->number 1055 '<= compare-numbers ;; 1070 '> compare-numbers 1085 '>= compare-numbers 1100 '== compare-numbers 1115 'max number+->number 1125 'min number+->number 1135 'dec' number->number 1142 'dec number->number 1149 'unchecked-inc-int int->int 1156 'unchecked-inc number->number 1163 'unchecked-dec-int int->int 1170 'unchecked-dec number->number 1177 'unchecked-negate-int int->int 1184 'unchecked-negate number->number 1191 'unchecked-add-int int->int->int 1198 'unchecked-add number->number->number 1205 'unchecked-subtract-int int->int->int 1212 'unchecked-subtract number->number->number 1219 'unchecked-multiply-int int->int->int 1226 'unchecked-multiply number->number->number 1233 'unchecked-divide-int int->int->int 1240 'unchecked-remainder-int int->int->int 1247 'pos? number->boolean 1254 'neg? number->boolean 1261 'quot number->number->number 1269 'rem number->number->number 1277 'rationalize number->number ;; 1286 'bit-not 1293 ' bit - and ;; 1302 'bit-or 1311 ' bit - xor ;; 1320 'bit-and-not 1331 ' bit - clear ;; 1337 'bit-set ;; 1343 'bit-flip 1349 ' bit - test ;; 1356 'bit-shift-left ;; 1362 'bit-shift-right 1368 ' unsigned - bit - shift - right 1374 'integer? any->boolean 1386 'even? number->boolean 1394 'odd? number->boolean 1400 'int? any->boolean 1408 'pos-int? any->boolean 1414 'neg-int? any->boolean 1420 'nat-int? any->boolean 1426 'double? any->boolean 1433 'complement {:arities {1 {:args [:ifn] :ret :fn}}} 1445 'constantly {:arities {1 {:ret :fn}}} 1451 'identity a->a 1459 'peek {:arities {1 {:args [:stack] :ret :any}}} 1467 'pop {:arities {1 {:args [:stack] :ret :stack}}} 1478 'map-entry? any->boolean 1484 ' contains ? 'contains? {:arities {2 {:args [#{:associative :set :string} :any] :ret :boolean}}} NOTE : get is an any->any function on any object that implements . ;; 1494 'get ;; 1504 'dissoc {:arities {:varargs {:args [:nilable/map {:op :rest :spec :any}] :ret :nilable/map}}} 1518 ' disj 1534 'find {:arities {2 {:args [:nilable/associative :any]}}} 1540 'select-keys {:arities {2 {:args [:nilable/associative :seqable] :ret :map}}} 1555 NOTE : keys and vals can be called on seqs of MapEntry 's , hence not : associative . 'keys {:arities {1 {:args [:seqable] :ret :seq}}} 1561 'vals {:arities {1 {:args [:seqable] :ret :seq}}} 1567 ' key ;; 1574 'val 1581 'rseq {:arities {1 {:args [#{:vector :sorted-map}] :req :seq}}} ;; 1589 'name 1597 'namespace {:arities {1 {:ret :string}}} 1605 'boolean any->boolean 1612 'ident? any->boolean 1617 'simple-ident? any->boolean 1622 'qualified-ident? any->boolean 1627 'simple-symbol? any->boolean 1632 'qualified-symbol? any->boolean 1637 'simple-keyword? any->boolean 1642 'qualified-keyword? any->boolean 1647 ' locking ;; 1659 '.. ;; 1677 '-> 1693 ' - > > 1723 ' global - hierarchy 1725 ' defmulti 1783 ' defmethod ;; 1789 'remove-all-methods 1796 ' remove - method 1803 ' prefer - method 1811 ' methods ;; 1817 'get-method 1824 ' prefers 1841 ' if - let 'if-let {:fn (fn [[_ then else]] (tu/union-type then else))} 1861 ' when - let 'when-let {:fn (fn [args] (tu/union-type :nil (last args)))} 1876 ' if - some 1896 ' when - some 1913 ' push - thread - bindings 1931 ' pop - thread - bindings 1939 ' get - thread - bindings 1947 ' binding 1973 ' with - bindings * 1986 ' with - bindings 1994 ' bound - fn * 2006 ' bound - fn 2015 ' find - var ;; 2054 'agent ' set - agent - send - executor ! ;; 2095 'set-agent-send-off-executor! ;; 2101 'send-via 2111 ' send 2122 ' send - off 2133 ' release - pending - sends ;; 2144 'add-watch ;; 2162 'remove-watch 2169 ' agent - error 2177 ' restart - agent 2194 ' set - error - handler ! 2204 ' error - handler ;; 2212 'set-error-mode! 2229 ' error - mode 2236 ' agent - errors 2246 ' clear - agent - errors 2254 ' shutdown - agents ;; 2262 'ref 2306 ' deref 2327 'atom {:ret :atom} 2345 'swap! {:arities {:varargs {:args [:atom :ifn [{:op :rest :spec :any}]] :ret :any}}} 2357 ' swap - vals ! 2368 ' compare - and - set ! 2376 'reset! {:arities {2 {:args [:atom :any] :ret :any}}} 2383 ' reset - vals ! 2389 ' set - validator ! ;; 2400 'get-validator 2406 ' alter - meta ! 2416 ' reset - meta ! 2422 ' commute 2443 ' alter ;; 2455 'ref-set 2463 ' ref - history - count 2470 ' ref - min - history ;; 2479 'ref-max-history 2488 ' ensure ;; 2498 'sync ;; 2512 'io! 2525 ' volatile ! 2532 ' vreset ! 2539 ' vswap ! 2548 'volatile? any->boolean 2557 'comp {:arities {:varargs [{:op :rest :spec :ifn}] :ret :ifn}} 2576 'juxt {:arities {:varargs {:args [:ifn {:op :rest :spec :ifn}] :ret :ifn}}} 2614 'partial {:arities {:varargs {:args [:ifn {:op :rest :spec :any}] :ret :ifn}}} 2647 ' sequence 2672 'every? {:arities {2 {:args [:ifn :seqable] :ret :boolean}}} 2684 'not-every? {:arities {2 {:args [:ifn :seqable] :ret :boolean}}} 2693 'some {:arities {2 {:args [:ifn :seqable] :ret :any}}} 2703 'not-any? {:arities {2 {:args [:ifn :seqable] :ret :boolean}}} 2712 ' dotimes 2727 'map {:arities {1 {:args [:ifn] :ret :transducer} :varargs {:args '[:ifn :seqable [{:op :rest :spec :seqable}]] :ret :seq}}} 2776 ' declare ;; 2781 'cat 2783 'mapcat {:arities {1 {:args [:ifn] :ret :transducer} :varargs {:args '[:ifn :seqable [{:op :rest :spec :seqable}]] :ret :seq}}} 2793 'filter {:arities {1 {:args [:ifn] :ret :transducer} 2 {:args [:ifn :seqable] :ret :seq}}} 2826 'remove {:arities {1 {:args [:ifn] :ret :transducer} 2 {:args [:ifn :seqable] :ret :seq}}} 2836 ' reduced 2842 'reduced? any->boolean ;; 2849 'ensure-reduced 2855 ' unreduced 2861 'take {:arities {1 {:args [:nat-int] :ret :transducer} 2 {:args [:nat-int :seqable] :ret :seq}}} 2888 'take-while {:arities {1 {:args [:ifn] :ret :transducer} 2 {:args [:ifn :seqable] :ret :seq}}} 2909 'drop {:arities {1 {:args [:nat-int] :ret :transducer} 2 {:args [:nat-int :seqable] :ret :seq}}} 2934 'drop-last {:arities {1 {:args [:seqable] :ret :seq} 2 {:args [:nat-int :seqable] :ret :seq}}} 2941 'take-last {:arities {2 {:args [:nat-int :seqable] :ret :seq}}} 2952 'drop-while {:arities {1 {:args [:ifn] :ret :transducer} 2 {:args [:ifn :seqable] :ret :seq}}} 2979 'cycle seqable->seq 2985 'split-at {:arities {2 {:args [:nat-int :seqable] :ret :vector}}} 2992 'split-with {:arities {2 {:args [:ifn :seqable] :ret :vector}}} 2999 'repeat {:arities {1 {:args [:any] :ret :seq} 2 {:args [:nat-int :any]}}} ;; 3006 'replicate (deprecated) 3013 'iterate {:arities {2 {:args [:ifn :any] :ret :seq}}} 3019 'range {:arities {0 {:ret :seq} 1 {:args [:number] :ret :seq} 2 {:args [:number :number] :ret :seq} 3 {:args [:number :number :number] :ret :seq}}} 3041 'merge {:arities {:varargs {:args [{:op :rest :spec :seqable}] :ret :nilable/map}}} 3051 'merge-with {:arities {:varargs {:args [:ifn {:op :rest :spec :seqable}] :ret :nilable/map}}} 3071 'zipmap {:arities {2 {:args [:seqable :seqable] :ret :map}}} 3085 ' line - seq 3094 ' comparator 3102 ' sort 3119 ' sort - by ;; 3133 'dorun 3148 ' doall 3164 ' nthnext 3174 ' nthrest 3184 'partition {:arities {2 {:args [:int :seqable] :ret :seq} 3 {:args [:int :int :seqable] :ret :seq} 4 {:args [:int :int :seqable :seqable] :ret :seq}}} 3210 ' eval ;; 3216 'doseq ;; 3274 'await 3291 ' await1 ;; 3296 'await-for 3313 ' dotimes ;; 3342 'transient 3349 ' persistent ! 3358 ' conj ! ;; 3368 'assoc! 3381 ' dissoc ! 3392 ' pop ! 3400 ' disj ! 3425 ' import ;; 3443 'into-array 3460 ' class ;; 3466 'type 3473 ' num ;; 3480 'long ;; 3486 'float 3492 ' double ;; 3498 'short ;; 3504 'byte 'byte {:arities {1 {:args [#{:byte :number :char}] :ret :byte}}} 3510 ' char ;; 3516 'unchecked-byte 3522 ' unchecked - short 3528 ' unchecked - char 3534 ' unchecked - int ;; 3540 'unchecked-long ;; 3546 'unchecked-float 3552 ' unchecked - double 3559 'number? any->boolean ;; 3566 'mod 3576 'ratio? any->boolean 3582 ' numerator ;; 3590 'denominator ;; 3598 'decimal? any->boolean 3604 'float? any->boolean 3612 'rational? any->boolean 3619 ' bigint 3633 ' biginteger 3647 ' bigdec 3663 ' print - method ;; 3666 'print-dup 3677 ' pr 3697 ' newline ;; 3705 'flush ;; 3714 'prn 3724 ' print ;; 3733 'println ;; 3741 'read 3770 ' read+string 3796 ' read - line 3805 ' read - string 3818 'subvec {:arities {2 {:args [:vector :nat-int] :ret :vector} 3 {:args [:vector :nat-int :nat-int] :ret :vector}}} 3831 ' with - open 3852 ' doto ;; 3871 'memfn ;; 3884 'time 3898 ' ;; 3905 'aclone 3912 ' aget ;; 3923 'aset 3986 ' make - array ;; 4003 'to-array-2d ;; 4018 'macroexpand-1 4026 ' macroexpand 4038 ' create - struct ;; 4045 'defstruct ;; 4052 'struct-map ;; 4062 'struct 4071 ' accessor 4082 ' load - reader 4089 ' load - string 4099 'set? any->boolean ;; 4105 'set {:ret :set} ;; 4126 'find-ns ;; 4132 'create-ns ;; 4140 'remove-ns 4147 ' all - ns ;; 4153 'the-ns 4164 ' ns - name ;; 4171 'ns-map ' ns - unmap 4189 ' ns - publics 4200 ' ns - imports ;; 4207 'ns-interns 4217 ' refer 4254 ' ns - refers 4264 ' alias 4274 ' ns - aliases 4281 ' ns - unalias 4288 'take-nth {:arities {1 {:args [:int] :ret :transducer} 2 {:args [:int :seqable] :ret :seq}}} ;; 4309 'interleave 4327 ' var - get ;; 4333 'var-set 4340 ' with - local - vars 4359 ' ns - resolve 4372 ' resolve 4379 ' array - map 4389 ' destructure 4481 ' let 4513 ' fn 'fn {:arities {:varargs {:ret :fn}}} 4575 ' loop 4600 ' when - first 4614 ' lazy - cat ;; 4624 'for 'for {:arities {2 {:ret :seq}}} ;; 4711 'comment 4716 ' with - out - str ;; 4727 'with-in-str 4736 ' pr - str ;; 4745 'prn-str 4754 ' print - str 4763 ' println - str ;; 4794 'ex-info 'ex-info {:arities {2 {:args [:nilable/string :map] :ret :throwable} 3 {:args [:nilable/string :map :any] :ret :throwable}}} 4803 ' ex - data 4800 ' ex - message 4808 ' ex - cause 4816 ' assert 4829 ' test 4839 're-pattern {:arities {1 {:args [#{:string :regex}] ;; arg can also be a regex... :ret :regex}}} 4849 're - matcher 4858 're - groups 4874 're-seq {:arities {2 {:args [:regex :string] :ret :seq}}} 4886 're-matches {:arities {2 {:args [:regex :string] :ret #{:vector :string}}}} 4898 're-find {:arities {1 {:args [:any] ;; matcher :ret #{:vector :string}} 2 {:args [:regex :string] :ret #{:vector :string}}}} ;; 4911 'rand 4919 ' rand - int ;; 4925 'defn- 4931 ' tree - seq 'tree-seq {:arities {3 {:args [:ifn :ifn :any] :ret :seq}}} 4948 ' file - seq ;; 4958 'xml-seq 4968 'special-symbol? any->boolean 4975 'var? any->boolean 4981 'subs {:arities {2 {:args [:string :nat-int] :ret :string} 3 {:args [:string :nat-int :nat-int] :ret :string}}} 4989 'max-key {:arities {:varargs {:args [:ifn :any {:op :rest :spec :any}] :ret :any}}} 5009 'min-key {:arities {:varargs {:args [:ifn :any {:op :rest :spec :any}] :ret :any}}} 5029 'distinct {:arities {0 {:args [] :ret :transducer} 1 {:args [:seqable] :ret :seq}}} 5058 ' replace ;; 5076 'dosync 5086 ' with - precision 5109 ' subseq 5126 ' rsubseq 5143 ' repeatedly ;; 5152 'add-classpath 5165 ' hash ;; 5175 'mix-collection-hash 5186 ' hash - ordered - coll 5195 ' hash - unordered - coll 5206 'interpose {:arities {1 {:args [:any] :ret :transducer} 2 {:args [:any :seqable] :ret :seq}}} 5229 ' definline ;; 5241 'empty 5249 ' amap ;; 5265 'areduce 5277 ' float - array 5285 ' boolean - array 5293 ' byte - array ;; 5301 'char-array 5309 ' short - array 5317 ' double - array 5325 ' object - array ;; 5332 'int-array 5340 ' long - array 5348 ' booleans 5353 ' bytes 5358 ' chars 5363 ' shorts ;; 5368 'floats 5373 ' ints ;; 5378 'doubles 5383 ' longs 5388 'bytes? any->boolean 5397 ' seque 5443 'class? any->boolean ;; 5505 'alter-var-root 5512 ' bound ? 5520 ' thread - bound ? 5528 ' make - hierarchy ;; 5537 'not-empty 5543 ' bases ;; 5553 'supers 5564 ' isa ? 5585 ' parents 5598 ' ancestors ;; 5614 'descendants ;; 5626 'derive 5662 ' flatten 5664 ' underive ;; 5685 'distinct? 5702 ' resultset - seq ;; 5721 'iterator-seq ;; 5731 'enumeration-seq 5738 ' format 'format {:arities {:varargs {:args [:string {:op :rest :spec :any}] :ret :string}}} 5746 ' printf 5753 ' gen - class ;; 5755 'with-loading-context 5764 ' ns 5822 ' refer - clojure ;; 5828 'defonce ;; 6007 'require ;; 6082 'requiring-resolve 6093 ' use 6104 ' loaded - libs 6109 ' load ;; 6128 'compile 6142 'get-in {:arities {2 {:args [:nilable/associative :seqable] :ret :any} 3 {:args [:nilable/associative :seqable :any] :ret :any}}} 6152 'assoc-in {:arities {3 {:args [:nilable/associative :seqable :any] :ret :associative}}} 6172 'update-in {:arities {:varargs {:args [:nilable/associative :seqable :ifn {:op :rest :spec :any}] :ret :associative}}} 6188 'update {:arities {:varargs {:args [:nilable/associative :any :ifn {:op :rest :spec :any}] :ret :associative}}} ;; 6206 'empty? 'empty? seqable->boolean 6213 'coll? any->boolean 6219 'list? any->boolean 6225 'seqable? any->boolean 6230 'ifn? any->boolean ;; 6237 'fn? any->boolean 6244 'associative? any->boolean 6250 'sequential? any->boolean 6256 'sorted? any->boolean 6262 'counted? any->boolean 6268 'reversible? any->boolean 6274 'indexed? any->boolean 6279 ' * 1 6284 ' * 2 6289 ' * 3 6294 ' * e ;; 6299 'trampoline 6317 ' intern 6333 ' while 6343 ' memoize 6359 ' condp 6530 'future? any->boolean 6536 ' future - done ? 6543 ' letfn 6556 'fnil {:arities {2 {:args [:ifn :any] :ret :ifn} 3 {:args [:ifn :any :any] :ret :ifn} 4 {:args [:ifn :any :any :any] :ret :ifn}}} ;; 6697 'case ;; 6780 'Inst ;; 6780 'inst-ms* ;; 6787 'inst-ms 6793 'inst? any->boolean 6805 'uuid? any->boolean 6810 'reduce {:arities {2 {:args [:ifn :seqable] :ret :any} 3 {:args [:ifn :any :seqable] :ret :any}}} ;; 6847 'reduce-kv ;; 6858 'completing 6870 ' transduce 6887 'into {:arities {0 {:args [] :ret :coll} 1 {:args [:coll]} 2 {:args [:coll :seqable]} 3 {:args [:coll :transducer :seqable]}} :fn (fn [args] (let [t (:tag (first args))] (if (identical? :any t) :coll t)))} 6903 'mapv {:arities {1 {:args [:ifn] :ret :transducer} :varargs {:args '[:ifn :seqable {:op :rest :spec :seqable}] :ret :vector}}} 6921 'filterv {:arities {2 {:args [:ifn :seqable] :ret :vector}}} 6942 ' slurp ;; 6954 'spit ;; 6963 'future-call 6990 ' future ;; 7000 'future-cancel 7006 ' future - cancelled ? 7012 ' pmap ;; 7037 'pcalls ;; 7044 'pvalues 7069 ' * clojure - version * 7081 ' clojure - version ;; 7096 'promise ;; 7127 'deliver 7136 'flatten {:arities {1 {:args [:nilable/sequential] :ret :sequential}}} ;; 7146 'group-by {:arities {2 {:args [:ifn :seqable] :ret :map}}} 7160 'partition-by {:arities {1 {:args [:ifn] :ret :transducer} 2 {:args [:ifn :seqable] :ret :seq}}} 7203 'frequencies {:arities {1 {:args [:seqable] :ret :map}}} 7214 ' reductions ;; 7231 'rand-nth ;; 7240 'partition-all {:arities {1 {:args [:int] :ret :transducer} 2 {:args [:int :seqable] :ret :seq} 3 {:args [:int :int :seqable] :ret :seq}}} 7274 'shuffle {:arities {1 {:args [:coll] :ret :coll}}} ;; 7283 'map-indexed {:arities {1 {:args [:ifn] :ret :transducer} 2 {:args [:ifn :seqable] :ret :seq}}} 7313 'keep {:arities {1 {:args [:ifn] :ret :transducer} 2 {:args [:ifn :seqable] :ret :seq}}} ;; 7283 'keep-indexed {:arities {1 {:args [:ifn] :ret :transducer} 2 {:args [:ifn :seqable] :ret :seq}}} ;; 7384 'bounded-count 7396 'every-pred {:arities {:varargs {:args [:ifn {:op :rest :spec :ifn}] :ret :ifn}}} 7436 'some-fn {:arities {:varargs {:args [:ifn {:op :rest :spec :ifn}] :ret :ifn}}} 7498 ' with - redefs - fn ;; 7518 'with-redefs ;; 7533 'realized? ;; 7538 'cond-> ;; 7555 'cond->> ;; 7572 'as-> 7584 ' some- > ;; 7598 'some->> 7619 ' cat 7631 ' halt - when 7655 'dedupe {:arities {0 {:args [] :ret :transducer} 1 {:args [:seqable] :ret :seq}}} ;; 7673 'random-sample ;; 7682 'Eduction ;; 7682 '->Eduction 7694 ' eduction 7710 ' run ! ;; 7719 'tagged-literal? any->boolean 7725 ' tagged - literal ;; 7732 'reader-conditional? any->boolean ;; 7738 'reader-conditional 7750 ' default - data - readers 7758 ' * data - readers * 7787 ' * default - data - reader - fn * 7845 'uri? any->boolean ;; 7868 'add-tap ;; 7879 'remove-tap ;; 7886 'tap> }) (def cljs-core (assoc clojure-core 'keyword {:arities {1 {:args [#{:string :keyword :symbol}] :ret :keyword} 2 {:args [#{:nilable/string :keyword :symbol} #{:string :keyword :symbol}] :ret :keyword}}}))
null
https://raw.githubusercontent.com/clj-kondo/clj-kondo/b5827368ea71413efa6fe9306bcdaa0c61da753b/src/clj_kondo/impl/types/clojure/core.clj
clojure
sorted in order of appearance in a lot of this work was already figured out here: arity-1 function that returns the same type 407 'sorted-map-by 695 'chunk-append 710 'chunk-cons 767 'if-not 1031 1043 1070 1286 'bit-not 1302 'bit-or 1320 'bit-and-not 1337 'bit-set 1343 'bit-flip 1356 'bit-shift-left 1362 'bit-shift-right 1494 'get 1504 1574 'val 1589 'name 1659 '.. 1677 '-> 1789 'remove-all-methods 1817 'get-method 2054 'agent 2095 'set-agent-send-off-executor! 2101 'send-via 2144 'add-watch 2162 'remove-watch 2212 'set-error-mode! 2262 'ref 2400 'get-validator 2455 'ref-set 2479 'ref-max-history 2498 'sync 2512 'io! 2781 'cat 2849 'ensure-reduced 3006 'replicate (deprecated) 3133 'dorun 3216 'doseq 3274 'await 3296 'await-for 3342 'transient 3368 'assoc! 3443 'into-array 3466 'type 3480 'long 3486 'float 3498 'short 3504 'byte 3516 'unchecked-byte 3540 'unchecked-long 3546 'unchecked-float 3566 'mod 3590 'denominator 3598 3666 'print-dup 3705 'flush 3714 'prn 3733 'println 3741 'read 3871 'memfn 3884 'time 3905 'aclone 3923 'aset 4003 'to-array-2d 4018 'macroexpand-1 4045 'defstruct 4052 'struct-map 4062 'struct 4105 4126 'find-ns 4132 'create-ns 4140 'remove-ns 4153 'the-ns 4171 'ns-map 4207 'ns-interns 4309 'interleave 4333 'var-set 4624 'for 4711 'comment 4727 'with-in-str 4745 'prn-str 4794 'ex-info arg can also be a regex... matcher 4911 'rand 4925 'defn- 4958 'xml-seq 5076 'dosync 5152 'add-classpath 5175 'mix-collection-hash 5241 'empty 5265 'areduce 5301 'char-array 5332 'int-array 5368 'floats 5378 'doubles 5505 'alter-var-root 5537 'not-empty 5553 'supers 5614 'descendants 5626 'derive 5685 'distinct? 5721 'iterator-seq 5731 'enumeration-seq 5755 'with-loading-context 5828 'defonce 6007 'require 6082 'requiring-resolve 6128 'compile 6206 'empty? 6237 6299 'trampoline 6697 'case 6780 'Inst 6780 'inst-ms* 6787 'inst-ms 6847 'reduce-kv 6858 'completing 6954 'spit 6963 'future-call 7000 'future-cancel 7037 'pcalls 7044 'pvalues 7096 'promise 7127 'deliver 7146 7231 'rand-nth 7240 7283 7283 7384 'bounded-count 7518 'with-redefs 7533 'realized? 7538 'cond-> 7555 'cond->> 7572 'as-> 7598 'some->> 7673 'random-sample 7682 'Eduction 7682 '->Eduction 7719 7732 7738 'reader-conditional 7868 'add-tap 7879 'remove-tap 7886 'tap>
(ns clj-kondo.impl.types.clojure.core {:no-doc true} (:require [clj-kondo.impl.types.utils :as tu])) (def seqable->seq {:arities {1 {:args [:seqable] :ret :seq}}}) (def seqable->boolean {:arities {1 {:args [:seqable] :ret :boolean}}}) (def seqable->any {:arities {1 {:args [:seqable] :ret :any}}}) (def any->boolean {:arities {1 {:ret :boolean}}}) (def a->a {:arities {1 {:args [:any]}} :fn #(:tag (first %))}) (def number->number {:arities {1 {:args [:number] :ret :number}}}) (def number->number->number {:arities {2 {:args [:number :number] :ret :number}}}) (def number*->number {:arities {:varargs {:args [{:op :rest :spec :number}] :ret :number}}}) (def number+->number {:arities {:varargs {:args [:number {:op :rest :spec :number}] :ret :number}}}) (def number->boolean {:arities {:varargs {:args [:number] :ret :boolean}}}) (def compare-numbers {:arities {:varargs {:args [{:op :rest :spec :number}] :ret :boolean}}}) (def int->int {:arities {1 {:args [:int] :ret :int}}}) (def int->int->int {:arities {2 {:args [:int :int] :ret :int}}}) (def clojure-core {'if {:fn (fn [[_ then else]] (tu/union-type then else))} 'let {:fn last} 16 'list {:arities {:varargs {:ret :list}}} 22 'cons {:arities {2 {:args [:any :seqable]}}} 49 'first seqable->any 57 'next seqable->seq 66 'rest seqable->seq 75 'conj {:arities {0 {:args [:nilable/coll] :ret :coll} :varargs {:args [:nilable/coll {:op :rest :spec :any}] :ret :coll}}} 91 'second seqable->any 98 'ffirst seqable->any 105 'nfirst seqable->seq 112 'fnext seqable->any 119 'nnext seqable->seq 126 'seq {:arities {1 {:args [:seqable] :ret :seq}}} 139 'instance? any->boolean 146 'seq? any->boolean 153 'char? any->boolean 160 'string? any->boolean 167 'map? any->boolean 181 'assoc {:arities {3 {:args [:nilable/associative :any :any]} :varargs {:min-arity 3 :args '[:nilable/associative :any :any {:op :rest :spec [:any :any]}]}} :fn (fn [args] (let [farg (first args)] (if-let [t (:tag farg)] (case t :map :map :vector :vector (if (and (map? t) (identical? :map (:type t))) t :associative)) :associative)))} 202 'meta {:arities {1 {:ret :nilable/map}}} 211 'with-meta a->a 262 'last seqable->any 272 'butlast seqable->seq 283 ' defn 338 ' to - array 346 ' cast 353 'vector {:arities {:varargs {:ret :vector}}} 367 'vec {:arities {1 {:ret :vector}}} 379 'hash-map {:arities {:varargs {:args [{:op :rest :spec [:any :any]}] :ret :map}}} 389 'hash-set {:arities {:varargs {:ret :set}}} 398 'sorted-map {:arities {:varargs {:ret :sorted-map}}} 417 ' sorted - set 425 ' sorted - set - by 436 'nil? any->boolean 444 ' defmacro 493 ' when 'when {:fn (fn [args] (tu/union-type :nil (last args)))} 499 ' when - not 'when-not {:fn (fn [args] (tu/union-type :nil (last args)))} 505 'false? any->boolean 512 'true? any->boolean 519 'boolean? any->boolean 524 'not any->boolean 531 'some? any->boolean 538 'any? any->boolean 544 'str {:arities {:varargs {:args [{:op :rest :spec :any}] :ret :string}}} 562 'symbol? any->boolean 568 'keyword? any->boolean 574 ' cond 'cond {:fn (fn [args] (loop [args (seq args) last-cond nil rets []] (if args (let [next-cond (first args) args (rest args) next-ret (first args) args (next args)] (recur args next-cond (conj rets next-ret))) (if (identical? :keyword (:tag last-cond)) (reduce tu/union-type #{} rets) (reduce tu/union-type :nil rets)))))} 589 'symbol {:arities {1 {:args [#{:symbol :string :keyword}] :ret :symbol} 2 {:args [:nilable/string :string] :ret :symbol}}} 604 ' 614 ' keyword 'keyword {:arities {1 {:args [#{:symbol :string :keyword}] :ret :keyword} 2 {:args [:nilable/string :string] :ret :keyword}}} 625 ' find - keyword 648 'list* {:arities {:varargs {:args [{:op :rest :spec :any :last :seqable}] :ret :list}}} 660 'apply {:arities {:varargs {:args [:ifn {:op :rest :spec :any :last :seqable}] :ret :any}}} 675 ' vary - meta 'lazy-seq {:arities {:varargs {:ret :seq}}} 692 ' chunk - buffer 698 ' chunk 701 ' chunk - first 704 ' chunk - rest 707 ' chunk - next 715 'chunked-seq? any->boolean 718 'concat {:arities {:varargs {:args [{:op :rest :spec :seqable}] :ret :seq}}} 746 ' delay 755 'delay? any->boolean 761 ' force 775 'identical? {:arities {2 {:ret :boolean}}} 783 '= {:arities {:varargs {:ret :boolean}}} 819 'not= {:arities {:varargs {:ret :boolean}}} 831 ' compare 'compare {:arities {2 {:ret :number}}} 842 ' and 'and {:fn (fn [args] (reduce tu/union-type :nil args))} 854 ' or 'or {:fn (fn [args] (reduce tu/union-type #{} args))} 867 'zero? any->boolean 874 'count {:arities {1 {:args [:seqable] :ret :number}}} 882 'int {:arities {1 {:args [#{:number :char}] :ret :int}}} 889 'nth {:arities {2 {:args [:seqable :int] :ret :any} 3 {:args [:seqable :int :any] :ret :any}}} 900 '< compare-numbers 915 'inc' number->number 922 'inc number->number 947 'reverse {:arities {1 {:args [:seqable]}} :ret :seq} 972 '+' number*->number 984 '+ number*->number 996 '*' number*->number 1008 '* number*->number 1020 '/ number+->number '-' number+->number '- number+->number 1055 '<= compare-numbers '> compare-numbers 1085 '>= compare-numbers 1100 '== compare-numbers 1115 'max number+->number 1125 'min number+->number 1135 'dec' number->number 1142 'dec number->number 1149 'unchecked-inc-int int->int 1156 'unchecked-inc number->number 1163 'unchecked-dec-int int->int 1170 'unchecked-dec number->number 1177 'unchecked-negate-int int->int 1184 'unchecked-negate number->number 1191 'unchecked-add-int int->int->int 1198 'unchecked-add number->number->number 1205 'unchecked-subtract-int int->int->int 1212 'unchecked-subtract number->number->number 1219 'unchecked-multiply-int int->int->int 1226 'unchecked-multiply number->number->number 1233 'unchecked-divide-int int->int->int 1240 'unchecked-remainder-int int->int->int 1247 'pos? number->boolean 1254 'neg? number->boolean 1261 'quot number->number->number 1269 'rem number->number->number 1277 'rationalize number->number 1293 ' bit - and 1311 ' bit - xor 1331 ' bit - clear 1349 ' bit - test 1368 ' unsigned - bit - shift - right 1374 'integer? any->boolean 1386 'even? number->boolean 1394 'odd? number->boolean 1400 'int? any->boolean 1408 'pos-int? any->boolean 1414 'neg-int? any->boolean 1420 'nat-int? any->boolean 1426 'double? any->boolean 1433 'complement {:arities {1 {:args [:ifn] :ret :fn}}} 1445 'constantly {:arities {1 {:ret :fn}}} 1451 'identity a->a 1459 'peek {:arities {1 {:args [:stack] :ret :any}}} 1467 'pop {:arities {1 {:args [:stack] :ret :stack}}} 1478 'map-entry? any->boolean 1484 ' contains ? 'contains? {:arities {2 {:args [#{:associative :set :string} :any] :ret :boolean}}} NOTE : get is an any->any function on any object that implements . 'dissoc {:arities {:varargs {:args [:nilable/map {:op :rest :spec :any}] :ret :nilable/map}}} 1518 ' disj 1534 'find {:arities {2 {:args [:nilable/associative :any]}}} 1540 'select-keys {:arities {2 {:args [:nilable/associative :seqable] :ret :map}}} 1555 NOTE : keys and vals can be called on seqs of MapEntry 's , hence not : associative . 'keys {:arities {1 {:args [:seqable] :ret :seq}}} 1561 'vals {:arities {1 {:args [:seqable] :ret :seq}}} 1567 ' key 1581 'rseq {:arities {1 {:args [#{:vector :sorted-map}] :req :seq}}} 1597 'namespace {:arities {1 {:ret :string}}} 1605 'boolean any->boolean 1612 'ident? any->boolean 1617 'simple-ident? any->boolean 1622 'qualified-ident? any->boolean 1627 'simple-symbol? any->boolean 1632 'qualified-symbol? any->boolean 1637 'simple-keyword? any->boolean 1642 'qualified-keyword? any->boolean 1647 ' locking 1693 ' - > > 1723 ' global - hierarchy 1725 ' defmulti 1783 ' defmethod 1796 ' remove - method 1803 ' prefer - method 1811 ' methods 1824 ' prefers 1841 ' if - let 'if-let {:fn (fn [[_ then else]] (tu/union-type then else))} 1861 ' when - let 'when-let {:fn (fn [args] (tu/union-type :nil (last args)))} 1876 ' if - some 1896 ' when - some 1913 ' push - thread - bindings 1931 ' pop - thread - bindings 1939 ' get - thread - bindings 1947 ' binding 1973 ' with - bindings * 1986 ' with - bindings 1994 ' bound - fn * 2006 ' bound - fn 2015 ' find - var ' set - agent - send - executor ! 2111 ' send 2122 ' send - off 2133 ' release - pending - sends 2169 ' agent - error 2177 ' restart - agent 2194 ' set - error - handler ! 2204 ' error - handler 2229 ' error - mode 2236 ' agent - errors 2246 ' clear - agent - errors 2254 ' shutdown - agents 2306 ' deref 2327 'atom {:ret :atom} 2345 'swap! {:arities {:varargs {:args [:atom :ifn [{:op :rest :spec :any}]] :ret :any}}} 2357 ' swap - vals ! 2368 ' compare - and - set ! 2376 'reset! {:arities {2 {:args [:atom :any] :ret :any}}} 2383 ' reset - vals ! 2389 ' set - validator ! 2406 ' alter - meta ! 2416 ' reset - meta ! 2422 ' commute 2443 ' alter 2463 ' ref - history - count 2470 ' ref - min - history 2488 ' ensure 2525 ' volatile ! 2532 ' vreset ! 2539 ' vswap ! 2548 'volatile? any->boolean 2557 'comp {:arities {:varargs [{:op :rest :spec :ifn}] :ret :ifn}} 2576 'juxt {:arities {:varargs {:args [:ifn {:op :rest :spec :ifn}] :ret :ifn}}} 2614 'partial {:arities {:varargs {:args [:ifn {:op :rest :spec :any}] :ret :ifn}}} 2647 ' sequence 2672 'every? {:arities {2 {:args [:ifn :seqable] :ret :boolean}}} 2684 'not-every? {:arities {2 {:args [:ifn :seqable] :ret :boolean}}} 2693 'some {:arities {2 {:args [:ifn :seqable] :ret :any}}} 2703 'not-any? {:arities {2 {:args [:ifn :seqable] :ret :boolean}}} 2712 ' dotimes 2727 'map {:arities {1 {:args [:ifn] :ret :transducer} :varargs {:args '[:ifn :seqable [{:op :rest :spec :seqable}]] :ret :seq}}} 2776 ' declare 2783 'mapcat {:arities {1 {:args [:ifn] :ret :transducer} :varargs {:args '[:ifn :seqable [{:op :rest :spec :seqable}]] :ret :seq}}} 2793 'filter {:arities {1 {:args [:ifn] :ret :transducer} 2 {:args [:ifn :seqable] :ret :seq}}} 2826 'remove {:arities {1 {:args [:ifn] :ret :transducer} 2 {:args [:ifn :seqable] :ret :seq}}} 2836 ' reduced 2842 'reduced? any->boolean 2855 ' unreduced 2861 'take {:arities {1 {:args [:nat-int] :ret :transducer} 2 {:args [:nat-int :seqable] :ret :seq}}} 2888 'take-while {:arities {1 {:args [:ifn] :ret :transducer} 2 {:args [:ifn :seqable] :ret :seq}}} 2909 'drop {:arities {1 {:args [:nat-int] :ret :transducer} 2 {:args [:nat-int :seqable] :ret :seq}}} 2934 'drop-last {:arities {1 {:args [:seqable] :ret :seq} 2 {:args [:nat-int :seqable] :ret :seq}}} 2941 'take-last {:arities {2 {:args [:nat-int :seqable] :ret :seq}}} 2952 'drop-while {:arities {1 {:args [:ifn] :ret :transducer} 2 {:args [:ifn :seqable] :ret :seq}}} 2979 'cycle seqable->seq 2985 'split-at {:arities {2 {:args [:nat-int :seqable] :ret :vector}}} 2992 'split-with {:arities {2 {:args [:ifn :seqable] :ret :vector}}} 2999 'repeat {:arities {1 {:args [:any] :ret :seq} 2 {:args [:nat-int :any]}}} 3013 'iterate {:arities {2 {:args [:ifn :any] :ret :seq}}} 3019 'range {:arities {0 {:ret :seq} 1 {:args [:number] :ret :seq} 2 {:args [:number :number] :ret :seq} 3 {:args [:number :number :number] :ret :seq}}} 3041 'merge {:arities {:varargs {:args [{:op :rest :spec :seqable}] :ret :nilable/map}}} 3051 'merge-with {:arities {:varargs {:args [:ifn {:op :rest :spec :seqable}] :ret :nilable/map}}} 3071 'zipmap {:arities {2 {:args [:seqable :seqable] :ret :map}}} 3085 ' line - seq 3094 ' comparator 3102 ' sort 3119 ' sort - by 3148 ' doall 3164 ' nthnext 3174 ' nthrest 3184 'partition {:arities {2 {:args [:int :seqable] :ret :seq} 3 {:args [:int :int :seqable] :ret :seq} 4 {:args [:int :int :seqable :seqable] :ret :seq}}} 3210 ' eval 3291 ' await1 3313 ' dotimes 3349 ' persistent ! 3358 ' conj ! 3381 ' dissoc ! 3392 ' pop ! 3400 ' disj ! 3425 ' import 3460 ' class 3473 ' num 3492 ' double 'byte {:arities {1 {:args [#{:byte :number :char}] :ret :byte}}} 3510 ' char 3522 ' unchecked - short 3528 ' unchecked - char 3534 ' unchecked - int 3552 ' unchecked - double 3559 'number? any->boolean 3576 'ratio? any->boolean 3582 ' numerator 'decimal? any->boolean 3604 'float? any->boolean 3612 'rational? any->boolean 3619 ' bigint 3633 ' biginteger 3647 ' bigdec 3663 ' print - method 3677 ' pr 3697 ' newline 3724 ' print 3770 ' read+string 3796 ' read - line 3805 ' read - string 3818 'subvec {:arities {2 {:args [:vector :nat-int] :ret :vector} 3 {:args [:vector :nat-int :nat-int] :ret :vector}}} 3831 ' with - open 3852 ' doto 3898 ' 3912 ' aget 3986 ' make - array 4026 ' macroexpand 4038 ' create - struct 4071 ' accessor 4082 ' load - reader 4089 ' load - string 4099 'set? any->boolean 'set {:ret :set} 4147 ' all - ns 4164 ' ns - name ' ns - unmap 4189 ' ns - publics 4200 ' ns - imports 4217 ' refer 4254 ' ns - refers 4264 ' alias 4274 ' ns - aliases 4281 ' ns - unalias 4288 'take-nth {:arities {1 {:args [:int] :ret :transducer} 2 {:args [:int :seqable] :ret :seq}}} 4327 ' var - get 4340 ' with - local - vars 4359 ' ns - resolve 4372 ' resolve 4379 ' array - map 4389 ' destructure 4481 ' let 4513 ' fn 'fn {:arities {:varargs {:ret :fn}}} 4575 ' loop 4600 ' when - first 4614 ' lazy - cat 'for {:arities {2 {:ret :seq}}} 4716 ' with - out - str 4736 ' pr - str 4754 ' print - str 4763 ' println - str 'ex-info {:arities {2 {:args [:nilable/string :map] :ret :throwable} 3 {:args [:nilable/string :map :any] :ret :throwable}}} 4803 ' ex - data 4800 ' ex - message 4808 ' ex - cause 4816 ' assert 4829 ' test 4839 :ret :regex}}} 4849 're - matcher 4858 're - groups 4874 're-seq {:arities {2 {:args [:regex :string] :ret :seq}}} 4886 're-matches {:arities {2 {:args [:regex :string] :ret #{:vector :string}}}} 4898 :ret #{:vector :string}} 2 {:args [:regex :string] :ret #{:vector :string}}}} 4919 ' rand - int 4931 ' tree - seq 'tree-seq {:arities {3 {:args [:ifn :ifn :any] :ret :seq}}} 4948 ' file - seq 4968 'special-symbol? any->boolean 4975 'var? any->boolean 4981 'subs {:arities {2 {:args [:string :nat-int] :ret :string} 3 {:args [:string :nat-int :nat-int] :ret :string}}} 4989 'max-key {:arities {:varargs {:args [:ifn :any {:op :rest :spec :any}] :ret :any}}} 5009 'min-key {:arities {:varargs {:args [:ifn :any {:op :rest :spec :any}] :ret :any}}} 5029 'distinct {:arities {0 {:args [] :ret :transducer} 1 {:args [:seqable] :ret :seq}}} 5058 ' replace 5086 ' with - precision 5109 ' subseq 5126 ' rsubseq 5143 ' repeatedly 5165 ' hash 5186 ' hash - ordered - coll 5195 ' hash - unordered - coll 5206 'interpose {:arities {1 {:args [:any] :ret :transducer} 2 {:args [:any :seqable] :ret :seq}}} 5229 ' definline 5249 ' amap 5277 ' float - array 5285 ' boolean - array 5293 ' byte - array 5309 ' short - array 5317 ' double - array 5325 ' object - array 5340 ' long - array 5348 ' booleans 5353 ' bytes 5358 ' chars 5363 ' shorts 5373 ' ints 5383 ' longs 5388 'bytes? any->boolean 5397 ' seque 5443 'class? any->boolean 5512 ' bound ? 5520 ' thread - bound ? 5528 ' make - hierarchy 5543 ' bases 5564 ' isa ? 5585 ' parents 5598 ' ancestors 5662 ' flatten 5664 ' underive 5702 ' resultset - seq 5738 ' format 'format {:arities {:varargs {:args [:string {:op :rest :spec :any}] :ret :string}}} 5746 ' printf 5753 ' gen - class 5764 ' ns 5822 ' refer - clojure 6093 ' use 6104 ' loaded - libs 6109 ' load 6142 'get-in {:arities {2 {:args [:nilable/associative :seqable] :ret :any} 3 {:args [:nilable/associative :seqable :any] :ret :any}}} 6152 'assoc-in {:arities {3 {:args [:nilable/associative :seqable :any] :ret :associative}}} 6172 'update-in {:arities {:varargs {:args [:nilable/associative :seqable :ifn {:op :rest :spec :any}] :ret :associative}}} 6188 'update {:arities {:varargs {:args [:nilable/associative :any :ifn {:op :rest :spec :any}] :ret :associative}}} 'empty? seqable->boolean 6213 'coll? any->boolean 6219 'list? any->boolean 6225 'seqable? any->boolean 6230 'ifn? any->boolean 'fn? any->boolean 6244 'associative? any->boolean 6250 'sequential? any->boolean 6256 'sorted? any->boolean 6262 'counted? any->boolean 6268 'reversible? any->boolean 6274 'indexed? any->boolean 6279 ' * 1 6284 ' * 2 6289 ' * 3 6294 ' * e 6317 ' intern 6333 ' while 6343 ' memoize 6359 ' condp 6530 'future? any->boolean 6536 ' future - done ? 6543 ' letfn 6556 'fnil {:arities {2 {:args [:ifn :any] :ret :ifn} 3 {:args [:ifn :any :any] :ret :ifn} 4 {:args [:ifn :any :any :any] :ret :ifn}}} 6793 'inst? any->boolean 6805 'uuid? any->boolean 6810 'reduce {:arities {2 {:args [:ifn :seqable] :ret :any} 3 {:args [:ifn :any :seqable] :ret :any}}} 6870 ' transduce 6887 'into {:arities {0 {:args [] :ret :coll} 1 {:args [:coll]} 2 {:args [:coll :seqable]} 3 {:args [:coll :transducer :seqable]}} :fn (fn [args] (let [t (:tag (first args))] (if (identical? :any t) :coll t)))} 6903 'mapv {:arities {1 {:args [:ifn] :ret :transducer} :varargs {:args '[:ifn :seqable {:op :rest :spec :seqable}] :ret :vector}}} 6921 'filterv {:arities {2 {:args [:ifn :seqable] :ret :vector}}} 6942 ' slurp 6990 ' future 7006 ' future - cancelled ? 7012 ' pmap 7069 ' * clojure - version * 7081 ' clojure - version 7136 'flatten {:arities {1 {:args [:nilable/sequential] :ret :sequential}}} 'group-by {:arities {2 {:args [:ifn :seqable] :ret :map}}} 7160 'partition-by {:arities {1 {:args [:ifn] :ret :transducer} 2 {:args [:ifn :seqable] :ret :seq}}} 7203 'frequencies {:arities {1 {:args [:seqable] :ret :map}}} 7214 ' reductions 'partition-all {:arities {1 {:args [:int] :ret :transducer} 2 {:args [:int :seqable] :ret :seq} 3 {:args [:int :int :seqable] :ret :seq}}} 7274 'shuffle {:arities {1 {:args [:coll] :ret :coll}}} 'map-indexed {:arities {1 {:args [:ifn] :ret :transducer} 2 {:args [:ifn :seqable] :ret :seq}}} 7313 'keep {:arities {1 {:args [:ifn] :ret :transducer} 2 {:args [:ifn :seqable] :ret :seq}}} 'keep-indexed {:arities {1 {:args [:ifn] :ret :transducer} 2 {:args [:ifn :seqable] :ret :seq}}} 7396 'every-pred {:arities {:varargs {:args [:ifn {:op :rest :spec :ifn}] :ret :ifn}}} 7436 'some-fn {:arities {:varargs {:args [:ifn {:op :rest :spec :ifn}] :ret :ifn}}} 7498 ' with - redefs - fn 7584 ' some- > 7619 ' cat 7631 ' halt - when 7655 'dedupe {:arities {0 {:args [] :ret :transducer} 1 {:args [:seqable] :ret :seq}}} 7694 ' eduction 7710 ' run ! 'tagged-literal? any->boolean 7725 ' tagged - literal 'reader-conditional? any->boolean 7750 ' default - data - readers 7758 ' * data - readers * 7787 ' * default - data - reader - fn * 7845 'uri? any->boolean }) (def cljs-core (assoc clojure-core 'keyword {:arities {1 {:args [#{:string :keyword :symbol}] :ret :keyword} 2 {:args [#{:nilable/string :keyword :symbol} #{:string :keyword :symbol}] :ret :keyword}}}))
391e2502278c91b5a50329e2617b56a736da46e06590ad2356daee6be53344e6
jwiegley/notes
IOState.hs
# LANGUAGE DeriveFunctor # # LANGUAGE FlexibleInstances # # LANGUAGE MultiParamTypeClasses # module IOState where import Control.DeepSeq import Control.Exception import Control.Monad import Control.Monad.IO.Class import Control.Monad.State.Class import Control.Monad.Trans.State (execStateT) import Criterion import Criterion.Main import Data.IORef import System.IO.Unsafe global :: IORef Int # NOINLINE global # global = unsafePerformIO $ newIORef 0 data IOState s a = IOState { getIOState :: IO a } deriving (Functor) runIOState :: IOState Int a -> Int -> IO Int runIOState (IOState m) s = do writeIORef global s _ <- m readIORef global instance Monad (IOState s) where return = IOState . return IOState m >>= f = IOState $ m >>= getIOState . f instance MonadIO (IOState s) where liftIO = IOState instance MonadState Int (IOState Int) where get = IOState $ readIORef global put s = IOState $ writeIORef global s instance NFData a => NFData (IO a) where rnf = unsafePerformIO . fmap rnf getPut :: (Num a, MonadState a m, MonadIO m) => Int -> m a getPut n = do x <- get put $! x + 1 if n == 0 then return x else getPut (pred n) main = do go 1 runIOState defaultMain [ bench "StateT Int IO" $ nf (go 100) execStateT , bench "IOState Int" $ nf (go 100) runIOState ] where go :: (Num a, MonadState a m, MonadIO m) => Int -> (m [a] -> Int -> IO Int) -> IO Int go n f = f (replicateM n (getPut 100)) 1
null
https://raw.githubusercontent.com/jwiegley/notes/24574b02bfd869845faa1521854f90e4e8bf5e9a/gists/f719a3d41696d48f6005/misc/IOState.hs
haskell
# LANGUAGE DeriveFunctor # # LANGUAGE FlexibleInstances # # LANGUAGE MultiParamTypeClasses # module IOState where import Control.DeepSeq import Control.Exception import Control.Monad import Control.Monad.IO.Class import Control.Monad.State.Class import Control.Monad.Trans.State (execStateT) import Criterion import Criterion.Main import Data.IORef import System.IO.Unsafe global :: IORef Int # NOINLINE global # global = unsafePerformIO $ newIORef 0 data IOState s a = IOState { getIOState :: IO a } deriving (Functor) runIOState :: IOState Int a -> Int -> IO Int runIOState (IOState m) s = do writeIORef global s _ <- m readIORef global instance Monad (IOState s) where return = IOState . return IOState m >>= f = IOState $ m >>= getIOState . f instance MonadIO (IOState s) where liftIO = IOState instance MonadState Int (IOState Int) where get = IOState $ readIORef global put s = IOState $ writeIORef global s instance NFData a => NFData (IO a) where rnf = unsafePerformIO . fmap rnf getPut :: (Num a, MonadState a m, MonadIO m) => Int -> m a getPut n = do x <- get put $! x + 1 if n == 0 then return x else getPut (pred n) main = do go 1 runIOState defaultMain [ bench "StateT Int IO" $ nf (go 100) execStateT , bench "IOState Int" $ nf (go 100) runIOState ] where go :: (Num a, MonadState a m, MonadIO m) => Int -> (m [a] -> Int -> IO Int) -> IO Int go n f = f (replicateM n (getPut 100)) 1
30ffc1210339fe5ba2c4da1c4dff79f2f0968364b85abf3cd27311cfa8db403b
jarohen/bounce
system.clj
(ns bounce.system (:require [clojure.set :as set] [com.stuartsierra.dependency :as deps])) (def ^:private !system (atom nil)) (defrecord StartedComponent [value stop!]) (defn ->started-component ([value] (if (instance? StartedComponent value) value (->StartedComponent value (fn [])))) ([value stop!] (->StartedComponent value stop!))) (defn- resolve-dep [ns dep] (cond (var? dep) dep (symbol? dep) (or (ns-resolve ns dep) (throw (ex-info "Could not resolve dependency" {:dep dep}))))) (defn- parse-component-opts [[maybe-opts & body] {:keys [ns]}] (if (and (map? maybe-opts) (seq body)) (merge {:body body :bounce/deps (->> (:bounce/deps maybe-opts) (into #{} (map (fn [dep] (resolve-dep ns dep)))))} (select-keys maybe-opts #{:bounce/params})) {:body (cons maybe-opts body)})) (defmacro defcomponent [sym & body] (let [{:keys [bounce/deps bounce/params body]} (parse-component-opts body {:ns *ns*}) sym (-> sym (with-meta {:dynamic true}))] `(do (defonce ~sym nil) (doto (var ~sym) (alter-meta! merge {:bounce/deps '~deps :bounce/component (fn ~(symbol (str "start-" (name sym))) [~(or params `_#)] (->started-component (do ~@body)))}))))) (defmacro with-stop [value & body] `(->started-component ~value (fn ~'stop [] ~@body))) (defn fmap-component [component f] (let [{:keys [value stop!]} (->started-component component)] (->started-component (f value) stop!))) (defn order-deps [deps] (loop [[dep & more-deps] (seq deps) seen #{} g (deps/graph)] (if dep (let [upstream-deps (:bounce/deps (meta dep))] (recur (distinct (remove seen (concat more-deps upstream-deps))) (conj seen dep) (reduce (fn [g upstream-dep] (deps/depend g dep upstream-dep)) (deps/depend g :system dep) upstream-deps))) (remove #{:system} (deps/topo-sort g))))) (defn start-system ([deps] (start-system deps {})) ([deps {:bounce/keys [params overrides]}] (let [dep-order (order-deps deps) start-fn (reduce (fn [f dep] (fn [system] (let [component-fn (or (get overrides dep) (:bounce/component (meta dep))) started-component (->started-component (component-fn (get params dep)))] (with-bindings {dep (:value started-component)} (try (f (assoc system dep started-component)) (catch Exception e (try ((:stop! started-component)) (catch Exception e (.printStackTrace e))) (throw e))))))) identity (reverse dep-order))] {:dep-order dep-order :components (start-fn {})}))) (defn stop-system [{:keys [dep-order components] :as system}] (let [stop-fn (reduce (fn [f dep] (fn [system] (let [{:keys [value stop!]} (get components dep)] (with-bindings {dep value} (f (assoc system dep value)) (stop!))))) identity (reverse dep-order))] (stop-fn {}) (set dep-order))) (defn with-system* [started-system f] (with-bindings (->> (:components started-system) (into {} (map (fn [[component-var {:keys [value]}]] [component-var value])))) (try (f) (finally (stop-system started-system))))) (defmacro with-system [started-system & body] `(with-system* ~started-system (fn [] ~@body))) (def ^:private !opts (atom nil)) (defn set-opts! ([deps] (set-opts! deps {})) ([deps opts] (reset! !opts [deps opts]))) (defn start! [] (when-let [[deps opts] @!opts] (let [deps (->> deps (into #{} (keep (fn [dep] (ns-resolve (doto (symbol (namespace dep)) require) dep)))))] (if-not (compare-and-set! !system nil :starting) (throw (ex-info "System is already starting/started" {:system @!system})) (try (let [{:keys [dep-order components] :as started-system} (start-system deps opts)] (doseq [[dep {:keys [value]}] components] (alter-var-root dep (constantly value))) (reset! !system started-system) (set dep-order)) (catch Exception e (reset! !system nil) (throw e))))))) (defn stop! [] (let [system @!system] (when (and (map? system) (compare-and-set! !system system :stopping)) (try (stop-system system) (finally (reset! !system nil)))))) (defn restart! [] (stop!) (start!))
null
https://raw.githubusercontent.com/jarohen/bounce/0ca5317ef2d9e43b8add9ce8d1fad2d6155493bb/src/bounce/system.clj
clojure
(ns bounce.system (:require [clojure.set :as set] [com.stuartsierra.dependency :as deps])) (def ^:private !system (atom nil)) (defrecord StartedComponent [value stop!]) (defn ->started-component ([value] (if (instance? StartedComponent value) value (->StartedComponent value (fn [])))) ([value stop!] (->StartedComponent value stop!))) (defn- resolve-dep [ns dep] (cond (var? dep) dep (symbol? dep) (or (ns-resolve ns dep) (throw (ex-info "Could not resolve dependency" {:dep dep}))))) (defn- parse-component-opts [[maybe-opts & body] {:keys [ns]}] (if (and (map? maybe-opts) (seq body)) (merge {:body body :bounce/deps (->> (:bounce/deps maybe-opts) (into #{} (map (fn [dep] (resolve-dep ns dep)))))} (select-keys maybe-opts #{:bounce/params})) {:body (cons maybe-opts body)})) (defmacro defcomponent [sym & body] (let [{:keys [bounce/deps bounce/params body]} (parse-component-opts body {:ns *ns*}) sym (-> sym (with-meta {:dynamic true}))] `(do (defonce ~sym nil) (doto (var ~sym) (alter-meta! merge {:bounce/deps '~deps :bounce/component (fn ~(symbol (str "start-" (name sym))) [~(or params `_#)] (->started-component (do ~@body)))}))))) (defmacro with-stop [value & body] `(->started-component ~value (fn ~'stop [] ~@body))) (defn fmap-component [component f] (let [{:keys [value stop!]} (->started-component component)] (->started-component (f value) stop!))) (defn order-deps [deps] (loop [[dep & more-deps] (seq deps) seen #{} g (deps/graph)] (if dep (let [upstream-deps (:bounce/deps (meta dep))] (recur (distinct (remove seen (concat more-deps upstream-deps))) (conj seen dep) (reduce (fn [g upstream-dep] (deps/depend g dep upstream-dep)) (deps/depend g :system dep) upstream-deps))) (remove #{:system} (deps/topo-sort g))))) (defn start-system ([deps] (start-system deps {})) ([deps {:bounce/keys [params overrides]}] (let [dep-order (order-deps deps) start-fn (reduce (fn [f dep] (fn [system] (let [component-fn (or (get overrides dep) (:bounce/component (meta dep))) started-component (->started-component (component-fn (get params dep)))] (with-bindings {dep (:value started-component)} (try (f (assoc system dep started-component)) (catch Exception e (try ((:stop! started-component)) (catch Exception e (.printStackTrace e))) (throw e))))))) identity (reverse dep-order))] {:dep-order dep-order :components (start-fn {})}))) (defn stop-system [{:keys [dep-order components] :as system}] (let [stop-fn (reduce (fn [f dep] (fn [system] (let [{:keys [value stop!]} (get components dep)] (with-bindings {dep value} (f (assoc system dep value)) (stop!))))) identity (reverse dep-order))] (stop-fn {}) (set dep-order))) (defn with-system* [started-system f] (with-bindings (->> (:components started-system) (into {} (map (fn [[component-var {:keys [value]}]] [component-var value])))) (try (f) (finally (stop-system started-system))))) (defmacro with-system [started-system & body] `(with-system* ~started-system (fn [] ~@body))) (def ^:private !opts (atom nil)) (defn set-opts! ([deps] (set-opts! deps {})) ([deps opts] (reset! !opts [deps opts]))) (defn start! [] (when-let [[deps opts] @!opts] (let [deps (->> deps (into #{} (keep (fn [dep] (ns-resolve (doto (symbol (namespace dep)) require) dep)))))] (if-not (compare-and-set! !system nil :starting) (throw (ex-info "System is already starting/started" {:system @!system})) (try (let [{:keys [dep-order components] :as started-system} (start-system deps opts)] (doseq [[dep {:keys [value]}] components] (alter-var-root dep (constantly value))) (reset! !system started-system) (set dep-order)) (catch Exception e (reset! !system nil) (throw e))))))) (defn stop! [] (let [system @!system] (when (and (map? system) (compare-and-set! !system system :stopping)) (try (stop-system system) (finally (reset! !system nil)))))) (defn restart! [] (stop!) (start!))