_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
d63ea13b68320074585a3452c9e0691c32694ed672dddaeed260f72fbf6d5f8d
kelamg/HtDP2e-workthrough
ex354.rkt
The first three lines of this file were inserted by . They record metadata ;; about the language level of this file in a form that our tools can easily process. #reader(lib "htdp-intermediate-lambda-reader.ss" "lang")((modname ex354) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f))) (require 2htdp/abstraction) (define-struct add (left right)) (define-struct mul (left right)) A BSL - var - expr is one of : ; – Number ; – Symbol ; – (make-add BSL-var-expr BSL-var-expr) ; – (make-mul BSL-var-expr BSL-var-expr) A BSL - expr is one of : ;; - Number - ( make - add BSL - expr BSL - expr ) - ( make - mul BSL - expr BSL - expr ) A NumRet is a Number An AL ( short for association list ) is [ List - of Association ] . An Association is a list of two items : ; (cons Symbol (cons Number '())) (define AL '((x 3) (y 5))) BSL - var - expr - > [ Or NumRet error ] ;; produces a value for ex ;; if ex passes numeric? ;; produces an error otherwise (check-expect (eval-variable 42) 42) (check-expect (eval-variable (make-add 10 32)) 42) (check-expect (eval-variable (make-mul 10 42)) 420) (check-error (eval-variable 'x)) (check-error (eval-variable (make-add 'x 32))) (define (eval-variable ex) (match ex [(? not-numeric?) (error "eval-variable: non-numeric expr")] [(? number?) ex] [(add l r) (+ (eval-variable l) (eval-variable r))] [(mul l r) (* (eval-variable l) (eval-variable r))])) BSL - var - expr AL - > [ Or NumRet error ] ;; produces a value for ex if numeric ? passes after applying ` subst ` to all assocs in da ;; produces an error otherwise (check-expect (eval-variable* 42 AL) 42) (check-expect (eval-variable* 'x AL) 3) (check-expect (eval-variable* (make-add 'x 'y) AL) 8) (check-error (eval-variable* 'z AL)) (check-error (eval-variable* (make-mul 'z 'x) AL)) (define (eval-variable* ex da) (eval-variable (foldl (λ (assoc expr) (subst expr (first assoc) (second assoc))) ex da))) ;; BSL-var-expr Symbol Number -> BSL-var-expr ;; produces a BSL-var-expr like ex ;; with all occurences of x replaced by v (check-expect (subst 'x 'x 5) 5) (check-expect (subst (make-add 'x 3) 'x 5) (make-add 5 3)) (check-expect (subst (make-add (make-mul 'x 'x) (make-mul 'y 'y)) 'x 5) (make-add (make-mul 5 5) (make-mul 'y 'y))) (define (subst ex x v) (match ex [(? number?) ex] [(? symbol?) (if (symbol=? ex x) v ex)] [(add l r) (make-add (subst l x v) (subst r x v))] [(mul l r) (make-mul (subst l x v) (subst r x v))])) ;; BSL-var-expr -> Boolean produces # true if ex is also a BSL - expr (check-expect (numeric? 'x) #false) (check-expect (numeric? (make-add 'x 3)) #false) (check-expect (numeric? (make-add 10 32)) #true) (check-expect (numeric? (make-mul 10 32)) #true) (define (numeric? ex) (match ex [(? number?) #true] [(add l r) (andmap numeric? (list l r))] [(mul l r) (andmap numeric? (list l r))] [else #false])) (define (not-numeric? ex) (not (numeric? ex)))
null
https://raw.githubusercontent.com/kelamg/HtDP2e-workthrough/ec05818d8b667a3c119bea8d1d22e31e72e0a958/HtDP/Intertwined-Data/ex354.rkt
racket
about the language level of this file in a form that our tools can easily process. – Number – Symbol – (make-add BSL-var-expr BSL-var-expr) – (make-mul BSL-var-expr BSL-var-expr) - Number (cons Symbol (cons Number '())) produces a value for ex if ex passes numeric? produces an error otherwise produces a value for ex produces an error otherwise BSL-var-expr Symbol Number -> BSL-var-expr produces a BSL-var-expr like ex with all occurences of x replaced by v BSL-var-expr -> Boolean
The first three lines of this file were inserted by . They record metadata #reader(lib "htdp-intermediate-lambda-reader.ss" "lang")((modname ex354) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f))) (require 2htdp/abstraction) (define-struct add (left right)) (define-struct mul (left right)) A BSL - var - expr is one of : A BSL - expr is one of : - ( make - add BSL - expr BSL - expr ) - ( make - mul BSL - expr BSL - expr ) A NumRet is a Number An AL ( short for association list ) is [ List - of Association ] . An Association is a list of two items : (define AL '((x 3) (y 5))) BSL - var - expr - > [ Or NumRet error ] (check-expect (eval-variable 42) 42) (check-expect (eval-variable (make-add 10 32)) 42) (check-expect (eval-variable (make-mul 10 42)) 420) (check-error (eval-variable 'x)) (check-error (eval-variable (make-add 'x 32))) (define (eval-variable ex) (match ex [(? not-numeric?) (error "eval-variable: non-numeric expr")] [(? number?) ex] [(add l r) (+ (eval-variable l) (eval-variable r))] [(mul l r) (* (eval-variable l) (eval-variable r))])) BSL - var - expr AL - > [ Or NumRet error ] if numeric ? passes after applying ` subst ` to all assocs in da (check-expect (eval-variable* 42 AL) 42) (check-expect (eval-variable* 'x AL) 3) (check-expect (eval-variable* (make-add 'x 'y) AL) 8) (check-error (eval-variable* 'z AL)) (check-error (eval-variable* (make-mul 'z 'x) AL)) (define (eval-variable* ex da) (eval-variable (foldl (λ (assoc expr) (subst expr (first assoc) (second assoc))) ex da))) (check-expect (subst 'x 'x 5) 5) (check-expect (subst (make-add 'x 3) 'x 5) (make-add 5 3)) (check-expect (subst (make-add (make-mul 'x 'x) (make-mul 'y 'y)) 'x 5) (make-add (make-mul 5 5) (make-mul 'y 'y))) (define (subst ex x v) (match ex [(? number?) ex] [(? symbol?) (if (symbol=? ex x) v ex)] [(add l r) (make-add (subst l x v) (subst r x v))] [(mul l r) (make-mul (subst l x v) (subst r x v))])) produces # true if ex is also a BSL - expr (check-expect (numeric? 'x) #false) (check-expect (numeric? (make-add 'x 3)) #false) (check-expect (numeric? (make-add 10 32)) #true) (check-expect (numeric? (make-mul 10 32)) #true) (define (numeric? ex) (match ex [(? number?) #true] [(add l r) (andmap numeric? (list l r))] [(mul l r) (andmap numeric? (list l r))] [else #false])) (define (not-numeric? ex) (not (numeric? ex)))
082208618780dfc7c815b1110dbbb266aaa228e6a55000509fe7df866fd65046
nvim-treesitter/nvim-treesitter
highlights.scm
(comment) @comment (null) @constant.builtin [ (true) (false) ] @boolean (number) @number (unit) @keyword (string) @string (multiline_string) @string (string (escape_sequence) @string.escape) (unquoted_string) @string [ "url" "file" "classpath" "required" ] @keyword (include "include" @include) (substitution ["${" "${?" "}"] @punctuation.special) (substitution (_) @field) (path (_) @field) (value [":" "=" "+=" ] @operator) [ "(" ")" "[" "]" "{" "}" ] @punctuation.bracket [ "," ] @punctuation.delimiter (unquoted_path "." @punctuation.delimiter)
null
https://raw.githubusercontent.com/nvim-treesitter/nvim-treesitter/00ebda5fd85df357f2dc56bc1236c36f5f204e48/queries/hocon/highlights.scm
scheme
(comment) @comment (null) @constant.builtin [ (true) (false) ] @boolean (number) @number (unit) @keyword (string) @string (multiline_string) @string (string (escape_sequence) @string.escape) (unquoted_string) @string [ "url" "file" "classpath" "required" ] @keyword (include "include" @include) (substitution ["${" "${?" "}"] @punctuation.special) (substitution (_) @field) (path (_) @field) (value [":" "=" "+=" ] @operator) [ "(" ")" "[" "]" "{" "}" ] @punctuation.bracket [ "," ] @punctuation.delimiter (unquoted_path "." @punctuation.delimiter)
baf161a59e58062ba283ee30d7203a069f086facf777e668ff2905cd529ffc31
rmloveland/scheme48-0.53
session.scm
Copyright ( c ) 1993 - 1999 by and . See file COPYING . ; Session data ; The initializers are saved in images. (define *session-data-initializers* '()) (define (make-session-data-slot! init) (let ((slot (length *session-data-initializers*))) (set! *session-data-initializers* (cons init *session-data-initializers*)) (if (vector? (session-data)) (set-session-data! (list->vector (reverse (cons init (reverse (vector->list (session-data)))))))) slot)) (define (session-data-ref slot) (vector-ref (session-data) slot)) (define (session-data-set! slot value) (vector-set! (session-data) slot value)) (define (initialize-session-data!) (set-session-data! (list->vector (reverse *session-data-initializers*))))
null
https://raw.githubusercontent.com/rmloveland/scheme48-0.53/1ae4531fac7150bd2af42d124da9b50dd1b89ec1/scheme/rts/session.scm
scheme
Session data The initializers are saved in images.
Copyright ( c ) 1993 - 1999 by and . See file COPYING . (define *session-data-initializers* '()) (define (make-session-data-slot! init) (let ((slot (length *session-data-initializers*))) (set! *session-data-initializers* (cons init *session-data-initializers*)) (if (vector? (session-data)) (set-session-data! (list->vector (reverse (cons init (reverse (vector->list (session-data)))))))) slot)) (define (session-data-ref slot) (vector-ref (session-data) slot)) (define (session-data-set! slot value) (vector-set! (session-data) slot value)) (define (initialize-session-data!) (set-session-data! (list->vector (reverse *session-data-initializers*))))
5cbef854c3607d573c6cfeb3f78d5111409fbc863dbbefe1e22a54f8eacb13c3
godfat/sandbox
combos.hs
import Control.Monad -- concatMap combos0 :: [[a]] -> [[a]] combos0 [] = [[]] combos0 (xs:xss) = concatMap (\rs -> map (:rs) xs) (combos0 xss) -- list comprehension combos1 :: [[a]] -> [[a]] combos1 [] = [[]] combos1 (xs:xss) = [ x : rs | x <- xs, rs <- combos1 xss ] combos2 :: [[a]] -> [[a]] combos2 [] = [[]] combos2 (xs:xss) = do{ x <- xs; rs <- combos2 xss; return (x : rs) } combos3 :: [[a]] -> [[a]] combos3 [] = [[]] combos3 (xs:xss) = xs `monadic_cons` (combos3 xss) where monadic_cons = liftM2 (:) -- list monad combos :: [[a]] -> [[a]] combos = foldr (liftM2 (:)) [[]] * Main > combos [ [ 0 .. 2],[3 .. 4],[5 .. 7 ] ] [ [ 0,3,5],[0,3,6],[0,3,7],[0,4,5],[0,4,6],[0,4,7 ] , [ 1,3,5],[1,3,6],[1,3,7],[1,4,5],[1,4,6],[1,4,7 ] , [ 2,3,5],[2,3,6],[2,3,7],[2,4,5],[2,4,6],[2,4,7 ] ] *Main> combos [[0..2],[3..4],[5..7]] [[0,3,5],[0,3,6],[0,3,7],[0,4,5],[0,4,6],[0,4,7], [1,3,5],[1,3,6],[1,3,7],[1,4,5],[1,4,6],[1,4,7], [2,3,5],[2,3,6],[2,3,7],[2,4,5],[2,4,6],[2,4,7]] -}
null
https://raw.githubusercontent.com/godfat/sandbox/eb6294238f92543339adfdfb4ba88586ba0e82b8/haskell/combos.hs
haskell
concatMap list comprehension list monad
import Control.Monad combos0 :: [[a]] -> [[a]] combos0 [] = [[]] combos0 (xs:xss) = concatMap (\rs -> map (:rs) xs) (combos0 xss) combos1 :: [[a]] -> [[a]] combos1 [] = [[]] combos1 (xs:xss) = [ x : rs | x <- xs, rs <- combos1 xss ] combos2 :: [[a]] -> [[a]] combos2 [] = [[]] combos2 (xs:xss) = do{ x <- xs; rs <- combos2 xss; return (x : rs) } combos3 :: [[a]] -> [[a]] combos3 [] = [[]] combos3 (xs:xss) = xs `monadic_cons` (combos3 xss) where monadic_cons = liftM2 (:) combos :: [[a]] -> [[a]] combos = foldr (liftM2 (:)) [[]] * Main > combos [ [ 0 .. 2],[3 .. 4],[5 .. 7 ] ] [ [ 0,3,5],[0,3,6],[0,3,7],[0,4,5],[0,4,6],[0,4,7 ] , [ 1,3,5],[1,3,6],[1,3,7],[1,4,5],[1,4,6],[1,4,7 ] , [ 2,3,5],[2,3,6],[2,3,7],[2,4,5],[2,4,6],[2,4,7 ] ] *Main> combos [[0..2],[3..4],[5..7]] [[0,3,5],[0,3,6],[0,3,7],[0,4,5],[0,4,6],[0,4,7], [1,3,5],[1,3,6],[1,3,7],[1,4,5],[1,4,6],[1,4,7], [2,3,5],[2,3,6],[2,3,7],[2,4,5],[2,4,6],[2,4,7]] -}
14409813a2d381052b513e5c8ab3b5fb212c6585cf55d945f3152810628d41f3
reborg/clojure-essential-reference
3.clj
< 1 > ;; #'user/output < 2 > ;; evaluated 1
null
https://raw.githubusercontent.com/reborg/clojure-essential-reference/c37fa19d45dd52b2995a191e3e96f0ebdc3f6d69/Sequences/OtherGenerators/lazy-seq/3.clj
clojure
#'user/output evaluated
< 1 > < 2 > 1
14480e26ecab7f2893fab8b92d0dff5ad3e37f56a14d95ed39708cb6b146eb44
awakesecurity/spectacle
Prop.hs
# LANGUAGE AllowAmbiguousTypes # {-# LANGUAGE OverloadedStrings #-} {-# OPTIONS_HADDOCK show-extensions #-} -- | -- Module : Language.Spectacle.Specification.Prop Copyright : ( c ) Arista Networks , 2022 - 2023 License : Apache License 2.0 , see LICENSE -- -- Stability : stable Portability : non - portable ( GHC extensions ) -- -- TODO: docs -- -- @since 1.0.0 module Language.Spectacle.Specification.Prop ( -- * Temporal Formula TemporalType (PropG, PropF, PropGF, PropFG), -- ** Projection toFormula, toModality, -- * Temporal Operators Modality (Always, Infinitely, Eventually, Stays), -- ** Pretty Printing ppModality, ) where import Data.Kind (Type) import GHC.TypeLits (Symbol) import Prettyprinter (Doc) import Prettyprinter.Render.Terminal (AnsiStyle) import Data.Ascript (Ascribe) import Language.Spectacle.AST.Temporal (Temporal) -- --------------------------------------------------------------------------------------------------------------------- data TemporalType :: [Ascribe Symbol Type] -> Modality -> Type where PropG :: Temporal ctx Bool -> TemporalType ctx 'Always PropF :: Temporal ctx Bool -> TemporalType ctx 'Eventually PropGF :: Temporal ctx Bool -> TemporalType ctx 'Infinitely PropFG :: Temporal ctx Bool -> TemporalType ctx 'Stays toFormula :: TemporalType ctx op -> Temporal ctx Bool toFormula = \case PropG form -> form PropF form -> form PropGF form -> form PropFG form -> form toModality :: TemporalType ctx op -> Modality toModality = \case PropG {} -> Always PropF {} -> Eventually PropGF {} -> Infinitely PropFG {} -> Stays data Modality = Always | Eventually | Infinitely | Stays deriving stock (Eq, Enum, Ord, Show) ppModality :: Modality -> Doc AnsiStyle ppModality = \case Always -> "always" Eventually -> "eventually" Infinitely -> "infinitely" Stays -> "stays-as"
null
https://raw.githubusercontent.com/awakesecurity/spectacle/430680c28b26dabb50f466948180eb59ba72fc8e/src/Language/Spectacle/Specification/Prop.hs
haskell
# LANGUAGE OverloadedStrings # # OPTIONS_HADDOCK show-extensions # | Module : Language.Spectacle.Specification.Prop Stability : stable TODO: docs @since 1.0.0 * Temporal Formula ** Projection * Temporal Operators ** Pretty Printing ---------------------------------------------------------------------------------------------------------------------
# LANGUAGE AllowAmbiguousTypes # Copyright : ( c ) Arista Networks , 2022 - 2023 License : Apache License 2.0 , see LICENSE Portability : non - portable ( GHC extensions ) module Language.Spectacle.Specification.Prop TemporalType (PropG, PropF, PropGF, PropFG), toFormula, toModality, Modality (Always, Infinitely, Eventually, Stays), ppModality, ) where import Data.Kind (Type) import GHC.TypeLits (Symbol) import Prettyprinter (Doc) import Prettyprinter.Render.Terminal (AnsiStyle) import Data.Ascript (Ascribe) import Language.Spectacle.AST.Temporal (Temporal) data TemporalType :: [Ascribe Symbol Type] -> Modality -> Type where PropG :: Temporal ctx Bool -> TemporalType ctx 'Always PropF :: Temporal ctx Bool -> TemporalType ctx 'Eventually PropGF :: Temporal ctx Bool -> TemporalType ctx 'Infinitely PropFG :: Temporal ctx Bool -> TemporalType ctx 'Stays toFormula :: TemporalType ctx op -> Temporal ctx Bool toFormula = \case PropG form -> form PropF form -> form PropGF form -> form PropFG form -> form toModality :: TemporalType ctx op -> Modality toModality = \case PropG {} -> Always PropF {} -> Eventually PropGF {} -> Infinitely PropFG {} -> Stays data Modality = Always | Eventually | Infinitely | Stays deriving stock (Eq, Enum, Ord, Show) ppModality :: Modality -> Doc AnsiStyle ppModality = \case Always -> "always" Eventually -> "eventually" Infinitely -> "infinitely" Stays -> "stays-as"
58ea9932cb12f0a77febd5f42c060d96405bff6abab074d67cb944a5891ee829
zwizwa/erl_tools
ghci.erl
%% FIXME: Special case ExoBERT . Later bootstrap todo : %% %% - start ghci %% - start loop - use to get pid %% - save pid for later control %% - proper restart even if loop is running: %% exo:restart(ghci_bert). %% %% - start loop: exo : ) ! { cmds,[":reload","start " ] } . %% %% - stop loop: %% bert_rpc:call("localhost",7890,control,stop,[]). %% %% - alternatively, get pid via this, then send SIGINT bert_rpc : call("localhost",7890,control , pid , [ ] ) . %% Wrapper for ghci. %% See also ghcid.erl Notes %% - NIH: Building what I actually need, instead of trying to shoe-horn %% ghcid into exo. I already have file change notifications, so just %% need simple reload and test run. %% %% - The proper way to do this is to move to ghcide. %% %% - The module is stateful: there is an idea of a "current" module %% that exposes a "test" function. %% %% - GHCI output can be redirected to a "buffer", which implements a ' clear ' and { ' } %% %% - Ad-hoc synchronization use the '#' character to encode %% continuations as hex-encoded binary terms. %% %% - Data exchange should go over a side channel. Since this is used %% in redo scripts, it seems simplest to just communicate through %% files. E.g. pass in/out file as parameters, and use the '#' %% mechanism to signal. %% -module(ghci). -export([start_link/1, handle/2, call/5]). start_link(#{ ghci_cmd := Cmd, module := Module } = Config) -> {ok, serv:start( {handler, fun() -> %% After initial load, send an optional initialization %% message, e.g. to start a service inside ghci. case maps:find(init_msg, Config) of error -> ok; {ok, Msg} -> self() ! Msg end, %% It is assumed a test module is loaded at all times. %% The test itself doesn't need to run at startup. handle( {load, Module}, maps:put( port, open_port({spawn, Cmd}, [use_stdio, exit_status]), Config)) end, fun ?MODULE:handle/2})}. handle(clear, State) -> LogBuf = maps:get(log_buf, State, fun log_buf/1), LogBuf(clear), %% FIXME: this seems to have no effect with exo config State; handle(_Msg={cmds, Cmds}, #{ port := Port } = State) -> log : " , [ _ Msg ] ) , port_command(Port, [[Cmd, "\n"] || Cmd <- Cmds]), State; handle({load, Module}, State) -> handle({cmds,[tools:format(":load ~s",[Module])]}, maps:put(module, Module, State)); %% This is very ad-hoc, but we do our best to: %% - Ensure the correct module is loaded %% - Ensure an ack that the caller can use to sync on %% This way it is still possible to have multiple calls in flight. %% %% Note that the sync is just an empty event. To determine success %% programmatically, a side effect needs to be used, e.g. the %% existence of a file. handle({run,Module,Function,Arg,SyncString}, State0 = #{module := CurrentModule}) -> State = case Module == CurrentModule of true -> State0; false -> handle({load, Module}, State0) end, log:info("run: ~p~n", [{Module,Function}]), LogBuf = maps:get(log_buf, State, fun log_buf/1), LogBuf(clear), %% FIXME: this seems to have no effect with exo config handle( {cmds, [":reload", %% ":show modules", tools:format( "~s.~s ~s", [Module, Function, Arg]), tools:format( "Prelude.putStrLn \"\\n~s\"", [SyncString])]}, State); Run with Erlang continuation encoded in the ack string . handle({run_cont,Module,Function,Arg,Cont}, State) -> SyncString = [$#, tools:hex(erlang:term_to_binary(Cont))], handle({run,Module,Function,Arg,SyncString}, State); %% Data coming from ghci gets chopped into lines and passed to a %% log_buf. Mostly modeled after emacs buffer: supports append lines %% + buffer clear. Line framing is used to be able to easily encode %% some in-band data. handle({Port, {data, Data}}, #{ port := Port } = State) -> %% log:info("Data = ~999p~n", [Data]), LogBuf = maps:get(log_buf, State, fun log_buf/1), Buf = maps:get(buf, State, []), Buf1 = log_lines(LogBuf, Data, Buf), maps:put(buf, Buf1, State); handle({Port, {exit_status,_}}=Msg, #{ port := Port }) -> exit(Msg); handle({_,dump}=Msg, State) -> obj:handle(Msg, State); handle(Msg, State) -> log:info("unknown: ~p~n", Msg), throw({?MODULE,unknown_msg,Msg}), State. log_buf({line, Line}) -> log:info("~s~n",[Line]); log_buf(_) -> ok. flat(L) -> lists:flatten(L). %% Abstract logger. log_lines(_, [], Line) -> flat(Line); log_lines(B, [$\n|Tail], Line) -> dispatch_line(B, Line), log_lines(B, Tail,[]); log_lines(B, [Char|Tail], Line) -> log_lines(B,Tail,[Line,Char]). dispatch_line(B, Line) -> case flat(Line) of [$#|Enc]=Flat -> try Bin = iolist_to_binary(tools:unhex(Enc)), Term = binary_to_term(Bin), Term() catch C:E -> log:info("WARNING: decoding: ~p~n", [{C,E}]), B({line,Flat}) end; Flat -> B({line, Flat}) end. %% Synchronous call. This is very raw, e.g. no return values, but %% good enough for now when storing values in the file system, %% e.g. for redo.erl %% FIXME: It might be enough to store the erlang term in the daemon %% and use a generic ack marker. Anyway, all just very ad-hoc code %% that needs to be cleaned up once the full chain is up. %% FIXME: At the very least allow for pass/fail without relying on %% timeouts. When doing pass/fail it's possible to return anything %% really, so let it return a string instead. %% FIXME: Scrape error messages to avoid timeout. They are fairly %% uniform, ending in ": error:" Note that that would give %% multiple acks, so it needs to be stateful. call(Ghci, Module, Function, Arg, TimeOut) -> log:info("ghci:call ~999p~n", [{Module,Function,Arg,TimeOut}]), Pid = self(), Ref = erlang:make_ref(), Ghci ! {run_cont, Module, Function, Arg, fun() -> Pid ! Ref end}, receive Ref -> ok after TimeOut -> {error, timeout} end.
null
https://raw.githubusercontent.com/zwizwa/erl_tools/affd4060ab5b963e0cc8fcfd4a1ca5023aa518d3/src/ghci.erl
erlang
FIXME: - start ghci - start loop - save pid for later control - proper restart even if loop is running: exo:restart(ghci_bert). - start loop: - stop loop: bert_rpc:call("localhost",7890,control,stop,[]). - alternatively, get pid via this, then send SIGINT Wrapper for ghci. See also ghcid.erl - NIH: Building what I actually need, instead of trying to shoe-horn ghcid into exo. I already have file change notifications, so just need simple reload and test run. - The proper way to do this is to move to ghcide. - The module is stateful: there is an idea of a "current" module that exposes a "test" function. - GHCI output can be redirected to a "buffer", which implements a - Ad-hoc synchronization use the '#' character to encode continuations as hex-encoded binary terms. - Data exchange should go over a side channel. Since this is used in redo scripts, it seems simplest to just communicate through files. E.g. pass in/out file as parameters, and use the '#' mechanism to signal. After initial load, send an optional initialization message, e.g. to start a service inside ghci. It is assumed a test module is loaded at all times. The test itself doesn't need to run at startup. FIXME: this seems to have no effect with exo config This is very ad-hoc, but we do our best to: - Ensure the correct module is loaded - Ensure an ack that the caller can use to sync on This way it is still possible to have multiple calls in flight. Note that the sync is just an empty event. To determine success programmatically, a side effect needs to be used, e.g. the existence of a file. FIXME: this seems to have no effect with exo config ":show modules", Data coming from ghci gets chopped into lines and passed to a log_buf. Mostly modeled after emacs buffer: supports append lines + buffer clear. Line framing is used to be able to easily encode some in-band data. log:info("Data = ~999p~n", [Data]), Abstract logger. Synchronous call. This is very raw, e.g. no return values, but good enough for now when storing values in the file system, e.g. for redo.erl FIXME: It might be enough to store the erlang term in the daemon and use a generic ack marker. Anyway, all just very ad-hoc code that needs to be cleaned up once the full chain is up. FIXME: At the very least allow for pass/fail without relying on timeouts. When doing pass/fail it's possible to return anything really, so let it return a string instead. FIXME: Scrape error messages to avoid timeout. They are fairly uniform, ending in ": error:" Note that that would give multiple acks, so it needs to be stateful.
Special case ExoBERT . Later bootstrap todo : - use to get pid exo : ) ! { cmds,[":reload","start " ] } . bert_rpc : call("localhost",7890,control , pid , [ ] ) . Notes ' clear ' and { ' } -module(ghci). -export([start_link/1, handle/2, call/5]). start_link(#{ ghci_cmd := Cmd, module := Module } = Config) -> {ok, serv:start( {handler, fun() -> case maps:find(init_msg, Config) of error -> ok; {ok, Msg} -> self() ! Msg end, handle( {load, Module}, maps:put( port, open_port({spawn, Cmd}, [use_stdio, exit_status]), Config)) end, fun ?MODULE:handle/2})}. handle(clear, State) -> LogBuf = maps:get(log_buf, State, fun log_buf/1), State; handle(_Msg={cmds, Cmds}, #{ port := Port } = State) -> log : " , [ _ Msg ] ) , port_command(Port, [[Cmd, "\n"] || Cmd <- Cmds]), State; handle({load, Module}, State) -> handle({cmds,[tools:format(":load ~s",[Module])]}, maps:put(module, Module, State)); handle({run,Module,Function,Arg,SyncString}, State0 = #{module := CurrentModule}) -> State = case Module == CurrentModule of true -> State0; false -> handle({load, Module}, State0) end, log:info("run: ~p~n", [{Module,Function}]), LogBuf = maps:get(log_buf, State, fun log_buf/1), handle( {cmds, [":reload", tools:format( "~s.~s ~s", [Module, Function, Arg]), tools:format( "Prelude.putStrLn \"\\n~s\"", [SyncString])]}, State); Run with Erlang continuation encoded in the ack string . handle({run_cont,Module,Function,Arg,Cont}, State) -> SyncString = [$#, tools:hex(erlang:term_to_binary(Cont))], handle({run,Module,Function,Arg,SyncString}, State); handle({Port, {data, Data}}, #{ port := Port } = State) -> LogBuf = maps:get(log_buf, State, fun log_buf/1), Buf = maps:get(buf, State, []), Buf1 = log_lines(LogBuf, Data, Buf), maps:put(buf, Buf1, State); handle({Port, {exit_status,_}}=Msg, #{ port := Port }) -> exit(Msg); handle({_,dump}=Msg, State) -> obj:handle(Msg, State); handle(Msg, State) -> log:info("unknown: ~p~n", Msg), throw({?MODULE,unknown_msg,Msg}), State. log_buf({line, Line}) -> log:info("~s~n",[Line]); log_buf(_) -> ok. flat(L) -> lists:flatten(L). log_lines(_, [], Line) -> flat(Line); log_lines(B, [$\n|Tail], Line) -> dispatch_line(B, Line), log_lines(B, Tail,[]); log_lines(B, [Char|Tail], Line) -> log_lines(B,Tail,[Line,Char]). dispatch_line(B, Line) -> case flat(Line) of [$#|Enc]=Flat -> try Bin = iolist_to_binary(tools:unhex(Enc)), Term = binary_to_term(Bin), Term() catch C:E -> log:info("WARNING: decoding: ~p~n", [{C,E}]), B({line,Flat}) end; Flat -> B({line, Flat}) end. call(Ghci, Module, Function, Arg, TimeOut) -> log:info("ghci:call ~999p~n", [{Module,Function,Arg,TimeOut}]), Pid = self(), Ref = erlang:make_ref(), Ghci ! {run_cont, Module, Function, Arg, fun() -> Pid ! Ref end}, receive Ref -> ok after TimeOut -> {error, timeout} end.
b47a5ac681f2a3488b4e48297a582d4b36cb04ceb7ab616266b9cd22aa9e0af5
borodust/alien-works
utils.lisp
(cl:in-package :alien-works.tools.resources) (declaim (special *scene* *mesh* *material* *images* *materials*)) (a:define-constant +attribute-alignment+ 4) (defvar *dry-run* nil) (defmacro with-ai-struct ((var type &optional value) &body body) `(cref:c-let ((,var (:struct ,type) :from ,(or value var))) ,@body)) (defmacro with-scene ((scene-var) &body body) `(with-ai-struct (,scene-var %ai:scene *scene*) ,@body)) (defmacro with-mesh ((mesh-var &optional mesh-val) &body body) `(with-ai-struct (,mesh-var %ai:mesh (or ,mesh-val *mesh*)) ,@body)) (defmacro with-material ((var &optional value) &body body) `(with-ai-struct (,var %ai:material (or ,value *material*)) ,@body)) (defmacro with-material-property ((var &optional value) &body body) `(with-ai-struct (,var %ai:material-property ,value) ,@body)) (defmacro with-vector3d ((var &optional src) &body body) (if src `(cref:c-let ((,var (:struct %ai:vector3d) :from ,src)) ,@body) `(cref:c-val ((,var (:struct %ai:vector3d))) ,@body))) (defmacro with-vector3d* ((&rest bindings) &body body) (u:expand-multibinding 'with-vector3d bindings body)) (defmacro with-color4d ((var &optional src) &body body) (if src `(cref:c-let ((,var (:struct %ai:color4d) :from ,src)) ,@body) `(cref:c-val ((,var (:struct %ai:color4d))) ,@body))) (defmacro with-face ((var &optional src) &body body) (if src `(cref:c-let ((,var (:struct %ai:face) :from ,src)) ,@body) `(cref:c-val ((,var (:struct %ai:face))) ,@body))) (defun ai-string-to-lisp (ai-string) (cref:c-val ((ai-string (:struct %ai:string))) (cffi:foreign-string-to-lisp (ai-string :data &) :count (ai-string :length)))) (defmacro write-primitives (buffer type values) (a:with-gensyms (idx value) (a:once-only (buffer) `(cref:c-val ((,buffer ,type)) (loop for ,value in ,values for ,idx from 0 unless *dry-run* do (setf (,buffer ,idx) ,value) finally (return (* (cffi:foreign-type-size ,type) (1+ ,idx)))))))) (defun write-float (buffer &rest values) (write-primitives buffer :float values)) (defun write-int16 (buffer &rest values) (write-primitives buffer :int16 values)) (defun write-uint16 (buffer &rest values) (write-primitives buffer :uint16 values)) (defun write-uint32 (buffer &rest values) (write-primitives buffer :uint32 values)) (defun write-int8 (buffer &rest values) (write-primitives buffer :int8 values)) (defun normalize-uint8 (float) (let ((uint8-size (1- (ash 1 8)))) (round (* uint8-size (rem float 1f0))))) (defun denormalize-uint8 (value) (let ((uint8-size (1- (ash 1 8)))) (float (/ value uint8-size) 0f0))) (defun normalize-int16 (float) (let ((int16-size (1- (ash 1 15)))) (round (* int16-size (rem float 1f0))))) (defun normalize-uint16 (float) (let ((int16-size (1- (ash 1 16)))) (round (* int16-size (rem float 1f0))))) (defun calc-alignment-padding (bytes) (let* ((offset (mod bytes +attribute-alignment+))) (if (zerop offset) 0 (- +attribute-alignment+ offset)))) (defun align-buffer (buffer) (let* ((address (cffi:pointer-address buffer)) (shift (calc-alignment-padding address))) (values (cffi:inc-pointer buffer shift) shift))) (defmacro dry-run (&body body) `(let ((*dry-run* t)) ,@body)) (defun make-simple-array (size type) #+lispworks (make-array size :element-type type :allocation :static) #+(or sbcl ccl ecl) (make-array size :element-type type) #-(or sbcl ccl ecl lispworks) (error "make-simple-array is not implemented for ~A" (lisp-implementation-type))) (defmacro with-simple-array-pointer ((pointer-var simple-array) &body body) (a:once-only (simple-array) #+sbcl `(sb-sys:with-pinned-objects (,simple-array) (let ((,pointer-var (sb-sys:vector-sap (sb-ext:array-storage-vector ,simple-array)))) ,@body)) #+ccl `(ccl:with-pointer-to-ivector (,pointer-var ,simple-array) ,@body) #+ecl `(let ((,pointer-var (si:make-foreign-data-from-array ,simple-array))) ,@body) #+lispworks `(fli:with-dynamic-lisp-array-pointer (,pointer-var ,simple-array) ,@body) #-(or sbcl ccl ecl lispworks) (error "with-simple-array-pointer is not implemented for ~A" (lisp-implementation-type))))
null
https://raw.githubusercontent.com/borodust/alien-works/a69254723ca02ddef691974f5daa52aaabfbce0b/tools/resources/scene/utils.lisp
lisp
(cl:in-package :alien-works.tools.resources) (declaim (special *scene* *mesh* *material* *images* *materials*)) (a:define-constant +attribute-alignment+ 4) (defvar *dry-run* nil) (defmacro with-ai-struct ((var type &optional value) &body body) `(cref:c-let ((,var (:struct ,type) :from ,(or value var))) ,@body)) (defmacro with-scene ((scene-var) &body body) `(with-ai-struct (,scene-var %ai:scene *scene*) ,@body)) (defmacro with-mesh ((mesh-var &optional mesh-val) &body body) `(with-ai-struct (,mesh-var %ai:mesh (or ,mesh-val *mesh*)) ,@body)) (defmacro with-material ((var &optional value) &body body) `(with-ai-struct (,var %ai:material (or ,value *material*)) ,@body)) (defmacro with-material-property ((var &optional value) &body body) `(with-ai-struct (,var %ai:material-property ,value) ,@body)) (defmacro with-vector3d ((var &optional src) &body body) (if src `(cref:c-let ((,var (:struct %ai:vector3d) :from ,src)) ,@body) `(cref:c-val ((,var (:struct %ai:vector3d))) ,@body))) (defmacro with-vector3d* ((&rest bindings) &body body) (u:expand-multibinding 'with-vector3d bindings body)) (defmacro with-color4d ((var &optional src) &body body) (if src `(cref:c-let ((,var (:struct %ai:color4d) :from ,src)) ,@body) `(cref:c-val ((,var (:struct %ai:color4d))) ,@body))) (defmacro with-face ((var &optional src) &body body) (if src `(cref:c-let ((,var (:struct %ai:face) :from ,src)) ,@body) `(cref:c-val ((,var (:struct %ai:face))) ,@body))) (defun ai-string-to-lisp (ai-string) (cref:c-val ((ai-string (:struct %ai:string))) (cffi:foreign-string-to-lisp (ai-string :data &) :count (ai-string :length)))) (defmacro write-primitives (buffer type values) (a:with-gensyms (idx value) (a:once-only (buffer) `(cref:c-val ((,buffer ,type)) (loop for ,value in ,values for ,idx from 0 unless *dry-run* do (setf (,buffer ,idx) ,value) finally (return (* (cffi:foreign-type-size ,type) (1+ ,idx)))))))) (defun write-float (buffer &rest values) (write-primitives buffer :float values)) (defun write-int16 (buffer &rest values) (write-primitives buffer :int16 values)) (defun write-uint16 (buffer &rest values) (write-primitives buffer :uint16 values)) (defun write-uint32 (buffer &rest values) (write-primitives buffer :uint32 values)) (defun write-int8 (buffer &rest values) (write-primitives buffer :int8 values)) (defun normalize-uint8 (float) (let ((uint8-size (1- (ash 1 8)))) (round (* uint8-size (rem float 1f0))))) (defun denormalize-uint8 (value) (let ((uint8-size (1- (ash 1 8)))) (float (/ value uint8-size) 0f0))) (defun normalize-int16 (float) (let ((int16-size (1- (ash 1 15)))) (round (* int16-size (rem float 1f0))))) (defun normalize-uint16 (float) (let ((int16-size (1- (ash 1 16)))) (round (* int16-size (rem float 1f0))))) (defun calc-alignment-padding (bytes) (let* ((offset (mod bytes +attribute-alignment+))) (if (zerop offset) 0 (- +attribute-alignment+ offset)))) (defun align-buffer (buffer) (let* ((address (cffi:pointer-address buffer)) (shift (calc-alignment-padding address))) (values (cffi:inc-pointer buffer shift) shift))) (defmacro dry-run (&body body) `(let ((*dry-run* t)) ,@body)) (defun make-simple-array (size type) #+lispworks (make-array size :element-type type :allocation :static) #+(or sbcl ccl ecl) (make-array size :element-type type) #-(or sbcl ccl ecl lispworks) (error "make-simple-array is not implemented for ~A" (lisp-implementation-type))) (defmacro with-simple-array-pointer ((pointer-var simple-array) &body body) (a:once-only (simple-array) #+sbcl `(sb-sys:with-pinned-objects (,simple-array) (let ((,pointer-var (sb-sys:vector-sap (sb-ext:array-storage-vector ,simple-array)))) ,@body)) #+ccl `(ccl:with-pointer-to-ivector (,pointer-var ,simple-array) ,@body) #+ecl `(let ((,pointer-var (si:make-foreign-data-from-array ,simple-array))) ,@body) #+lispworks `(fli:with-dynamic-lisp-array-pointer (,pointer-var ,simple-array) ,@body) #-(or sbcl ccl ecl lispworks) (error "with-simple-array-pointer is not implemented for ~A" (lisp-implementation-type))))
b355a0ad20c5bd12db8f1ba46aa6b268e0a8cf5d892fcd9a60ad4a15fdbae158
ghcjs/jsaddle
Warp.hs
# LANGUAGE CPP # # LANGUAGE LambdaCase # {-# LANGUAGE OverloadedStrings #-} ----------------------------------------------------------------------------- -- -- Module : Language.Javascript.JSaddle.WebSockets Copyright : ( c ) License : MIT -- Maintainer : < > -- -- | -- ----------------------------------------------------------------------------- module Language.Javascript.JSaddle.Warp ( * Running JSM over WebSockets run #ifndef ghcjs_HOST_OS , module Language.Javascript.JSaddle.WebSockets #endif ) where #ifndef ghcjs_HOST_OS import Network.Wai.Handler.Warp (defaultSettings, setTimeout, setPort, runSettings) import Network.WebSockets (defaultConnectionOptions) import Language.Javascript.JSaddle.Types (JSM) import Language.Javascript.JSaddle.Run (syncPoint) import Language.Javascript.JSaddle.WebSockets #endif -- | Run the given 'JSM' action as the main entry point. Either directly in GHCJS or as a Warp server on the given port on GHC . #ifdef ghcjs_HOST_OS run :: Int -> IO () -> IO () run _port = id #else run :: Int -> JSM () -> IO () run port f = runSettings (setPort port (setTimeout 3600 defaultSettings)) =<< jsaddleOr defaultConnectionOptions (f >> syncPoint) jsaddleApp #endif
null
https://raw.githubusercontent.com/ghcjs/jsaddle/97273656e28790ab6e35c827f8086cf47bfbedca/jsaddle-warp/src/Language/Javascript/JSaddle/Warp.hs
haskell
# LANGUAGE OverloadedStrings # --------------------------------------------------------------------------- Module : Language.Javascript.JSaddle.WebSockets | --------------------------------------------------------------------------- | Run the given 'JSM' action as the main entry point. Either directly
# LANGUAGE CPP # # LANGUAGE LambdaCase # Copyright : ( c ) License : MIT Maintainer : < > module Language.Javascript.JSaddle.Warp ( * Running JSM over WebSockets run #ifndef ghcjs_HOST_OS , module Language.Javascript.JSaddle.WebSockets #endif ) where #ifndef ghcjs_HOST_OS import Network.Wai.Handler.Warp (defaultSettings, setTimeout, setPort, runSettings) import Network.WebSockets (defaultConnectionOptions) import Language.Javascript.JSaddle.Types (JSM) import Language.Javascript.JSaddle.Run (syncPoint) import Language.Javascript.JSaddle.WebSockets #endif in GHCJS or as a Warp server on the given port on GHC . #ifdef ghcjs_HOST_OS run :: Int -> IO () -> IO () run _port = id #else run :: Int -> JSM () -> IO () run port f = runSettings (setPort port (setTimeout 3600 defaultSettings)) =<< jsaddleOr defaultConnectionOptions (f >> syncPoint) jsaddleApp #endif
11f2e956dde6cfb666f9e0b3b3a7f09bbbdb46432e98164ea302febff21539b7
CoNarrative/precept
project.clj
(defproject fullstack "0.0.0" :dependencies [[org.clojure/clojure "1.9.0-alpha17"] [ch.qos.logback/logback-classic "1.1.7"] [cljs-ajax "0.5.8"] [compojure "1.5.2"] [cprop "0.1.10"] [hiccup "1.0.5"] [luminus-http-kit "0.1.4"] [luminus-nrepl "0.1.4"] [luminus/ring-ttl-session "0.3.1"] [metosin/compojure-api "1.1.10" :exclusions [prismatic/schema]] [metosin/ring-http-response "0.8.1"] [mount "0.1.11"] [org.clojure/clojurescript "1.9.854"] [org.clojure/core.async "0.3.442"] [org.clojure/tools.cli "0.3.5"] [org.clojure/tools.logging "0.3.1"] [precept "0.5.0-alpha"] [reagent "0.6.0"] [reagent-utils "0.2.0"] [ring-middleware-format "0.7.2"] [ring/ring-core "1.5.1"] [ring/ring-defaults "0.2.3"] [secretary "1.2.3"] [selmer "1.10.6"] [com.taoensso/sente "1.11.0"]] :jvm-opts ["-server" "-Dconf=.lein-env"] :source-paths ["src/clj" "src/cljc"] :test-paths ["test"] :resource-paths ["resources" "target/cljsbuild"] :target-path "target/%s/" :main fullstack.core :plugins [[lein-cprop "1.0.1"] [lein-cljsbuild "1.1.4"]] :clean-targets ^{:protect false} [:target-path [:cljsbuild :builds :app :compiler :output-dir] [:cljsbuild :builds :app :compiler :output-to]] :figwheel {:http-server-root "public" :nrepl-port 7002 :css-dirs ["resources/public/css"] :nrepl-middleware [cemerick.piggieback/wrap-cljs-repl]} :profiles {:dev [:project/dev :profiles/dev] :test [:project/dev :project/test :profiles/test] :project/dev {:dependencies [[prone "1.1.4"] [ring/ring-mock "0.3.0"] [ring/ring-devel "1.5.1"] [pjstadig/humane-test-output "0.8.1"] [binaryage/devtools "0.9.0"] [com.cemerick/piggieback "0.2.2-SNAPSHOT"] [doo "0.1.7"] [org.clojure/test.check "0.9.0"] [figwheel-sidecar "0.5.11"]] :plugins [[com.jakemccrary/lein-test-refresh "0.18.1"] [lein-doo "0.1.7"] [lein-figwheel "0.5.11"] [org.clojure/clojurescript "1.9.671"]] :cljsbuild {:builds {:app {:source-paths ["src/cljs" "src/cljc" "env/dev/cljs"] :compiler {:main "fullstack.app" :asset-path "/js/out" :output-to "target/cljsbuild/public/js/app.js" :output-dir "target/cljsbuild/public/js/out" :source-map true :optimizations :none :pretty-print true}}}} :doo {:build "test"} :source-paths ["env/dev/clj"] :resource-paths ["env/dev/resources"] :repl-options {:init-ns user} :injections [(require 'pjstadig.humane-test-output) (pjstadig.humane-test-output/activate!)]} :project/test {:resource-paths ["env/test/resources"] :cljsbuild {:builds {:test {:source-paths ["src/cljs" "test/cljs"] :compiler {:output-to "target/test.js" :main "fullstack.doo-runner" :optimizations :whitespace :pretty-print true}}}}} :profiles/dev {} :profiles/test {}})
null
https://raw.githubusercontent.com/CoNarrative/precept/6078286cae641b924a2bffca4ecba19dcc304dde/examples/fullstack/project.clj
clojure
(defproject fullstack "0.0.0" :dependencies [[org.clojure/clojure "1.9.0-alpha17"] [ch.qos.logback/logback-classic "1.1.7"] [cljs-ajax "0.5.8"] [compojure "1.5.2"] [cprop "0.1.10"] [hiccup "1.0.5"] [luminus-http-kit "0.1.4"] [luminus-nrepl "0.1.4"] [luminus/ring-ttl-session "0.3.1"] [metosin/compojure-api "1.1.10" :exclusions [prismatic/schema]] [metosin/ring-http-response "0.8.1"] [mount "0.1.11"] [org.clojure/clojurescript "1.9.854"] [org.clojure/core.async "0.3.442"] [org.clojure/tools.cli "0.3.5"] [org.clojure/tools.logging "0.3.1"] [precept "0.5.0-alpha"] [reagent "0.6.0"] [reagent-utils "0.2.0"] [ring-middleware-format "0.7.2"] [ring/ring-core "1.5.1"] [ring/ring-defaults "0.2.3"] [secretary "1.2.3"] [selmer "1.10.6"] [com.taoensso/sente "1.11.0"]] :jvm-opts ["-server" "-Dconf=.lein-env"] :source-paths ["src/clj" "src/cljc"] :test-paths ["test"] :resource-paths ["resources" "target/cljsbuild"] :target-path "target/%s/" :main fullstack.core :plugins [[lein-cprop "1.0.1"] [lein-cljsbuild "1.1.4"]] :clean-targets ^{:protect false} [:target-path [:cljsbuild :builds :app :compiler :output-dir] [:cljsbuild :builds :app :compiler :output-to]] :figwheel {:http-server-root "public" :nrepl-port 7002 :css-dirs ["resources/public/css"] :nrepl-middleware [cemerick.piggieback/wrap-cljs-repl]} :profiles {:dev [:project/dev :profiles/dev] :test [:project/dev :project/test :profiles/test] :project/dev {:dependencies [[prone "1.1.4"] [ring/ring-mock "0.3.0"] [ring/ring-devel "1.5.1"] [pjstadig/humane-test-output "0.8.1"] [binaryage/devtools "0.9.0"] [com.cemerick/piggieback "0.2.2-SNAPSHOT"] [doo "0.1.7"] [org.clojure/test.check "0.9.0"] [figwheel-sidecar "0.5.11"]] :plugins [[com.jakemccrary/lein-test-refresh "0.18.1"] [lein-doo "0.1.7"] [lein-figwheel "0.5.11"] [org.clojure/clojurescript "1.9.671"]] :cljsbuild {:builds {:app {:source-paths ["src/cljs" "src/cljc" "env/dev/cljs"] :compiler {:main "fullstack.app" :asset-path "/js/out" :output-to "target/cljsbuild/public/js/app.js" :output-dir "target/cljsbuild/public/js/out" :source-map true :optimizations :none :pretty-print true}}}} :doo {:build "test"} :source-paths ["env/dev/clj"] :resource-paths ["env/dev/resources"] :repl-options {:init-ns user} :injections [(require 'pjstadig.humane-test-output) (pjstadig.humane-test-output/activate!)]} :project/test {:resource-paths ["env/test/resources"] :cljsbuild {:builds {:test {:source-paths ["src/cljs" "test/cljs"] :compiler {:output-to "target/test.js" :main "fullstack.doo-runner" :optimizations :whitespace :pretty-print true}}}}} :profiles/dev {} :profiles/test {}})
260b33812b80db2dab40e6ea2121873a93ef441b20ef31a7d1a79d5666dd31cb
openmusic-project/openmusic
test.lisp
;;;; -*- Mode: Lisp -*- $ I d : test.lisp 658 2008 - 11 - 21 18:27:24Z binghe $ (in-package :cl-user) UDP Echo Test : use macros (defun udp-echo-test-3 (&optional (port 10000)) (let* ((fn #'(lambda (data) (map '(simple-array (unsigned-byte 8) (*)) #'char-code (format nil "receive from ~A:~A -> ~A" (comm+:ip-address-string comm+:*client-address*) comm+:*client-port* (map 'string #'code-char data))))) (server-process (comm+:start-udp-server :function fn :service port))) (unwind-protect (comm+:with-udp-stream (stream "localhost" port :read-timeout 1 :errorp t) (let ((data "Hello, world!")) (format stream "~A" data) = " ~% " or # \Newline (force-output stream) (format t "STREAM: Send message: ~A~%" data) (let ((echo (read-line stream nil nil))) (format t "STREAM: Recv message: ~A~%" echo)))) (comm+:stop-udp-server server-process)))) (defun udp-echo-test-4 (&optional (port 10000)) (let* ((server-process (comm+:start-udp-server :function #'reverse :service port))) (unwind-protect (comm+:with-udp-socket (socket :read-timeout 10) (let ((data #(1 2 3 4 5 6 7 8 9 10))) (comm+:send-message socket data :host "localhost" :service port) (format t "SOCKET: Send message: ~A~%" data) (let ((echo (multiple-value-list (comm+:receive-message socket :max-buffer-size 8)))) (format t "SOCKET: Recv message: ~A~%" echo)))) (comm+:stop-udp-server server-process)))) (defun udp-echo-test-5 (&optional (port 10000)) "Limit MAX-BUFFER-SIZE, less than send bytes." (let* ((echo-fn #'(lambda (data) data)) (server-process (comm+:start-udp-server :function echo-fn :service port))) (unwind-protect (comm+:with-connected-udp-socket (socket "localhost" port :read-timeout 1 :errorp t) (let ((data #(1 2 3 4 5 6 7 8 9 10))) (princ (comm+:send-message socket data :host nil :service nil)) (format t "SOCKET: Send message: ~A~%" data) (let ((echo (multiple-value-list (comm+:receive-message socket :max-buffer-size 8)))) (format t "SOCKET: Recv message: ~A~%" echo)))) (comm+:stop-udp-server server-process)))) (defun loop-test (&optional (port 3500)) (labels ((echo-fn (data) data)) (loop for i from 1 to 10 do (let ((server (comm+:start-udp-server :function #'echo-fn :service port :loop-time 0.3))) (comm+:with-udp-socket (socket :read-timeout 1) (let ((data #(1 2 3 4 5 6 7 8 9 10))) (comm+:send-message socket data (length data) "localhost" port) (format t "SOCKET: Send message: ~A~%" data) (let ((echo (multiple-value-list (comm+:receive-message socket)))) (format t "SOCKET: Recv message: ~A~%" echo)))) (princ (comm+:stop-udp-server server :wait t)))))) (defun rtt-test-1 (&optional (port 10000)) "RTT test" (let ((server-process (comm+:start-udp-server :function #'reverse :service port))) (unwind-protect (comm+:with-connected-udp-socket (socket "localhost" port :errorp t) (comm+:sync-message socket "xxxxABCDEFGH" :max-receive-length 8 :encode-function #'(lambda (x) (values (map 'vector #'char-code x) 0)) :decode-function #'(lambda (x) (values (map 'string #'code-char x) 0)))) (comm+:stop-udp-server server-process)))) (defun rtt-test-2 (&optional (port 10000)) "RTT test, no server" (comm+:with-udp-socket (socket) (handler-case (comm+:sync-message socket "xxxxABCDEFGH" :host "localhost" :service port :max-receive-length 8 :encode-function #'(lambda (x) (values (map 'vector #'char-code x) 0)) :decode-function #'(lambda (x) (values (map 'string #'code-char x) 0))) (error (c) (format t "Got a condition (~A): ~A~%" (type-of c) c))))) #-mswindows (defun wait-test-1 (&optional (port 10000)) (let* ((server-process (comm+:start-udp-server :function #'reverse :service port))) (unwind-protect (comm+:with-udp-socket (socket) (let ((data #(1 2 3 4 5 6 7 8 9 10))) (comm+:send-message socket data :host "localhost" :service port) (format t "SOCKET: Send message: ~A~%" data) ;;; wait the socket until it's available (comm+:wait-for-input socket) (let ((echo (multiple-value-list (comm+:receive-message socket :max-buffer-size 8)))) (format t "SOCKET: Recv message: ~A~%" echo)))) (comm+:stop-udp-server server-process)))) #-mswindows (defun mcast-test-1 (&optional (host "224.0.0.1") (port 10000)) "Send one get three" (let* ((echo-fn #'(lambda (data) data)) (server-processes (mapcar #'(lambda (x) (comm+:start-udp-server :function echo-fn :service port :announce t :address host :multicast t)) '(nil nil nil)))) (unwind-protect (comm+:with-connected-udp-socket (socket host port :read-timeout 1 :errorp t) (let ((data #(1 2 3 4 5 6 7 8 9 10))) (format t "~A~%" (comm+:send-message socket data)) (format t "SOCKET: Send message: ~A~%" data) (dotimes (i 3) (let ((echo (multiple-value-list (comm+:receive-message socket :max-buffer-size 8)))) (format t "SOCKET: Recv message: ~A~%" echo))))) (mapcar #'comm+:stop-udp-server server-processes))))
null
https://raw.githubusercontent.com/openmusic-project/openmusic/9560c064512a1598cd57bcc9f0151c0815178e6f/OPENMUSIC/code/api/externals/lispworks-udp/test.lisp
lisp
-*- Mode: Lisp -*- wait the socket until it's available
$ I d : test.lisp 658 2008 - 11 - 21 18:27:24Z binghe $ (in-package :cl-user) UDP Echo Test : use macros (defun udp-echo-test-3 (&optional (port 10000)) (let* ((fn #'(lambda (data) (map '(simple-array (unsigned-byte 8) (*)) #'char-code (format nil "receive from ~A:~A -> ~A" (comm+:ip-address-string comm+:*client-address*) comm+:*client-port* (map 'string #'code-char data))))) (server-process (comm+:start-udp-server :function fn :service port))) (unwind-protect (comm+:with-udp-stream (stream "localhost" port :read-timeout 1 :errorp t) (let ((data "Hello, world!")) (format stream "~A" data) = " ~% " or # \Newline (force-output stream) (format t "STREAM: Send message: ~A~%" data) (let ((echo (read-line stream nil nil))) (format t "STREAM: Recv message: ~A~%" echo)))) (comm+:stop-udp-server server-process)))) (defun udp-echo-test-4 (&optional (port 10000)) (let* ((server-process (comm+:start-udp-server :function #'reverse :service port))) (unwind-protect (comm+:with-udp-socket (socket :read-timeout 10) (let ((data #(1 2 3 4 5 6 7 8 9 10))) (comm+:send-message socket data :host "localhost" :service port) (format t "SOCKET: Send message: ~A~%" data) (let ((echo (multiple-value-list (comm+:receive-message socket :max-buffer-size 8)))) (format t "SOCKET: Recv message: ~A~%" echo)))) (comm+:stop-udp-server server-process)))) (defun udp-echo-test-5 (&optional (port 10000)) "Limit MAX-BUFFER-SIZE, less than send bytes." (let* ((echo-fn #'(lambda (data) data)) (server-process (comm+:start-udp-server :function echo-fn :service port))) (unwind-protect (comm+:with-connected-udp-socket (socket "localhost" port :read-timeout 1 :errorp t) (let ((data #(1 2 3 4 5 6 7 8 9 10))) (princ (comm+:send-message socket data :host nil :service nil)) (format t "SOCKET: Send message: ~A~%" data) (let ((echo (multiple-value-list (comm+:receive-message socket :max-buffer-size 8)))) (format t "SOCKET: Recv message: ~A~%" echo)))) (comm+:stop-udp-server server-process)))) (defun loop-test (&optional (port 3500)) (labels ((echo-fn (data) data)) (loop for i from 1 to 10 do (let ((server (comm+:start-udp-server :function #'echo-fn :service port :loop-time 0.3))) (comm+:with-udp-socket (socket :read-timeout 1) (let ((data #(1 2 3 4 5 6 7 8 9 10))) (comm+:send-message socket data (length data) "localhost" port) (format t "SOCKET: Send message: ~A~%" data) (let ((echo (multiple-value-list (comm+:receive-message socket)))) (format t "SOCKET: Recv message: ~A~%" echo)))) (princ (comm+:stop-udp-server server :wait t)))))) (defun rtt-test-1 (&optional (port 10000)) "RTT test" (let ((server-process (comm+:start-udp-server :function #'reverse :service port))) (unwind-protect (comm+:with-connected-udp-socket (socket "localhost" port :errorp t) (comm+:sync-message socket "xxxxABCDEFGH" :max-receive-length 8 :encode-function #'(lambda (x) (values (map 'vector #'char-code x) 0)) :decode-function #'(lambda (x) (values (map 'string #'code-char x) 0)))) (comm+:stop-udp-server server-process)))) (defun rtt-test-2 (&optional (port 10000)) "RTT test, no server" (comm+:with-udp-socket (socket) (handler-case (comm+:sync-message socket "xxxxABCDEFGH" :host "localhost" :service port :max-receive-length 8 :encode-function #'(lambda (x) (values (map 'vector #'char-code x) 0)) :decode-function #'(lambda (x) (values (map 'string #'code-char x) 0))) (error (c) (format t "Got a condition (~A): ~A~%" (type-of c) c))))) #-mswindows (defun wait-test-1 (&optional (port 10000)) (let* ((server-process (comm+:start-udp-server :function #'reverse :service port))) (unwind-protect (comm+:with-udp-socket (socket) (let ((data #(1 2 3 4 5 6 7 8 9 10))) (comm+:send-message socket data :host "localhost" :service port) (format t "SOCKET: Send message: ~A~%" data) (comm+:wait-for-input socket) (let ((echo (multiple-value-list (comm+:receive-message socket :max-buffer-size 8)))) (format t "SOCKET: Recv message: ~A~%" echo)))) (comm+:stop-udp-server server-process)))) #-mswindows (defun mcast-test-1 (&optional (host "224.0.0.1") (port 10000)) "Send one get three" (let* ((echo-fn #'(lambda (data) data)) (server-processes (mapcar #'(lambda (x) (comm+:start-udp-server :function echo-fn :service port :announce t :address host :multicast t)) '(nil nil nil)))) (unwind-protect (comm+:with-connected-udp-socket (socket host port :read-timeout 1 :errorp t) (let ((data #(1 2 3 4 5 6 7 8 9 10))) (format t "~A~%" (comm+:send-message socket data)) (format t "SOCKET: Send message: ~A~%" data) (dotimes (i 3) (let ((echo (multiple-value-list (comm+:receive-message socket :max-buffer-size 8)))) (format t "SOCKET: Recv message: ~A~%" echo))))) (mapcar #'comm+:stop-udp-server server-processes))))
19c96e47d1871477eb39b0d2f460147f5737f5dcbc8bc21c3faaa01dcf97ba88
MyDataFlow/ttalk-server
meck_args_matcher.erl
%%%============================================================================ Licensed under the Apache License , Version 2.0 ( the " License " ) ; %%% you may not use this file except in compliance with the License. %%% You may obtain a copy of the License at %%% %%% -2.0 %%% %%% Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , %%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %%% See the License for the specific language governing permissions and %%% limitations under the License. %%%============================================================================ @private -module(meck_args_matcher). -export_type([args_spec/0]). -export_type([opt_args_spec/0]). -export_type([args_matcher/0]). %% API -export([new/1]). -export([arity/1]). -export([match/2]). %%%============================================================================ %%% Definitions %%%============================================================================ -record(args_matcher, {opt_args_pattern :: opt_args_pattern(), comp_match_spec :: ets:comp_match_spec(), has_matchers :: boolean()}). %%%============================================================================ %%% Types %%%============================================================================ -type opt_args_spec() :: args_spec() | '_'. -type args_spec() :: args_pattern() | non_neg_integer(). -type opt_args_pattern() :: args_pattern() | '_'. -type args_pattern() :: [any() | '_' | meck_matcher:matcher()]. -opaque args_matcher() :: #args_matcher{}. %%%============================================================================ %%% API %%%============================================================================ -spec new(opt_args_spec()) -> args_matcher(). new('_') -> MatchSpecItem = meck_util:match_spec_item({'_'}), CompMatchSpec = ets:match_spec_compile([MatchSpecItem]), #args_matcher{opt_args_pattern = '_', comp_match_spec = CompMatchSpec, has_matchers = false}; new(Arity) when is_number(Arity) -> ArgsPattern = lists:duplicate(Arity, '_'), MatchSpecItem = meck_util:match_spec_item({ArgsPattern}), CompMatchSpec = ets:match_spec_compile([MatchSpecItem]), #args_matcher{opt_args_pattern = ArgsPattern, comp_match_spec = CompMatchSpec, has_matchers = false}; new(ArgsPattern) when is_list(ArgsPattern) -> {HasMatchers, Pattern} = case strip_off_matchers(ArgsPattern) of unchanged -> {false, ArgsPattern}; StrippedArgsSpec -> {true, StrippedArgsSpec} end, MatchSpecItem = meck_util:match_spec_item({Pattern}), CompMatchSpec = ets:match_spec_compile([MatchSpecItem]), #args_matcher{opt_args_pattern = ArgsPattern, comp_match_spec = CompMatchSpec, has_matchers = HasMatchers}. -spec arity(args_matcher()) -> Arity::non_neg_integer(). arity(#args_matcher{opt_args_pattern = ArgsPattern}) -> erlang:length(ArgsPattern). -spec match(Args::any(), args_matcher()) -> boolean(). match(Args, #args_matcher{opt_args_pattern = OptArgsPattern, comp_match_spec = CompMatchSpec, has_matchers = HasMatchers}) -> case ets:match_spec_run([{Args}], CompMatchSpec) of [] -> false; _Matches when HasMatchers andalso erlang:is_list(OptArgsPattern) -> check_by_matchers(Args, OptArgsPattern); _Matches -> true end. %%%============================================================================ Internal functions %%%============================================================================ -spec strip_off_matchers(args_pattern()) -> NewArgsPattern::args_pattern() | unchanged. strip_off_matchers(ArgsPattern) -> strip_off_matchers(ArgsPattern, [], false). -spec strip_off_matchers(args_pattern(), Stripped::[any() | '_'], boolean()) -> NewArgsPattern::args_pattern() | unchanged. strip_off_matchers([ArgPattern | Rest], Stripped, HasMatchers) -> case meck_matcher:is_matcher(ArgPattern) of true -> strip_off_matchers(Rest, ['_' | Stripped], true); _ -> strip_off_matchers(Rest, [ArgPattern | Stripped], HasMatchers) end; strip_off_matchers([], Stripped, true) -> lists:reverse(Stripped); strip_off_matchers([], _Stripped, false) -> unchanged. -spec check_by_matchers(Args ::[any()], MaybeMatchers::[any()]) -> boolean(). check_by_matchers([Arg | RestArgs], [MaybeMatcher | RestMaybeMatchers]) -> case meck_matcher:match_ignore(Arg, MaybeMatcher) of true -> check_by_matchers(RestArgs, RestMaybeMatchers); _Else -> false end; check_by_matchers([], []) -> true.
null
https://raw.githubusercontent.com/MyDataFlow/ttalk-server/07a60d5d74cd86aedd1f19c922d9d3abf2ebf28d/deps/meck/src/meck_args_matcher.erl
erlang
============================================================================ you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ============================================================================ API ============================================================================ Definitions ============================================================================ ============================================================================ Types ============================================================================ ============================================================================ API ============================================================================ ============================================================================ ============================================================================
Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , @private -module(meck_args_matcher). -export_type([args_spec/0]). -export_type([opt_args_spec/0]). -export_type([args_matcher/0]). -export([new/1]). -export([arity/1]). -export([match/2]). -record(args_matcher, {opt_args_pattern :: opt_args_pattern(), comp_match_spec :: ets:comp_match_spec(), has_matchers :: boolean()}). -type opt_args_spec() :: args_spec() | '_'. -type args_spec() :: args_pattern() | non_neg_integer(). -type opt_args_pattern() :: args_pattern() | '_'. -type args_pattern() :: [any() | '_' | meck_matcher:matcher()]. -opaque args_matcher() :: #args_matcher{}. -spec new(opt_args_spec()) -> args_matcher(). new('_') -> MatchSpecItem = meck_util:match_spec_item({'_'}), CompMatchSpec = ets:match_spec_compile([MatchSpecItem]), #args_matcher{opt_args_pattern = '_', comp_match_spec = CompMatchSpec, has_matchers = false}; new(Arity) when is_number(Arity) -> ArgsPattern = lists:duplicate(Arity, '_'), MatchSpecItem = meck_util:match_spec_item({ArgsPattern}), CompMatchSpec = ets:match_spec_compile([MatchSpecItem]), #args_matcher{opt_args_pattern = ArgsPattern, comp_match_spec = CompMatchSpec, has_matchers = false}; new(ArgsPattern) when is_list(ArgsPattern) -> {HasMatchers, Pattern} = case strip_off_matchers(ArgsPattern) of unchanged -> {false, ArgsPattern}; StrippedArgsSpec -> {true, StrippedArgsSpec} end, MatchSpecItem = meck_util:match_spec_item({Pattern}), CompMatchSpec = ets:match_spec_compile([MatchSpecItem]), #args_matcher{opt_args_pattern = ArgsPattern, comp_match_spec = CompMatchSpec, has_matchers = HasMatchers}. -spec arity(args_matcher()) -> Arity::non_neg_integer(). arity(#args_matcher{opt_args_pattern = ArgsPattern}) -> erlang:length(ArgsPattern). -spec match(Args::any(), args_matcher()) -> boolean(). match(Args, #args_matcher{opt_args_pattern = OptArgsPattern, comp_match_spec = CompMatchSpec, has_matchers = HasMatchers}) -> case ets:match_spec_run([{Args}], CompMatchSpec) of [] -> false; _Matches when HasMatchers andalso erlang:is_list(OptArgsPattern) -> check_by_matchers(Args, OptArgsPattern); _Matches -> true end. Internal functions -spec strip_off_matchers(args_pattern()) -> NewArgsPattern::args_pattern() | unchanged. strip_off_matchers(ArgsPattern) -> strip_off_matchers(ArgsPattern, [], false). -spec strip_off_matchers(args_pattern(), Stripped::[any() | '_'], boolean()) -> NewArgsPattern::args_pattern() | unchanged. strip_off_matchers([ArgPattern | Rest], Stripped, HasMatchers) -> case meck_matcher:is_matcher(ArgPattern) of true -> strip_off_matchers(Rest, ['_' | Stripped], true); _ -> strip_off_matchers(Rest, [ArgPattern | Stripped], HasMatchers) end; strip_off_matchers([], Stripped, true) -> lists:reverse(Stripped); strip_off_matchers([], _Stripped, false) -> unchanged. -spec check_by_matchers(Args ::[any()], MaybeMatchers::[any()]) -> boolean(). check_by_matchers([Arg | RestArgs], [MaybeMatcher | RestMaybeMatchers]) -> case meck_matcher:match_ignore(Arg, MaybeMatcher) of true -> check_by_matchers(RestArgs, RestMaybeMatchers); _Else -> false end; check_by_matchers([], []) -> true.
ed13208a2a9740f4ae5d03924582c9caaa436635b2721ac0d3b034b729fd57b2
tkych/lisp-dojo
023.lisp
Last modified : 2013 - 10 - 15 19:00:32 tkych (define-practice :id 023 :name my-member :level 0 :problem " MY-MEMBER item list => generalized-boolean Make function MY-MEMBER. Examples: (my-member 1 '(0 1 2 3)) => (1 2 3) (my-member 4 '(0 1 2 3)) => () (my-member 1 '()) => () (my-member \"1\" (list (copy-seq \"0\") (copy-seq \"1\") (copy-seq \"2\") (copy-seq \"3\"))) => () (my-member \"1\" (list (copy-seq \"0\") (copy-seq \"1\") (copy-seq \"2\") (copy-seq \"3\")) :test #'equal) => (\"1\" \"2\" \"3\") " :hint nil :solutions " * (defun my-member (item lst &key (test #'eql)) (loop for xs on lst when (funcall test item (first xs)) do (RETURN xs))) * (defun my-member (item lst &key (test #'eql)) (if (endp lst) nil (if (funcall test item (first lst)) lst (my-member item (rest lst) :test test)))) * (defun my-member (item lst &key (test #'eql)) (labels ((rec (lst) (if (endp lst) nil (if (funcall test item (first lst)) lst (rec (rest lst)))))) (rec lst)))" :reference " * " :test-env nil :test ((=>? (my-member 1 '(0 1 2 3)) (1 2 3)) (=>? (my-member 4 '(0 1 2 3)) ()) (=>? (my-member 1 '()) ()) (=>? (my-member "1" (list (copy-seq "0") (copy-seq "1") (copy-seq "2") (copy-seq "3"))) ()) (=>? (my-member "1" (list (copy-seq "0") (copy-seq "1") (copy-seq "2") (copy-seq "3")) :test #'equal) ("1" "2" "3"))) )
null
https://raw.githubusercontent.com/tkych/lisp-dojo/ba83d025bc03101eec43ec6be44585d7b076caf6/practices/023.lisp
lisp
Last modified : 2013 - 10 - 15 19:00:32 tkych (define-practice :id 023 :name my-member :level 0 :problem " MY-MEMBER item list => generalized-boolean Make function MY-MEMBER. Examples: (my-member 1 '(0 1 2 3)) => (1 2 3) (my-member 4 '(0 1 2 3)) => () (my-member 1 '()) => () (my-member \"1\" (list (copy-seq \"0\") (copy-seq \"1\") (copy-seq \"2\") (copy-seq \"3\"))) => () (my-member \"1\" (list (copy-seq \"0\") (copy-seq \"1\") (copy-seq \"2\") (copy-seq \"3\")) :test #'equal) => (\"1\" \"2\" \"3\") " :hint nil :solutions " * (defun my-member (item lst &key (test #'eql)) (loop for xs on lst when (funcall test item (first xs)) do (RETURN xs))) * (defun my-member (item lst &key (test #'eql)) (if (endp lst) nil (if (funcall test item (first lst)) lst (my-member item (rest lst) :test test)))) * (defun my-member (item lst &key (test #'eql)) (labels ((rec (lst) (if (endp lst) nil (if (funcall test item (first lst)) lst (rec (rest lst)))))) (rec lst)))" :reference " * " :test-env nil :test ((=>? (my-member 1 '(0 1 2 3)) (1 2 3)) (=>? (my-member 4 '(0 1 2 3)) ()) (=>? (my-member 1 '()) ()) (=>? (my-member "1" (list (copy-seq "0") (copy-seq "1") (copy-seq "2") (copy-seq "3"))) ()) (=>? (my-member "1" (list (copy-seq "0") (copy-seq "1") (copy-seq "2") (copy-seq "3")) :test #'equal) ("1" "2" "3"))) )
ee795155b17390236048b68c7bfc18cfda39ddb188d06757d464b54b16efb364
kthielen/stlcc
Type.hs
# LANGUAGE MultiParamTypeClasses , FunctionalDependencies , FlexibleInstances , TypeSynonymInstances # module STLC.Type where import Util.Annotated import Util.Sequence import Util.Tuples import Util.String import Util.Num import Data.Set as Set hiding (map, filter, (\\)) import Data.List as List hiding (delete, union) import GHC.Word import Data.Maybe {- Types -} data Ty a = TPrim a String | TVar a String | TFn a CallConv [Ty a] (Ty a) | TVariant a [(String, Ty a)] | TRecord a [(String, Ty a)] | TExists a String (Ty a) | TArray a (Ty a) | TMu a String (Ty a) deriving (Ord) instance Annotated Ty where annotation (TPrim x _) = x annotation (TVar x _) = x annotation (TFn x _ _ _) = x annotation (TVariant x _) = x annotation (TRecord x _) = x annotation (TExists x _ _) = x annotation (TArray x _) = x annotation (TMu x _ _) = x annotations (TPrim a _) = [a] annotations (TVar a _) = [a] annotations (TFn a _ as r) = concatMap annotations as ++ annotations r ++ [a] annotations (TVariant a cs) = concat [annotations t | (_, t) <- cs] ++ [a] annotations (TRecord a cs) = concat [annotations t | (_, t) <- cs] ++ [a] annotations (TExists a _ t) = annotations t ++ [a] annotations (TArray a t) = annotations t ++ [a] annotations (TMu a _ t) = annotations t ++ [a] data CallConv = CFn deriving (Eq, Ord, Show) data CPrim a = CByte a Word8 | CChar a Char | CShort a Int | CInt a Int | CFloat a Float | CString a String | CUnit a deriving (Eq, Ord) instance Functor Ty where fmap f (TPrim x c0) = TPrim (f x) c0 fmap f (TVar x c0) = TVar (f x) c0 fmap f (TFn x cc args rty) = TFn (f x) cc (map (fmap f) args) (fmap f rty) fmap f (TVariant x defs) = TVariant (f x) [(lbl, fmap f ty) | (lbl, ty) <- defs] fmap f (TRecord x defs) = TRecord (f x) [(lbl, fmap f ty) | (lbl, ty) <- defs] fmap f (TExists x vn ety) = TExists (f x) vn (fmap f ety) fmap f (TArray x aty) = TArray (f x) (fmap f aty) fmap f (TMu x vn rty) = TMu (f x) vn (fmap f rty) instance Eq (Ty a) where (TPrim _ x) == (TPrim _ x') = x == x' (TVar _ x) == (TVar _ x') = x == x' (TFn _ cc atys rty) == (TFn _ cc' atys' rty') = cc == cc' && atys == atys' && rty == rty' (TVariant _ fs) == (TVariant _ fs') = fs == fs' (TRecord _ fs) == (TRecord _ fs') = fs == fs' (TExists _ x ty) == (TExists _ x' ty') | x == x' = ty == ty' (TExists _ x ty) == (TExists _ x' ty') = tyRename ty x x' == ty' && ty == tyRename ty' x' x (TArray _ ty) == (TArray _ ty') = ty == ty' (TMu _ x ty) == (TMu _ x' ty') | x == x' = ty == ty' (TMu _ x ty) == (TMu _ x' ty') = tyRename ty x x' == ty' && ty == tyRename ty' x' x _ == _ = False instance Show (Ty a) where show (TPrim _ s) = s show (TVar _ s) = s show (TFn _ cc as r) = "(" ++ cdelim (map show as) ", " ++ ") -> " ++ show r show (TVariant _ fs) = "<" ++ showFields ":" fs ++ ">" show (TRecord _ fs) = "{" ++ showFields ":" fs ++ "}" show (TExists _ v ty) = "exists " ++ v ++ "." ++ show ty show (TArray _ e) = "[" ++ show e ++ "]" show (TMu _ x ty) = "mu " ++ x ++ "." ++ show ty instance Functor CPrim where fmap f (CByte x c0) = CByte (f x) c0 fmap f (CChar x c0) = CChar (f x) c0 fmap f (CShort x c0) = CShort (f x) c0 fmap f (CInt x c0) = CInt (f x) c0 fmap f (CFloat x c0) = CFloat (f x) c0 fmap f (CString x c0) = CString (f x) c0 fmap f (CUnit x) = CUnit (f x) instance Annotated CPrim where annotation (CByte a _) = a annotation (CChar a _) = a annotation (CShort a _) = a annotation (CInt a _) = a annotation (CFloat a _) = a annotation (CString a _) = a annotation (CUnit a) = a annotations c = [annotation c] instance Show (CPrim a) where show (CByte _ x) = show x show (CChar _ x) = show x show (CShort _ x) = show x show (CInt _ x) = show x show (CFloat _ x) = show x show (CString _ x) = show x show (CUnit _) = "()" showFields :: Show t => String -> [(String, t)] -> String showFields eq fs = cdelim [lbl ++ eq ++ show e | (lbl, e) <- fs] "; " isArrayTy :: Ty a -> Bool isArrayTy (TArray _ _) = True isArrayTy _ = False isExType :: Ty a -> Bool isExType (TExists _ _ _) = True isExType _ = False isFNTy :: Ty a -> Bool isFNTy (TFn _ _ _ _) = True isFNTy _ = False fnArgTys :: Ty a -> [Ty a] fnArgTys (TFn _ _ atys _) = atys fnArgTys fty = error ("Cannot apply a value of type '" ++ show fty ++ "'.") fnRTy :: Ty a -> Ty a fnRTy (TFn _ _ _ r) = r fnRTy fty = error ("Cannot apply a value of type '" ++ show fty ++ "'.") vtype :: Annotation a => Ty a -> String -> Ty a vtype (TVariant a vs) v = suj (lookup v vs) (describe a ++ ": Unable to lookup '" ++ v ++ "' in the variant " ++ show (TVariant a vs)) vtype ty lbl = error (describe (annotation ty) ++ ": Not a variant type: " ++ show ty ++ ", can't read " ++ lbl ++ ".") vlookup :: Annotation a => Ty a -> String -> Ty a vlookup t@(TVariant a vs) v = suj (lookup v vs) (describe a ++ ": Unable to lookup '" ++ v ++ "' in the variant " ++ show t) vlookup t lbl = error (describe (annotation t) ++ ": Not a variant type: " ++ show t ++ ", can't read " ++ lbl ++ ".") vtags :: Ty a -> [(String, Ty a)] vtags (TVariant _ vs) = vs vindex :: [(String, Ty a)] -> String -> Int vindex ts t = at t (map first ts) rlookup :: Annotation a => Ty a -> String -> Ty a rlookup t@(TRecord a fs) f = suj (lookup f fs) (describe a ++ ": Unable to lookup '" ++ f ++ "' in the record " ++ show t) rlookup t lbl = error (describe (annotation t) ++ ": Unable to lookup the label '" ++ lbl ++ "' in a non-record type: " ++ show t) rtype :: Annotation a => Ty a -> String -> Ty a rtype (TRecord a fs) f = suj (lookup f fs) (describe a ++ ": Unable to lookup '" ++ f ++ "' in the record " ++ show (TRecord a fs)) rtype ty lbl = error (describe (annotation ty) ++ ": Unable to lookup the label '" ++ lbl ++ "' in a non-record type: " ++ show ty) rfields :: Ty a -> [(String, Ty a)] rfields (TRecord _ fs) = fs arrTy :: Ty a -> Ty a arrTy (TArray _ x) = x exname :: Ty a -> String -> Ty a exname (TExists _ x ty) tv = tyRename ty x tv exname e _ = error ("Not an existential type: " ++ show e) tyRename :: Ty a -> String -> String -> Ty a tyRename (TPrim d x) _ _ = TPrim d x tyRename (TVar d x) o n | x == o = TVar d n tyRename (TVar d x) o n = TVar d x tyRename (TFn d cc as r) o n = TFn d cc [tyRename a o n | a <- as] (tyRename r o n) tyRename (TVariant d fs) o n = TVariant d [(f, tyRename t o n) | (f, t) <- fs] tyRename (TRecord d fs) o n = TRecord d [(f, tyRename t o n) | (f, t) <- fs] tyRename (TExists d x t) o _ | x == o = TExists d x t tyRename (TExists d x t) o n = TExists d x (tyRename t o n) tyRename (TArray d t) o n = TArray d (tyRename t o n) tyRename (TMu d x ty) o _ | x == o = TMu d x ty tyRename (TMu d x ty) o n = TMu d x (tyRename ty o n) tyBinderNames :: Ty a -> [String] tyBinderNames (TPrim _ _) = [] tyBinderNames (TVar _ _) = [] tyBinderNames (TFn _ _ args rty) = concatMap tyBinderNames (rty:args) tyBinderNames (TVariant _ fs) = concatMap (tyBinderNames . snd) fs tyBinderNames (TRecord _ fs) = concatMap (tyBinderNames . snd) fs tyBinderNames (TExists _ v ty) = v : tyBinderNames ty tyBinderNames (TArray _ ty) = tyBinderNames ty tyBinderNames (TMu _ v ty) = v : tyBinderNames ty tyFreshBinder :: Ty a -> String tyFreshBinder ty = first [tn | tn <- allNames, not (tn `elem` usedNames)] where usedNames = tyBinderNames ty allNames = "a":"b":"c":"d":"e":"f":"g":"h":"i":"j":"k":"l":"m":"n":"o":"p":"q":"r":"s":"t":"u":"v":"w":"x":"y":"z":["t"++show i | i <- [0..]] rollTy :: Ty a -> Ty a -> Ty a rollTy rty ty = TMu a x (roll ty) where a = annotation ty x = tyFreshBinder ty roll ty' | rty == ty' = TVar a x roll (TPrim a x) = TPrim a x roll (TVar a x) = TVar a x roll (TFn a cc args rty) = TFn a cc (map roll args) (roll rty) roll (TVariant a fs) = TVariant a [(v, roll ty) | (v, ty) <- fs] roll (TRecord a fs) = TRecord a [(v, roll ty) | (v, ty) <- fs] roll (TExists a x ty) = TExists a x (roll ty) roll (TArray a ty) = TArray a (roll ty) roll (TMu a x ty) = TMu a x (roll ty) unrollTy :: Ty a -> Ty a -> Ty a unrollTy rty ty = unroll ty where unroll (TPrim a x) = TPrim a x unroll (TVar a x) = TVar a x unroll (TFn a cc args rty) = TFn a cc (map unroll args) (unroll rty) unroll (TVariant a fs) = TVariant a [(v, unroll ty) | (v, ty) <- fs] unroll (TRecord a fs) = TRecord a [(v, unroll ty) | (v, ty) <- fs] unroll (TExists a x ty) = TExists a x (unroll ty) unroll (TArray a ty) = TArray a (unroll ty) unroll rty'@(TMu _ x b) | rty == rty' = rewriteTy rty x b unroll (TMu a y ty) = TMu a y (unroll ty) rewriteTy :: Ty a -> String -> Ty a -> Ty a rewriteTy rty _ (TPrim a x) = TPrim a x rewriteTy rty x (TVar _ x') | x' == x = rty rewriteTy rty _ (TVar a x) = TVar a x rewriteTy rty x (TFn a cc args rty') = TFn a cc (map (rewriteTy rty x) args) (rewriteTy rty x rty') rewriteTy rty x (TVariant a fs) = TVariant a [(v, rewriteTy rty x ty) | (v, ty) <- fs] rewriteTy rty x (TRecord a fs) = TRecord a [(v, rewriteTy rty x ty) | (v, ty) <- fs] rewriteTy rty x (TExists a x' ty) | x == x' = TExists a x' ty rewriteTy rty x (TExists a y ty) = TExists a y (rewriteTy rty x ty) rewriteTy rty x (TArray a ty) = TArray a (rewriteTy rty x ty) rewriteTy rty x (TMu a x' ty) | x == x' = TMu a x' ty rewriteTy rty x (TMu a y ty) = TMu a y (rewriteTy rty x ty) isPrimTy :: String -> Bool isPrimTy "unit" = True isPrimTy "byte" = True isPrimTy "char" = True isPrimTy "short" = True isPrimTy "int" = True isPrimTy "float" = True isPrimTy _ = False expandTy :: [(String, Ty a)] -> Ty a -> Ty a expandTy defs (TPrim a x) = TPrim a x expandTy defs (TVar a v) = select (lookup v defs) where select (Just ty') = ty' select Nothing = TVar a v expandTy defs (TFn a cc args rty) = TFn a cc (map (expandTy defs) args) (expandTy defs rty) expandTy defs (TVariant a fs) = TVariant a [(v, expandTy defs ty) | (v, ty) <- fs] expandTy defs (TRecord a fs) = TRecord a [(v, expandTy defs ty) | (v, ty) <- fs] expandTy defs (TExists a v ty) = TExists a v (expandTy defs ty) expandTy defs (TArray a ty) = TArray a (expandTy defs ty) expandTy defs (TMu a x ty) = TMu a x (expandTy defs ty) variantCaseID :: Ty a -> String -> Int variantCaseID (TVariant _ ts) lbl = atBy (\(x,_) -> x == lbl) ts primTy :: CPrim a -> Ty a primTy (CByte a _) = TPrim a "byte" primTy (CChar a _) = TPrim a "char" primTy (CShort a _) = TPrim a "short" primTy (CInt a _) = TPrim a "int" primTy (CFloat a _) = TPrim a "float" primTy (CString a _) = TArray a (TPrim a "char") primTy (CUnit a) = TPrim a "unit" tyFV :: Ty a -> [String] tyFV (TPrim _ _) = [] tyFV (TVar _ x) = [x] tyFV (TFn _ _ atys rty) = concatMap tyFV atys ++ tyFV rty tyFV (TVariant _ cs) = concatMap (tyFV . snd) cs tyFV (TRecord _ cs) = concatMap (tyFV . snd) cs tyFV (TExists _ vn ty) = tyFV ty \\ [vn] tyFV (TArray _ ty) = tyFV ty tyFV (TMu _ vn ty) = tyFV ty \\ [vn] {- Type environments and top-level bindings -} class Show tenv => TypeEnv tenv a | tenv -> a where emptyTEnv :: tenv isTopLevelVar :: tenv -> String -> Bool tydef :: tenv -> String -> Maybe (Ty a) pushtys :: tenv -> [(String, Ty a)] -> tenv pushty :: tenv -> String -> Ty a -> tenv pushtysTop :: tenv -> [(String, Ty a)] -> tenv pushtyTop :: tenv -> String -> Ty a -> tenv varnames :: tenv -> [String] mapTyFn :: (String -> Ty a -> Ty a) -> tenv -> tenv updateVarTy :: String -> (Ty a -> Ty a) -> tenv -> tenv pushty tenv v ty = pushtys tenv [(v, ty)] pushtysTop = pushtys pushtyTop tenv v ty = pushtysTop tenv [(v, ty)] instance TypeEnv [[(String, Ty a)]] a where emptyTEnv = [] isTopLevelVar [] v = False isTopLevelVar [frame] v = isJust (lookup v frame) isTopLevelVar (frame:_) v | isJust (lookup v frame) = False isTopLevelVar (_:frames) v = isTopLevelVar frames v tydef [] v = Nothing tydef (frame:frames) v = either Just (const (tydef frames v)) (choice $ lookup v frame) pushtys te vs = vs : te pushtysTop te vs = reverse (ins (reverse te)) where ins [] = [vs] ins (f:fs) = (vs++f):fs varnames te = concatMap (map fst) te mapTyFn f tenv = [[(x, f x ty) | (x, ty) <- frame] | frame <- tenv] updateVarTy v u [] = [] updateVarTy v u (f:fs) | isJust (lookup v f) = [if vn == v then (vn, u ty) else (vn, ty) | (vn, ty) <- f] : fs updateVarTy v u (f:fs) = f : updateVarTy v u fs isdef :: TypeEnv tenv a => tenv -> String -> Bool isdef tenv v = mb (tydef tenv v) where mb (Just _) = True mb _ = False
null
https://raw.githubusercontent.com/kthielen/stlcc/369492daad6498a93c00f5924a99ceb65b5f1062/STLC/Type.hs
haskell
Types Type environments and top-level bindings
# LANGUAGE MultiParamTypeClasses , FunctionalDependencies , FlexibleInstances , TypeSynonymInstances # module STLC.Type where import Util.Annotated import Util.Sequence import Util.Tuples import Util.String import Util.Num import Data.Set as Set hiding (map, filter, (\\)) import Data.List as List hiding (delete, union) import GHC.Word import Data.Maybe data Ty a = TPrim a String | TVar a String | TFn a CallConv [Ty a] (Ty a) | TVariant a [(String, Ty a)] | TRecord a [(String, Ty a)] | TExists a String (Ty a) | TArray a (Ty a) | TMu a String (Ty a) deriving (Ord) instance Annotated Ty where annotation (TPrim x _) = x annotation (TVar x _) = x annotation (TFn x _ _ _) = x annotation (TVariant x _) = x annotation (TRecord x _) = x annotation (TExists x _ _) = x annotation (TArray x _) = x annotation (TMu x _ _) = x annotations (TPrim a _) = [a] annotations (TVar a _) = [a] annotations (TFn a _ as r) = concatMap annotations as ++ annotations r ++ [a] annotations (TVariant a cs) = concat [annotations t | (_, t) <- cs] ++ [a] annotations (TRecord a cs) = concat [annotations t | (_, t) <- cs] ++ [a] annotations (TExists a _ t) = annotations t ++ [a] annotations (TArray a t) = annotations t ++ [a] annotations (TMu a _ t) = annotations t ++ [a] data CallConv = CFn deriving (Eq, Ord, Show) data CPrim a = CByte a Word8 | CChar a Char | CShort a Int | CInt a Int | CFloat a Float | CString a String | CUnit a deriving (Eq, Ord) instance Functor Ty where fmap f (TPrim x c0) = TPrim (f x) c0 fmap f (TVar x c0) = TVar (f x) c0 fmap f (TFn x cc args rty) = TFn (f x) cc (map (fmap f) args) (fmap f rty) fmap f (TVariant x defs) = TVariant (f x) [(lbl, fmap f ty) | (lbl, ty) <- defs] fmap f (TRecord x defs) = TRecord (f x) [(lbl, fmap f ty) | (lbl, ty) <- defs] fmap f (TExists x vn ety) = TExists (f x) vn (fmap f ety) fmap f (TArray x aty) = TArray (f x) (fmap f aty) fmap f (TMu x vn rty) = TMu (f x) vn (fmap f rty) instance Eq (Ty a) where (TPrim _ x) == (TPrim _ x') = x == x' (TVar _ x) == (TVar _ x') = x == x' (TFn _ cc atys rty) == (TFn _ cc' atys' rty') = cc == cc' && atys == atys' && rty == rty' (TVariant _ fs) == (TVariant _ fs') = fs == fs' (TRecord _ fs) == (TRecord _ fs') = fs == fs' (TExists _ x ty) == (TExists _ x' ty') | x == x' = ty == ty' (TExists _ x ty) == (TExists _ x' ty') = tyRename ty x x' == ty' && ty == tyRename ty' x' x (TArray _ ty) == (TArray _ ty') = ty == ty' (TMu _ x ty) == (TMu _ x' ty') | x == x' = ty == ty' (TMu _ x ty) == (TMu _ x' ty') = tyRename ty x x' == ty' && ty == tyRename ty' x' x _ == _ = False instance Show (Ty a) where show (TPrim _ s) = s show (TVar _ s) = s show (TFn _ cc as r) = "(" ++ cdelim (map show as) ", " ++ ") -> " ++ show r show (TVariant _ fs) = "<" ++ showFields ":" fs ++ ">" show (TRecord _ fs) = "{" ++ showFields ":" fs ++ "}" show (TExists _ v ty) = "exists " ++ v ++ "." ++ show ty show (TArray _ e) = "[" ++ show e ++ "]" show (TMu _ x ty) = "mu " ++ x ++ "." ++ show ty instance Functor CPrim where fmap f (CByte x c0) = CByte (f x) c0 fmap f (CChar x c0) = CChar (f x) c0 fmap f (CShort x c0) = CShort (f x) c0 fmap f (CInt x c0) = CInt (f x) c0 fmap f (CFloat x c0) = CFloat (f x) c0 fmap f (CString x c0) = CString (f x) c0 fmap f (CUnit x) = CUnit (f x) instance Annotated CPrim where annotation (CByte a _) = a annotation (CChar a _) = a annotation (CShort a _) = a annotation (CInt a _) = a annotation (CFloat a _) = a annotation (CString a _) = a annotation (CUnit a) = a annotations c = [annotation c] instance Show (CPrim a) where show (CByte _ x) = show x show (CChar _ x) = show x show (CShort _ x) = show x show (CInt _ x) = show x show (CFloat _ x) = show x show (CString _ x) = show x show (CUnit _) = "()" showFields :: Show t => String -> [(String, t)] -> String showFields eq fs = cdelim [lbl ++ eq ++ show e | (lbl, e) <- fs] "; " isArrayTy :: Ty a -> Bool isArrayTy (TArray _ _) = True isArrayTy _ = False isExType :: Ty a -> Bool isExType (TExists _ _ _) = True isExType _ = False isFNTy :: Ty a -> Bool isFNTy (TFn _ _ _ _) = True isFNTy _ = False fnArgTys :: Ty a -> [Ty a] fnArgTys (TFn _ _ atys _) = atys fnArgTys fty = error ("Cannot apply a value of type '" ++ show fty ++ "'.") fnRTy :: Ty a -> Ty a fnRTy (TFn _ _ _ r) = r fnRTy fty = error ("Cannot apply a value of type '" ++ show fty ++ "'.") vtype :: Annotation a => Ty a -> String -> Ty a vtype (TVariant a vs) v = suj (lookup v vs) (describe a ++ ": Unable to lookup '" ++ v ++ "' in the variant " ++ show (TVariant a vs)) vtype ty lbl = error (describe (annotation ty) ++ ": Not a variant type: " ++ show ty ++ ", can't read " ++ lbl ++ ".") vlookup :: Annotation a => Ty a -> String -> Ty a vlookup t@(TVariant a vs) v = suj (lookup v vs) (describe a ++ ": Unable to lookup '" ++ v ++ "' in the variant " ++ show t) vlookup t lbl = error (describe (annotation t) ++ ": Not a variant type: " ++ show t ++ ", can't read " ++ lbl ++ ".") vtags :: Ty a -> [(String, Ty a)] vtags (TVariant _ vs) = vs vindex :: [(String, Ty a)] -> String -> Int vindex ts t = at t (map first ts) rlookup :: Annotation a => Ty a -> String -> Ty a rlookup t@(TRecord a fs) f = suj (lookup f fs) (describe a ++ ": Unable to lookup '" ++ f ++ "' in the record " ++ show t) rlookup t lbl = error (describe (annotation t) ++ ": Unable to lookup the label '" ++ lbl ++ "' in a non-record type: " ++ show t) rtype :: Annotation a => Ty a -> String -> Ty a rtype (TRecord a fs) f = suj (lookup f fs) (describe a ++ ": Unable to lookup '" ++ f ++ "' in the record " ++ show (TRecord a fs)) rtype ty lbl = error (describe (annotation ty) ++ ": Unable to lookup the label '" ++ lbl ++ "' in a non-record type: " ++ show ty) rfields :: Ty a -> [(String, Ty a)] rfields (TRecord _ fs) = fs arrTy :: Ty a -> Ty a arrTy (TArray _ x) = x exname :: Ty a -> String -> Ty a exname (TExists _ x ty) tv = tyRename ty x tv exname e _ = error ("Not an existential type: " ++ show e) tyRename :: Ty a -> String -> String -> Ty a tyRename (TPrim d x) _ _ = TPrim d x tyRename (TVar d x) o n | x == o = TVar d n tyRename (TVar d x) o n = TVar d x tyRename (TFn d cc as r) o n = TFn d cc [tyRename a o n | a <- as] (tyRename r o n) tyRename (TVariant d fs) o n = TVariant d [(f, tyRename t o n) | (f, t) <- fs] tyRename (TRecord d fs) o n = TRecord d [(f, tyRename t o n) | (f, t) <- fs] tyRename (TExists d x t) o _ | x == o = TExists d x t tyRename (TExists d x t) o n = TExists d x (tyRename t o n) tyRename (TArray d t) o n = TArray d (tyRename t o n) tyRename (TMu d x ty) o _ | x == o = TMu d x ty tyRename (TMu d x ty) o n = TMu d x (tyRename ty o n) tyBinderNames :: Ty a -> [String] tyBinderNames (TPrim _ _) = [] tyBinderNames (TVar _ _) = [] tyBinderNames (TFn _ _ args rty) = concatMap tyBinderNames (rty:args) tyBinderNames (TVariant _ fs) = concatMap (tyBinderNames . snd) fs tyBinderNames (TRecord _ fs) = concatMap (tyBinderNames . snd) fs tyBinderNames (TExists _ v ty) = v : tyBinderNames ty tyBinderNames (TArray _ ty) = tyBinderNames ty tyBinderNames (TMu _ v ty) = v : tyBinderNames ty tyFreshBinder :: Ty a -> String tyFreshBinder ty = first [tn | tn <- allNames, not (tn `elem` usedNames)] where usedNames = tyBinderNames ty allNames = "a":"b":"c":"d":"e":"f":"g":"h":"i":"j":"k":"l":"m":"n":"o":"p":"q":"r":"s":"t":"u":"v":"w":"x":"y":"z":["t"++show i | i <- [0..]] rollTy :: Ty a -> Ty a -> Ty a rollTy rty ty = TMu a x (roll ty) where a = annotation ty x = tyFreshBinder ty roll ty' | rty == ty' = TVar a x roll (TPrim a x) = TPrim a x roll (TVar a x) = TVar a x roll (TFn a cc args rty) = TFn a cc (map roll args) (roll rty) roll (TVariant a fs) = TVariant a [(v, roll ty) | (v, ty) <- fs] roll (TRecord a fs) = TRecord a [(v, roll ty) | (v, ty) <- fs] roll (TExists a x ty) = TExists a x (roll ty) roll (TArray a ty) = TArray a (roll ty) roll (TMu a x ty) = TMu a x (roll ty) unrollTy :: Ty a -> Ty a -> Ty a unrollTy rty ty = unroll ty where unroll (TPrim a x) = TPrim a x unroll (TVar a x) = TVar a x unroll (TFn a cc args rty) = TFn a cc (map unroll args) (unroll rty) unroll (TVariant a fs) = TVariant a [(v, unroll ty) | (v, ty) <- fs] unroll (TRecord a fs) = TRecord a [(v, unroll ty) | (v, ty) <- fs] unroll (TExists a x ty) = TExists a x (unroll ty) unroll (TArray a ty) = TArray a (unroll ty) unroll rty'@(TMu _ x b) | rty == rty' = rewriteTy rty x b unroll (TMu a y ty) = TMu a y (unroll ty) rewriteTy :: Ty a -> String -> Ty a -> Ty a rewriteTy rty _ (TPrim a x) = TPrim a x rewriteTy rty x (TVar _ x') | x' == x = rty rewriteTy rty _ (TVar a x) = TVar a x rewriteTy rty x (TFn a cc args rty') = TFn a cc (map (rewriteTy rty x) args) (rewriteTy rty x rty') rewriteTy rty x (TVariant a fs) = TVariant a [(v, rewriteTy rty x ty) | (v, ty) <- fs] rewriteTy rty x (TRecord a fs) = TRecord a [(v, rewriteTy rty x ty) | (v, ty) <- fs] rewriteTy rty x (TExists a x' ty) | x == x' = TExists a x' ty rewriteTy rty x (TExists a y ty) = TExists a y (rewriteTy rty x ty) rewriteTy rty x (TArray a ty) = TArray a (rewriteTy rty x ty) rewriteTy rty x (TMu a x' ty) | x == x' = TMu a x' ty rewriteTy rty x (TMu a y ty) = TMu a y (rewriteTy rty x ty) isPrimTy :: String -> Bool isPrimTy "unit" = True isPrimTy "byte" = True isPrimTy "char" = True isPrimTy "short" = True isPrimTy "int" = True isPrimTy "float" = True isPrimTy _ = False expandTy :: [(String, Ty a)] -> Ty a -> Ty a expandTy defs (TPrim a x) = TPrim a x expandTy defs (TVar a v) = select (lookup v defs) where select (Just ty') = ty' select Nothing = TVar a v expandTy defs (TFn a cc args rty) = TFn a cc (map (expandTy defs) args) (expandTy defs rty) expandTy defs (TVariant a fs) = TVariant a [(v, expandTy defs ty) | (v, ty) <- fs] expandTy defs (TRecord a fs) = TRecord a [(v, expandTy defs ty) | (v, ty) <- fs] expandTy defs (TExists a v ty) = TExists a v (expandTy defs ty) expandTy defs (TArray a ty) = TArray a (expandTy defs ty) expandTy defs (TMu a x ty) = TMu a x (expandTy defs ty) variantCaseID :: Ty a -> String -> Int variantCaseID (TVariant _ ts) lbl = atBy (\(x,_) -> x == lbl) ts primTy :: CPrim a -> Ty a primTy (CByte a _) = TPrim a "byte" primTy (CChar a _) = TPrim a "char" primTy (CShort a _) = TPrim a "short" primTy (CInt a _) = TPrim a "int" primTy (CFloat a _) = TPrim a "float" primTy (CString a _) = TArray a (TPrim a "char") primTy (CUnit a) = TPrim a "unit" tyFV :: Ty a -> [String] tyFV (TPrim _ _) = [] tyFV (TVar _ x) = [x] tyFV (TFn _ _ atys rty) = concatMap tyFV atys ++ tyFV rty tyFV (TVariant _ cs) = concatMap (tyFV . snd) cs tyFV (TRecord _ cs) = concatMap (tyFV . snd) cs tyFV (TExists _ vn ty) = tyFV ty \\ [vn] tyFV (TArray _ ty) = tyFV ty tyFV (TMu _ vn ty) = tyFV ty \\ [vn] class Show tenv => TypeEnv tenv a | tenv -> a where emptyTEnv :: tenv isTopLevelVar :: tenv -> String -> Bool tydef :: tenv -> String -> Maybe (Ty a) pushtys :: tenv -> [(String, Ty a)] -> tenv pushty :: tenv -> String -> Ty a -> tenv pushtysTop :: tenv -> [(String, Ty a)] -> tenv pushtyTop :: tenv -> String -> Ty a -> tenv varnames :: tenv -> [String] mapTyFn :: (String -> Ty a -> Ty a) -> tenv -> tenv updateVarTy :: String -> (Ty a -> Ty a) -> tenv -> tenv pushty tenv v ty = pushtys tenv [(v, ty)] pushtysTop = pushtys pushtyTop tenv v ty = pushtysTop tenv [(v, ty)] instance TypeEnv [[(String, Ty a)]] a where emptyTEnv = [] isTopLevelVar [] v = False isTopLevelVar [frame] v = isJust (lookup v frame) isTopLevelVar (frame:_) v | isJust (lookup v frame) = False isTopLevelVar (_:frames) v = isTopLevelVar frames v tydef [] v = Nothing tydef (frame:frames) v = either Just (const (tydef frames v)) (choice $ lookup v frame) pushtys te vs = vs : te pushtysTop te vs = reverse (ins (reverse te)) where ins [] = [vs] ins (f:fs) = (vs++f):fs varnames te = concatMap (map fst) te mapTyFn f tenv = [[(x, f x ty) | (x, ty) <- frame] | frame <- tenv] updateVarTy v u [] = [] updateVarTy v u (f:fs) | isJust (lookup v f) = [if vn == v then (vn, u ty) else (vn, ty) | (vn, ty) <- f] : fs updateVarTy v u (f:fs) = f : updateVarTy v u fs isdef :: TypeEnv tenv a => tenv -> String -> Bool isdef tenv v = mb (tydef tenv v) where mb (Just _) = True mb _ = False
91d281949541b2f37c37d9ba7862ef90376f1bf3ca8ad2325536664259910bd1
exercism/haskell
CustomSet.hs
module CustomSet ( delete , difference , empty , fromList , insert , intersection , isDisjointFrom , isSubsetOf , member , null , size , toList , union ) where import Prelude hiding (null) data CustomSet a = Dummy deriving (Eq, Show) delete :: a -> CustomSet a -> CustomSet a delete x set = error "You need to implement this function." difference :: CustomSet a -> CustomSet a -> CustomSet a difference setA setB = error "You need to implement this function." empty :: CustomSet a empty = error "You need to implement this function." fromList :: [a] -> CustomSet a fromList xs = error "You need to implement this function." insert :: a -> CustomSet a -> CustomSet a insert x set = error "You need to implement this function." intersection :: CustomSet a -> CustomSet a -> CustomSet a intersection setA setB = error "You need to implement this function." isDisjointFrom :: CustomSet a -> CustomSet a -> Bool isDisjointFrom setA setB = error "You need to implement this function." isSubsetOf :: CustomSet a -> CustomSet a -> Bool isSubsetOf setA setB = error "You need to implement this function." member :: a -> CustomSet a -> Bool member x set = error "You need to implement this function." null :: CustomSet a -> Bool null set = error "You need to implement this function." size :: CustomSet a -> Int size set = error "You need to implement this function." toList :: CustomSet a -> [a] toList set = error "You need to implement this function." union :: CustomSet a -> CustomSet a -> CustomSet a union setA setB = error "You need to implement this function."
null
https://raw.githubusercontent.com/exercism/haskell/2b98084efc7d5ab098975c462f7977ee19c2fd29/exercises/practice/custom-set/src/CustomSet.hs
haskell
module CustomSet ( delete , difference , empty , fromList , insert , intersection , isDisjointFrom , isSubsetOf , member , null , size , toList , union ) where import Prelude hiding (null) data CustomSet a = Dummy deriving (Eq, Show) delete :: a -> CustomSet a -> CustomSet a delete x set = error "You need to implement this function." difference :: CustomSet a -> CustomSet a -> CustomSet a difference setA setB = error "You need to implement this function." empty :: CustomSet a empty = error "You need to implement this function." fromList :: [a] -> CustomSet a fromList xs = error "You need to implement this function." insert :: a -> CustomSet a -> CustomSet a insert x set = error "You need to implement this function." intersection :: CustomSet a -> CustomSet a -> CustomSet a intersection setA setB = error "You need to implement this function." isDisjointFrom :: CustomSet a -> CustomSet a -> Bool isDisjointFrom setA setB = error "You need to implement this function." isSubsetOf :: CustomSet a -> CustomSet a -> Bool isSubsetOf setA setB = error "You need to implement this function." member :: a -> CustomSet a -> Bool member x set = error "You need to implement this function." null :: CustomSet a -> Bool null set = error "You need to implement this function." size :: CustomSet a -> Int size set = error "You need to implement this function." toList :: CustomSet a -> [a] toList set = error "You need to implement this function." union :: CustomSet a -> CustomSet a -> CustomSet a union setA setB = error "You need to implement this function."
d3cf65ae8775b0cf84826743ae62c5eaa8dcdbd6c3f5f61589033a7ced7558bb
aryx/xix
printexc.ml
(***********************************************************************) (* *) (* Objective Caml *) (* *) , projet Cristal , INRIA Rocquencourt (* *) Copyright 1996 Institut National de Recherche en Informatique et Automatique . Distributed only by permission . (* *) (***********************************************************************) open Printf;; let locfmt = match Sys.os_type with | _ -> ("File \"%s\", line %d, characters %d-%d: %s" : ('a, 'b, 'c) format) ;; let field x i = let f = Obj.field x i in if not (Obj.is_block f) then sprintf "%d" (Obj.magic f : int) (* can also be a char *) else if Obj.tag f = 252 then sprintf "\"%s\"" (String.escaped (Obj.magic f : string)) else if Obj.tag f = 253 then string_of_float (Obj.magic f : float) else "_" ;; let rec other_fields x i = if i >= Obj.size x then "" else sprintf ", %s%s" (field x i) (other_fields x (i+1)) ;; let fields x = match Obj.size x with | 0 -> "" | 1 -> "" | 2 -> sprintf "(%s)" (field x 1) | n -> sprintf "(%s%s)" (field x 1) (other_fields x 2) ;; let to_string = function | Out_of_memory -> "Out of memory"; | Stack_overflow -> "Stack overflow"; | Match_failure(file, first_char, last_char) -> sprintf locfmt file 0 first_char last_char "Pattern matching failed"; | Assert_failure(file, first_char, last_char) -> sprintf locfmt file 0 first_char last_char "Assertion failed"; | x -> let x = Obj.repr x in let constructor = (Obj.magic(Obj.field (Obj.field x 0) 0) : string) in constructor ^ (fields x) ;; let print fct arg = try fct arg with x -> eprintf "Uncaught exception: %s\n" (to_string x); flush stderr; raise x let catch fct arg = try fct arg with x -> flush stdout; eprintf "Uncaught exception: %s\n" (to_string x); exit 2 type loc_info = | Known_location of bool (* is_raise *) * string (* module *) * int (* pos *) | Unknown_location of bool (*is_raise*) external get_exception_backtrace: unit -> loc_info array option = "caml_get_exception_backtrace" let format_loc_info pos li = let is_raise = match li with | Known_location(is_raise, _, _) -> is_raise | Unknown_location(is_raise) -> is_raise in let info = if is_raise then if pos = 0 then "Raised at" else "Re-raised at" else if pos = 0 then "Raised by primitive operation at" else "Called from" in match li with | Known_location(is_raise, modname, charpos) -> sprintf "%s module %s, character %d" info modname charpos | Unknown_location(is_raise) -> sprintf "%s unknown location" info let get_backtrace () = match get_exception_backtrace() with | None -> "(Program not linked with -g, cannot print stack backtrace)\n" | Some a -> let b = Buffer.create 1024 in for i = 0 to Array.length a - 1 do if a.(i) <> Unknown_location true then Buffer.add_string b (Printf.sprintf "%s\n" (format_loc_info i a.(i))) done; Buffer.contents b
null
https://raw.githubusercontent.com/aryx/xix/60ce1bd9a3f923e0e8bb2192f8938a9aa49c739c/lib_core/stdlib/printexc.ml
ocaml
********************************************************************* Objective Caml ********************************************************************* can also be a char is_raise module pos is_raise
, projet Cristal , INRIA Rocquencourt Copyright 1996 Institut National de Recherche en Informatique et Automatique . Distributed only by permission . open Printf;; let locfmt = match Sys.os_type with | _ -> ("File \"%s\", line %d, characters %d-%d: %s" : ('a, 'b, 'c) format) ;; let field x i = let f = Obj.field x i in if not (Obj.is_block f) then else if Obj.tag f = 252 then sprintf "\"%s\"" (String.escaped (Obj.magic f : string)) else if Obj.tag f = 253 then string_of_float (Obj.magic f : float) else "_" ;; let rec other_fields x i = if i >= Obj.size x then "" else sprintf ", %s%s" (field x i) (other_fields x (i+1)) ;; let fields x = match Obj.size x with | 0 -> "" | 1 -> "" | 2 -> sprintf "(%s)" (field x 1) | n -> sprintf "(%s%s)" (field x 1) (other_fields x 2) ;; let to_string = function | Out_of_memory -> "Out of memory"; | Stack_overflow -> "Stack overflow"; | Match_failure(file, first_char, last_char) -> sprintf locfmt file 0 first_char last_char "Pattern matching failed"; | Assert_failure(file, first_char, last_char) -> sprintf locfmt file 0 first_char last_char "Assertion failed"; | x -> let x = Obj.repr x in let constructor = (Obj.magic(Obj.field (Obj.field x 0) 0) : string) in constructor ^ (fields x) ;; let print fct arg = try fct arg with x -> eprintf "Uncaught exception: %s\n" (to_string x); flush stderr; raise x let catch fct arg = try fct arg with x -> flush stdout; eprintf "Uncaught exception: %s\n" (to_string x); exit 2 type loc_info = external get_exception_backtrace: unit -> loc_info array option = "caml_get_exception_backtrace" let format_loc_info pos li = let is_raise = match li with | Known_location(is_raise, _, _) -> is_raise | Unknown_location(is_raise) -> is_raise in let info = if is_raise then if pos = 0 then "Raised at" else "Re-raised at" else if pos = 0 then "Raised by primitive operation at" else "Called from" in match li with | Known_location(is_raise, modname, charpos) -> sprintf "%s module %s, character %d" info modname charpos | Unknown_location(is_raise) -> sprintf "%s unknown location" info let get_backtrace () = match get_exception_backtrace() with | None -> "(Program not linked with -g, cannot print stack backtrace)\n" | Some a -> let b = Buffer.create 1024 in for i = 0 to Array.length a - 1 do if a.(i) <> Unknown_location true then Buffer.add_string b (Printf.sprintf "%s\n" (format_loc_info i a.(i))) done; Buffer.contents b
403864ab98d3a9433f23194623e27369d1e75eb7deff0e5a661b6be5f2a2de56
fortytools/holumbus
PdfToText.hs
# OPTIONS # -- ------------------------------------------------------------ module Holumbus.Crawler.PdfToText where import Control.Concurrent.MVar import qualified Control.Exception as CE import qualified Data.ByteString.Lazy as BS import Data.String.Unicode ( utf8ToUnicode ) import System.Directory ( getTemporaryDirectory , removeFile ) import System.FilePath ( (</>) ) import System.Process ( rawSystem ) import System.Posix.Process ( getProcessID ) import System.IO.Unsafe ( unsafePerformIO ) import Text.XML.HXT.Core -- ------------------------------------------------------------ -- | Conversion of pdf data into plain text. The conversion is done -- by calling an external program @pdftotext@ (contained in linux packages @xpdf@). IO is done via the ByteString API . pdfToText :: String -> IO String pdfToText = pdfToTextBS . BS.pack . map (toEnum . fromEnum) pdfToTextBS :: BS.ByteString -> IO String pdfToTextBS inp = ( do fns@(fn1, fn2) <- requestPdf BS.writeFile fn1 inp _ <- rawSystem "pdftotext" ["-q", "-enc", "UTF-8", fn1, fn2] removeFile fn1 res <- BS.readFile fn2 BS.length res `seq` removeFile fn2 releasePdf fns return ( fst . utf8ToUnicode . map (toEnum . fromEnum) . BS.unpack $ res ) ) `mycatch` ( const $ return "" ) where mycatch :: IO a -> (CE.SomeException -> IO a) -> IO a mycatch = CE.catch pdfToTextA :: IOSArrow String String pdfToTextA = perform ( traceString 2 (("pdfToTextA input:\n" ++) . take 128 . show) ) >>> arrIO pdfToText >>> perform ( traceString 2 (( "pdfToText result:\n" ++ ) . take 128 . show) ) -- ------------------------------------------------------------ The pdftotext call is not thread save pdfResource :: MVar (FilePath, FilePath) pdfResource = unsafePerformIO $ tmpFiles >>= newMVar where tmpFiles = do td <- getTemporaryDirectory pid <- getProcessID let fn1 = fn td pid "pdfToText.pdf" let fn2 = fn td pid "pdfToText.txt" return (fn1, fn2) fn d p f = d </> (show p ++ "-" ++ f) # NOINLINE pdfResource # requestPdf :: IO (FilePath, FilePath) requestPdf = takeMVar pdfResource releasePdf :: (FilePath, FilePath) -> IO () releasePdf = putMVar pdfResource -- ------------------------------------------------------------
null
https://raw.githubusercontent.com/fortytools/holumbus/4b2f7b832feab2715a4d48be0b07dca018eaa8e8/Holumbus-Searchengine/src/Holumbus/Crawler/PdfToText.hs
haskell
------------------------------------------------------------ ------------------------------------------------------------ | Conversion of pdf data into plain text. The conversion is done by calling an external program @pdftotext@ (contained in linux packages @xpdf@). ------------------------------------------------------------ ------------------------------------------------------------
# OPTIONS # module Holumbus.Crawler.PdfToText where import Control.Concurrent.MVar import qualified Control.Exception as CE import qualified Data.ByteString.Lazy as BS import Data.String.Unicode ( utf8ToUnicode ) import System.Directory ( getTemporaryDirectory , removeFile ) import System.FilePath ( (</>) ) import System.Process ( rawSystem ) import System.Posix.Process ( getProcessID ) import System.IO.Unsafe ( unsafePerformIO ) import Text.XML.HXT.Core IO is done via the ByteString API . pdfToText :: String -> IO String pdfToText = pdfToTextBS . BS.pack . map (toEnum . fromEnum) pdfToTextBS :: BS.ByteString -> IO String pdfToTextBS inp = ( do fns@(fn1, fn2) <- requestPdf BS.writeFile fn1 inp _ <- rawSystem "pdftotext" ["-q", "-enc", "UTF-8", fn1, fn2] removeFile fn1 res <- BS.readFile fn2 BS.length res `seq` removeFile fn2 releasePdf fns return ( fst . utf8ToUnicode . map (toEnum . fromEnum) . BS.unpack $ res ) ) `mycatch` ( const $ return "" ) where mycatch :: IO a -> (CE.SomeException -> IO a) -> IO a mycatch = CE.catch pdfToTextA :: IOSArrow String String pdfToTextA = perform ( traceString 2 (("pdfToTextA input:\n" ++) . take 128 . show) ) >>> arrIO pdfToText >>> perform ( traceString 2 (( "pdfToText result:\n" ++ ) . take 128 . show) ) The pdftotext call is not thread save pdfResource :: MVar (FilePath, FilePath) pdfResource = unsafePerformIO $ tmpFiles >>= newMVar where tmpFiles = do td <- getTemporaryDirectory pid <- getProcessID let fn1 = fn td pid "pdfToText.pdf" let fn2 = fn td pid "pdfToText.txt" return (fn1, fn2) fn d p f = d </> (show p ++ "-" ++ f) # NOINLINE pdfResource # requestPdf :: IO (FilePath, FilePath) requestPdf = takeMVar pdfResource releasePdf :: (FilePath, FilePath) -> IO () releasePdf = putMVar pdfResource
51d344b47b78ba5cb81c4b80eb3edfd600e2ea777f073c508be5dfbe4f68fff0
bhaskara/programmable-reinforcement-learning
test-tree.lisp
(defpackage test-tree (:use cl utils tree)) (in-package test-tree) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; basic tree construction, consistency ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (setf n1 (make-node :node-label 'foo) n2 (add-new-child n1 nil 'bar) n3 (add-new-child n1 nil 'baz) n4 (add-new-child n2 'qux-edge 'qux) n5 (add-new-child n2 'oof-edge 'oof)) (setf e1 (make-edge n5 n1)) (setf e2 (find 'qux-edge (child-edges n2) :key #'edge-label)) (setf e3 (parent-edge n5)) (do-tests "consistency checking" (is-inconsistent-tree n1 t) nil (is-inconsistent-tree n1 nil) nil (is-inconsistent-tree n2 t) 'not-root (is-inconsistent-tree n2 nil) nil (progn (push e1 (child-edges n5)) (is-inconsistent-tree n1 t)) 'cycle (progn (deletef (child-edges n5) e1) (is-inconsistent-tree n1 t)) nil (progn (setf (tail e2) n1) (is-inconsistent-tree n1 t)) 'incorrect-child-edge (progn (setf (tail e2) n2) (is-inconsistent-tree n2 nil)) nil (progn (setf (parent-edge n5) (parent-edge n3)) (is-inconsistent-tree n1 t)) 'incorrect-parent-edge) (do-tests "tree traversal" (progn (setf (parent-edge n5) e3) (map-preorder 'list #'node-label n1)) '(foo bar qux oof baz) (map-postorder 'list #'node-label n1) '(qux oof bar baz foo)) (do-tests "tree modification" (progn (add-subtree n3 nil (copy-subtree n2) 0) (setf (node-label (get-child (get-child n3 0) 1)) 'ooof) (map-preorder 'list #'node-label n1)) '(foo bar qux oof baz bar qux ooof) (progn (setf tr (copy-subtree (get-child n3 0))) (add-subtree n1 nil tr 1) (map-preorder 'list #'node-label n1)) '(foo bar qux oof bar qux ooof baz bar qux ooof) (progn (setf deleted (remove-subtree (get-child n1 0))) (map-preorder 'list #'node-label n1)) '(foo bar qux ooof baz bar qux ooof) (map-postorder 'list #'node-label n1) '(qux ooof bar qux ooof bar baz foo) (is-consistent-tree deleted t) t (map-preorder 'list #'node-label deleted) '(bar qux oof) )
null
https://raw.githubusercontent.com/bhaskara/programmable-reinforcement-learning/8afc98116a8f78163b3f86076498d84b3f596217/lisp/data-struct/tree/test-tree.lisp
lisp
basic tree construction, consistency
(defpackage test-tree (:use cl utils tree)) (in-package test-tree) (setf n1 (make-node :node-label 'foo) n2 (add-new-child n1 nil 'bar) n3 (add-new-child n1 nil 'baz) n4 (add-new-child n2 'qux-edge 'qux) n5 (add-new-child n2 'oof-edge 'oof)) (setf e1 (make-edge n5 n1)) (setf e2 (find 'qux-edge (child-edges n2) :key #'edge-label)) (setf e3 (parent-edge n5)) (do-tests "consistency checking" (is-inconsistent-tree n1 t) nil (is-inconsistent-tree n1 nil) nil (is-inconsistent-tree n2 t) 'not-root (is-inconsistent-tree n2 nil) nil (progn (push e1 (child-edges n5)) (is-inconsistent-tree n1 t)) 'cycle (progn (deletef (child-edges n5) e1) (is-inconsistent-tree n1 t)) nil (progn (setf (tail e2) n1) (is-inconsistent-tree n1 t)) 'incorrect-child-edge (progn (setf (tail e2) n2) (is-inconsistent-tree n2 nil)) nil (progn (setf (parent-edge n5) (parent-edge n3)) (is-inconsistent-tree n1 t)) 'incorrect-parent-edge) (do-tests "tree traversal" (progn (setf (parent-edge n5) e3) (map-preorder 'list #'node-label n1)) '(foo bar qux oof baz) (map-postorder 'list #'node-label n1) '(qux oof bar baz foo)) (do-tests "tree modification" (progn (add-subtree n3 nil (copy-subtree n2) 0) (setf (node-label (get-child (get-child n3 0) 1)) 'ooof) (map-preorder 'list #'node-label n1)) '(foo bar qux oof baz bar qux ooof) (progn (setf tr (copy-subtree (get-child n3 0))) (add-subtree n1 nil tr 1) (map-preorder 'list #'node-label n1)) '(foo bar qux oof bar qux ooof baz bar qux ooof) (progn (setf deleted (remove-subtree (get-child n1 0))) (map-preorder 'list #'node-label n1)) '(foo bar qux ooof baz bar qux ooof) (map-postorder 'list #'node-label n1) '(qux ooof bar qux ooof bar baz foo) (is-consistent-tree deleted t) t (map-preorder 'list #'node-label deleted) '(bar qux oof) )
4c6e38fbef6576a46bd9a51ecad450d1c3cc0787014b1d3d7228de68e159d58f
bsaleil/lc
primes.scm.scm
;;------------------------------------------------------------------------------ Macros (##define-macro (def-macro form . body) `(##define-macro ,form (let () ,@body))) (def-macro (FLOATvector-const . lst) `',(list->vector lst)) (def-macro (FLOATvector? x) `(vector? ,x)) (def-macro (FLOATvector . lst) `(vector ,@lst)) (def-macro (FLOATmake-vector n . init) `(make-vector ,n ,@init)) (def-macro (FLOATvector-ref v i) `(vector-ref ,v ,i)) (def-macro (FLOATvector-set! v i x) `(vector-set! ,v ,i ,x)) (def-macro (FLOATvector-length v) `(vector-length ,v)) (def-macro (nuc-const . lst) `',(list->vector lst)) (def-macro (FLOAT+ . lst) `(+ ,@lst)) (def-macro (FLOAT- . lst) `(- ,@lst)) (def-macro (FLOAT* . lst) `(* ,@lst)) (def-macro (FLOAT/ . lst) `(/ ,@lst)) (def-macro (FLOAT= . lst) `(= ,@lst)) (def-macro (FLOAT< . lst) `(< ,@lst)) (def-macro (FLOAT<= . lst) `(<= ,@lst)) (def-macro (FLOAT> . lst) `(> ,@lst)) (def-macro (FLOAT>= . lst) `(>= ,@lst)) (def-macro (FLOATnegative? . lst) `(negative? ,@lst)) (def-macro (FLOATpositive? . lst) `(positive? ,@lst)) (def-macro (FLOATzero? . lst) `(zero? ,@lst)) (def-macro (FLOATabs . lst) `(abs ,@lst)) (def-macro (FLOATsin . lst) `(sin ,@lst)) (def-macro (FLOATcos . lst) `(cos ,@lst)) (def-macro (FLOATatan . lst) `(atan ,@lst)) (def-macro (FLOATsqrt . lst) `(sqrt ,@lst)) (def-macro (FLOATmin . lst) `(min ,@lst)) (def-macro (FLOATmax . lst) `(max ,@lst)) (def-macro (FLOATround . lst) `(round ,@lst)) (def-macro (FLOATinexact->exact . lst) `(inexact->exact ,@lst)) (def-macro (GENERIC+ . lst) `(+ ,@lst)) (def-macro (GENERIC- . lst) `(- ,@lst)) (def-macro (GENERIC* . lst) `(* ,@lst)) (def-macro (GENERIC/ . lst) `(/ ,@lst)) (def-macro (GENERICquotient . lst) `(quotient ,@lst)) (def-macro (GENERICremainder . lst) `(remainder ,@lst)) (def-macro (GENERICmodulo . lst) `(modulo ,@lst)) (def-macro (GENERIC= . lst) `(= ,@lst)) (def-macro (GENERIC< . lst) `(< ,@lst)) (def-macro (GENERIC<= . lst) `(<= ,@lst)) (def-macro (GENERIC> . lst) `(> ,@lst)) (def-macro (GENERIC>= . lst) `(>= ,@lst)) (def-macro (GENERICexpt . lst) `(expt ,@lst)) ;;------------------------------------------------------------------------------ Functions used by LC to get time info (def-macro (##lc-time expr) (let ((sym (gensym))) `(let ((r (##lc-exec-stats (lambda () ,expr)))) (##print-perm-string "CPU time: ") (##print-double (+ (cdr (assoc "User time" (cdr r))) (cdr (assoc "Sys time" (cdr r))))) (##print-perm-string "\n") (##print-perm-string "GC CPU time: ") (##print-double (+ (cdr (assoc "GC user time" (cdr r))) (cdr (assoc "GC sys time" (cdr r))))) (##print-perm-string "\n") (map (lambda (el) (##print-perm-string (car el)) (##print-perm-string ": ") (##print-double (cdr el)) (##print-perm-string "\n")) (cdr r)) r))) (define (##lc-exec-stats thunk) (let* ((at-start (##process-statistics)) (result (thunk)) (at-end (##process-statistics))) (define (get-info msg idx) (cons msg (- (f64vector-ref at-end idx) (f64vector-ref at-start idx)))) (list result (get-info "User time" 0) (get-info "Sys time" 1) (get-info "Real time" 2) (get-info "GC user time" 3) (get-info "GC sys time" 4) (get-info "GC real time" 5) (get-info "Nb gcs" 6)))) ;;------------------------------------------------------------------------------ (define (run-bench name count ok? run) (let loop ((i count) (result '(undefined))) (if (< 0 i) (loop (- i 1) (run)) result))) (define (run-benchmark name count ok? run-maker . args) (let ((run (apply run-maker args))) (let ((result (car (##lc-time (run-bench name count ok? run))))) (if (not (ok? result)) (begin (display "*** wrong result ***") (newline) (display "*** got: ") (write result) (newline)))))) ; Gabriel benchmarks (define boyer-iters 20) (define browse-iters 600) (define cpstak-iters 1000) (define ctak-iters 100) (define dderiv-iters 2000000) (define deriv-iters 2000000) (define destruc-iters 500) (define diviter-iters 1000000) (define divrec-iters 1000000) (define puzzle-iters 100) (define tak-iters 2000) (define takl-iters 300) (define trav1-iters 100) (define trav2-iters 20) (define triangl-iters 10) and benchmarks (define ack-iters 10) (define array1-iters 1) (define cat-iters 1) (define string-iters 10) (define sum1-iters 10) (define sumloop-iters 10) (define tail-iters 1) (define wc-iters 1) ; C benchmarks (define fft-iters 2000) (define fib-iters 5) (define fibfp-iters 2) (define mbrot-iters 100) (define nucleic-iters 5) (define pnpoly-iters 100000) (define sum-iters 20000) (define sumfp-iters 20000) (define tfib-iters 20) ; Other benchmarks (define conform-iters 40) (define dynamic-iters 20) (define earley-iters 200) (define fibc-iters 500) (define graphs-iters 300) (define lattice-iters 1) (define matrix-iters 400) (define maze-iters 4000) (define mazefun-iters 1000) (define nqueens-iters 2000) (define paraffins-iters 1000) (define peval-iters 200) (define pi-iters 2) (define primes-iters 100000) (define ray-iters 5) (define scheme-iters 20000) (define simplex-iters 100000) (define slatex-iters 20) (define perm9-iters 10) (define nboyer-iters 100) (define sboyer-iters 100) (define gcbench-iters 1) (define compiler-iters 300) (define nbody-iters 1) (define fftrad4-iters 4) PRIMES -- Compute primes less than 100 , written by . (define (interval-list m n) (if (> m n) '() (cons m (interval-list (+ 1 m) n)))) (define (sieve l) (letrec ((remove-multiples (lambda (n l) (if (null? l) '() (if (= (modulo (car l) n) 0) (remove-multiples n (cdr l)) (cons (car l) (remove-multiples n (cdr l)))))))) (if (null? l) '() (cons (car l) (sieve (remove-multiples (car l) (cdr l))))))) (define (primes<= n) (sieve (interval-list 2 n))) (define (main) (run-benchmark "primes" primes-iters (lambda (result) (equal? result '(2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97))) (lambda (n) (lambda () (primes<= n))) 100)) (main)
null
https://raw.githubusercontent.com/bsaleil/lc/ee7867fd2bdbbe88924300e10b14ea717ee6434b/tools/benchtimes/resultVMIL-lc-gsc-lc/LCnaive/primes.scm.scm
scheme
------------------------------------------------------------------------------ ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ Gabriel benchmarks C benchmarks Other benchmarks
Macros (##define-macro (def-macro form . body) `(##define-macro ,form (let () ,@body))) (def-macro (FLOATvector-const . lst) `',(list->vector lst)) (def-macro (FLOATvector? x) `(vector? ,x)) (def-macro (FLOATvector . lst) `(vector ,@lst)) (def-macro (FLOATmake-vector n . init) `(make-vector ,n ,@init)) (def-macro (FLOATvector-ref v i) `(vector-ref ,v ,i)) (def-macro (FLOATvector-set! v i x) `(vector-set! ,v ,i ,x)) (def-macro (FLOATvector-length v) `(vector-length ,v)) (def-macro (nuc-const . lst) `',(list->vector lst)) (def-macro (FLOAT+ . lst) `(+ ,@lst)) (def-macro (FLOAT- . lst) `(- ,@lst)) (def-macro (FLOAT* . lst) `(* ,@lst)) (def-macro (FLOAT/ . lst) `(/ ,@lst)) (def-macro (FLOAT= . lst) `(= ,@lst)) (def-macro (FLOAT< . lst) `(< ,@lst)) (def-macro (FLOAT<= . lst) `(<= ,@lst)) (def-macro (FLOAT> . lst) `(> ,@lst)) (def-macro (FLOAT>= . lst) `(>= ,@lst)) (def-macro (FLOATnegative? . lst) `(negative? ,@lst)) (def-macro (FLOATpositive? . lst) `(positive? ,@lst)) (def-macro (FLOATzero? . lst) `(zero? ,@lst)) (def-macro (FLOATabs . lst) `(abs ,@lst)) (def-macro (FLOATsin . lst) `(sin ,@lst)) (def-macro (FLOATcos . lst) `(cos ,@lst)) (def-macro (FLOATatan . lst) `(atan ,@lst)) (def-macro (FLOATsqrt . lst) `(sqrt ,@lst)) (def-macro (FLOATmin . lst) `(min ,@lst)) (def-macro (FLOATmax . lst) `(max ,@lst)) (def-macro (FLOATround . lst) `(round ,@lst)) (def-macro (FLOATinexact->exact . lst) `(inexact->exact ,@lst)) (def-macro (GENERIC+ . lst) `(+ ,@lst)) (def-macro (GENERIC- . lst) `(- ,@lst)) (def-macro (GENERIC* . lst) `(* ,@lst)) (def-macro (GENERIC/ . lst) `(/ ,@lst)) (def-macro (GENERICquotient . lst) `(quotient ,@lst)) (def-macro (GENERICremainder . lst) `(remainder ,@lst)) (def-macro (GENERICmodulo . lst) `(modulo ,@lst)) (def-macro (GENERIC= . lst) `(= ,@lst)) (def-macro (GENERIC< . lst) `(< ,@lst)) (def-macro (GENERIC<= . lst) `(<= ,@lst)) (def-macro (GENERIC> . lst) `(> ,@lst)) (def-macro (GENERIC>= . lst) `(>= ,@lst)) (def-macro (GENERICexpt . lst) `(expt ,@lst)) Functions used by LC to get time info (def-macro (##lc-time expr) (let ((sym (gensym))) `(let ((r (##lc-exec-stats (lambda () ,expr)))) (##print-perm-string "CPU time: ") (##print-double (+ (cdr (assoc "User time" (cdr r))) (cdr (assoc "Sys time" (cdr r))))) (##print-perm-string "\n") (##print-perm-string "GC CPU time: ") (##print-double (+ (cdr (assoc "GC user time" (cdr r))) (cdr (assoc "GC sys time" (cdr r))))) (##print-perm-string "\n") (map (lambda (el) (##print-perm-string (car el)) (##print-perm-string ": ") (##print-double (cdr el)) (##print-perm-string "\n")) (cdr r)) r))) (define (##lc-exec-stats thunk) (let* ((at-start (##process-statistics)) (result (thunk)) (at-end (##process-statistics))) (define (get-info msg idx) (cons msg (- (f64vector-ref at-end idx) (f64vector-ref at-start idx)))) (list result (get-info "User time" 0) (get-info "Sys time" 1) (get-info "Real time" 2) (get-info "GC user time" 3) (get-info "GC sys time" 4) (get-info "GC real time" 5) (get-info "Nb gcs" 6)))) (define (run-bench name count ok? run) (let loop ((i count) (result '(undefined))) (if (< 0 i) (loop (- i 1) (run)) result))) (define (run-benchmark name count ok? run-maker . args) (let ((run (apply run-maker args))) (let ((result (car (##lc-time (run-bench name count ok? run))))) (if (not (ok? result)) (begin (display "*** wrong result ***") (newline) (display "*** got: ") (write result) (newline)))))) (define boyer-iters 20) (define browse-iters 600) (define cpstak-iters 1000) (define ctak-iters 100) (define dderiv-iters 2000000) (define deriv-iters 2000000) (define destruc-iters 500) (define diviter-iters 1000000) (define divrec-iters 1000000) (define puzzle-iters 100) (define tak-iters 2000) (define takl-iters 300) (define trav1-iters 100) (define trav2-iters 20) (define triangl-iters 10) and benchmarks (define ack-iters 10) (define array1-iters 1) (define cat-iters 1) (define string-iters 10) (define sum1-iters 10) (define sumloop-iters 10) (define tail-iters 1) (define wc-iters 1) (define fft-iters 2000) (define fib-iters 5) (define fibfp-iters 2) (define mbrot-iters 100) (define nucleic-iters 5) (define pnpoly-iters 100000) (define sum-iters 20000) (define sumfp-iters 20000) (define tfib-iters 20) (define conform-iters 40) (define dynamic-iters 20) (define earley-iters 200) (define fibc-iters 500) (define graphs-iters 300) (define lattice-iters 1) (define matrix-iters 400) (define maze-iters 4000) (define mazefun-iters 1000) (define nqueens-iters 2000) (define paraffins-iters 1000) (define peval-iters 200) (define pi-iters 2) (define primes-iters 100000) (define ray-iters 5) (define scheme-iters 20000) (define simplex-iters 100000) (define slatex-iters 20) (define perm9-iters 10) (define nboyer-iters 100) (define sboyer-iters 100) (define gcbench-iters 1) (define compiler-iters 300) (define nbody-iters 1) (define fftrad4-iters 4) PRIMES -- Compute primes less than 100 , written by . (define (interval-list m n) (if (> m n) '() (cons m (interval-list (+ 1 m) n)))) (define (sieve l) (letrec ((remove-multiples (lambda (n l) (if (null? l) '() (if (= (modulo (car l) n) 0) (remove-multiples n (cdr l)) (cons (car l) (remove-multiples n (cdr l)))))))) (if (null? l) '() (cons (car l) (sieve (remove-multiples (car l) (cdr l))))))) (define (primes<= n) (sieve (interval-list 2 n))) (define (main) (run-benchmark "primes" primes-iters (lambda (result) (equal? result '(2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97))) (lambda (n) (lambda () (primes<= n))) 100)) (main)
9ef0115deaa9c5207ea24ea57dd63819ac356e4c100ef869acc1819078589016
meooow25/haccepted
PruferBench.hs
module PruferBench where import Criterion import Prufer ( graphToSeq, seqToGraph ) import Util ( evalR, randPruferSeq, sizedBench ) benchmark :: Benchmark benchmark = bgroup "Prufer" Convert a Prufer sequence to a tree of n nodes bgroup "seqToGraph" $ map benchSeqToGraph sizes Convert a tree of n nodes to a Prufer sequence , bgroup "graphToSeq" $ map benchGraphToSeq sizes ] sizes :: [Int] sizes = [100, 10000, 1000000] benchSeqToGraph :: Int -> Benchmark benchSeqToGraph n = sizedBench n gen $ nf $ seqToGraph (1, n) where gen = evalR $ randPruferSeq n benchGraphToSeq :: Int -> Benchmark benchGraphToSeq n = sizedBench n gen $ nf graphToSeq where gen = evalR $ seqToGraph (1, n) <$> randPruferSeq n
null
https://raw.githubusercontent.com/meooow25/haccepted/2bc153ca95038de3b8bac83eee4419b3ecc116c5/bench/PruferBench.hs
haskell
module PruferBench where import Criterion import Prufer ( graphToSeq, seqToGraph ) import Util ( evalR, randPruferSeq, sizedBench ) benchmark :: Benchmark benchmark = bgroup "Prufer" Convert a Prufer sequence to a tree of n nodes bgroup "seqToGraph" $ map benchSeqToGraph sizes Convert a tree of n nodes to a Prufer sequence , bgroup "graphToSeq" $ map benchGraphToSeq sizes ] sizes :: [Int] sizes = [100, 10000, 1000000] benchSeqToGraph :: Int -> Benchmark benchSeqToGraph n = sizedBench n gen $ nf $ seqToGraph (1, n) where gen = evalR $ randPruferSeq n benchGraphToSeq :: Int -> Benchmark benchGraphToSeq n = sizedBench n gen $ nf graphToSeq where gen = evalR $ seqToGraph (1, n) <$> randPruferSeq n
0d04fd493a02f2bb7e21ea7b6b962176867d855d2fd76afc1ef93016566b8fd4
elastic/eui-cljs
icon_memory.cljs
(ns eui.icon-memory (:require ["@elastic/eui/lib/components/icon/assets/memory.js" :as eui])) (def memory eui/icon)
null
https://raw.githubusercontent.com/elastic/eui-cljs/ad60b57470a2eb8db9bca050e02f52dd964d9f8e/src/eui/icon_memory.cljs
clojure
(ns eui.icon-memory (:require ["@elastic/eui/lib/components/icon/assets/memory.js" :as eui])) (def memory eui/icon)
c16383d80f713d4dfc0176dbc3a9619883ed5db93302106ec93b32668c890ac1
lierdakil/pandoc-crossref
CustomLabels.hs
pandoc - crossref is a pandoc filter for numbering figures , equations , tables and cross - references to them . Copyright ( C ) 2015 < > This program is free software ; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation ; either version 2 of the License , or ( at your option ) any later version . This program is distributed in the hope that it will be useful , but WITHOUT ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU General Public License for more details . You should have received a copy of the GNU General Public License along with this program ; if not , write to the Free Software Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , USA . pandoc-crossref is a pandoc filter for numbering figures, equations, tables and cross-references to them. Copyright (C) 2015 Nikolay Yakimov <> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -} {-# LANGUAGE OverloadedStrings #-} module Text.Pandoc.CrossRef.Util.CustomLabels (customLabel, customHeadingLabel) where import qualified Data.Text as T import Text.Numeral.Roman import Text.Pandoc.CrossRef.Util.Meta import Text.Pandoc.Definition customLabel :: Meta -> T.Text -> Int -> Maybe T.Text customLabel meta ref i | refLabel <- T.takeWhile (/=':') ref , Just cl <- lookupMeta (refLabel <> "Labels") meta = mkLabel i (refLabel <> "Labels") cl | otherwise = Nothing customHeadingLabel :: Meta -> Int -> Int -> Maybe T.Text customHeadingLabel meta lvl i | Just cl <- getMetaList Just "secLevelLabels" meta (lvl-1) = mkLabel i "secLevelLabels" cl | otherwise = Nothing mkLabel :: Int -> T.Text -> MetaValue -> Maybe T.Text mkLabel i n lt | MetaList _ <- lt , Just val <- toString n <$> getList (i-1) lt = Just val | toString n lt == "arabic" = Nothing | toString n lt == "roman" = Just $ toRoman i | toString n lt == "lowercase roman" = Just $ T.toLower $ toRoman i | Just (startWith, _) <- T.uncons =<< T.stripPrefix "alpha " (toString n lt) = Just . T.singleton $ [startWith..] !! (i-1) | otherwise = error $ "Unknown numeration type: " ++ show lt
null
https://raw.githubusercontent.com/lierdakil/pandoc-crossref/e65a6cde871d0d5ec40628f7f51c2bdbab7784b7/lib-internal/Text/Pandoc/CrossRef/Util/CustomLabels.hs
haskell
# LANGUAGE OverloadedStrings #
pandoc - crossref is a pandoc filter for numbering figures , equations , tables and cross - references to them . Copyright ( C ) 2015 < > This program is free software ; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation ; either version 2 of the License , or ( at your option ) any later version . This program is distributed in the hope that it will be useful , but WITHOUT ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU General Public License for more details . You should have received a copy of the GNU General Public License along with this program ; if not , write to the Free Software Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , USA . pandoc-crossref is a pandoc filter for numbering figures, equations, tables and cross-references to them. Copyright (C) 2015 Nikolay Yakimov <> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -} module Text.Pandoc.CrossRef.Util.CustomLabels (customLabel, customHeadingLabel) where import qualified Data.Text as T import Text.Numeral.Roman import Text.Pandoc.CrossRef.Util.Meta import Text.Pandoc.Definition customLabel :: Meta -> T.Text -> Int -> Maybe T.Text customLabel meta ref i | refLabel <- T.takeWhile (/=':') ref , Just cl <- lookupMeta (refLabel <> "Labels") meta = mkLabel i (refLabel <> "Labels") cl | otherwise = Nothing customHeadingLabel :: Meta -> Int -> Int -> Maybe T.Text customHeadingLabel meta lvl i | Just cl <- getMetaList Just "secLevelLabels" meta (lvl-1) = mkLabel i "secLevelLabels" cl | otherwise = Nothing mkLabel :: Int -> T.Text -> MetaValue -> Maybe T.Text mkLabel i n lt | MetaList _ <- lt , Just val <- toString n <$> getList (i-1) lt = Just val | toString n lt == "arabic" = Nothing | toString n lt == "roman" = Just $ toRoman i | toString n lt == "lowercase roman" = Just $ T.toLower $ toRoman i | Just (startWith, _) <- T.uncons =<< T.stripPrefix "alpha " (toString n lt) = Just . T.singleton $ [startWith..] !! (i-1) | otherwise = error $ "Unknown numeration type: " ++ show lt
fe8ad50cf87280a1937ab94131e9f55109452d5ba73ce1014eab7bdd49959b72
input-output-hk/plutus
NamesSpec.hs
module NamesSpec ( names ) where import PlutusIR.Generators.AST import PlutusIR.Mark import PlutusIR.Transform.Rename import PlutusCore.Rename import PlutusCore.Test import Test.Tasty names :: TestTree names = testGroup "names" [ test_scopingGood genProgram rename , test_scopingBad genProgram markNonFreshProgram renameProgramM ]
null
https://raw.githubusercontent.com/input-output-hk/plutus/75d60c48320068e918f1f260367d080031c970b5/plutus-core/plutus-ir/test/NamesSpec.hs
haskell
module NamesSpec ( names ) where import PlutusIR.Generators.AST import PlutusIR.Mark import PlutusIR.Transform.Rename import PlutusCore.Rename import PlutusCore.Test import Test.Tasty names :: TestTree names = testGroup "names" [ test_scopingGood genProgram rename , test_scopingBad genProgram markNonFreshProgram renameProgramM ]
b14777645ff1c479857ea7e81926766bf718b300a1d56178a2a581f662828f29
marijnh/Postmodern
trivial-utf-8.lisp
-*- Mode : LISP ; Syntax : Ansi - Common - Lisp ; Base : 10 ; Package : CL - POSTGRES - TRIVIAL - UTF-8 ; -*- ;;; Minimal utf-8 decoding and encoding library. ;;; ;;; See -lisp.net/project/trivial-utf-8/ (no longer maintained?) ;;; This file is being kept in case we need to make patches or additions (in-package :cl-postgres-trivial-utf-8) (eval-when (:compile-toplevel :load-toplevel :execute) (defparameter *optimize* '(optimize (speed 3) #-ecl(safety 0) #+ecl(safety 1) (space 0) (debug 1) (compilation-speed 0)))) (defun utf-8-byte-length (string) "Calculate the amount of bytes needed to encode a string." (declare (type string string) #'*optimize*) (let ((length (length string)) (string (coerce string 'simple-string))) (loop :for char :across string :do (let ((code (char-code char))) (when (> code 127) (incf length (cond ((< code 2048) 1) ((< code 65536) 2) (t 3)))))) length)) (defmacro as-utf-8-bytes (char writer) "Given a character, calls the writer function for every byte in the encoded form of that character." (let ((char-code (gensym))) `(let ((,char-code (char-code ,char))) (declare (type fixnum ,char-code)) (cond ((< ,char-code 128) (,writer ,char-code)) ((< ,char-code 2048) (,writer (logior #b11000000 (ldb (byte 5 6) ,char-code))) (,writer (logior #b10000000 (ldb (byte 6 0) ,char-code)))) ((< ,char-code 65536) (,writer (logior #b11100000 (ldb (byte 4 12) ,char-code))) (,writer (logior #b10000000 (ldb (byte 6 6) ,char-code))) (,writer (logior #b10000000 (ldb (byte 6 0) ,char-code)))) (t (,writer (logior #b11110000 (ldb (byte 3 18) ,char-code))) (,writer (logior #b10000000 (ldb (byte 6 12) ,char-code))) (,writer (logior #b10000000 (ldb (byte 6 6) ,char-code))) (,writer (logior #b10000000 (ldb (byte 6 0) ,char-code)))))))) (defun string-to-utf-8-bytes (string &key null-terminate) "Convert a string into an array of unsigned bytes containing its utf-8 representation." (declare (type string string) #.*optimize*) (let ((buffer (make-array (+ (the fixnum (utf-8-byte-length string)) (if null-terminate 1 0)) :element-type '(unsigned-byte 8) :initial-element 0)) (position 0) (string (coerce string 'simple-string))) (declare (type (array (unsigned-byte 8)) buffer) (type fixnum position)) (macrolet ((add-byte (byte) `(progn (setf (aref buffer position) ,byte) (incf position)))) (loop :for char :across string :do (as-utf-8-bytes char add-byte))) (when null-terminate (setf (elt buffer (1- (length buffer))) 0)) buffer)) (defun write-utf-8-bytes (string output &key null-terminate) "Write a string to a byte-stream, encoding it as utf-8." (declare (type string string) (type stream output) #.*optimize*) (macrolet ((byte-out (byte) `(write-byte ,byte output))) (let ((string (coerce string 'simple-string))) (loop :for char :across string :do (as-utf-8-bytes char byte-out)))) (when null-terminate (write-byte 0 output))) (define-condition utf-8-decoding-error (simple-error) ((message :initarg :message) (byte :initarg :byte :initform nil)) (:report (lambda (err stream) (format stream (slot-value err 'message) (slot-value err 'byte))))) (declaim (inline utf-8-group-size)) (defun utf-8-group-size (byte) "Determine the amount of bytes that are part of the character starting with a given byte." (declare (type fixnum byte) #.*optimize*) (cond ((zerop (logand byte #b10000000)) 1) ((= (logand byte #b11100000) #b11000000) 2) ((= (logand byte #b11110000) #b11100000) 3) ((= (logand byte #b11111000) #b11110000) 4) (t (error 'utf-8-decoding-error :byte byte :message "Invalid byte at start of character: 0x~X")))) (defun utf-8-string-length (bytes &key (start 0) (end (length bytes))) "Calculate the length of the string encoded by the given bytes." (declare (type (simple-array (unsigned-byte 8) (*)) bytes) (type fixnum start end) #.*optimize*) (loop :with i :of-type fixnum = start :with string-length = 0 :while (< i end) :do (progn (incf (the fixnum string-length) 1) (incf i (utf-8-group-size (elt bytes i)))) :finally (return string-length))) (defun get-utf-8-character (bytes group-size &optional (start 0)) "Given an array of bytes and the amount of bytes to use, extract the character starting at the given start position." (declare (type (simple-array (unsigned-byte 8) (*)) bytes) (type fixnum group-size start) #.*optimize*) (labels ((next-byte () (prog1 (elt bytes start) (incf start))) (six-bits (byte) (unless (= (logand byte #b11000000) #b10000000) (error 'utf-8-decoding-error :byte byte :message "Invalid byte 0x~X inside a character.")) (ldb (byte 6 0) byte))) (case group-size (1 (next-byte)) (2 (logior (ash (ldb (byte 5 0) (next-byte)) 6) (six-bits (next-byte)))) (3 (logior (ash (ldb (byte 4 0) (next-byte)) 12) (ash (six-bits (next-byte)) 6) (six-bits (next-byte)))) (4 (logior (ash (ldb (byte 3 0) (next-byte)) 18) (ash (six-bits (next-byte)) 12) (ash (six-bits (next-byte)) 6) (six-bits (next-byte))))))) (defun utf-8-bytes-to-string (bytes-in &key (start 0) (end (length bytes-in))) "Convert a byte array containing utf-8 encoded characters into the string it encodes." (declare (type vector bytes-in) (type fixnum start end) #.*optimize*) (loop :with bytes = (coerce bytes-in '(simple-array (unsigned-byte 8) (*))) :with buffer = (make-string (utf-8-string-length bytes :start start :end end) :element-type 'character) :with array-position :of-type fixnum = start :with string-position :of-type fixnum = 0 :while (< array-position end) :do (let* ((char (elt bytes array-position)) (current-group (utf-8-group-size char))) (when (> (+ current-group array-position) end) (error 'utf-8-decoding-error :message "Unfinished character at end of byte array.")) (setf (char buffer string-position) (code-char (get-utf-8-character bytes current-group array-position))) (incf string-position 1) (incf array-position current-group)) :finally (return buffer))) (defun read-utf-8-string (input &key null-terminated stop-at-eof (char-length -1) (byte-length -1)) "Read utf-8 encoded data from a byte stream and construct a string with the characters found. When null-terminated is given it will stop reading at a null character, stop-at-eof tells it to stop at the end of file without raising an error, and the char-length and byte-length parameters can be used to specify the max amount of characters or bytes to read." (declare (type stream input) (type fixnum byte-length char-length) #.*optimize*) (let ((buffer (make-array 4 :element-type '(unsigned-byte 8) :initial-element 0)) (bytes-read 0) (string (make-array 64 :element-type 'character :adjustable t :fill-pointer 0))) (declare (type fixnum bytes-read)) (loop (when (or (and (/= -1 byte-length) (>= bytes-read byte-length)) (and (/= -1 char-length) (= char-length (length string)))) (return)) (let ((next-char (read-byte input (not stop-at-eof) :eof))) (when (or (eq next-char :eof) (and null-terminated (eq next-char 0))) (return)) (let ((current-group (utf-8-group-size next-char))) (incf bytes-read current-group) (cond ((= current-group 1) (vector-push-extend (code-char next-char) string)) (t (setf (elt buffer 0) next-char) (loop :for i :from 1 :below current-group :for next-char = (read-byte input nil :eof) :do (when (eq next-char :eof) (error 'utf-8-decoding-error :message "Unfinished character at end of input.")) :do (setf (elt buffer i) next-char)) (vector-push-extend (code-char (get-utf-8-character buffer current-group)) string)))))) string))
null
https://raw.githubusercontent.com/marijnh/Postmodern/d54e494000e1915a7046e8d825cb635555957e85/cl-postgres/trivial-utf-8.lisp
lisp
Syntax : Ansi - Common - Lisp ; Base : 10 ; Package : CL - POSTGRES - TRIVIAL - UTF-8 ; -*- Minimal utf-8 decoding and encoding library. See -lisp.net/project/trivial-utf-8/ (no longer maintained?) This file is being kept in case we need to make patches or additions
(in-package :cl-postgres-trivial-utf-8) (eval-when (:compile-toplevel :load-toplevel :execute) (defparameter *optimize* '(optimize (speed 3) #-ecl(safety 0) #+ecl(safety 1) (space 0) (debug 1) (compilation-speed 0)))) (defun utf-8-byte-length (string) "Calculate the amount of bytes needed to encode a string." (declare (type string string) #'*optimize*) (let ((length (length string)) (string (coerce string 'simple-string))) (loop :for char :across string :do (let ((code (char-code char))) (when (> code 127) (incf length (cond ((< code 2048) 1) ((< code 65536) 2) (t 3)))))) length)) (defmacro as-utf-8-bytes (char writer) "Given a character, calls the writer function for every byte in the encoded form of that character." (let ((char-code (gensym))) `(let ((,char-code (char-code ,char))) (declare (type fixnum ,char-code)) (cond ((< ,char-code 128) (,writer ,char-code)) ((< ,char-code 2048) (,writer (logior #b11000000 (ldb (byte 5 6) ,char-code))) (,writer (logior #b10000000 (ldb (byte 6 0) ,char-code)))) ((< ,char-code 65536) (,writer (logior #b11100000 (ldb (byte 4 12) ,char-code))) (,writer (logior #b10000000 (ldb (byte 6 6) ,char-code))) (,writer (logior #b10000000 (ldb (byte 6 0) ,char-code)))) (t (,writer (logior #b11110000 (ldb (byte 3 18) ,char-code))) (,writer (logior #b10000000 (ldb (byte 6 12) ,char-code))) (,writer (logior #b10000000 (ldb (byte 6 6) ,char-code))) (,writer (logior #b10000000 (ldb (byte 6 0) ,char-code)))))))) (defun string-to-utf-8-bytes (string &key null-terminate) "Convert a string into an array of unsigned bytes containing its utf-8 representation." (declare (type string string) #.*optimize*) (let ((buffer (make-array (+ (the fixnum (utf-8-byte-length string)) (if null-terminate 1 0)) :element-type '(unsigned-byte 8) :initial-element 0)) (position 0) (string (coerce string 'simple-string))) (declare (type (array (unsigned-byte 8)) buffer) (type fixnum position)) (macrolet ((add-byte (byte) `(progn (setf (aref buffer position) ,byte) (incf position)))) (loop :for char :across string :do (as-utf-8-bytes char add-byte))) (when null-terminate (setf (elt buffer (1- (length buffer))) 0)) buffer)) (defun write-utf-8-bytes (string output &key null-terminate) "Write a string to a byte-stream, encoding it as utf-8." (declare (type string string) (type stream output) #.*optimize*) (macrolet ((byte-out (byte) `(write-byte ,byte output))) (let ((string (coerce string 'simple-string))) (loop :for char :across string :do (as-utf-8-bytes char byte-out)))) (when null-terminate (write-byte 0 output))) (define-condition utf-8-decoding-error (simple-error) ((message :initarg :message) (byte :initarg :byte :initform nil)) (:report (lambda (err stream) (format stream (slot-value err 'message) (slot-value err 'byte))))) (declaim (inline utf-8-group-size)) (defun utf-8-group-size (byte) "Determine the amount of bytes that are part of the character starting with a given byte." (declare (type fixnum byte) #.*optimize*) (cond ((zerop (logand byte #b10000000)) 1) ((= (logand byte #b11100000) #b11000000) 2) ((= (logand byte #b11110000) #b11100000) 3) ((= (logand byte #b11111000) #b11110000) 4) (t (error 'utf-8-decoding-error :byte byte :message "Invalid byte at start of character: 0x~X")))) (defun utf-8-string-length (bytes &key (start 0) (end (length bytes))) "Calculate the length of the string encoded by the given bytes." (declare (type (simple-array (unsigned-byte 8) (*)) bytes) (type fixnum start end) #.*optimize*) (loop :with i :of-type fixnum = start :with string-length = 0 :while (< i end) :do (progn (incf (the fixnum string-length) 1) (incf i (utf-8-group-size (elt bytes i)))) :finally (return string-length))) (defun get-utf-8-character (bytes group-size &optional (start 0)) "Given an array of bytes and the amount of bytes to use, extract the character starting at the given start position." (declare (type (simple-array (unsigned-byte 8) (*)) bytes) (type fixnum group-size start) #.*optimize*) (labels ((next-byte () (prog1 (elt bytes start) (incf start))) (six-bits (byte) (unless (= (logand byte #b11000000) #b10000000) (error 'utf-8-decoding-error :byte byte :message "Invalid byte 0x~X inside a character.")) (ldb (byte 6 0) byte))) (case group-size (1 (next-byte)) (2 (logior (ash (ldb (byte 5 0) (next-byte)) 6) (six-bits (next-byte)))) (3 (logior (ash (ldb (byte 4 0) (next-byte)) 12) (ash (six-bits (next-byte)) 6) (six-bits (next-byte)))) (4 (logior (ash (ldb (byte 3 0) (next-byte)) 18) (ash (six-bits (next-byte)) 12) (ash (six-bits (next-byte)) 6) (six-bits (next-byte))))))) (defun utf-8-bytes-to-string (bytes-in &key (start 0) (end (length bytes-in))) "Convert a byte array containing utf-8 encoded characters into the string it encodes." (declare (type vector bytes-in) (type fixnum start end) #.*optimize*) (loop :with bytes = (coerce bytes-in '(simple-array (unsigned-byte 8) (*))) :with buffer = (make-string (utf-8-string-length bytes :start start :end end) :element-type 'character) :with array-position :of-type fixnum = start :with string-position :of-type fixnum = 0 :while (< array-position end) :do (let* ((char (elt bytes array-position)) (current-group (utf-8-group-size char))) (when (> (+ current-group array-position) end) (error 'utf-8-decoding-error :message "Unfinished character at end of byte array.")) (setf (char buffer string-position) (code-char (get-utf-8-character bytes current-group array-position))) (incf string-position 1) (incf array-position current-group)) :finally (return buffer))) (defun read-utf-8-string (input &key null-terminated stop-at-eof (char-length -1) (byte-length -1)) "Read utf-8 encoded data from a byte stream and construct a string with the characters found. When null-terminated is given it will stop reading at a null character, stop-at-eof tells it to stop at the end of file without raising an error, and the char-length and byte-length parameters can be used to specify the max amount of characters or bytes to read." (declare (type stream input) (type fixnum byte-length char-length) #.*optimize*) (let ((buffer (make-array 4 :element-type '(unsigned-byte 8) :initial-element 0)) (bytes-read 0) (string (make-array 64 :element-type 'character :adjustable t :fill-pointer 0))) (declare (type fixnum bytes-read)) (loop (when (or (and (/= -1 byte-length) (>= bytes-read byte-length)) (and (/= -1 char-length) (= char-length (length string)))) (return)) (let ((next-char (read-byte input (not stop-at-eof) :eof))) (when (or (eq next-char :eof) (and null-terminated (eq next-char 0))) (return)) (let ((current-group (utf-8-group-size next-char))) (incf bytes-read current-group) (cond ((= current-group 1) (vector-push-extend (code-char next-char) string)) (t (setf (elt buffer 0) next-char) (loop :for i :from 1 :below current-group :for next-char = (read-byte input nil :eof) :do (when (eq next-char :eof) (error 'utf-8-decoding-error :message "Unfinished character at end of input.")) :do (setf (elt buffer i) next-char)) (vector-push-extend (code-char (get-utf-8-character buffer current-group)) string)))))) string))
242488f4b60522a599305e859005eafbe4bec9bada9986963b11f98fbb72d79a
LCBH/UKano
movenew.ml
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Cryptographic protocol verifier * * * * , , and * * * * Copyright ( C ) INRIA , CNRS 2000 - 2020 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Cryptographic protocol verifier * * * * Bruno Blanchet, Vincent Cheval, and Marc Sylvestre * * * * Copyright (C) INRIA, CNRS 2000-2020 * * * *************************************************************) This program is free software ; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation ; either version 2 of the License , or ( at your option ) any later version . This program is distributed in the hope that it will be useful , but WITHOUT ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU General Public License for more details ( in file LICENSE ) . You should have received a copy of the GNU 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 This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details (in file LICENSE). You should have received a copy of the GNU 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 Types (* Move restrictions under inputs to make the analysis more precise *) let rec put_new l p = match l with [] -> p | ((a,args,occ)::l') -> Restr(a,args,put_new l' p,occ) let rec move_new accu = function Nil -> Nil | NamedProcess(s, tl, p) -> let ( l1,l2 ) = List.partition ( fun ( f , _ , _ ) - > List.exists ( Terms.occurs_f f ) tl ) accu in put_new l1 ( NamedProcess(s , tl , ) ) if List.exists (fun (f, _, _) -> (List.exists (Terms.occurs_f f) tl)) accu then NamedProcess(s, [], move_new accu p) else NamedProcess(s, tl, move_new accu p) | Par(p1,p2) -> put_new accu (Par(move_new [] p1, move_new [] p2)) | Repl(p,occ) -> put_new accu (Repl (move_new [] p,occ)) | Restr(f, args, p,occ) -> move_new ((f,args, occ)::accu) p | Test(t,p1,p2,occ) -> if p2 <> Nil then put_new accu (Test(t, move_new [] p1, move_new [] p2,occ)) else let (l1,l2) = List.partition (fun (f,_,_) -> Terms.occurs_f f t) accu in put_new l1 (Test(t,move_new l2 p1,Nil,occ)) | Input(t,pat,p,occ) -> let (l1,l2) = List.partition (fun (f,_,_) -> Terms.occurs_f f t || Terms.occurs_f_pat f pat) accu in put_new l1 (Input(t,pat, move_new l2 p,occ)) | Output(t1,t2,p,occ) -> let (l1,l2) = List.partition (fun (f,_,_) -> Terms.occurs_f f t1 || Terms.occurs_f f t2) accu in put_new l1 (Output(t1,t2,move_new l2 p,occ)) | Let(pat,t,p,p',occ) -> if p' <> Nil then put_new accu (Let(pat, t, move_new [] p, move_new [] p',occ)) else let (l1,l2) = List.partition (fun (f,_,_) -> Terms.occurs_f f t || Terms.occurs_f_pat f pat) accu in put_new l1 (Let(pat, t, move_new l2 p, Nil,occ)) | LetFilter(vl,fact,p,q,occ) -> if q <> Nil then put_new accu (LetFilter(vl,fact,move_new [] p, move_new [] q,occ)) else let (l1,l2) = List.partition (fun (f,_,_) -> Terms.occurs_f_fact f fact) accu in put_new l1 (LetFilter(vl, fact, move_new l2 p,Nil,occ)) | Event(t1,env_args,p,occ) -> let (l1,l2) = List.partition (fun (f,_,_) -> Terms.occurs_f f t1) accu in put_new l1 (Event(t1, env_args, move_new l2 p, occ)) | Insert(t1,p,occ) -> let (l1,l2) = List.partition (fun (f,_,_) -> Terms.occurs_f f t1) accu in put_new l1 (Insert(t1, move_new l2 p, occ)) | Get(pat,t1,p,q,occ) -> if q <> Nil then put_new accu (Get(pat,t1,move_new [] p, move_new [] q,occ)) else let (l1,l2) = List.partition (fun (f,_,_) -> Terms.occurs_f f t1 || Terms.occurs_f_pat f pat) accu in put_new l1 (Get(pat, t1, move_new l2 p, Nil, occ)) | Phase(n,p,occ) -> Phase(n, move_new accu p,occ) | Barrier(n, tag, p,occ) -> Barrier(n, tag, move_new accu p,occ) | AnnBarrier _ -> Parsing_helper.internal_error "Annotated barriers should not appear here (5)" let move_new p = move_new [] p
null
https://raw.githubusercontent.com/LCBH/UKano/13c046ddaca48b45d3652c3ea08e21599e051527/proverif2.01/src/movenew.ml
ocaml
Move restrictions under inputs to make the analysis more precise
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Cryptographic protocol verifier * * * * , , and * * * * Copyright ( C ) INRIA , CNRS 2000 - 2020 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Cryptographic protocol verifier * * * * Bruno Blanchet, Vincent Cheval, and Marc Sylvestre * * * * Copyright (C) INRIA, CNRS 2000-2020 * * * *************************************************************) This program is free software ; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation ; either version 2 of the License , or ( at your option ) any later version . This program is distributed in the hope that it will be useful , but WITHOUT ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU General Public License for more details ( in file LICENSE ) . You should have received a copy of the GNU 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 This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details (in file LICENSE). You should have received a copy of the GNU 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 Types let rec put_new l p = match l with [] -> p | ((a,args,occ)::l') -> Restr(a,args,put_new l' p,occ) let rec move_new accu = function Nil -> Nil | NamedProcess(s, tl, p) -> let ( l1,l2 ) = List.partition ( fun ( f , _ , _ ) - > List.exists ( Terms.occurs_f f ) tl ) accu in put_new l1 ( NamedProcess(s , tl , ) ) if List.exists (fun (f, _, _) -> (List.exists (Terms.occurs_f f) tl)) accu then NamedProcess(s, [], move_new accu p) else NamedProcess(s, tl, move_new accu p) | Par(p1,p2) -> put_new accu (Par(move_new [] p1, move_new [] p2)) | Repl(p,occ) -> put_new accu (Repl (move_new [] p,occ)) | Restr(f, args, p,occ) -> move_new ((f,args, occ)::accu) p | Test(t,p1,p2,occ) -> if p2 <> Nil then put_new accu (Test(t, move_new [] p1, move_new [] p2,occ)) else let (l1,l2) = List.partition (fun (f,_,_) -> Terms.occurs_f f t) accu in put_new l1 (Test(t,move_new l2 p1,Nil,occ)) | Input(t,pat,p,occ) -> let (l1,l2) = List.partition (fun (f,_,_) -> Terms.occurs_f f t || Terms.occurs_f_pat f pat) accu in put_new l1 (Input(t,pat, move_new l2 p,occ)) | Output(t1,t2,p,occ) -> let (l1,l2) = List.partition (fun (f,_,_) -> Terms.occurs_f f t1 || Terms.occurs_f f t2) accu in put_new l1 (Output(t1,t2,move_new l2 p,occ)) | Let(pat,t,p,p',occ) -> if p' <> Nil then put_new accu (Let(pat, t, move_new [] p, move_new [] p',occ)) else let (l1,l2) = List.partition (fun (f,_,_) -> Terms.occurs_f f t || Terms.occurs_f_pat f pat) accu in put_new l1 (Let(pat, t, move_new l2 p, Nil,occ)) | LetFilter(vl,fact,p,q,occ) -> if q <> Nil then put_new accu (LetFilter(vl,fact,move_new [] p, move_new [] q,occ)) else let (l1,l2) = List.partition (fun (f,_,_) -> Terms.occurs_f_fact f fact) accu in put_new l1 (LetFilter(vl, fact, move_new l2 p,Nil,occ)) | Event(t1,env_args,p,occ) -> let (l1,l2) = List.partition (fun (f,_,_) -> Terms.occurs_f f t1) accu in put_new l1 (Event(t1, env_args, move_new l2 p, occ)) | Insert(t1,p,occ) -> let (l1,l2) = List.partition (fun (f,_,_) -> Terms.occurs_f f t1) accu in put_new l1 (Insert(t1, move_new l2 p, occ)) | Get(pat,t1,p,q,occ) -> if q <> Nil then put_new accu (Get(pat,t1,move_new [] p, move_new [] q,occ)) else let (l1,l2) = List.partition (fun (f,_,_) -> Terms.occurs_f f t1 || Terms.occurs_f_pat f pat) accu in put_new l1 (Get(pat, t1, move_new l2 p, Nil, occ)) | Phase(n,p,occ) -> Phase(n, move_new accu p,occ) | Barrier(n, tag, p,occ) -> Barrier(n, tag, move_new accu p,occ) | AnnBarrier _ -> Parsing_helper.internal_error "Annotated barriers should not appear here (5)" let move_new p = move_new [] p
f64c83e2456315d4656bb44649f1b7474198ddbb7f42f7aa1071a59d381cef38
Perry961002/SICP
exa2.1.3-what-is-data.scm
(define (cons x y) (define (dispatch m) (cond ((= m 0) x) ((= m 1) y) (else (error "Argument not 0 or 1 -- CONS" m)))) dispatch) (define (car z) (z 0)) (define (cdr z) (z 1))
null
https://raw.githubusercontent.com/Perry961002/SICP/89d539e600a73bec42d350592f0ac626e041bf16/Chap2/example/exa2.1.3-what-is-data.scm
scheme
(define (cons x y) (define (dispatch m) (cond ((= m 0) x) ((= m 1) y) (else (error "Argument not 0 or 1 -- CONS" m)))) dispatch) (define (car z) (z 0)) (define (cdr z) (z 1))
480c07ff013f077d4d9d8679a45edb1261d953b2e9af70a68c04d4d07c7bf36f
input-output-hk/plutus
Internal.hs
-- editorconfig-checker-disable-file -- | The internal module of the type checker that defines the actual algorithms, -- but not the user-facing API. {-# LANGUAGE ConstraintKinds #-} # LANGUAGE DerivingStrategies # # LANGUAGE LambdaCase # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE RankNTypes # module PlutusIR.TypeCheck.Internal ( BuiltinTypes (..) , TypeCheckConfig (..) , TypeCheckT , MonadKindCheck , MonadTypeCheck , MonadTypeCheckPir , tccBuiltinTypes , PirTCConfig (..) , AllowEscape (..) , inferTypeM , checkTypeM , runTypeCheckM ) where import PlutusPrelude import PlutusIR import PlutusIR.Compiler.Datatype import PlutusIR.Compiler.Provenance import PlutusIR.Compiler.Types import PlutusIR.Error import PlutusIR.MkPir qualified as PIR import PlutusIR.Transform.Rename () import PlutusCore (toPatFuncKind, tyVarDeclName, typeAnn) import PlutusCore.Error as PLC we mirror inferTypeM , checkTypeM of plc - tc and extend it for plutus - ir terms import PlutusCore.TypeCheck.Internal hiding (checkTypeM, inferTypeM, runTypeCheckM) import Control.Monad.Error.Lens import Control.Monad.Except -- Using @transformers@ rather than @mtl@, because the former doesn't impose the 'Monad' constraint -- on 'local'. import Control.Monad.Trans.Reader import Data.Foldable import Universe Note [ PLC Typechecker code reuse ] For PIR kind - checking , we reuse ` checkKindM ` , ` inferKindM ` directly from the PLC typechecker . For PIR type - checking , we port the ` checkTypeM ` and ` inferTypeM ` from PLC typechecker . The port is a direct copy , except for the modifications of ` Term ` to ` PIR.Term ` and error type signatures and ` throwError ` to accommodate for the new pir type - errors . These modifications are currently necessary since PIR.Term ADT /= PLC.Term ADT . We then extend this ported ` PIR.inferTypeM ` with cases for inferring type of LetRec and LetNonRec . See Note [ Notation ] of PlutusCore . . Internal for the notation of inference rules , which appear in the comments . For PIR kind-checking, we reuse `checkKindM`, `inferKindM` directly from the PLC typechecker. For PIR type-checking, we port the `checkTypeM` and `inferTypeM` from PLC typechecker. The port is a direct copy, except for the modifications of `Term` to `PIR.Term` and error type signatures and `throwError` to accommodate for the new pir type-errors. These modifications are currently necessary since PIR.Term ADT /= PLC.Term ADT. We then extend this ported `PIR.inferTypeM` with cases for inferring type of LetRec and LetNonRec. See Note [Notation] of PlutusCore.TypeCheck.Internal for the notation of inference rules, which appear in the comments. -} Note [ PIR vs Paper Syntax Difference ] Link to the paper : < -recursion/latest/download-by-type/doc-pdf/unraveling-recursion > FIR 's syntax requires that the data - constructor is annotated with a * list of its argument types * ( domain ) , instead of requiring a single valid type T ( usually in the form ` dataconstr : arg1 - > arg2 - > ... argn ` ) The codomain is also left out of the syntax and implied to be of the type ` [ TypeCons tyarg1 tyarg2 ... tyargn ] ` ( what would be expected for a non - GADT ) . Finally , the leading " forall type - parameters " are implicit ( since they are consider in scope ) . PIR 's syntax requires that a full ( valid ) type is written for the data - constructor , using the syntax for types ( the forall type - parameters remains implicit ) . This means that the codomain has to be be explicitly given in PIR . To make sure that the PIR - user has written down the expected non - GADT type we do an extra codomainCheck . This codomainCheck will have to be relaxed if / when PIR introduces GADTs . More importantly , since the type for the PIR data - constructor can be any syntax - valid type , the PIR user may have placed inside there a non - normalized type there . Currently , the PIR typechecker will assume the types of all data - constructors are prior normalized * before * type - checking , otherwise the PIR typechecking and PIR compilation will fail . See NOTE [ Normalization of data - constructors ' types ] at PlutusIR.Compiler . Datatype Link to the paper: <-recursion/latest/download-by-type/doc-pdf/unraveling-recursion> FIR's syntax requires that the data-constructor is annotated with a *list of its argument types* (domain), instead of requiring a single valid type T (usually in the form `dataconstr : arg1 -> arg2 ->... argn`) The codomain is also left out of the syntax and implied to be of the type `[TypeCons tyarg1 tyarg2 ... tyargn]` (what would be expected for a non-GADT). Finally, the leading "forall type-parameters" are implicit (since they are consider in scope). PIR's syntax requires that a full (valid) type is written for the data-constructor, using the syntax for types (the forall type-parameters remains implicit). This means that the codomain has to be be explicitly given in PIR. To make sure that the PIR-user has written down the expected non-GADT type we do an extra codomainCheck. This codomainCheck will have to be relaxed if/when PIR introduces GADTs. More importantly, since the type for the PIR data-constructor can be any syntax-valid type, the PIR user may have placed inside there a non-normalized type there. Currently, the PIR typechecker will assume the types of all data-constructors are prior normalized *before* type-checking, otherwise the PIR typechecking and PIR compilation will fail. See NOTE [Normalization of data-constructors' types] at PlutusIR.Compiler.Datatype -} Note [ PIR vs Paper Escaping Types Difference ] Link to the paper : < -recursion/latest/download-by-type/doc-pdf/unraveling-recursion > In FIR paper 's Fig.6 , T - Let and T - LetRec rules dictate that : Gamma ! - inTerm : : * for two reasons : 1 . check ( locally ) that the kind of the in - term 's inferred type is indeed * 2 . ensure that the inferred type does not escaping its scope ( hence Gamma ) This is in general true for the PIR implementation as well , except in the special case when a Type is inferred for the top - level expression ( ` program`-level ) . In contrast to ( 2 ) , we allow such a " top - level " type to escape its scope ; the reasoning is that PIR programs with toplevel escaping types would behave correctly when they are translated down to PLC . Even in the case where we let the type variables escape , ( 1 ) must still hold : the kind of the escaping type should still be star . Unfortunately , in order to check that we 'd have to use the variables which are no longer in scope . So we skip the rule ( Gamma ! - inTermTopLevel : : * ) in case of top - level inferred types . The implementation has a user - configurable flag to let the typechecker know if the current term under examination is at the program 's " top - level " position , and thus allow its type to escape . The flag is automatically set to no - type - escape when typechecking inside a let 's rhs term . Link to the paper: <-recursion/latest/download-by-type/doc-pdf/unraveling-recursion> In FIR paper's Fig.6, T-Let and T-LetRec rules dictate that: Gamma !- inTerm :: * for two reasons: 1. check (locally) that the kind of the in-term's inferred type is indeed * 2. ensure that the inferred type does not escaping its scope (hence Gamma) This is in general true for the PIR implementation as well, except in the special case when a Type is inferred for the top-level expression (`program`-level). In contrast to (2), we allow such a "top-level" type to escape its scope; the reasoning is that PIR programs with toplevel escaping types would behave correctly when they are translated down to PLC. Even in the case where we let the type variables escape, (1) must still hold: the kind of the escaping type should still be star. Unfortunately, in order to check that we'd have to use the variables which are no longer in scope. So we skip the rule (Gamma !- inTermTopLevel :: *) in case of top-level inferred types. The implementation has a user-configurable flag to let the typechecker know if the current term under examination is at the program's "top-level" position, and thus allow its type to escape. The flag is automatically set to no-type-escape when typechecking inside a let termbind's rhs term. -} -- | a shorthand for our pir-specialized tc functions type PirTCEnv uni fun m = TypeCheckT uni fun (PirTCConfig uni fun) m | The constraints that are required for type checking IR . type MonadTypeCheckPir err uni fun ann m = ( MonadTypeCheck err (Term TyName Name uni fun ()) uni fun ann m IR has additional type errors , see ' TypeErrorExt ' . ) # # # # # # # # # # # # # # # # # # # # # # # # # # # # # Port of Type checking # # # # # # # # # # # # # # # # # # # # # # # # # # # # Taken from ` PlutusCore . . Internal ` -- See the [Global uniqueness] and [Type rules] notes. | Check a ' Term ' against a ' NormalizedType ' . checkTypeM :: MonadTypeCheckPir err uni fun ann m => ann -> Term TyName Name uni fun ann -> Normalized (Type TyName uni ()) -> PirTCEnv uni fun m () [ ! - term : vTermTy ] vTermTy ~ vTy -- --------------------------------------------- -- [check| G !- term : vTy] checkTypeM ann term vTy = do vTermTy <- inferTypeM term when (vTermTy /= vTy) $ throwing _TypeError (TypeMismatch ann (void term) (unNormalized vTy) vTermTy) -- See the [Global uniqueness] and [Type rules] notes. -- | Synthesize the type of a term, returning a normalized type. inferTypeM :: forall err m uni fun ann. MonadTypeCheckPir err uni fun ann m => Term TyName Name uni fun ann -> PirTCEnv uni fun m (Normalized (Type TyName uni ())) -- c : vTy -- ------------------------- [ ! - con c : vTy ] inferTypeM (Constant _ (Some (ValueOf uni _))) = -- See Note [Normalization of built-in types]. normalizeTypeM $ PIR.mkTyBuiltinOf () uni [ - bi : vTy ] -- ------------------------------ [ ! - builtin bi : vTy ] inferTypeM (Builtin ann bn) = lookupBuiltinM ann bn [ v : ty ] ty ~ > vTy -- --------------------------------- [ v : vTy ] inferTypeM (Var ann name) = lookupVarM ann name [ check| G ! - dom : : * ] dom ~ > vDom [ , n : dom ! - body : ] -- ---------------------------------------------------------------------------- [ ! - lam n dom body : vDom - > vCod ] inferTypeM (LamAbs ann n dom body) = do checkKindM ann dom $ Type () vDom <- normalizeTypeM $ void dom TyFun () <<$>> pure vDom <<*>> withVar n vDom (inferTypeM body) [ , n : : nK ! - body : vBodyTy ] -- --------------------------------------------------- [ ! - abs n nK body : all ( n : : nK ) vBodyTy ] inferTypeM (TyAbs _ n nK body) = do let nK_ = void nK TyForall () n nK_ <<$>> withTyVar n nK_ (inferTypeM body) [ ! - fun : vDom - > vCod ] [ check| G ! - arg : ] -- ------------------------------------------------------------ [ ! - fun arg : ] inferTypeM (Apply ann fun arg) = do vFunTy <- inferTypeM fun case unNormalized vFunTy of TyFun _ vDom vCod -> do -- Subparts of a normalized type, so normalized. checkTypeM ann arg $ Normalized vDom pure $ Normalized vCod _ -> throwing _TypeError (TypeMismatch ann (void fun) (TyFun () dummyType dummyType) vFunTy) [ ! - body : all ( n : : nK ) ] [ check| G ! - ty : : tyK ] ty ~ > vTy -- ------------------------------------------------------------------------------- [ ! - body { ty } : NORM ( [ vTy / n ] vCod ) ] inferTypeM (TyInst ann body ty) = do vBodyTy <- inferTypeM body case unNormalized vBodyTy of TyForall _ n nK vCod -> do checkKindM ann ty nK vTy <- normalizeTypeM $ void ty substNormalizeTypeM vTy n vCod _ -> throwing _TypeError (TypeMismatch ann (void body) (TyForall () dummyTyName dummyKind dummyType) vBodyTy) [ ! - arg : : k ] [ check| G ! - pat : : ( k - > * ) - > k - > * ] pat ~ > vPat arg ~ > vArg [ check| G ! - term : NORM ( ( \(a : : k ) - > a ) vArg ) ] -- ----------------------------------------------------------------------------------------------- [ - iwrap pat arg term : ] inferTypeM (IWrap ann pat arg term) = do k <- inferKindM arg checkKindM ann pat $ toPatFuncKind k vPat <- normalizeTypeM $ void pat vArg <- normalizeTypeM $ void arg checkTypeM ann term =<< unfoldIFixOf vPat vArg k pure $ TyIFix () <$> vPat <*> vArg [ ! - term : ] [ infer| G ! - vArg : : k ] -- ----------------------------------------------------------------------- [ term : NORM ( ( \(a : : k ) - > a ) vArg ) ] inferTypeM (Unwrap ann term) = do vTermTy <- inferTypeM term case unNormalized vTermTy of TyIFix _ vPat vArg -> do k <- inferKindM $ ann <$ vArg -- Subparts of a normalized type, so normalized. unfoldIFixOf (Normalized vPat) (Normalized vArg) k _ -> throwing _TypeError (TypeMismatch ann (void term) (TyIFix () dummyType dummyType) vTermTy) -- [check| G !- ty :: *] ty ~> vTy -- ---------------------------------- [ ! - error ty : vTy ] inferTypeM (Error ann ty) = do checkKindM ann ty $ Type () normalizeTypeM $ void ty # # # # # # # # # # # # # # # # Port end # # # # # # # # # # # # # # # # -- Note on symbols: '=>' means implies checkKindFromBinding(G , b ) checkTypeFromBinding(G , b ) ! null(bs ) = > [ , withVarsOfBinding(b),withTyVarsOfBinding(b ) ! - ( let nonrec { bs } in inT ) : ty ] null(bs ) = > [ , withVarsOfBinding(b),withTyVarsOfBinding(b ) ! - inT : ty ] ty ~ > vTy ------------------------------------------------- [ ! - ( let nonrec { b ; bs } in inT ) : vTy ] checkKindFromBinding(G,b) checkTypeFromBinding(G,b) !null(bs) => [infer| G,withVarsOfBinding(b),withTyVarsOfBinding(b) !- (let nonrec {bs} in inT) : ty] null(bs) => [infer| G,withVarsOfBinding(b),withTyVarsOfBinding(b) !- inT : ty] ty ~> vTy ------------------------------------------------- [infer| G !- (let nonrec {b ; bs} in inT) : vTy] -} inferTypeM (Let ann r@NonRec bs inTerm) = do -- Check each binding individually, then if ok, introduce its new type/vars to the (linearly) next let or inTerm ty <- substTypeBinds bs =<< foldr checkBindingThenScope (inferTypeM inTerm) bs -- check the in-term's inferred type has kind * (except at toplevel) checkStarInferred ann ty pure ty where checkBindingThenScope :: Binding TyName Name uni fun ann -> PirTCEnv uni fun m a -> PirTCEnv uni fun m a checkBindingThenScope b acc = do -- check that the kinds of the declared types are correct checkKindFromBinding b -- check that the types of declared terms are correct checkTypeFromBinding r b -- add new *normalized* termvariables to env -- Note that the order of adding typesVSkinds here does not matter withTyVarsOfBinding b $ withVarsOfBinding r b acc G'=G , withTyVarsOfBindings(bs ) forall b in bs . checkKindFromBinding(G ' , b ) G''=G',withVarsOfBindings(bs ) forall b in bs . checkTypeFromBinding(G '' , b ) [ '' ! - inT : ty ] ty ~ > vTy ------------------------------------------------- [ ! - ( let rec bs in inT ) : vTy ] G'=G,withTyVarsOfBindings(bs) forall b in bs. checkKindFromBinding(G', b) G''=G',withVarsOfBindings(bs) forall b in bs. checkTypeFromBinding(G'', b) [infer| G'' !- inT : ty] ty ~> vTy ------------------------------------------------- [infer| G !- (let rec bs in inT) : vTy] -} inferTypeM (Let ann r@Rec bs inTerm) = do ty <- withTyVarsOfBindings bs $ do -- check that the kinds of the declared types *over all bindings* are correct Note that , compared to NonRec , we need the newtyvars in scope to do kindchecking for_ bs checkKindFromBinding ty <- withVarsOfBindings r bs $ do -- check that the types of declared terms are correct Note that , compared to NonRec , we need the newtyvars+newvars in scope to do typechecking for_ bs $ checkTypeFromBinding r inferTypeM inTerm substTypeBinds bs ty -- check the in-term's inferred type has kind * (except at toplevel) checkStarInferred ann ty pure ty | This checks that a newly - introduced type variable is correctly kinded . ( b is ty::K = rhs ) = > [ check| G ! - rhs : : K ] ( b is term ( X::T ) = > [ check| G ! - T : : * ] ) ( b is data ( X::K ) tyarg1::K1 ... tyargN::KN = _ ) = > [ check| G , X::K , tyarg1::K1 ... tyargN::KN ! - [ X tyarg1 ... tyargN ] : : * ] -------------------------------------------------------------------------------------- checkKindFromBinding(G , b ) (b is ty::K = rhs) => [check| G !- rhs :: K] (b is term (X::T) => [check| G !- T :: *]) (b is data (X::K) tyarg1::K1 ... tyargN::KN = _) => [check| G, X::K, tyarg1::K1...tyargN::KN !- [X tyarg1 ... tyargN] :: *] -------------------------------------------------------------------------------------- checkKindFromBinding(G,b) -} checkKindFromBinding :: forall err m uni fun ann. MonadKindCheck err (Term TyName Name uni fun ()) uni fun ann m => Binding TyName Name uni fun ann -> PirTCEnv uni fun m () checkKindFromBinding = \case For a type binding , correct means that the the RHS is indeed kinded by the declared kind . TypeBind _ (TyVarDecl ann _ k) rhs -> checkKindM ann rhs $ void k -- For a term binding, correct means that the declared type has kind *. TermBind _ _ (VarDecl _ _ ty) _ -> checkKindM (typeAnn ty) ty $ Type () -- For a datatype binding, correct means that the type constructor has kind * when fully-applied to its type arguments. DatatypeBind _ dt@(Datatype ann tycon tyargs _ vdecls) -> tycon+tyargs must be in scope during kindchecking withTyVarDecls (tycon:tyargs) $ do -- the fully-applied type-constructor must be *-kinded checkKindM ann appliedTyCon $ Type () -- the types of all the data-constructors must be *-kinded for_ (_varDeclType <$> vdecls) $ checkKindM ann `flip` Type () where appliedTyCon :: Type TyName uni ann = mkDatatypeValueType ann dt | This checks that a newly - introduced variable has declared the * right type * for its term ( rhs term in case of termbind or implicit constructor term in case of dataconstructor ) . ( b is t : ty = _ ) = > [ check| G ! - t : nTy ] ty ~ > vTy --------------------------------------------------- checkTypeFromBinding(G , b ) (rhs term in case of termbind or implicit constructor term in case of dataconstructor). (b is t:ty = _) => [check| G !- t : nTy] ty ~> vTy --------------------------------------------------- checkTypeFromBinding(G,b) -} checkTypeFromBinding :: forall err m uni fun ann. MonadTypeCheckPir err uni fun ann m => Recursivity -> Binding TyName Name uni fun ann -> PirTCEnv uni fun m () checkTypeFromBinding recurs = \case TypeBind{} -> pure () -- no types to check TermBind _ _ (VarDecl ann _ ty) rhs -> -- See Note [PIR vs Paper Escaping Types Difference] withNoEscapingTypes (checkTypeM ann rhs . fmap void =<< normalizeTypeM ty) DatatypeBind _ dt@(Datatype ann _ tyargs _ constrs) -> for_ (_varDeclType <$> constrs) $ \ ty -> checkConRes ty *> checkNonRecScope ty where appliedTyCon :: Type TyName uni ann = mkDatatypeValueType ann dt checkConRes :: Type TyName uni ann -> PirTCEnv uni fun m () checkConRes ty = -- We earlier checked that datacons' type is *-kinded (using checkKindBinding), but this is not enough: we must also check that its result type is EXACTLY ` [ [ ] ... tyargn ] ` ( ignoring annotations ) when (void (funResultType ty) /= void appliedTyCon) . throwing _TypeErrorExt $ MalformedDataConstrResType ann appliedTyCon -- if nonrec binding, make sure that type-constructor is not part of the data-constructor's argument types. checkNonRecScope :: Type TyName uni ann -> PirTCEnv uni fun m () checkNonRecScope ty = case recurs of Rec -> pure () NonRec -> -- now we make sure that dataconstructor is not self-recursive, i.e. funargs don't contain tycon withTyVarDecls tyargs $ -- tycon not in scope here OPTIMIZE : we use inferKind for scope - checking , but a simple ADT - traversal would suffice for_ (funTyArgs ty) inferKindM -- | Check that the in-Term's inferred type of a Let has kind *. -- Skip this check at the top-level, to allow top-level types to escape; see Note [PIR vs Paper Escaping Types Difference]. checkStarInferred :: MonadKindCheck err (Term TyName Name uni fun ()) uni fun ann m => ann -> Normalized (Type TyName uni ()) -> PirTCEnv uni fun m () checkStarInferred ann t = do allowEscape <- view $ tceTypeCheckConfig . pirConfigAllowEscape case allowEscape of NoEscape -> checkKindM ann (ann <$ unNormalized t) $ Type () NOTE : we completely skip the check in case of toplevel because we would need an * final , extended Gamma environment * to run the kind - check in , but we can not easily get that since we are using a Reader for environments and not State YesEscape -> pure () -- | Changes the flag in nested-lets so to disallow returning a type outside of the type's scope withNoEscapingTypes :: PirTCEnv uni fun m a -> PirTCEnv uni fun m a withNoEscapingTypes = local $ set (tceTypeCheckConfig.pirConfigAllowEscape) NoEscape | Run a ' ' computation by supplying a ' TypeCheckConfig ' to it . Differs from its PLC version in that is passes an extra env flag ' YesEscape ' . runTypeCheckM :: PirTCConfig uni fun -> PirTCEnv uni fun m a -> m a runTypeCheckM config a = runReaderT a $ TypeCheckEnv config mempty mempty -- Helpers ---------- -- | For a single binding, generate the newly-introduce term-variables' types, -- normalize them, rename them and add them into scope. -- Newly-declared term variables are: variables of termbinds, constructors, destructor -- Note: Assumes that the input is globally-unique and preserves global-uniqueness -- Note to self: actually passing here recursivity is unnecessary, but we do it for sake of compiler/datatype.hs api withVarsOfBinding :: forall uni fun cfg ann m a. MonadNormalizeType uni m => Recursivity -> Binding TyName Name uni fun ann -> TypeCheckT uni fun cfg m a -> TypeCheckT uni fun cfg m a withVarsOfBinding _ TypeBind{} k = k withVarsOfBinding _ (TermBind _ _ vdecl _) k = do vTy <- normalizeTypeM $ _varDeclType vdecl -- no need to rename here withVar (_varDeclName vdecl) (void <$> vTy) k withVarsOfBinding r (DatatypeBind _ dt) k = do -- generate all the definitions (_tyconstrDef, constrDefs, destrDef) <- compileDatatypeDefs r (original dt) -- ignore the generated rhs terms of constructors/destructor let structorDecls = PIR.defVar <$> destrDef:constrDefs foldr normRenameScope k structorDecls where -- normalize, then introduce the vardecl to scope normRenameScope :: VarDecl TyName Name uni (Provenance ann) -> TypeCheckT uni fun cfg m a -> TypeCheckT uni fun cfg m a normRenameScope v acc = do normRenamedTy <- normalizeTypeM $ _varDeclType v withVar (_varDeclName v) (void <$> normRenamedTy) acc withVarsOfBindings :: (MonadNormalizeType uni m, Foldable t) => Recursivity -> t (Binding TyName Name uni fun ann) -> TypeCheckT uni fun cfg m a -> TypeCheckT uni fun cfg m a withVarsOfBindings r bs k = foldr (withVarsOfBinding r) k bs -- | Scope a typechecking computation with the given binding's newly-introducing type (if there is one) withTyVarsOfBinding :: Binding TyName name uni fun ann -> TypeCheckT uni fun cfg m a -> TypeCheckT uni fun cfg m a withTyVarsOfBinding = \case TypeBind _ tvdecl _ -> withTyVarDecls [tvdecl] DatatypeBind _ (Datatype _ tvdecl _ _ _) -> withTyVarDecls [tvdecl] TermBind{} -> id -- no type to introduce -- | Extend the typecheck reader environment with the kinds of the newly-introduced type variables of a binding. withTyVarsOfBindings :: Foldable f => f (Binding TyName name uni fun ann) -> TypeCheckT uni fun cfg m a -> TypeCheckT uni fun cfg m a withTyVarsOfBindings = flip $ foldr withTyVarsOfBinding -- | Helper to add type variables into a computation's environment. withTyVarDecls :: [TyVarDecl TyName ann] -> TypeCheckT uni fun cfg m a -> TypeCheckT uni fun cfg m a withTyVarDecls = flip . foldr $ \(TyVarDecl _ n k) -> withTyVar n $ void k -- | Substitute `TypeBind`s from the given list of `Binding`s in the given `Type`. This is so that @let a = ( con integer ) in \(x : a ) - > typechecks . substTypeBinds :: MonadNormalizeType uni m => NonEmpty (Binding TyName Name uni fun ann) -> Normalized (Type TyName uni ()) -> PirTCEnv uni fun m (Normalized (Type TyName uni ())) substTypeBinds = flip . foldrM $ \b ty -> case b of TypeBind _ tvar rhs -> do rhs' <- normalizeTypeM (void rhs) -- See Note [Normalizing substitution] for why `substNormalizeTypeM` -- doesn't take a normalized type. substNormalizeTypeM rhs' (tvar ^. tyVarDeclName) (unNormalized ty) _ -> pure ty
null
https://raw.githubusercontent.com/input-output-hk/plutus/78402fb44148ce97a0a30efe406ba431fc49006c/plutus-core/plutus-ir/src/PlutusIR/TypeCheck/Internal.hs
haskell
editorconfig-checker-disable-file | The internal module of the type checker that defines the actual algorithms, but not the user-facing API. # LANGUAGE ConstraintKinds # # LANGUAGE OverloadedStrings # Using @transformers@ rather than @mtl@, because the former doesn't impose the 'Monad' constraint on 'local'. | a shorthand for our pir-specialized tc functions See the [Global uniqueness] and [Type rules] notes. --------------------------------------------- [check| G !- term : vTy] See the [Global uniqueness] and [Type rules] notes. | Synthesize the type of a term, returning a normalized type. c : vTy ------------------------- See Note [Normalization of built-in types]. ------------------------------ --------------------------------- ---------------------------------------------------------------------------- --------------------------------------------------- ------------------------------------------------------------ Subparts of a normalized type, so normalized. ------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------- ----------------------------------------------------------------------- Subparts of a normalized type, so normalized. [check| G !- ty :: *] ty ~> vTy ---------------------------------- Note on symbols: '=>' means implies ----------------------------------------------- ----------------------------------------------- Check each binding individually, then if ok, introduce its new type/vars to the (linearly) next let or inTerm check the in-term's inferred type has kind * (except at toplevel) check that the kinds of the declared types are correct check that the types of declared terms are correct add new *normalized* termvariables to env Note that the order of adding typesVSkinds here does not matter ----------------------------------------------- ----------------------------------------------- check that the kinds of the declared types *over all bindings* are correct check that the types of declared terms are correct check the in-term's inferred type has kind * (except at toplevel) ------------------------------------------------------------------------------------ ------------------------------------------------------------------------------------ For a term binding, correct means that the declared type has kind *. For a datatype binding, correct means that the type constructor has kind * when fully-applied to its type arguments. the fully-applied type-constructor must be *-kinded the types of all the data-constructors must be *-kinded ------------------------------------------------- ------------------------------------------------- no types to check See Note [PIR vs Paper Escaping Types Difference] We earlier checked that datacons' type is *-kinded (using checkKindBinding), but this is not enough: if nonrec binding, make sure that type-constructor is not part of the data-constructor's argument types. now we make sure that dataconstructor is not self-recursive, i.e. funargs don't contain tycon tycon not in scope here | Check that the in-Term's inferred type of a Let has kind *. Skip this check at the top-level, to allow top-level types to escape; see Note [PIR vs Paper Escaping Types Difference]. | Changes the flag in nested-lets so to disallow returning a type outside of the type's scope Helpers -------- | For a single binding, generate the newly-introduce term-variables' types, normalize them, rename them and add them into scope. Newly-declared term variables are: variables of termbinds, constructors, destructor Note: Assumes that the input is globally-unique and preserves global-uniqueness Note to self: actually passing here recursivity is unnecessary, but we do it for sake of compiler/datatype.hs api no need to rename here generate all the definitions ignore the generated rhs terms of constructors/destructor normalize, then introduce the vardecl to scope | Scope a typechecking computation with the given binding's newly-introducing type (if there is one) no type to introduce | Extend the typecheck reader environment with the kinds of the newly-introduced type variables of a binding. | Helper to add type variables into a computation's environment. | Substitute `TypeBind`s from the given list of `Binding`s in the given `Type`. See Note [Normalizing substitution] for why `substNormalizeTypeM` doesn't take a normalized type.
# LANGUAGE DerivingStrategies # # LANGUAGE LambdaCase # # LANGUAGE RankNTypes # module PlutusIR.TypeCheck.Internal ( BuiltinTypes (..) , TypeCheckConfig (..) , TypeCheckT , MonadKindCheck , MonadTypeCheck , MonadTypeCheckPir , tccBuiltinTypes , PirTCConfig (..) , AllowEscape (..) , inferTypeM , checkTypeM , runTypeCheckM ) where import PlutusPrelude import PlutusIR import PlutusIR.Compiler.Datatype import PlutusIR.Compiler.Provenance import PlutusIR.Compiler.Types import PlutusIR.Error import PlutusIR.MkPir qualified as PIR import PlutusIR.Transform.Rename () import PlutusCore (toPatFuncKind, tyVarDeclName, typeAnn) import PlutusCore.Error as PLC we mirror inferTypeM , checkTypeM of plc - tc and extend it for plutus - ir terms import PlutusCore.TypeCheck.Internal hiding (checkTypeM, inferTypeM, runTypeCheckM) import Control.Monad.Error.Lens import Control.Monad.Except import Control.Monad.Trans.Reader import Data.Foldable import Universe Note [ PLC Typechecker code reuse ] For PIR kind - checking , we reuse ` checkKindM ` , ` inferKindM ` directly from the PLC typechecker . For PIR type - checking , we port the ` checkTypeM ` and ` inferTypeM ` from PLC typechecker . The port is a direct copy , except for the modifications of ` Term ` to ` PIR.Term ` and error type signatures and ` throwError ` to accommodate for the new pir type - errors . These modifications are currently necessary since PIR.Term ADT /= PLC.Term ADT . We then extend this ported ` PIR.inferTypeM ` with cases for inferring type of LetRec and LetNonRec . See Note [ Notation ] of PlutusCore . . Internal for the notation of inference rules , which appear in the comments . For PIR kind-checking, we reuse `checkKindM`, `inferKindM` directly from the PLC typechecker. For PIR type-checking, we port the `checkTypeM` and `inferTypeM` from PLC typechecker. The port is a direct copy, except for the modifications of `Term` to `PIR.Term` and error type signatures and `throwError` to accommodate for the new pir type-errors. These modifications are currently necessary since PIR.Term ADT /= PLC.Term ADT. We then extend this ported `PIR.inferTypeM` with cases for inferring type of LetRec and LetNonRec. See Note [Notation] of PlutusCore.TypeCheck.Internal for the notation of inference rules, which appear in the comments. -} Note [ PIR vs Paper Syntax Difference ] Link to the paper : < -recursion/latest/download-by-type/doc-pdf/unraveling-recursion > FIR 's syntax requires that the data - constructor is annotated with a * list of its argument types * ( domain ) , instead of requiring a single valid type T ( usually in the form ` dataconstr : arg1 - > arg2 - > ... argn ` ) The codomain is also left out of the syntax and implied to be of the type ` [ TypeCons tyarg1 tyarg2 ... tyargn ] ` ( what would be expected for a non - GADT ) . Finally , the leading " forall type - parameters " are implicit ( since they are consider in scope ) . PIR 's syntax requires that a full ( valid ) type is written for the data - constructor , using the syntax for types ( the forall type - parameters remains implicit ) . This means that the codomain has to be be explicitly given in PIR . To make sure that the PIR - user has written down the expected non - GADT type we do an extra codomainCheck . This codomainCheck will have to be relaxed if / when PIR introduces GADTs . More importantly , since the type for the PIR data - constructor can be any syntax - valid type , the PIR user may have placed inside there a non - normalized type there . Currently , the PIR typechecker will assume the types of all data - constructors are prior normalized * before * type - checking , otherwise the PIR typechecking and PIR compilation will fail . See NOTE [ Normalization of data - constructors ' types ] at PlutusIR.Compiler . Datatype Link to the paper: <-recursion/latest/download-by-type/doc-pdf/unraveling-recursion> FIR's syntax requires that the data-constructor is annotated with a *list of its argument types* (domain), instead of requiring a single valid type T (usually in the form `dataconstr : arg1 -> arg2 ->... argn`) The codomain is also left out of the syntax and implied to be of the type `[TypeCons tyarg1 tyarg2 ... tyargn]` (what would be expected for a non-GADT). Finally, the leading "forall type-parameters" are implicit (since they are consider in scope). PIR's syntax requires that a full (valid) type is written for the data-constructor, using the syntax for types (the forall type-parameters remains implicit). This means that the codomain has to be be explicitly given in PIR. To make sure that the PIR-user has written down the expected non-GADT type we do an extra codomainCheck. This codomainCheck will have to be relaxed if/when PIR introduces GADTs. More importantly, since the type for the PIR data-constructor can be any syntax-valid type, the PIR user may have placed inside there a non-normalized type there. Currently, the PIR typechecker will assume the types of all data-constructors are prior normalized *before* type-checking, otherwise the PIR typechecking and PIR compilation will fail. See NOTE [Normalization of data-constructors' types] at PlutusIR.Compiler.Datatype -} Note [ PIR vs Paper Escaping Types Difference ] Link to the paper : < -recursion/latest/download-by-type/doc-pdf/unraveling-recursion > In FIR paper 's Fig.6 , T - Let and T - LetRec rules dictate that : Gamma ! - inTerm : : * for two reasons : 1 . check ( locally ) that the kind of the in - term 's inferred type is indeed * 2 . ensure that the inferred type does not escaping its scope ( hence Gamma ) This is in general true for the PIR implementation as well , except in the special case when a Type is inferred for the top - level expression ( ` program`-level ) . In contrast to ( 2 ) , we allow such a " top - level " type to escape its scope ; the reasoning is that PIR programs with toplevel escaping types would behave correctly when they are translated down to PLC . Even in the case where we let the type variables escape , ( 1 ) must still hold : the kind of the escaping type should still be star . Unfortunately , in order to check that we 'd have to use the variables which are no longer in scope . So we skip the rule ( Gamma ! - inTermTopLevel : : * ) in case of top - level inferred types . The implementation has a user - configurable flag to let the typechecker know if the current term under examination is at the program 's " top - level " position , and thus allow its type to escape . The flag is automatically set to no - type - escape when typechecking inside a let 's rhs term . Link to the paper: <-recursion/latest/download-by-type/doc-pdf/unraveling-recursion> In FIR paper's Fig.6, T-Let and T-LetRec rules dictate that: Gamma !- inTerm :: * for two reasons: 1. check (locally) that the kind of the in-term's inferred type is indeed * 2. ensure that the inferred type does not escaping its scope (hence Gamma) This is in general true for the PIR implementation as well, except in the special case when a Type is inferred for the top-level expression (`program`-level). In contrast to (2), we allow such a "top-level" type to escape its scope; the reasoning is that PIR programs with toplevel escaping types would behave correctly when they are translated down to PLC. Even in the case where we let the type variables escape, (1) must still hold: the kind of the escaping type should still be star. Unfortunately, in order to check that we'd have to use the variables which are no longer in scope. So we skip the rule (Gamma !- inTermTopLevel :: *) in case of top-level inferred types. The implementation has a user-configurable flag to let the typechecker know if the current term under examination is at the program's "top-level" position, and thus allow its type to escape. The flag is automatically set to no-type-escape when typechecking inside a let termbind's rhs term. -} type PirTCEnv uni fun m = TypeCheckT uni fun (PirTCConfig uni fun) m | The constraints that are required for type checking IR . type MonadTypeCheckPir err uni fun ann m = ( MonadTypeCheck err (Term TyName Name uni fun ()) uni fun ann m IR has additional type errors , see ' TypeErrorExt ' . ) # # # # # # # # # # # # # # # # # # # # # # # # # # # # # Port of Type checking # # # # # # # # # # # # # # # # # # # # # # # # # # # # Taken from ` PlutusCore . . Internal ` | Check a ' Term ' against a ' NormalizedType ' . checkTypeM :: MonadTypeCheckPir err uni fun ann m => ann -> Term TyName Name uni fun ann -> Normalized (Type TyName uni ()) -> PirTCEnv uni fun m () [ ! - term : vTermTy ] vTermTy ~ vTy checkTypeM ann term vTy = do vTermTy <- inferTypeM term when (vTermTy /= vTy) $ throwing _TypeError (TypeMismatch ann (void term) (unNormalized vTy) vTermTy) inferTypeM :: forall err m uni fun ann. MonadTypeCheckPir err uni fun ann m => Term TyName Name uni fun ann -> PirTCEnv uni fun m (Normalized (Type TyName uni ())) [ ! - con c : vTy ] inferTypeM (Constant _ (Some (ValueOf uni _))) = normalizeTypeM $ PIR.mkTyBuiltinOf () uni [ - bi : vTy ] [ ! - builtin bi : vTy ] inferTypeM (Builtin ann bn) = lookupBuiltinM ann bn [ v : ty ] ty ~ > vTy [ v : vTy ] inferTypeM (Var ann name) = lookupVarM ann name [ check| G ! - dom : : * ] dom ~ > vDom [ , n : dom ! - body : ] [ ! - lam n dom body : vDom - > vCod ] inferTypeM (LamAbs ann n dom body) = do checkKindM ann dom $ Type () vDom <- normalizeTypeM $ void dom TyFun () <<$>> pure vDom <<*>> withVar n vDom (inferTypeM body) [ , n : : nK ! - body : vBodyTy ] [ ! - abs n nK body : all ( n : : nK ) vBodyTy ] inferTypeM (TyAbs _ n nK body) = do let nK_ = void nK TyForall () n nK_ <<$>> withTyVar n nK_ (inferTypeM body) [ ! - fun : vDom - > vCod ] [ check| G ! - arg : ] [ ! - fun arg : ] inferTypeM (Apply ann fun arg) = do vFunTy <- inferTypeM fun case unNormalized vFunTy of TyFun _ vDom vCod -> do checkTypeM ann arg $ Normalized vDom pure $ Normalized vCod _ -> throwing _TypeError (TypeMismatch ann (void fun) (TyFun () dummyType dummyType) vFunTy) [ ! - body : all ( n : : nK ) ] [ check| G ! - ty : : tyK ] ty ~ > vTy [ ! - body { ty } : NORM ( [ vTy / n ] vCod ) ] inferTypeM (TyInst ann body ty) = do vBodyTy <- inferTypeM body case unNormalized vBodyTy of TyForall _ n nK vCod -> do checkKindM ann ty nK vTy <- normalizeTypeM $ void ty substNormalizeTypeM vTy n vCod _ -> throwing _TypeError (TypeMismatch ann (void body) (TyForall () dummyTyName dummyKind dummyType) vBodyTy) [ ! - arg : : k ] [ check| G ! - pat : : ( k - > * ) - > k - > * ] pat ~ > vPat arg ~ > vArg [ check| G ! - term : NORM ( ( \(a : : k ) - > a ) vArg ) ] [ - iwrap pat arg term : ] inferTypeM (IWrap ann pat arg term) = do k <- inferKindM arg checkKindM ann pat $ toPatFuncKind k vPat <- normalizeTypeM $ void pat vArg <- normalizeTypeM $ void arg checkTypeM ann term =<< unfoldIFixOf vPat vArg k pure $ TyIFix () <$> vPat <*> vArg [ ! - term : ] [ infer| G ! - vArg : : k ] [ term : NORM ( ( \(a : : k ) - > a ) vArg ) ] inferTypeM (Unwrap ann term) = do vTermTy <- inferTypeM term case unNormalized vTermTy of TyIFix _ vPat vArg -> do k <- inferKindM $ ann <$ vArg unfoldIFixOf (Normalized vPat) (Normalized vArg) k _ -> throwing _TypeError (TypeMismatch ann (void term) (TyIFix () dummyType dummyType) vTermTy) [ ! - error ty : vTy ] inferTypeM (Error ann ty) = do checkKindM ann ty $ Type () normalizeTypeM $ void ty # # # # # # # # # # # # # # # # Port end # # # # # # # # # # # # # # # # checkKindFromBinding(G , b ) checkTypeFromBinding(G , b ) ! null(bs ) = > [ , withVarsOfBinding(b),withTyVarsOfBinding(b ) ! - ( let nonrec { bs } in inT ) : ty ] null(bs ) = > [ , withVarsOfBinding(b),withTyVarsOfBinding(b ) ! - inT : ty ] ty ~ > vTy [ ! - ( let nonrec { b ; bs } in inT ) : vTy ] checkKindFromBinding(G,b) checkTypeFromBinding(G,b) !null(bs) => [infer| G,withVarsOfBinding(b),withTyVarsOfBinding(b) !- (let nonrec {bs} in inT) : ty] null(bs) => [infer| G,withVarsOfBinding(b),withTyVarsOfBinding(b) !- inT : ty] ty ~> vTy [infer| G !- (let nonrec {b ; bs} in inT) : vTy] -} inferTypeM (Let ann r@NonRec bs inTerm) = do ty <- substTypeBinds bs =<< foldr checkBindingThenScope (inferTypeM inTerm) bs checkStarInferred ann ty pure ty where checkBindingThenScope :: Binding TyName Name uni fun ann -> PirTCEnv uni fun m a -> PirTCEnv uni fun m a checkBindingThenScope b acc = do checkKindFromBinding b checkTypeFromBinding r b withTyVarsOfBinding b $ withVarsOfBinding r b acc G'=G , withTyVarsOfBindings(bs ) forall b in bs . checkKindFromBinding(G ' , b ) G''=G',withVarsOfBindings(bs ) forall b in bs . checkTypeFromBinding(G '' , b ) [ '' ! - inT : ty ] ty ~ > vTy [ ! - ( let rec bs in inT ) : vTy ] G'=G,withTyVarsOfBindings(bs) forall b in bs. checkKindFromBinding(G', b) G''=G',withVarsOfBindings(bs) forall b in bs. checkTypeFromBinding(G'', b) [infer| G'' !- inT : ty] ty ~> vTy [infer| G !- (let rec bs in inT) : vTy] -} inferTypeM (Let ann r@Rec bs inTerm) = do ty <- withTyVarsOfBindings bs $ do Note that , compared to NonRec , we need the newtyvars in scope to do kindchecking for_ bs checkKindFromBinding ty <- withVarsOfBindings r bs $ do Note that , compared to NonRec , we need the newtyvars+newvars in scope to do typechecking for_ bs $ checkTypeFromBinding r inferTypeM inTerm substTypeBinds bs ty checkStarInferred ann ty pure ty | This checks that a newly - introduced type variable is correctly kinded . ( b is ty::K = rhs ) = > [ check| G ! - rhs : : K ] ( b is term ( X::T ) = > [ check| G ! - T : : * ] ) ( b is data ( X::K ) tyarg1::K1 ... tyargN::KN = _ ) = > [ check| G , X::K , tyarg1::K1 ... tyargN::KN ! - [ X tyarg1 ... tyargN ] : : * ] checkKindFromBinding(G , b ) (b is ty::K = rhs) => [check| G !- rhs :: K] (b is term (X::T) => [check| G !- T :: *]) (b is data (X::K) tyarg1::K1 ... tyargN::KN = _) => [check| G, X::K, tyarg1::K1...tyargN::KN !- [X tyarg1 ... tyargN] :: *] checkKindFromBinding(G,b) -} checkKindFromBinding :: forall err m uni fun ann. MonadKindCheck err (Term TyName Name uni fun ()) uni fun ann m => Binding TyName Name uni fun ann -> PirTCEnv uni fun m () checkKindFromBinding = \case For a type binding , correct means that the the RHS is indeed kinded by the declared kind . TypeBind _ (TyVarDecl ann _ k) rhs -> checkKindM ann rhs $ void k TermBind _ _ (VarDecl _ _ ty) _ -> checkKindM (typeAnn ty) ty $ Type () DatatypeBind _ dt@(Datatype ann tycon tyargs _ vdecls) -> tycon+tyargs must be in scope during kindchecking withTyVarDecls (tycon:tyargs) $ do checkKindM ann appliedTyCon $ Type () for_ (_varDeclType <$> vdecls) $ checkKindM ann `flip` Type () where appliedTyCon :: Type TyName uni ann = mkDatatypeValueType ann dt | This checks that a newly - introduced variable has declared the * right type * for its term ( rhs term in case of termbind or implicit constructor term in case of dataconstructor ) . ( b is t : ty = _ ) = > [ check| G ! - t : nTy ] ty ~ > vTy checkTypeFromBinding(G , b ) (rhs term in case of termbind or implicit constructor term in case of dataconstructor). (b is t:ty = _) => [check| G !- t : nTy] ty ~> vTy checkTypeFromBinding(G,b) -} checkTypeFromBinding :: forall err m uni fun ann. MonadTypeCheckPir err uni fun ann m => Recursivity -> Binding TyName Name uni fun ann -> PirTCEnv uni fun m () checkTypeFromBinding recurs = \case TermBind _ _ (VarDecl ann _ ty) rhs -> withNoEscapingTypes (checkTypeM ann rhs . fmap void =<< normalizeTypeM ty) DatatypeBind _ dt@(Datatype ann _ tyargs _ constrs) -> for_ (_varDeclType <$> constrs) $ \ ty -> checkConRes ty *> checkNonRecScope ty where appliedTyCon :: Type TyName uni ann = mkDatatypeValueType ann dt checkConRes :: Type TyName uni ann -> PirTCEnv uni fun m () checkConRes ty = we must also check that its result type is EXACTLY ` [ [ ] ... tyargn ] ` ( ignoring annotations ) when (void (funResultType ty) /= void appliedTyCon) . throwing _TypeErrorExt $ MalformedDataConstrResType ann appliedTyCon checkNonRecScope :: Type TyName uni ann -> PirTCEnv uni fun m () checkNonRecScope ty = case recurs of Rec -> pure () NonRec -> OPTIMIZE : we use inferKind for scope - checking , but a simple ADT - traversal would suffice for_ (funTyArgs ty) inferKindM checkStarInferred :: MonadKindCheck err (Term TyName Name uni fun ()) uni fun ann m => ann -> Normalized (Type TyName uni ()) -> PirTCEnv uni fun m () checkStarInferred ann t = do allowEscape <- view $ tceTypeCheckConfig . pirConfigAllowEscape case allowEscape of NoEscape -> checkKindM ann (ann <$ unNormalized t) $ Type () NOTE : we completely skip the check in case of toplevel because we would need an * final , extended Gamma environment * to run the kind - check in , but we can not easily get that since we are using a Reader for environments and not State YesEscape -> pure () withNoEscapingTypes :: PirTCEnv uni fun m a -> PirTCEnv uni fun m a withNoEscapingTypes = local $ set (tceTypeCheckConfig.pirConfigAllowEscape) NoEscape | Run a ' ' computation by supplying a ' TypeCheckConfig ' to it . Differs from its PLC version in that is passes an extra env flag ' YesEscape ' . runTypeCheckM :: PirTCConfig uni fun -> PirTCEnv uni fun m a -> m a runTypeCheckM config a = runReaderT a $ TypeCheckEnv config mempty mempty withVarsOfBinding :: forall uni fun cfg ann m a. MonadNormalizeType uni m => Recursivity -> Binding TyName Name uni fun ann -> TypeCheckT uni fun cfg m a -> TypeCheckT uni fun cfg m a withVarsOfBinding _ TypeBind{} k = k withVarsOfBinding _ (TermBind _ _ vdecl _) k = do vTy <- normalizeTypeM $ _varDeclType vdecl withVar (_varDeclName vdecl) (void <$> vTy) k withVarsOfBinding r (DatatypeBind _ dt) k = do (_tyconstrDef, constrDefs, destrDef) <- compileDatatypeDefs r (original dt) let structorDecls = PIR.defVar <$> destrDef:constrDefs foldr normRenameScope k structorDecls where normRenameScope :: VarDecl TyName Name uni (Provenance ann) -> TypeCheckT uni fun cfg m a -> TypeCheckT uni fun cfg m a normRenameScope v acc = do normRenamedTy <- normalizeTypeM $ _varDeclType v withVar (_varDeclName v) (void <$> normRenamedTy) acc withVarsOfBindings :: (MonadNormalizeType uni m, Foldable t) => Recursivity -> t (Binding TyName Name uni fun ann) -> TypeCheckT uni fun cfg m a -> TypeCheckT uni fun cfg m a withVarsOfBindings r bs k = foldr (withVarsOfBinding r) k bs withTyVarsOfBinding :: Binding TyName name uni fun ann -> TypeCheckT uni fun cfg m a -> TypeCheckT uni fun cfg m a withTyVarsOfBinding = \case TypeBind _ tvdecl _ -> withTyVarDecls [tvdecl] DatatypeBind _ (Datatype _ tvdecl _ _ _) -> withTyVarDecls [tvdecl] withTyVarsOfBindings :: Foldable f => f (Binding TyName name uni fun ann) -> TypeCheckT uni fun cfg m a -> TypeCheckT uni fun cfg m a withTyVarsOfBindings = flip $ foldr withTyVarsOfBinding withTyVarDecls :: [TyVarDecl TyName ann] -> TypeCheckT uni fun cfg m a -> TypeCheckT uni fun cfg m a withTyVarDecls = flip . foldr $ \(TyVarDecl _ n k) -> withTyVar n $ void k This is so that @let a = ( con integer ) in \(x : a ) - > typechecks . substTypeBinds :: MonadNormalizeType uni m => NonEmpty (Binding TyName Name uni fun ann) -> Normalized (Type TyName uni ()) -> PirTCEnv uni fun m (Normalized (Type TyName uni ())) substTypeBinds = flip . foldrM $ \b ty -> case b of TypeBind _ tvar rhs -> do rhs' <- normalizeTypeM (void rhs) substNormalizeTypeM rhs' (tvar ^. tyVarDeclName) (unNormalized ty) _ -> pure ty
c572f88a3bcaf05b87d8893d248761e76238cee7f44f135a1d324b3fac789af9
michaelballantyne/ee-lib
flip-intro-scope.rkt
#lang racket/base (provide flip-intro-scope) (require racket/private/check) (define (make-intro-scope-introducer) (define no-scope (datum->syntax #f 'foo)) (define intro-scope (syntax-local-identifier-as-binding (syntax-local-introduce no-scope))) (make-syntax-delta-introducer intro-scope no-scope)) (define/who (flip-intro-scope stx) (check who syntax? stx) ((make-intro-scope-introducer) stx 'flip))
null
https://raw.githubusercontent.com/michaelballantyne/ee-lib/30546646afc6c135f30e187d43b6cf943ece52d6/private/flip-intro-scope.rkt
racket
#lang racket/base (provide flip-intro-scope) (require racket/private/check) (define (make-intro-scope-introducer) (define no-scope (datum->syntax #f 'foo)) (define intro-scope (syntax-local-identifier-as-binding (syntax-local-introduce no-scope))) (make-syntax-delta-introducer intro-scope no-scope)) (define/who (flip-intro-scope stx) (check who syntax? stx) ((make-intro-scope-introducer) stx 'flip))
27c087b13f72062b4f61ad2bf3d0dfc7a2c3728e1d4bfd7fe128e7a0c0ef8dcb
rm-hull/big-bang
level_builder.cljs
(ns big-bang.examples.pacman.level-builder (:require [cljs.core.async :refer [chan <! map<] :as async] [clojure.string :refer [split-lines]] [dataview.ops :refer [create-reader]] [big-bang.examples.pacman.config :as config] [big-bang.examples.pacman.util :refer [posn into-channel]]) (:require-macros [cljs.core.async.macros :refer [go]])) (def pieces { "\u250F" (posn 4 4 config/cell-size) ; ┏ "\u2501" (posn 0 4 config/cell-size) ; ━ ┓ "\u2517" (posn 2 4 config/cell-size) ; ┗ "\u251B" (posn 3 4 config/cell-size) ; ┛ "\u2503" (posn 1 4 config/cell-size) ; ┃ ; TODO below bits to be removed - pills to draw separately "." (assoc (posn 16 0 (/ config/cell-size 2)) :target-offset (/ config/cell-size 4)) "O" (assoc (posn 20 0 (/ config/cell-size 2)) :target-offset (/ config/cell-size 4))}) (defn- make-directive "Takes target co-ordinates and a map-piece character. The layout directive for the map-piece is looked up and combined with the co-ords. The return value is a vector suitable for applying directly to ctx.drawImage" [[dx dy] map-piece] (let [{:keys [x y w h target-offset]} (pieces map-piece)] [x y w h (+ dx target-offset) (+ dy target-offset) w h])) (defn- convert-level "Converts a stream of unicode characters representing a level into a data structure indicating where the cell is to be drawn on a target canvas, and the source that will be drawn." [raw-level-data] (let [canvas-coords (for [y (range 0 config/height) x (range 0 config/width)] (map (partial * config/cell-size) [x y]))] (map make-directive canvas-coords (seq raw-level-data)))) (defn- make-ctx "Creates a CanvasRenderingContext2D with the given width and height." [[width height]] (let [canvas (.createElement js/document "canvas")] (set! (.-width canvas) width) (set! (.-height canvas) height) (.getContext canvas "2d"))) (defn- draw-cells "Draws cells from the sprite-map onto the given context according to the layout directives in the level. The context is returned (for threading)." [ctx level sprite-map] (loop [level level] (if (empty? level) ctx (when-let [[sx sy sw sh dx dy dw dh] (first level)] (.drawImage ctx sprite-map sx sy sw sh dx dy dw dh) (recur (rest level)))))) (defn- create-background-image [level-chan sprite-chan] (async/map (partial draw-cells (make-ctx config/background-size)) [level-chan sprite-chan])) (def get-background (memoize (fn [n] (let [c (chan)] (go (into-channel c (repeat (<! (create-background-image (async/take 1 (async/map< convert-level (config/level n))) (async/take 1 config/sprites)))))) c))))
null
https://raw.githubusercontent.com/rm-hull/big-bang/2825e7f0bb7615e1158a72d58f426bc1e33bd9ef/examples/pacman/src/level_builder.cljs
clojure
┏ ━ ┗ ┛ ┃ TODO below bits to be removed - pills to draw separately
(ns big-bang.examples.pacman.level-builder (:require [cljs.core.async :refer [chan <! map<] :as async] [clojure.string :refer [split-lines]] [dataview.ops :refer [create-reader]] [big-bang.examples.pacman.config :as config] [big-bang.examples.pacman.util :refer [posn into-channel]]) (:require-macros [cljs.core.async.macros :refer [go]])) (def pieces ┓ "." (assoc (posn 16 0 (/ config/cell-size 2)) :target-offset (/ config/cell-size 4)) "O" (assoc (posn 20 0 (/ config/cell-size 2)) :target-offset (/ config/cell-size 4))}) (defn- make-directive "Takes target co-ordinates and a map-piece character. The layout directive for the map-piece is looked up and combined with the co-ords. The return value is a vector suitable for applying directly to ctx.drawImage" [[dx dy] map-piece] (let [{:keys [x y w h target-offset]} (pieces map-piece)] [x y w h (+ dx target-offset) (+ dy target-offset) w h])) (defn- convert-level "Converts a stream of unicode characters representing a level into a data structure indicating where the cell is to be drawn on a target canvas, and the source that will be drawn." [raw-level-data] (let [canvas-coords (for [y (range 0 config/height) x (range 0 config/width)] (map (partial * config/cell-size) [x y]))] (map make-directive canvas-coords (seq raw-level-data)))) (defn- make-ctx "Creates a CanvasRenderingContext2D with the given width and height." [[width height]] (let [canvas (.createElement js/document "canvas")] (set! (.-width canvas) width) (set! (.-height canvas) height) (.getContext canvas "2d"))) (defn- draw-cells "Draws cells from the sprite-map onto the given context according to the layout directives in the level. The context is returned (for threading)." [ctx level sprite-map] (loop [level level] (if (empty? level) ctx (when-let [[sx sy sw sh dx dy dw dh] (first level)] (.drawImage ctx sprite-map sx sy sw sh dx dy dw dh) (recur (rest level)))))) (defn- create-background-image [level-chan sprite-chan] (async/map (partial draw-cells (make-ctx config/background-size)) [level-chan sprite-chan])) (def get-background (memoize (fn [n] (let [c (chan)] (go (into-channel c (repeat (<! (create-background-image (async/take 1 (async/map< convert-level (config/level n))) (async/take 1 config/sprites)))))) c))))
795074be2034f225af4adf522bf2717d0eb4453ad9e7a534a8d9727df9ba357f
tiancaiamao/yasfs
interpret.scm
(define (atom? o) (not (pair? o))) (define (evaluate e env cont) (if (atom? e) (if (symbol? e) (evaluate-variable e env cont) (cont e)) (case (car e) ((define) (evaluate-define (cadr e) (caddr e) env cont)) ((quote) (evaluate-quote (cadr e) env cont)) ((if) (evaluate-if (cadr e) (caddr e) (cadddr e) env cont)) ((begin) (evaluate-begin (cdr e) env cont)) ((set!) (evaluate-set! (cadr e) (caddr e) env cont)) ((lambda) (evaluate-lambda (cadr e) (cddr e) env cont)) (else (evaluate-application (car e) (cdr e) env cont))))) (define (evaluate-variable name env cont) (cont (let ((find (lookup-env-cell env name))) (if find (cdr find) (error "unbound variable in environment"))))) (define (evaluate-quote e env cont) (cont e)) (define (lookup-env-cell env name) (if (pair? env) (let ((parent (car env)) (binding (cdr env))) (or (assv name binding) (lookup-env-cell parent name))) #f)) (define (evaluate-if test et ef env cont) (evaluate test env (lambda (v) (evaluate (if v et ef) env cont)))) (define (evaluate-begin e* env cont) (if (pair? (cdr e*)) (evaluate (car e*) env (lambda (ignore) (evaluate-begin (cdr e*) env cont))) (evaluate (car e*) env cont))) (define (evaluate-set! name value env cont) (evaluate value env (lambda (v) (let ((env-cell (lookup-env-cell env name))) (if env-cell (cont (set-cdr! env-cell v)) (error "can't set unbound variable")))))) (define (evaluate-define name value env cont) (evaluate value env (lambda (v) (if (pair? env) (let* ((binding (cdr env)) (find (assv name binding))) (if find (cont (set-cdr! find value)) (cont (set-cdr! env (cons (cons name value) binding))))) (error "can't in null-env"))))) (define (extend-env n* v* env) (let ((binding (map cons n* v*))) (cons env binding))) (define (evaluate-lambda n* e* env cont) (cont (lambda (v* runtime-cont) (let ((new-env (extend-env n* v* env))) (runtime-cont (evaluate-begin e* new-env runtime-cont)))))) (define (evaluate-application f e* env cont) (define (evaluate-argument e* env cont) (if (pair? e*) (evaluate (car e*) env (lambda (v) (evaluate-argument (cdr e*) env (lambda (v*) (cont (cons v v*)) ) ) ) ) (cont '()) ) ) (evaluate-argument e* env (lambda (v*) (f v* cont)))) (define global-env (cons '() '())) (define toplevel-cont (lambda (v) v)) (define-syntax define-primitive (syntax-rules () ((_ name primitive arity) (evaluate-define 'name (lambda (v* cont) (if (= arity (length v*)) (cont (apply primitive v*)) (error "incorrect arity"))) global-env toplevel-cont)))) (define-primitive cons cons 2) (define-primitive + + 2) (define (interpret) (write (evaluate (read) global-env toplevel-cont)) (interpret))
null
https://raw.githubusercontent.com/tiancaiamao/yasfs/c138b7bf9a16ee70b90e5d18bdd45c60cd8e2f44/interpret.scm
scheme
(define (atom? o) (not (pair? o))) (define (evaluate e env cont) (if (atom? e) (if (symbol? e) (evaluate-variable e env cont) (cont e)) (case (car e) ((define) (evaluate-define (cadr e) (caddr e) env cont)) ((quote) (evaluate-quote (cadr e) env cont)) ((if) (evaluate-if (cadr e) (caddr e) (cadddr e) env cont)) ((begin) (evaluate-begin (cdr e) env cont)) ((set!) (evaluate-set! (cadr e) (caddr e) env cont)) ((lambda) (evaluate-lambda (cadr e) (cddr e) env cont)) (else (evaluate-application (car e) (cdr e) env cont))))) (define (evaluate-variable name env cont) (cont (let ((find (lookup-env-cell env name))) (if find (cdr find) (error "unbound variable in environment"))))) (define (evaluate-quote e env cont) (cont e)) (define (lookup-env-cell env name) (if (pair? env) (let ((parent (car env)) (binding (cdr env))) (or (assv name binding) (lookup-env-cell parent name))) #f)) (define (evaluate-if test et ef env cont) (evaluate test env (lambda (v) (evaluate (if v et ef) env cont)))) (define (evaluate-begin e* env cont) (if (pair? (cdr e*)) (evaluate (car e*) env (lambda (ignore) (evaluate-begin (cdr e*) env cont))) (evaluate (car e*) env cont))) (define (evaluate-set! name value env cont) (evaluate value env (lambda (v) (let ((env-cell (lookup-env-cell env name))) (if env-cell (cont (set-cdr! env-cell v)) (error "can't set unbound variable")))))) (define (evaluate-define name value env cont) (evaluate value env (lambda (v) (if (pair? env) (let* ((binding (cdr env)) (find (assv name binding))) (if find (cont (set-cdr! find value)) (cont (set-cdr! env (cons (cons name value) binding))))) (error "can't in null-env"))))) (define (extend-env n* v* env) (let ((binding (map cons n* v*))) (cons env binding))) (define (evaluate-lambda n* e* env cont) (cont (lambda (v* runtime-cont) (let ((new-env (extend-env n* v* env))) (runtime-cont (evaluate-begin e* new-env runtime-cont)))))) (define (evaluate-application f e* env cont) (define (evaluate-argument e* env cont) (if (pair? e*) (evaluate (car e*) env (lambda (v) (evaluate-argument (cdr e*) env (lambda (v*) (cont (cons v v*)) ) ) ) ) (cont '()) ) ) (evaluate-argument e* env (lambda (v*) (f v* cont)))) (define global-env (cons '() '())) (define toplevel-cont (lambda (v) v)) (define-syntax define-primitive (syntax-rules () ((_ name primitive arity) (evaluate-define 'name (lambda (v* cont) (if (= arity (length v*)) (cont (apply primitive v*)) (error "incorrect arity"))) global-env toplevel-cont)))) (define-primitive cons cons 2) (define-primitive + + 2) (define (interpret) (write (evaluate (read) global-env toplevel-cont)) (interpret))
d838e1e837a9b111cc74ce55b4aa48ac57a3be595d4f37ce4ce89f3275b696e4
cardmagic/lucash
waitcodes.scm
Scsh routines for analysing exit codes returned by WAIT . Copyright ( c ) 1994 by . See file COPYING . ;;; ;;; To port these to a new OS, consult /usr/include/sys/wait.h, and check the WIFEXITED , WEXITSTATUS , WIFSTOPPED , WSTOPSIG , ;;; WIFSIGNALED, and WTERMSIG macros for the magic fields they use. These definitions are for NeXTSTEP . ;;; ;;; I could have done a portable version by making C calls for this, ;;; but it's such overkill. ;;; If process terminated normally, return the exit code, otw #f. (define (status:exit-val status) (and (zero? (bitwise-and #xFF status)) (bitwise-and #xFF (arithmetic-shift status -8)))) ;;; If the process was suspended, return the suspending signal, otw #f. (define (status:stop-sig status) (and (not (zero? (bitwise-and status #x40))) (bitwise-and #x7F (arithmetic-shift status -8)))) ;;; If the process terminated abnormally, ;;; return the terminating signal, otw #f. (define (status:term-sig status) (and (not (zero? (bitwise-and status #xFF))) ; Didn't exit. (zero? (bitwise-and status #x40)) ; Not suspended. (bitwise-and status #x7F))) ;;; Flags. (define wait/poll #o100) ; Don't hang if nothing to wait for. Report on suspended , too .
null
https://raw.githubusercontent.com/cardmagic/lucash/0452d410430d12140c14948f7f583624f819cdad/reference/scsh-0.6.6/scsh/solaris/waitcodes.scm
scheme
To port these to a new OS, consult /usr/include/sys/wait.h, WIFSIGNALED, and WTERMSIG macros for the magic fields they use. I could have done a portable version by making C calls for this, but it's such overkill. If process terminated normally, return the exit code, otw #f. If the process was suspended, return the suspending signal, otw #f. If the process terminated abnormally, return the terminating signal, otw #f. Didn't exit. Not suspended. Flags. Don't hang if nothing to wait for.
Scsh routines for analysing exit codes returned by WAIT . Copyright ( c ) 1994 by . See file COPYING . and check the WIFEXITED , WEXITSTATUS , WIFSTOPPED , WSTOPSIG , These definitions are for NeXTSTEP . (define (status:exit-val status) (and (zero? (bitwise-and #xFF status)) (bitwise-and #xFF (arithmetic-shift status -8)))) (define (status:stop-sig status) (and (not (zero? (bitwise-and status #x40))) (bitwise-and #x7F (arithmetic-shift status -8)))) (define (status:term-sig status) (bitwise-and status #x7F))) Report on suspended , too .
bc2e98a86361e598a5ca4cbeebcdc28e5e2d1eb43c106fd60fd391ffbdd2ffb7
mfoemmel/erlang-otp
percept_analyzer.erl
%% %% %CopyrightBegin% %% Copyright Ericsson AB 2007 - 2009 . All Rights Reserved . %% The contents of this file are subject to the Erlang Public License , Version 1.1 , ( the " License " ) ; you may not use this file except in %% compliance with the License. You should have received a copy of the %% Erlang Public License along with this software. If not, it can be %% retrieved online 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. %% %% %CopyrightEnd% %% @doc Utility functions to operate on percept data. These functions should %% be considered experimental. Behaviour may change in future releases. -module(percept_analyzer). -export([ minmax/1, waiting_activities/1, activities2count/2, activities2count/3, activities2count2/2, analyze_activities/2, runnable_count/1, runnable_count/2, seconds2ts/2, minmax_activities/2, mean/1 ]). -include("percept.hrl"). %%========================================================================== %% Interface functions %% %%========================================================================== , Y } ] ) - > { MinX , MinY , MaxX , MaxY } %% X = number() %% Y = number() %% MinX = number() %% MinY = number() %% MaxX = number() %% MaxY = number() @doc Returns the min and of a set of 2 - dimensional numbers . minmax(Data) -> Xs = [ X || {X,_Y} <- Data], Ys = [ Y || {_X, Y} <- Data], {lists:min(Xs), lists:min(Ys), lists:max(Xs), lists:max(Ys)}. ( ) ] ) - > { Mean , , N } %% Mean = float() %% StdDev = float() %% N = integer() %% @doc Calculates the mean and the standard deviation of a set of %% numbers. mean([]) -> {0, 0, 0}; mean([Value]) -> {Value, 0, 1}; mean(List) -> mean(List, {0, 0, 0}). mean([], {Sum, SumSquare, N}) -> Mean = Sum / N, StdDev = math:sqrt((SumSquare - Sum*Sum/N)/(N - 1)), {Mean, StdDev, N}; mean([Value | List], {Sum, SumSquare, N}) -> mean(List, {Sum + Value, SumSquare + Value*Value, N + 1}). activities2count2(Acts, StartTs) -> Start = inactive_start_states(Acts), activities2count2(Acts, StartTs, Start, []). activities2count2([], _, _, Out) -> lists:reverse(Out); activities2count2([#activity{ id = Id, timestamp = Ts, state = active} | Acts], StartTs, {Proc,Port}, Out) when is_pid(Id) -> activities2count2(Acts, StartTs, {Proc + 1, Port}, [{?seconds(Ts, StartTs), Proc + 1, Port}|Out]); activities2count2([#activity{ id = Id, timestamp = Ts, state = inactive} | Acts], StartTs, {Proc,Port}, Out) when is_pid(Id) -> activities2count2(Acts, StartTs, {Proc - 1, Port}, [{?seconds(Ts, StartTs), Proc - 1, Port}|Out]); activities2count2([#activity{ id = Id, timestamp = Ts, state = active} | Acts], StartTs, {Proc,Port}, Out) when is_port(Id) -> activities2count2(Acts, StartTs, {Proc, Port + 1}, [{?seconds(Ts, StartTs), Proc, Port + 1}|Out]); activities2count2([#activity{ id = Id, timestamp = Ts, state = inactive} | Acts], StartTs, {Proc,Port}, Out) when is_port(Id) -> activities2count2(Acts, StartTs, {Proc, Port - 1}, [{?seconds(Ts, StartTs), Proc, Port - 1}|Out]). inactive_start_states(Acts) -> D = activity_start_states(Acts, dict:new()), dict:fold(fun (K, inactive, {Procs, Ports}) when is_pid(K) -> {Procs + 1, Ports}; (K, inactive, {Procs, Ports}) when is_port(K) -> {Procs, Ports + 1}; (_, _, {Procs, Ports}) -> {Procs, Ports} end, {0,0}, D). activity_start_states([], D) -> D; activity_start_states([#activity{id = Id, state = State}|Acts], D) -> case dict:is_key(Id, D) of true -> activity_start_states(Acts, D); false -> activity_start_states(Acts, dict:store(Id, State, D)) end. @spec activities2count(#activity { } , timestamp ( ) ) - > Result Result = [ { Time , ProcessCount , PortCount } ] %% Time = float() ProcessCount = integer ( ) PortCount = integer ( ) %% @doc Calculate the resulting active processes and ports during %% the activity interval. %% Also checks active/inactive consistency. %% A task will always begin with an active state and end with an inactive state. activities2count(Acts, StartTs) when is_list(Acts) -> activities2count(Acts, StartTs, separated). activities2count(Acts, StartTs, Type) when is_list(Acts) -> activities2count_loop(Acts, {StartTs, {0,0}}, Type, []). activities2count_loop([], _, _, Out) -> lists:reverse(Out); activities2count_loop( [#activity{ timestamp = Ts, id = Id, runnable_count = Rc} | Acts], {StartTs, {Procs, Ports}}, separated, Out) -> Time = ?seconds(Ts, StartTs), case Id of Id when is_port(Id) -> Entry = {Time, Procs, Rc}, activities2count_loop(Acts, {StartTs, {Procs, Rc}}, separated, [Entry | Out]); Id when is_pid(Id) -> Entry = {Time, Rc, Ports}, activities2count_loop(Acts, {StartTs, {Rc, Ports}}, separated, [Entry | Out]); _ -> activities2count_loop(Acts, {StartTs,{Procs, Ports}}, separated, Out) end; activities2count_loop( [#activity{ timestamp = Ts, id = Id, runnable_count = Rc} | Acts], {StartTs, {Procs, Ports}}, summated, Out) -> Time = ?seconds(Ts, StartTs), case Id of Id when is_port(Id) -> Entry = {Time, Procs + Rc}, activities2count_loop(Acts, {StartTs, {Procs, Rc}}, summated, [Entry | Out]); Id when is_pid(Id) -> Entry = {Time, Rc + Ports}, activities2count_loop(Acts, {StartTs, {Rc, Ports}}, summated, [Entry | Out]) end. @spec waiting_activities([#activity { } ] ) - > FunctionList FunctionList = [ { Seconds , Mfa , { Mean , , N } } ] %% Seconds = float() Mfa = ( ) %% Mean = float() %% StdDev = float() %% N = integer() %% @doc Calculates the time, both average and total, that a process has spent %% in a receive state at specific function. However, if there are multiple receives %% in a function it cannot differentiate between them. waiting_activities(Activities) -> ListedMfas = waiting_activities_mfa_list(Activities, []), Unsorted = lists:foldl( fun (Mfa, MfaList) -> {Total, WaitingTimes} = get({waiting_mfa, Mfa}), % cleanup erlang:erase({waiting_mfa, Mfa}), % statistics of receive waiting places Stats = mean(WaitingTimes), [{Total, Mfa, Stats} | MfaList] end, [], ListedMfas), lists:sort(fun ({A,_,_},{B,_,_}) -> if A > B -> true; true -> false end end, Unsorted). Generate lists of receive waiting times per mfa %% Out: ListedMfas = [ ( ) ] %% Intrisnic: get({waiting , ( ) } ) - > [ { waiting , ( ) } , { Total , [ WaitingTime ] } ) %% WaitingTime = float() waiting_activities_mfa_list([], ListedMfas) -> ListedMfas; waiting_activities_mfa_list([Activity|Activities], ListedMfas) -> #activity{id = Pid, state = Act, timestamp = Time, where = MFA} = Activity, case Act of active -> waiting_activities_mfa_list(Activities, ListedMfas); inactive -> % Want to know how long the wait is in a receive, % it is given via the next activity case Activities of [] -> [Info] = percept_db:select(information, Pid), case Info#information.stop of undefined -> % get profile end time Waited = ?seconds( percept_db:select({system,stop_ts}), Time); Time2 -> Waited = ?seconds(Time2, Time) end, case get({waiting_mfa, MFA}) of undefined -> put({waiting_mfa, MFA}, {Waited, [Waited]}), [MFA | ListedMfas]; {Total, TimedMfa} -> put({waiting_mfa, MFA}, {Total + Waited, [Waited | TimedMfa]}), ListedMfas end; [#activity{timestamp=Time2, id = Pid, state = active} | _ ] -> % Calculate waiting time Waited = ?seconds(Time2, Time), % Get previous entry case get({waiting_mfa, MFA}) of undefined -> % add entry to list put({waiting_mfa, MFA}, {Waited, [Waited]}), waiting_activities_mfa_list(Activities, [MFA|ListedMfas]); {Total, TimedMfa} -> put({waiting_mfa, MFA}, {Total + Waited, [Waited | TimedMfa]}), waiting_activities_mfa_list(Activities, ListedMfas) end; _ -> error end end. %% seconds2ts(Seconds, StartTs) -> TS %% In: %% Seconds = float() %% StartTs = timestamp() %% Out: %% TS = timestamp() @spec seconds2ts(float ( ) , StartTs::{integer(),integer(),integer ( ) } ) - > timestamp ( ) @doc Calculates a timestamp given a duration in seconds and a starting timestamp . seconds2ts(Seconds, {Ms, S, Us}) -> % Calculate mega seconds integer MsInteger = trunc(Seconds) div 1000000 , Calculate the reminder for seconds SInteger = trunc(Seconds), Calculate the reminder for micro seconds UsInteger = trunc((Seconds - SInteger) * 1000000), % Wrap overflows UsOut = (UsInteger + Us) rem 1000000, SOut = ((SInteger + S) + (UsInteger + Us) div 1000000) rem 1000000, MsOut = (MsInteger+ Ms) + ((SInteger + S) + (UsInteger + Us) div 1000000) div 1000000, {MsOut, SOut, UsOut}. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Analyze interval for concurrency % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% @spec analyze_activities(integer ( ) , [ # activity { } ] ) - > [ { integer(),#activity { } } ] %% @hidden analyze_activities(Threshold, Activities) -> RunnableCount = runnable_count(Activities, 0), analyze_runnable_activities(Threshold, RunnableCount). runnable_count(Activities , StartValue ) - > RunnableCount %% In: %% Activities = [activity()] %% StartValue = integer() %% Out: RunnableCount = [ { integer ( ) , activity ( ) } ] %% Purpose: %% Calculate the runnable count of a given interval of generic %% activities. %% @spec runnable_count([#activity{}]) -> [{integer(),#activity{}}] %% @hidden runnable_count(Activities) -> Threshold = runnable_count_threshold(Activities), runnable_count(Activities, Threshold, []). runnable_count_threshold(Activities) -> CountedActs = runnable_count(Activities, 0), Counts = [C || {C, _} <- CountedActs], Min = lists:min(Counts), 0 - Min. @spec runnable_count([#activity{}],integer ( ) ) - > [ { integer(),#activity { } } ] %% @hidden runnable_count(Activities, StartCount) when is_integer(StartCount) -> runnable_count(Activities, StartCount, []). runnable_count([], _ , Out) -> lists:reverse(Out); runnable_count([A | As], PrevCount, Out) -> case A#activity.state of active -> runnable_count(As, PrevCount + 1, [{PrevCount + 1, A} | Out]); inactive -> runnable_count(As, PrevCount - 1, [{PrevCount - 1, A} | Out]) end. %% In: %% Threshold = integer(), %% RunnableActivities = [{Rc, activity()}] Rc = integer ( ) analyze_runnable_activities(Threshold, RunnableActivities) -> analyze_runnable_activities(Threshold, RunnableActivities, []). analyze_runnable_activities( _z, [], Out) -> lists:reverse(Out); analyze_runnable_activities(Threshold, [{Rc, Act} | RunnableActs], Out) -> if Rc =< Threshold -> analyze_runnable_activities(Threshold, RunnableActs, [{Rc,Act} | Out]); true -> analyze_runnable_activities(Threshold, RunnableActs, Out) end. minmax_activity(Activities , Count ) - > { Min , } %% In: %% Activities = [activity()] InitialCount = non_neg_integer ( ) %% Out: { Min , } %% Min = non_neg_integer() = non_neg_integer ( ) %% Purpose: %% Minimal and maximal activity during an activity interval. %% Initial activity count needs to be supplied. @spec minmax_activities([#activity { } ] , integer ( ) ) - > { integer ( ) , integer ( ) } %% @doc Calculates the minimum and maximum of runnable activites (processes % and ports) during the interval of reffered by the activity list. minmax_activities(Activities, Count) -> minmax_activities(Activities, Count, {Count, Count}). minmax_activities([], _, Out) -> Out; minmax_activities([A|Acts], Count, {Min, Max}) -> case A#activity.state of active -> minmax_activities(Acts, Count + 1, {Min, lists:max([Count + 1, Max])}); inactive -> minmax_activities(Acts, Count - 1, {lists:min([Count - 1, Min]), Max}) end.
null
https://raw.githubusercontent.com/mfoemmel/erlang-otp/9c6fdd21e4e6573ca6f567053ff3ac454d742bc2/lib/percept/src/percept_analyzer.erl
erlang
%CopyrightBegin% compliance with the License. You should have received a copy of the Erlang Public License along with this software. If not, it can be retrieved online 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. %CopyrightEnd% @doc Utility functions to operate on percept data. These functions should be considered experimental. Behaviour may change in future releases. ========================================================================== ========================================================================== X = number() Y = number() MinX = number() MinY = number() MaxX = number() MaxY = number() Mean = float() StdDev = float() N = integer() @doc Calculates the mean and the standard deviation of a set of numbers. Time = float() @doc Calculate the resulting active processes and ports during the activity interval. Also checks active/inactive consistency. A task will always begin with an active state and end with an inactive state. Seconds = float() Mean = float() StdDev = float() N = integer() @doc Calculates the time, both average and total, that a process has spent in a receive state at specific function. However, if there are multiple receives in a function it cannot differentiate between them. cleanup statistics of receive waiting places Out: Intrisnic: WaitingTime = float() Want to know how long the wait is in a receive, it is given via the next activity get profile end time Calculate waiting time Get previous entry add entry to list seconds2ts(Seconds, StartTs) -> TS In: Seconds = float() StartTs = timestamp() Out: TS = timestamp() Calculate mega seconds integer Wrap overflows Analyze interval for concurrency @hidden In: Activities = [activity()] StartValue = integer() Out: Purpose: Calculate the runnable count of a given interval of generic activities. @spec runnable_count([#activity{}]) -> [{integer(),#activity{}}] @hidden @hidden In: Threshold = integer(), RunnableActivities = [{Rc, activity()}] In: Activities = [activity()] Out: Min = non_neg_integer() Purpose: Minimal and maximal activity during an activity interval. Initial activity count needs to be supplied. @doc Calculates the minimum and maximum of runnable activites (processes and ports) during the interval of reffered by the activity list.
Copyright Ericsson AB 2007 - 2009 . All Rights Reserved . The contents of this file are subject to the Erlang Public License , Version 1.1 , ( the " License " ) ; you may not use this file except in Software distributed under the License is distributed on an " AS IS " -module(percept_analyzer). -export([ minmax/1, waiting_activities/1, activities2count/2, activities2count/3, activities2count2/2, analyze_activities/2, runnable_count/1, runnable_count/2, seconds2ts/2, minmax_activities/2, mean/1 ]). -include("percept.hrl"). Interface functions , Y } ] ) - > { MinX , MinY , MaxX , MaxY } @doc Returns the min and of a set of 2 - dimensional numbers . minmax(Data) -> Xs = [ X || {X,_Y} <- Data], Ys = [ Y || {_X, Y} <- Data], {lists:min(Xs), lists:min(Ys), lists:max(Xs), lists:max(Ys)}. ( ) ] ) - > { Mean , , N } mean([]) -> {0, 0, 0}; mean([Value]) -> {Value, 0, 1}; mean(List) -> mean(List, {0, 0, 0}). mean([], {Sum, SumSquare, N}) -> Mean = Sum / N, StdDev = math:sqrt((SumSquare - Sum*Sum/N)/(N - 1)), {Mean, StdDev, N}; mean([Value | List], {Sum, SumSquare, N}) -> mean(List, {Sum + Value, SumSquare + Value*Value, N + 1}). activities2count2(Acts, StartTs) -> Start = inactive_start_states(Acts), activities2count2(Acts, StartTs, Start, []). activities2count2([], _, _, Out) -> lists:reverse(Out); activities2count2([#activity{ id = Id, timestamp = Ts, state = active} | Acts], StartTs, {Proc,Port}, Out) when is_pid(Id) -> activities2count2(Acts, StartTs, {Proc + 1, Port}, [{?seconds(Ts, StartTs), Proc + 1, Port}|Out]); activities2count2([#activity{ id = Id, timestamp = Ts, state = inactive} | Acts], StartTs, {Proc,Port}, Out) when is_pid(Id) -> activities2count2(Acts, StartTs, {Proc - 1, Port}, [{?seconds(Ts, StartTs), Proc - 1, Port}|Out]); activities2count2([#activity{ id = Id, timestamp = Ts, state = active} | Acts], StartTs, {Proc,Port}, Out) when is_port(Id) -> activities2count2(Acts, StartTs, {Proc, Port + 1}, [{?seconds(Ts, StartTs), Proc, Port + 1}|Out]); activities2count2([#activity{ id = Id, timestamp = Ts, state = inactive} | Acts], StartTs, {Proc,Port}, Out) when is_port(Id) -> activities2count2(Acts, StartTs, {Proc, Port - 1}, [{?seconds(Ts, StartTs), Proc, Port - 1}|Out]). inactive_start_states(Acts) -> D = activity_start_states(Acts, dict:new()), dict:fold(fun (K, inactive, {Procs, Ports}) when is_pid(K) -> {Procs + 1, Ports}; (K, inactive, {Procs, Ports}) when is_port(K) -> {Procs, Ports + 1}; (_, _, {Procs, Ports}) -> {Procs, Ports} end, {0,0}, D). activity_start_states([], D) -> D; activity_start_states([#activity{id = Id, state = State}|Acts], D) -> case dict:is_key(Id, D) of true -> activity_start_states(Acts, D); false -> activity_start_states(Acts, dict:store(Id, State, D)) end. @spec activities2count(#activity { } , timestamp ( ) ) - > Result Result = [ { Time , ProcessCount , PortCount } ] ProcessCount = integer ( ) PortCount = integer ( ) activities2count(Acts, StartTs) when is_list(Acts) -> activities2count(Acts, StartTs, separated). activities2count(Acts, StartTs, Type) when is_list(Acts) -> activities2count_loop(Acts, {StartTs, {0,0}}, Type, []). activities2count_loop([], _, _, Out) -> lists:reverse(Out); activities2count_loop( [#activity{ timestamp = Ts, id = Id, runnable_count = Rc} | Acts], {StartTs, {Procs, Ports}}, separated, Out) -> Time = ?seconds(Ts, StartTs), case Id of Id when is_port(Id) -> Entry = {Time, Procs, Rc}, activities2count_loop(Acts, {StartTs, {Procs, Rc}}, separated, [Entry | Out]); Id when is_pid(Id) -> Entry = {Time, Rc, Ports}, activities2count_loop(Acts, {StartTs, {Rc, Ports}}, separated, [Entry | Out]); _ -> activities2count_loop(Acts, {StartTs,{Procs, Ports}}, separated, Out) end; activities2count_loop( [#activity{ timestamp = Ts, id = Id, runnable_count = Rc} | Acts], {StartTs, {Procs, Ports}}, summated, Out) -> Time = ?seconds(Ts, StartTs), case Id of Id when is_port(Id) -> Entry = {Time, Procs + Rc}, activities2count_loop(Acts, {StartTs, {Procs, Rc}}, summated, [Entry | Out]); Id when is_pid(Id) -> Entry = {Time, Rc + Ports}, activities2count_loop(Acts, {StartTs, {Rc, Ports}}, summated, [Entry | Out]) end. @spec waiting_activities([#activity { } ] ) - > FunctionList FunctionList = [ { Seconds , Mfa , { Mean , , N } } ] Mfa = ( ) waiting_activities(Activities) -> ListedMfas = waiting_activities_mfa_list(Activities, []), Unsorted = lists:foldl( fun (Mfa, MfaList) -> {Total, WaitingTimes} = get({waiting_mfa, Mfa}), erlang:erase({waiting_mfa, Mfa}), Stats = mean(WaitingTimes), [{Total, Mfa, Stats} | MfaList] end, [], ListedMfas), lists:sort(fun ({A,_,_},{B,_,_}) -> if A > B -> true; true -> false end end, Unsorted). Generate lists of receive waiting times per mfa ListedMfas = [ ( ) ] get({waiting , ( ) } ) - > [ { waiting , ( ) } , { Total , [ WaitingTime ] } ) waiting_activities_mfa_list([], ListedMfas) -> ListedMfas; waiting_activities_mfa_list([Activity|Activities], ListedMfas) -> #activity{id = Pid, state = Act, timestamp = Time, where = MFA} = Activity, case Act of active -> waiting_activities_mfa_list(Activities, ListedMfas); inactive -> case Activities of [] -> [Info] = percept_db:select(information, Pid), case Info#information.stop of undefined -> Waited = ?seconds( percept_db:select({system,stop_ts}), Time); Time2 -> Waited = ?seconds(Time2, Time) end, case get({waiting_mfa, MFA}) of undefined -> put({waiting_mfa, MFA}, {Waited, [Waited]}), [MFA | ListedMfas]; {Total, TimedMfa} -> put({waiting_mfa, MFA}, {Total + Waited, [Waited | TimedMfa]}), ListedMfas end; [#activity{timestamp=Time2, id = Pid, state = active} | _ ] -> Waited = ?seconds(Time2, Time), case get({waiting_mfa, MFA}) of undefined -> put({waiting_mfa, MFA}, {Waited, [Waited]}), waiting_activities_mfa_list(Activities, [MFA|ListedMfas]); {Total, TimedMfa} -> put({waiting_mfa, MFA}, {Total + Waited, [Waited | TimedMfa]}), waiting_activities_mfa_list(Activities, ListedMfas) end; _ -> error end end. @spec seconds2ts(float ( ) , StartTs::{integer(),integer(),integer ( ) } ) - > timestamp ( ) @doc Calculates a timestamp given a duration in seconds and a starting timestamp . seconds2ts(Seconds, {Ms, S, Us}) -> MsInteger = trunc(Seconds) div 1000000 , Calculate the reminder for seconds SInteger = trunc(Seconds), Calculate the reminder for micro seconds UsInteger = trunc((Seconds - SInteger) * 1000000), UsOut = (UsInteger + Us) rem 1000000, SOut = ((SInteger + S) + (UsInteger + Us) div 1000000) rem 1000000, MsOut = (MsInteger+ Ms) + ((SInteger + S) + (UsInteger + Us) div 1000000) div 1000000, {MsOut, SOut, UsOut}. @spec analyze_activities(integer ( ) , [ # activity { } ] ) - > [ { integer(),#activity { } } ] analyze_activities(Threshold, Activities) -> RunnableCount = runnable_count(Activities, 0), analyze_runnable_activities(Threshold, RunnableCount). runnable_count(Activities , StartValue ) - > RunnableCount RunnableCount = [ { integer ( ) , activity ( ) } ] runnable_count(Activities) -> Threshold = runnable_count_threshold(Activities), runnable_count(Activities, Threshold, []). runnable_count_threshold(Activities) -> CountedActs = runnable_count(Activities, 0), Counts = [C || {C, _} <- CountedActs], Min = lists:min(Counts), 0 - Min. @spec runnable_count([#activity{}],integer ( ) ) - > [ { integer(),#activity { } } ] runnable_count(Activities, StartCount) when is_integer(StartCount) -> runnable_count(Activities, StartCount, []). runnable_count([], _ , Out) -> lists:reverse(Out); runnable_count([A | As], PrevCount, Out) -> case A#activity.state of active -> runnable_count(As, PrevCount + 1, [{PrevCount + 1, A} | Out]); inactive -> runnable_count(As, PrevCount - 1, [{PrevCount - 1, A} | Out]) end. Rc = integer ( ) analyze_runnable_activities(Threshold, RunnableActivities) -> analyze_runnable_activities(Threshold, RunnableActivities, []). analyze_runnable_activities( _z, [], Out) -> lists:reverse(Out); analyze_runnable_activities(Threshold, [{Rc, Act} | RunnableActs], Out) -> if Rc =< Threshold -> analyze_runnable_activities(Threshold, RunnableActs, [{Rc,Act} | Out]); true -> analyze_runnable_activities(Threshold, RunnableActs, Out) end. minmax_activity(Activities , Count ) - > { Min , } InitialCount = non_neg_integer ( ) { Min , } = non_neg_integer ( ) @spec minmax_activities([#activity { } ] , integer ( ) ) - > { integer ( ) , integer ( ) } minmax_activities(Activities, Count) -> minmax_activities(Activities, Count, {Count, Count}). minmax_activities([], _, Out) -> Out; minmax_activities([A|Acts], Count, {Min, Max}) -> case A#activity.state of active -> minmax_activities(Acts, Count + 1, {Min, lists:max([Count + 1, Max])}); inactive -> minmax_activities(Acts, Count - 1, {lists:min([Count - 1, Min]), Max}) end.
c03556e21e4c9a9510ee06854c9a7feb82f04b422d8b533911cf86cfc695ace7
lispm/FRL
domain.lisp
(include declar) (declare (macros t)) ;; ;; Knowledge Domains. ;; ;; see file dhl//rule.l for function domain ;; which allows the user to declare a domain. ;; (defmacro gather (domain args) `(apply (rvalue-only ,domain 'gather) (cons ,domain ,args))) (defun dput macro (arg) `(let ((/:comment-field 'domain/:) (/:not-comment-field 'not-domain/:) (slot-field 'domain) (inherit-slot-field nil) ($facet-field '$domain) ($not-facet-field '$not-domain)) (rput ,@(cdr arg)))) (defun dget macro (arg) `(let ((/:comment-field 'domain/:) (/:not-comment-field 'not-domain/:) (slot-field 'domain) (inherit-slot-field nil) ($facet-field '$domain) ($not-facet-field '$not-domain)) (rget ,@(cdr arg)))) (defun dremove macro (arg) `(let ((/:comment-field 'domain/:) (/:not-comment-field 'not-domain/:) (slot-field 'domain) (inherit-slot-field nil) ($facet-field '$domain) ($not-facet-field '$not-domain)) (rremove ,@(cdr arg)))) (defun dreplace macro (arg) `(let ((/:comment-field 'domain/:) (/:not-comment-field 'not-domain/:) (slot-field 'domain) (inherit-slot-field nil) ($facet-field '$domain) ($not-facet-field '$not-domain)) (rreplace ,@(cdr arg))))
null
https://raw.githubusercontent.com/lispm/FRL/1a2aadf71062a89474b1164e4539911011b3b63e/dhl/domain.lisp
lisp
Knowledge Domains. see file dhl//rule.l for function domain which allows the user to declare a domain.
(include declar) (declare (macros t)) (defmacro gather (domain args) `(apply (rvalue-only ,domain 'gather) (cons ,domain ,args))) (defun dput macro (arg) `(let ((/:comment-field 'domain/:) (/:not-comment-field 'not-domain/:) (slot-field 'domain) (inherit-slot-field nil) ($facet-field '$domain) ($not-facet-field '$not-domain)) (rput ,@(cdr arg)))) (defun dget macro (arg) `(let ((/:comment-field 'domain/:) (/:not-comment-field 'not-domain/:) (slot-field 'domain) (inherit-slot-field nil) ($facet-field '$domain) ($not-facet-field '$not-domain)) (rget ,@(cdr arg)))) (defun dremove macro (arg) `(let ((/:comment-field 'domain/:) (/:not-comment-field 'not-domain/:) (slot-field 'domain) (inherit-slot-field nil) ($facet-field '$domain) ($not-facet-field '$not-domain)) (rremove ,@(cdr arg)))) (defun dreplace macro (arg) `(let ((/:comment-field 'domain/:) (/:not-comment-field 'not-domain/:) (slot-field 'domain) (inherit-slot-field nil) ($facet-field '$domain) ($not-facet-field '$not-domain)) (rreplace ,@(cdr arg))))
24a68cc006a882fa86cdbbc14c011d6783d673535be24f600618b0e77843c465
erlangonrails/devdb
kai_tcp_server_SUITE.erl
Licensed under the Apache License , Version 2.0 ( the " License " ) ; you may not use this file except in compliance with the License . You may obtain a copy of % the License at % % -2.0 % % Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT % WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the % License for the specific language governing permissions and limitations under % the License. -module(kai_tcp_server_SUITE). -compile(export_all). -export([init/1, handle_call/3]). % for echo server -include("ct.hrl"). -include("kai.hrl"). -include("kai_test.hrl"). sequences() -> [{sequences1, [testcase1, testcase2, testcase3, testcase4]}]. all() -> [{sequence, sequences1}]. init_per_testcase(testcase4, Config) -> start_server(10), Config; init_per_testcase(_TestCase, Config) -> start_server(1), Config. start_server(MaxProcesses) -> kai_tcp_server:start_link( ?MODULE, [], #tcp_server_option{max_processes=MaxProcesses} ). end_per_testcase(_TestCase, _Config) -> kai_tcp_server:stop(), ok. testcase1() -> []. testcase1(_Conf) -> normal_test(), ok. normal_test() -> {ok, Socket} = connect_to_echo_server(), gen_tcp:send(Socket, <<"hello\r\n">>), case gen_tcp:recv(Socket, 0) of {ok, <<"hello\r\n">>} -> ok; _HelloError -> ct:fail(bad_echo_value) end, gen_tcp:send(Socket, <<"bye\r\n">>), case gen_tcp:recv(Socket, 0) of {ok, <<"cya\r\n">>} -> ok; _ByeError -> ct:fail(bad_return_value) end, gen_tcp:close(Socket), ok. testcase2() -> []. testcase2(_Conf) -> {ok, Socket} = connect_to_echo_server(), gen_tcp:send(Socket, <<"error\r\n">>), {error, closed} = gen_tcp:recv(Socket, 0), gen_tcp:close(Socket), normal_test(), % check the echo server rebooted. ok. testcase3() -> []. testcase3(_Conf) -> lists:foreach(fun (_N) -> {ok, Socket} = connect_to_echo_server(), gen_tcp:close(Socket) end, lists:seq(1, 10000)), ok. testcase4() -> []. testcase4(_Conf) -> Sockets = lists:map(fun (_N) -> {ok, Socket} = connect_to_echo_server(), Socket end, lists:seq(1, 5)), timer:sleep(100), % wait for increment. case kai_tcp_server:info(curr_connections) of 5 -> ok; Error -> ct:comment(io:format("bad_info:~p", [Error])), ct:fail(bad_info) end, lists:foreach(fun (Socket) -> gen_tcp:close(Socket) end, Sockets), ok. connect_to_echo_server() -> gen_tcp:connect( {127,0,0,1}, 11211, [binary, {packet, line}, {active, false}] ). % echo server init(_Args) -> {ok, {}}. handle_call(_Socket, <<"bye\r\n">>, State) -> {close, <<"cya\r\n">>, State}; handle_call(_Socket, <<"error\r\n">>, State) -> (fun(X) -> 1 / X end)(0), % to throw a bad arithmetic exception {close, <<"error\r\n">>, State}; handle_call(_Socket, Data, State) -> {reply, Data, State}.
null
https://raw.githubusercontent.com/erlangonrails/devdb/0e7eaa6bd810ec3892bfc3d933439560620d0941/dev/kai-0.4.0/test/kai_tcp_server_SUITE.erl
erlang
the License at -2.0 Unless required by applicable law or agreed to in writing, software WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. for echo server check the echo server rebooted. wait for increment. echo server to throw a bad arithmetic exception
Licensed under the Apache License , Version 2.0 ( the " License " ) ; you may not use this file except in compliance with the License . You may obtain a copy of distributed under the License is distributed on an " AS IS " BASIS , WITHOUT -module(kai_tcp_server_SUITE). -compile(export_all). -include("ct.hrl"). -include("kai.hrl"). -include("kai_test.hrl"). sequences() -> [{sequences1, [testcase1, testcase2, testcase3, testcase4]}]. all() -> [{sequence, sequences1}]. init_per_testcase(testcase4, Config) -> start_server(10), Config; init_per_testcase(_TestCase, Config) -> start_server(1), Config. start_server(MaxProcesses) -> kai_tcp_server:start_link( ?MODULE, [], #tcp_server_option{max_processes=MaxProcesses} ). end_per_testcase(_TestCase, _Config) -> kai_tcp_server:stop(), ok. testcase1() -> []. testcase1(_Conf) -> normal_test(), ok. normal_test() -> {ok, Socket} = connect_to_echo_server(), gen_tcp:send(Socket, <<"hello\r\n">>), case gen_tcp:recv(Socket, 0) of {ok, <<"hello\r\n">>} -> ok; _HelloError -> ct:fail(bad_echo_value) end, gen_tcp:send(Socket, <<"bye\r\n">>), case gen_tcp:recv(Socket, 0) of {ok, <<"cya\r\n">>} -> ok; _ByeError -> ct:fail(bad_return_value) end, gen_tcp:close(Socket), ok. testcase2() -> []. testcase2(_Conf) -> {ok, Socket} = connect_to_echo_server(), gen_tcp:send(Socket, <<"error\r\n">>), {error, closed} = gen_tcp:recv(Socket, 0), gen_tcp:close(Socket), ok. testcase3() -> []. testcase3(_Conf) -> lists:foreach(fun (_N) -> {ok, Socket} = connect_to_echo_server(), gen_tcp:close(Socket) end, lists:seq(1, 10000)), ok. testcase4() -> []. testcase4(_Conf) -> Sockets = lists:map(fun (_N) -> {ok, Socket} = connect_to_echo_server(), Socket end, lists:seq(1, 5)), case kai_tcp_server:info(curr_connections) of 5 -> ok; Error -> ct:comment(io:format("bad_info:~p", [Error])), ct:fail(bad_info) end, lists:foreach(fun (Socket) -> gen_tcp:close(Socket) end, Sockets), ok. connect_to_echo_server() -> gen_tcp:connect( {127,0,0,1}, 11211, [binary, {packet, line}, {active, false}] ). init(_Args) -> {ok, {}}. handle_call(_Socket, <<"bye\r\n">>, State) -> {close, <<"cya\r\n">>, State}; handle_call(_Socket, <<"error\r\n">>, State) -> {close, <<"error\r\n">>, State}; handle_call(_Socket, Data, State) -> {reply, Data, State}.
7864e69a0ab60bdd1c03e72550a71e087e070fbadabb4a6e131968a172942cc5
cirodrig/triolet
Rules.hs
module BuildSystem.Rules (generateTrioletCRules, generateTrioletPreprocessorRules, moveDataFiles, moveRtsDataFiles, compileRtsCFiles, compileRtsCxxFiles, compileRtsLltFiles, linkRts, compileTestDriver, generateShakeRules, shake, shakeWithRules) where import Control.Monad import Control.Monad.Trans import Data.Monoid import Debug.Trace import qualified Development.Shake as Shake import qualified Distribution.Simple.Build.PathsModule import qualified Distribution.Simple.Build.Macros import Distribution.Simple.Program import Distribution.PackageDescription import Distribution.Simple.LocalBuildInfo import Distribution.Simple.PreProcess import Distribution.Simple.Utils import Distribution.Verbosity import System.Directory import System.FilePath import qualified System.Info import BuildSystem.Args import BuildSystem.Command import BuildSystem.Config import BuildSystem.Path -- | Create a shake rule that exactly matches a string (?=) :: String -> Shake.Action () -> Shake.Rules () s ?= r = (s ==) Shake.?> \_ -> r | Create a shake rule that exactly matches either of two strings (??=) :: (String, String) -> Shake.Action () -> Shake.Rules () (s1, s2) ??= r = match Shake.?>> \_ -> r where match x | s1 == x || s2 == x = Just [s1, s2] | otherwise = Nothing -- | The autogenerated 'Paths' module generatePathsModule verb lbi = autogen_filename ?= do Shake.writeFile' autogen_filename paths_module where pkg_desc = localPkgDescr lbi paths_module = Distribution.Simple.Build.PathsModule.generate pkg_desc lbi autogen_filename = autogenPathsFile lbi -- | Auto-generated files describing properties of the target architecture generateMachineInfo verb lbi = (module_file, header_file) ??= do int_size <- getCSizeOf verb "int" ptr_size <- getCSizeOf verb "void *" liftIO $ createDirectoryIfMissingVerbose verb True $ dropFileName module_file liftIO $ createDirectoryIfMissingVerbose verb True $ dropFileName header_file Shake.writeFile' module_file $ module_text int_size ptr_size Shake.writeFile' header_file $ header_text int_size ptr_size where module_file = autogenMachineFile lbi header_file = autogenMachineHeaderFile lbi module_text int_size ptr_size = "-- Autogenerated module\n" ++ "module Machine where\n" ++ "targetWordSizeBytes :: Int\n" ++ "targetWordSizeBytes = " ++ show ptr_size ++ "\n" ++ "targetIntSizeBytes :: Int\n" ++ "targetIntSizeBytes = " ++ show int_size ++ "\n" header_text int_size ptr_size = "#ifndef _MACHINE_H_\n" ++ "#define _MACHINE_H_\n" ++ "#define WORD_SIZE " ++ show ptr_size ++ "\n" ++ "#define INT_SIZE " ++ show int_size ++ "\n" ++ "#endif\n" -- | Generate C headers required by generateCabalMacros verb lbi = dst_path ?= do let pkg_desc = localPkgDescr lbi let file_text = Distribution.Simple.Build.Macros.generate pkg_desc lbi Shake.writeFile' dst_path file_text where dst_path = cabalMacrosFile lbi | Create a rule to compile a C source file that is part of triolet compileCTrioletFile :: Verbosity -> LocalBuildInfo -> ExtraConfigFlags -> FilePath -- ^ Source file -> FilePath -- ^ Object file -> Shake.Rules () -- ^ Rule generator compileCTrioletFile verb lbi econfig src_file dst_file = -- Run the compiler let exe = getTrioletExe lbi configured_args = trioletCcArgs econfig exe lbi args = ["-c", src_file, "-o", dst_file] ++ configured_args Just cc = lookupProgram gccProgram $ withPrograms lbi in dst_file ?= do -- In addition to the source file, -- the auto-generated preprocessor macros file must exist Shake.need [src_file, cabalMacrosFile lbi] runCommand (invokeProgram verb cc args) | Create a rule to invoke GHC for the main Triolet executable . compileTriolet :: Verbosity -> LocalBuildInfo -> ExtraConfigFlags ^ All sources -> [FilePath] -- ^ All C objects -> FilePath -- ^ The 'Main' file -> Shake.Rules () compileTriolet verb lbi econfig hs_sources c_objects main = target ?= do Shake.need hs_sources Shake.need c_objects Invoke GHC to build Triolet let configured_args = trioletGhcArgs econfig exe lbi Source files that GHC will compile source_args = main : c_objects args = ["--make", "-o", target] ++ source_args ++ configured_args runCommand $ invokeProgram verb ghc args If profiling , invoke GHC again to build the profiled program let prof_args = args ++ trioletGhcProfArgs econfig exe lbi when is_prof $ runCommand $ invokeProgram verb ghc prof_args where Just ghc = lookupProgram ghcProgram $ withPrograms lbi exe = getTrioletExe lbi target = trioletFile lbi is_prof = withProfExe lbi -- | Run a C program to find the size of a C data type getCSizeOf :: Verbosity -> String -> Shake.Action Int getCSizeOf verb type_name = liftIO $ do tmpdir <- getTemporaryDirectory withTempDirectory verb tmpdir "setup." $ \mydir -> do let src_file = mydir </> "main.c" exe_file = mydir </> "main" -- Create and run a C program to get the size writeFile src_file sizeof_code rawSystemExit verb "gcc" [src_file, "-o", exe_file] sizeof_string <- rawSystemStdout verb exe_file [] size <- return $! read sizeof_string info verb $ "Calculated sizeof(" ++ type_name ++ ") = " ++ show size return size where sizeof_code = "#include <stdio.h>\n" ++ "int main() {\n" ++ " printf(\"%d\\n\", (int)sizeof(" ++ type_name ++ "));\n" ++ " return 0;\n" ++ "}\n" ------------------------------------------------------------------------------- Rules for building Triolet | Generate rules to compile all C files that are part of triolet . -- Return rules and a list of object files. generateTrioletCRules :: Verbosity -> LocalBuildInfo -> ExtraConfigFlags -> IO (Shake.Rules (), [FilePath]) generateTrioletCRules verb lbi econfig = liftM mconcat $ mapM generate_rule $ trioletCFiles lbi where search_paths = trioletSearchPaths lbi generate_rule c_file = do file_path <- findInSearchPaths search_paths c_file let obj_path = trioletBuildDir lbi </> (c_file `replaceExtension` ".o") -- Invoke C compiler let rule = compileCTrioletFile verb lbi econfig file_path obj_path return (rule, [obj_path]) | Find all files in Triolet that are auto - generated or preprocessed -- and generate rules for them. -- -- All modules are scanned. If a preprocessor input is found for a module, -- a rule is generated for it. The rules and a list of file paths is returned . generateTrioletPreprocessorRules :: Verbosity -> LocalBuildInfo -> IO (Shake.Rules (), [FilePath]) generateTrioletPreprocessorRules verb lbi = liftM mconcat $ mapM generate_rule $ trioletModulePaths lbi where generate_rule m = first_match m rules first_match m (r:rs) = do result <- r verb lbi search_paths m case result of Nothing -> first_match m rs Just (rule, path) -> return (rule, [path]) first_match m [] = error $ "Cannot find file or preprocessor input of " ++ (m `addExtension` ".hs") search_paths = trioletSearchPaths lbi -- Search rules. The 'findHaskellFile' rule must be last so that -- preprocessor files override .hs sources. rules = [findAlexFile, findHappyFile, findHscFile, findPathsFile, findMachineFile, findHaskellFile] findInputFile :: String -> (FilePath -> IO (Shake.Rules (), FilePath)) -> SearchPaths -> FilePath -> IO (Maybe (Shake.Rules (), FilePath)) findInputFile ext action search_paths path = do m_result <- optFindInSearchPaths search_paths (path `addExtension` ext) case m_result of Nothing -> return Nothing Just found_path -> liftM Just $ action found_path | If a @.hs@ file exists , then it will be used when building findHaskellFile _ _ search_paths path = findInputFile ".hs" (\p -> return (return (), p)) search_paths path -- | Autogenerated \"Paths\" file findPathsFile verb lbi search_paths path | path == autogenPathsPath lbi = do info verb $ "Will auto-generate " ++ (path `addExtension` ".hs") return $ Just (generatePathsModule verb lbi, autogenPathsFile lbi) | otherwise = return Nothing -- | Autogenerated \"Machine\" file. A rule is generated by ' ' . Do not generate a rule now . findMachineFile verb lbi search_paths path | path == autogenMachinePath lbi = do info verb $ "Will auto-generate " ++ (path `addExtension` ".hs") return $ Just (return (), autogenMachineFile lbi) | otherwise = return Nothing data Preprocessor = Preprocessor { ppExtension :: !String , ppReadableName :: !String , ppPrerequisites :: !(LocalBuildInfo -> FilePath -> [FilePath]) , ppCabalPreprocessor :: !(BuildInfo -> LocalBuildInfo -> PreProcessor) } noPrerequisites _ _ = [] -- | Attempt to generate Shake rules using the given preprocessor. -- Search for the preprocessor's input file and generate a rule. -- -- Return a 'Just' value on success, or 'Nothing' on failure usePreprocessor :: Preprocessor -> Verbosity -> LocalBuildInfo -> SearchPaths -> FilePath -> IO (Maybe (Shake.Rules (), FilePath)) usePreprocessor pp verb lbi search_paths path = findInputFile ext create_rule search_paths path where ext = ppExtension pp dst_path = trioletBuildDir lbi </> path `addExtension` ".hs" -- Create a Shake rule with the given input file path create_rule found_path = do info verb $ "Will generate " ++ dst_path ++ " with " ++ ppReadableName pp let exe = getTrioletExe lbi preprocessor = ppCabalPreprocessor pp (buildInfo exe) lbi prerequisites = ppPrerequisites pp lbi dst_path rule = dst_path ?= do Shake.need [found_path] Shake.need prerequisites liftIO $ runSimplePreProcessor preprocessor found_path dst_path verb return (rule, dst_path) findAlexFile = usePreprocessor $ Preprocessor ".x" "Alex" noPrerequisites ppAlex findHappyFile = usePreprocessor $ Preprocessor ".y" "Happy" noPrerequisites ppHappy findHscFile = usePreprocessor $ Preprocessor ".hsc" "Hsc2Hs" hsc_prerequisites ppHsc2hs where hsc_prerequisites lbi _ = [cabalMacrosFile lbi] ------------------------------------------------------------------------------- -- Rules for data files moveDataFile lbi file_path = dst_path ?= Shake.copyFile' src_path dst_path where dst_path = dataBuildDir lbi </> file_path src_path = dataSourceDir </> file_path -- | Move data files into the build directory moveDataFiles lbi = mconcat $ map (moveDataFile lbi) prebuiltDataFiles -- | Move compiled library files into the build directory moveRtsDataFiles lbi = do (prefix </> "coremodule.ti") Shake.*> \dst_path -> let src_path = rtsBuildDir lbi </> "coremodule.ti" in Shake.copyFile' src_path dst_path -- For each .llt file -- Copy 'build/rts/foo.llt.ti' to 'build/data/foo.ti' forM rtsLltSourceFiles $ \llt_file -> let dst_path = prefix </> llt_file `replaceExtension` ".ti" src_path = rtsBuildDir lbi </> llt_file `addExtension` ".ti" in dst_path ?= do Shake.copyFile' src_path dst_path where prefix = dataBuildDir lbi </> "interfaces" ------------------------------------------------------------------------------- -- Rules for the RTS dropPrefix (x:xs) (y:ys) | x == y = dropPrefix xs ys | otherwise = error "Unexpected prefix" dropPrefix [] ys = ys dropPathPrefix pfx p = dropPrefix (addTrailingPathSeparator pfx) p compileCRtsFile verb lbi econfig src_path obj_path = -- Run the compiler let exe = getTrioletExe lbi configured_args = rtsCcArgs False econfig exe lbi args = ["-c", src_path, "-g", "-o", obj_path] ++ configured_args -- We can't use 'gccProgram' here because it automatically inserts the flag -m32 if the compiler 's output is 32 - bit x86 code . -- The C compiler should generate target-compatible code. Just cc = lookupProgram (simpleProgram "gcc") $ withPrograms lbi in runCommand (invokeString verb "gcc" args) compileCxxRtsFile verb lbi econfig src_path obj_path = -- Run the compiler let exe = getTrioletExe lbi configured_args = rtsCcArgs True econfig exe lbi args = ["-g", "-c", src_path, "-o", obj_path] ++ configured_args Just cxx = lookupProgram (simpleProgram "g++") $ withPrograms lbi in runCommand (invokeProgram verb cxx args) compileLltRtsFile verb lbi econfig src_path obj_path = let triolet = trioletFile lbi data_args = ["-B", dataBuildDir lbi] args = data_args ++ [src_path, "--keep-c-files", "-o", obj_path] ++ rtsLltArgs econfig lbi in runCommand (invokeString verb triolet args) needRtsHeaders lbi = do Shake.need [autogenMachineHeaderFile lbi] Shake.need [dataBuildDir lbi </> f | f <- prebuiltDataFiles] compileRtsCFiles verb lbi econfig = build_dir ++ "//*.c.o" Shake.*> \obj_path -> do -- Remove the build directory prefix and the extension let file_name = dropExtension $ dropPathPrefix build_dir obj_path src_path = rtsSourceDir </> file_name needRtsHeaders lbi -- Depend on header files Shake.need [src_path] -- Depend on source file compileCRtsFile verb lbi econfig src_path obj_path where build_dir = rtsBuildDir lbi compileRtsCxxFiles verb lbi econfig = build_dir ++ "//*.cc.o" Shake.*> \obj_path -> do -- Remove the build directory prefix and the extension let file_name = dropExtension $ dropPathPrefix build_dir obj_path src_path = rtsSourceDir </> file_name needRtsHeaders lbi -- Depend on header files Shake.need [src_path] -- Depend on source file compileCxxRtsFile verb lbi econfig src_path obj_path where build_dir = rtsBuildDir lbi compileRtsLltFiles verb lbi econfig = target_patterns Shake.*>> \[obj_path, _] -> do -- Remove the build directory prefix and the extension let file_name = dropExtension $ dropPathPrefix build_dir obj_path src_path = rtsSourceDir </> file_name Shake.need [trioletFile lbi] -- Need compiler needRtsHeaders lbi -- Need headers Shake.need [src_path] -- Depend on source file compileLltRtsFile verb lbi econfig src_path obj_path where build_dir = rtsBuildDir lbi target_patterns = [build_dir ++ "//*.llt.o", build_dir ++ "//*.llt.ti"] compileRtsCoreFile verb lbi econfig = target_patterns Shake.*>> \[obj_path, _] -> do Shake.need [trioletFile lbi] -- Need compiler Shake.need [dataBuildDir lbi </> "symbols/coremodule"] -- Need coremodule Shake.need $ interfaceFiles lbi let triolet = trioletFile lbi data_args = ["-B", dataBuildDir lbi] args = data_args ++ ["--generate-builtin-library", "--keep-c-files", "-o", obj_path] runCommand (invokeString verb triolet args) where build_dir = rtsBuildDir lbi target_patterns = [build_dir </> "coremodule.o", build_dir </> "coremodule.ti"] linkRts verb lbi econfig = rtsFile lbi ?= do Shake.need objects let link_flags = targetLinkFlags econfig args = objects ++ ["-o", rtsFile lbi] ++ link_flags link_shared args where objects = [rtsBuildDir lbi </> f | f <- rtsObjectFiles] link_shared args = let (prog_name, os_args) = case System.Info.os of "linux" -> ("gcc", ["-shared"]) "darwin" -> ("libtool", ["-dynamic"]) _ -> error "Unrecognized operating system" in runCommand $ invokeString verb prog_name (os_args ++ args) ------------------------------------------------------------------------------- -- Rules for testing compileTestDriver verb lbi = test_file ?= do Triolet must be built first Shake.need [BuildSystem.Path.trioletFile lbi] Shake.need $ BuildSystem.Path.dataFiles lbi -- Find source files test_main_file <- liftIO $ findInSearchPaths testDriverSearchPaths testDriverMain test_src_files <- liftIO $ sequence [findInSearchPaths testDriverSearchPaths (f `addExtension` ".hs") | f <- testDriverModules] Shake.need (test_main_file : test_src_files) -- Compile it let configured_args = testDriverGhcArgs lbi args = ["--make", test_main_file, "-o", test_file] ++ configured_args Just ghc = lookupProgram ghcProgram $ withPrograms lbi runCommand $ invokeProgram verb ghc args where test_file = testDriverFile lbi ------------------------------------------------------------------------------- -- Top-level stuff -- | Define all shake rules generateShakeRules :: Verbosity -> LocalBuildInfo -> ExtraConfigFlags -> IO (Shake.Rules ()) generateShakeRules verb lbi econfig = do -- Scan for files and configuration data econfig <- readExtraConfigFile (pp_rules, triolet_hs_files) <- generateTrioletPreprocessorRules verb lbi (c_rules, triolet_obj_files) <- generateTrioletCRules verb lbi econfig main_file <- findTrioletMainFile lbi return $ do -- Define all rules here BuildSystem.Rules.generateMachineInfo verb lbi BuildSystem.Rules.generateCabalMacros verb lbi pp_rules c_rules BuildSystem.Rules.compileTriolet verb lbi econfig triolet_hs_files triolet_obj_files main_file BuildSystem.Rules.moveDataFiles lbi BuildSystem.Rules.moveRtsDataFiles lbi BuildSystem.Rules.compileRtsCFiles verb lbi econfig BuildSystem.Rules.compileRtsCxxFiles verb lbi econfig BuildSystem.Rules.compileRtsLltFiles verb lbi econfig compileRtsCoreFile verb lbi econfig BuildSystem.Rules.linkRts verb lbi econfig BuildSystem.Rules.compileTestDriver verb lbi return () shake :: Verbosity -> Shake.Rules () -> IO () shake verb rules = Shake.shake opts rules where opts = Shake.shakeOptions { Shake.shakeVerbosity = shake_verbosity} shake_verbosity | verb == silent = Shake.Silent | verb == normal = Shake.Normal | verb == verbose = Shake.Loud | verb == deafening = Shake.Diagnostic shakeWithRules :: Verbosity -> LocalBuildInfo -> ExtraConfigFlags -> Shake.Rules () -> IO () shakeWithRules verb lbi econfig rules = do base_rules <- generateShakeRules verb lbi econfig shake verb (base_rules >> rules)
null
https://raw.githubusercontent.com/cirodrig/triolet/e515a1dc0d6b3e546320eac7b71fb36cea5b53d0/BuildSystem/Rules.hs
haskell
| Create a shake rule that exactly matches a string | The autogenerated 'Paths' module | Auto-generated files describing properties of the target architecture | Generate C headers required by ^ Source file ^ Object file ^ Rule generator Run the compiler In addition to the source file, the auto-generated preprocessor macros file must exist ^ All C objects ^ The 'Main' file | Run a C program to find the size of a C data type Create and run a C program to get the size ----------------------------------------------------------------------------- Return rules and a list of object files. Invoke C compiler and generate rules for them. All modules are scanned. If a preprocessor input is found for a module, a rule is generated for it. Search rules. The 'findHaskellFile' rule must be last so that preprocessor files override .hs sources. | Autogenerated \"Paths\" file | Autogenerated \"Machine\" file. | Attempt to generate Shake rules using the given preprocessor. Search for the preprocessor's input file and generate a rule. Return a 'Just' value on success, or 'Nothing' on failure Create a Shake rule with the given input file path ----------------------------------------------------------------------------- Rules for data files | Move data files into the build directory | Move compiled library files into the build directory For each .llt file Copy 'build/rts/foo.llt.ti' to 'build/data/foo.ti' ----------------------------------------------------------------------------- Rules for the RTS Run the compiler We can't use 'gccProgram' here because it automatically inserts the The C compiler should generate target-compatible code. Run the compiler Remove the build directory prefix and the extension Depend on header files Depend on source file Remove the build directory prefix and the extension Depend on header files Depend on source file Remove the build directory prefix and the extension Need compiler Need headers Depend on source file Need compiler Need coremodule ----------------------------------------------------------------------------- Rules for testing Find source files Compile it ----------------------------------------------------------------------------- Top-level stuff | Define all shake rules Scan for files and configuration data Define all rules here
module BuildSystem.Rules (generateTrioletCRules, generateTrioletPreprocessorRules, moveDataFiles, moveRtsDataFiles, compileRtsCFiles, compileRtsCxxFiles, compileRtsLltFiles, linkRts, compileTestDriver, generateShakeRules, shake, shakeWithRules) where import Control.Monad import Control.Monad.Trans import Data.Monoid import Debug.Trace import qualified Development.Shake as Shake import qualified Distribution.Simple.Build.PathsModule import qualified Distribution.Simple.Build.Macros import Distribution.Simple.Program import Distribution.PackageDescription import Distribution.Simple.LocalBuildInfo import Distribution.Simple.PreProcess import Distribution.Simple.Utils import Distribution.Verbosity import System.Directory import System.FilePath import qualified System.Info import BuildSystem.Args import BuildSystem.Command import BuildSystem.Config import BuildSystem.Path (?=) :: String -> Shake.Action () -> Shake.Rules () s ?= r = (s ==) Shake.?> \_ -> r | Create a shake rule that exactly matches either of two strings (??=) :: (String, String) -> Shake.Action () -> Shake.Rules () (s1, s2) ??= r = match Shake.?>> \_ -> r where match x | s1 == x || s2 == x = Just [s1, s2] | otherwise = Nothing generatePathsModule verb lbi = autogen_filename ?= do Shake.writeFile' autogen_filename paths_module where pkg_desc = localPkgDescr lbi paths_module = Distribution.Simple.Build.PathsModule.generate pkg_desc lbi autogen_filename = autogenPathsFile lbi generateMachineInfo verb lbi = (module_file, header_file) ??= do int_size <- getCSizeOf verb "int" ptr_size <- getCSizeOf verb "void *" liftIO $ createDirectoryIfMissingVerbose verb True $ dropFileName module_file liftIO $ createDirectoryIfMissingVerbose verb True $ dropFileName header_file Shake.writeFile' module_file $ module_text int_size ptr_size Shake.writeFile' header_file $ header_text int_size ptr_size where module_file = autogenMachineFile lbi header_file = autogenMachineHeaderFile lbi module_text int_size ptr_size = "-- Autogenerated module\n" ++ "module Machine where\n" ++ "targetWordSizeBytes :: Int\n" ++ "targetWordSizeBytes = " ++ show ptr_size ++ "\n" ++ "targetIntSizeBytes :: Int\n" ++ "targetIntSizeBytes = " ++ show int_size ++ "\n" header_text int_size ptr_size = "#ifndef _MACHINE_H_\n" ++ "#define _MACHINE_H_\n" ++ "#define WORD_SIZE " ++ show ptr_size ++ "\n" ++ "#define INT_SIZE " ++ show int_size ++ "\n" ++ "#endif\n" generateCabalMacros verb lbi = dst_path ?= do let pkg_desc = localPkgDescr lbi let file_text = Distribution.Simple.Build.Macros.generate pkg_desc lbi Shake.writeFile' dst_path file_text where dst_path = cabalMacrosFile lbi | Create a rule to compile a C source file that is part of triolet compileCTrioletFile :: Verbosity -> LocalBuildInfo -> ExtraConfigFlags compileCTrioletFile verb lbi econfig src_file dst_file = let exe = getTrioletExe lbi configured_args = trioletCcArgs econfig exe lbi args = ["-c", src_file, "-o", dst_file] ++ configured_args Just cc = lookupProgram gccProgram $ withPrograms lbi in dst_file ?= do Shake.need [src_file, cabalMacrosFile lbi] runCommand (invokeProgram verb cc args) | Create a rule to invoke GHC for the main Triolet executable . compileTriolet :: Verbosity -> LocalBuildInfo -> ExtraConfigFlags ^ All sources -> Shake.Rules () compileTriolet verb lbi econfig hs_sources c_objects main = target ?= do Shake.need hs_sources Shake.need c_objects Invoke GHC to build Triolet let configured_args = trioletGhcArgs econfig exe lbi Source files that GHC will compile source_args = main : c_objects args = ["--make", "-o", target] ++ source_args ++ configured_args runCommand $ invokeProgram verb ghc args If profiling , invoke GHC again to build the profiled program let prof_args = args ++ trioletGhcProfArgs econfig exe lbi when is_prof $ runCommand $ invokeProgram verb ghc prof_args where Just ghc = lookupProgram ghcProgram $ withPrograms lbi exe = getTrioletExe lbi target = trioletFile lbi is_prof = withProfExe lbi getCSizeOf :: Verbosity -> String -> Shake.Action Int getCSizeOf verb type_name = liftIO $ do tmpdir <- getTemporaryDirectory withTempDirectory verb tmpdir "setup." $ \mydir -> do let src_file = mydir </> "main.c" exe_file = mydir </> "main" writeFile src_file sizeof_code rawSystemExit verb "gcc" [src_file, "-o", exe_file] sizeof_string <- rawSystemStdout verb exe_file [] size <- return $! read sizeof_string info verb $ "Calculated sizeof(" ++ type_name ++ ") = " ++ show size return size where sizeof_code = "#include <stdio.h>\n" ++ "int main() {\n" ++ " printf(\"%d\\n\", (int)sizeof(" ++ type_name ++ "));\n" ++ " return 0;\n" ++ "}\n" Rules for building Triolet | Generate rules to compile all C files that are part of triolet . generateTrioletCRules :: Verbosity -> LocalBuildInfo -> ExtraConfigFlags -> IO (Shake.Rules (), [FilePath]) generateTrioletCRules verb lbi econfig = liftM mconcat $ mapM generate_rule $ trioletCFiles lbi where search_paths = trioletSearchPaths lbi generate_rule c_file = do file_path <- findInSearchPaths search_paths c_file let obj_path = trioletBuildDir lbi </> (c_file `replaceExtension` ".o") let rule = compileCTrioletFile verb lbi econfig file_path obj_path return (rule, [obj_path]) | Find all files in Triolet that are auto - generated or preprocessed The rules and a list of file paths is returned . generateTrioletPreprocessorRules :: Verbosity -> LocalBuildInfo -> IO (Shake.Rules (), [FilePath]) generateTrioletPreprocessorRules verb lbi = liftM mconcat $ mapM generate_rule $ trioletModulePaths lbi where generate_rule m = first_match m rules first_match m (r:rs) = do result <- r verb lbi search_paths m case result of Nothing -> first_match m rs Just (rule, path) -> return (rule, [path]) first_match m [] = error $ "Cannot find file or preprocessor input of " ++ (m `addExtension` ".hs") search_paths = trioletSearchPaths lbi rules = [findAlexFile, findHappyFile, findHscFile, findPathsFile, findMachineFile, findHaskellFile] findInputFile :: String -> (FilePath -> IO (Shake.Rules (), FilePath)) -> SearchPaths -> FilePath -> IO (Maybe (Shake.Rules (), FilePath)) findInputFile ext action search_paths path = do m_result <- optFindInSearchPaths search_paths (path `addExtension` ext) case m_result of Nothing -> return Nothing Just found_path -> liftM Just $ action found_path | If a @.hs@ file exists , then it will be used when building findHaskellFile _ _ search_paths path = findInputFile ".hs" (\p -> return (return (), p)) search_paths path findPathsFile verb lbi search_paths path | path == autogenPathsPath lbi = do info verb $ "Will auto-generate " ++ (path `addExtension` ".hs") return $ Just (generatePathsModule verb lbi, autogenPathsFile lbi) | otherwise = return Nothing A rule is generated by ' ' . Do not generate a rule now . findMachineFile verb lbi search_paths path | path == autogenMachinePath lbi = do info verb $ "Will auto-generate " ++ (path `addExtension` ".hs") return $ Just (return (), autogenMachineFile lbi) | otherwise = return Nothing data Preprocessor = Preprocessor { ppExtension :: !String , ppReadableName :: !String , ppPrerequisites :: !(LocalBuildInfo -> FilePath -> [FilePath]) , ppCabalPreprocessor :: !(BuildInfo -> LocalBuildInfo -> PreProcessor) } noPrerequisites _ _ = [] usePreprocessor :: Preprocessor -> Verbosity -> LocalBuildInfo -> SearchPaths -> FilePath -> IO (Maybe (Shake.Rules (), FilePath)) usePreprocessor pp verb lbi search_paths path = findInputFile ext create_rule search_paths path where ext = ppExtension pp dst_path = trioletBuildDir lbi </> path `addExtension` ".hs" create_rule found_path = do info verb $ "Will generate " ++ dst_path ++ " with " ++ ppReadableName pp let exe = getTrioletExe lbi preprocessor = ppCabalPreprocessor pp (buildInfo exe) lbi prerequisites = ppPrerequisites pp lbi dst_path rule = dst_path ?= do Shake.need [found_path] Shake.need prerequisites liftIO $ runSimplePreProcessor preprocessor found_path dst_path verb return (rule, dst_path) findAlexFile = usePreprocessor $ Preprocessor ".x" "Alex" noPrerequisites ppAlex findHappyFile = usePreprocessor $ Preprocessor ".y" "Happy" noPrerequisites ppHappy findHscFile = usePreprocessor $ Preprocessor ".hsc" "Hsc2Hs" hsc_prerequisites ppHsc2hs where hsc_prerequisites lbi _ = [cabalMacrosFile lbi] moveDataFile lbi file_path = dst_path ?= Shake.copyFile' src_path dst_path where dst_path = dataBuildDir lbi </> file_path src_path = dataSourceDir </> file_path moveDataFiles lbi = mconcat $ map (moveDataFile lbi) prebuiltDataFiles moveRtsDataFiles lbi = do (prefix </> "coremodule.ti") Shake.*> \dst_path -> let src_path = rtsBuildDir lbi </> "coremodule.ti" in Shake.copyFile' src_path dst_path forM rtsLltSourceFiles $ \llt_file -> let dst_path = prefix </> llt_file `replaceExtension` ".ti" src_path = rtsBuildDir lbi </> llt_file `addExtension` ".ti" in dst_path ?= do Shake.copyFile' src_path dst_path where prefix = dataBuildDir lbi </> "interfaces" dropPrefix (x:xs) (y:ys) | x == y = dropPrefix xs ys | otherwise = error "Unexpected prefix" dropPrefix [] ys = ys dropPathPrefix pfx p = dropPrefix (addTrailingPathSeparator pfx) p compileCRtsFile verb lbi econfig src_path obj_path = let exe = getTrioletExe lbi configured_args = rtsCcArgs False econfig exe lbi args = ["-c", src_path, "-g", "-o", obj_path] ++ configured_args flag -m32 if the compiler 's output is 32 - bit x86 code . Just cc = lookupProgram (simpleProgram "gcc") $ withPrograms lbi in runCommand (invokeString verb "gcc" args) compileCxxRtsFile verb lbi econfig src_path obj_path = let exe = getTrioletExe lbi configured_args = rtsCcArgs True econfig exe lbi args = ["-g", "-c", src_path, "-o", obj_path] ++ configured_args Just cxx = lookupProgram (simpleProgram "g++") $ withPrograms lbi in runCommand (invokeProgram verb cxx args) compileLltRtsFile verb lbi econfig src_path obj_path = let triolet = trioletFile lbi data_args = ["-B", dataBuildDir lbi] args = data_args ++ [src_path, "--keep-c-files", "-o", obj_path] ++ rtsLltArgs econfig lbi in runCommand (invokeString verb triolet args) needRtsHeaders lbi = do Shake.need [autogenMachineHeaderFile lbi] Shake.need [dataBuildDir lbi </> f | f <- prebuiltDataFiles] compileRtsCFiles verb lbi econfig = build_dir ++ "//*.c.o" Shake.*> \obj_path -> do let file_name = dropExtension $ dropPathPrefix build_dir obj_path src_path = rtsSourceDir </> file_name compileCRtsFile verb lbi econfig src_path obj_path where build_dir = rtsBuildDir lbi compileRtsCxxFiles verb lbi econfig = build_dir ++ "//*.cc.o" Shake.*> \obj_path -> do let file_name = dropExtension $ dropPathPrefix build_dir obj_path src_path = rtsSourceDir </> file_name compileCxxRtsFile verb lbi econfig src_path obj_path where build_dir = rtsBuildDir lbi compileRtsLltFiles verb lbi econfig = target_patterns Shake.*>> \[obj_path, _] -> do let file_name = dropExtension $ dropPathPrefix build_dir obj_path src_path = rtsSourceDir </> file_name compileLltRtsFile verb lbi econfig src_path obj_path where build_dir = rtsBuildDir lbi target_patterns = [build_dir ++ "//*.llt.o", build_dir ++ "//*.llt.ti"] compileRtsCoreFile verb lbi econfig = target_patterns Shake.*>> \[obj_path, _] -> do Shake.need $ interfaceFiles lbi let triolet = trioletFile lbi data_args = ["-B", dataBuildDir lbi] args = data_args ++ ["--generate-builtin-library", "--keep-c-files", "-o", obj_path] runCommand (invokeString verb triolet args) where build_dir = rtsBuildDir lbi target_patterns = [build_dir </> "coremodule.o", build_dir </> "coremodule.ti"] linkRts verb lbi econfig = rtsFile lbi ?= do Shake.need objects let link_flags = targetLinkFlags econfig args = objects ++ ["-o", rtsFile lbi] ++ link_flags link_shared args where objects = [rtsBuildDir lbi </> f | f <- rtsObjectFiles] link_shared args = let (prog_name, os_args) = case System.Info.os of "linux" -> ("gcc", ["-shared"]) "darwin" -> ("libtool", ["-dynamic"]) _ -> error "Unrecognized operating system" in runCommand $ invokeString verb prog_name (os_args ++ args) compileTestDriver verb lbi = test_file ?= do Triolet must be built first Shake.need [BuildSystem.Path.trioletFile lbi] Shake.need $ BuildSystem.Path.dataFiles lbi test_main_file <- liftIO $ findInSearchPaths testDriverSearchPaths testDriverMain test_src_files <- liftIO $ sequence [findInSearchPaths testDriverSearchPaths (f `addExtension` ".hs") | f <- testDriverModules] Shake.need (test_main_file : test_src_files) let configured_args = testDriverGhcArgs lbi args = ["--make", test_main_file, "-o", test_file] ++ configured_args Just ghc = lookupProgram ghcProgram $ withPrograms lbi runCommand $ invokeProgram verb ghc args where test_file = testDriverFile lbi generateShakeRules :: Verbosity -> LocalBuildInfo -> ExtraConfigFlags -> IO (Shake.Rules ()) generateShakeRules verb lbi econfig = do econfig <- readExtraConfigFile (pp_rules, triolet_hs_files) <- generateTrioletPreprocessorRules verb lbi (c_rules, triolet_obj_files) <- generateTrioletCRules verb lbi econfig main_file <- findTrioletMainFile lbi return $ do BuildSystem.Rules.generateMachineInfo verb lbi BuildSystem.Rules.generateCabalMacros verb lbi pp_rules c_rules BuildSystem.Rules.compileTriolet verb lbi econfig triolet_hs_files triolet_obj_files main_file BuildSystem.Rules.moveDataFiles lbi BuildSystem.Rules.moveRtsDataFiles lbi BuildSystem.Rules.compileRtsCFiles verb lbi econfig BuildSystem.Rules.compileRtsCxxFiles verb lbi econfig BuildSystem.Rules.compileRtsLltFiles verb lbi econfig compileRtsCoreFile verb lbi econfig BuildSystem.Rules.linkRts verb lbi econfig BuildSystem.Rules.compileTestDriver verb lbi return () shake :: Verbosity -> Shake.Rules () -> IO () shake verb rules = Shake.shake opts rules where opts = Shake.shakeOptions { Shake.shakeVerbosity = shake_verbosity} shake_verbosity | verb == silent = Shake.Silent | verb == normal = Shake.Normal | verb == verbose = Shake.Loud | verb == deafening = Shake.Diagnostic shakeWithRules :: Verbosity -> LocalBuildInfo -> ExtraConfigFlags -> Shake.Rules () -> IO () shakeWithRules verb lbi econfig rules = do base_rules <- generateShakeRules verb lbi econfig shake verb (base_rules >> rules)
d8a0e989535a2425da048db131508deda0da40d6317cda7f9b3ec780d9d1ad8b
janestreet/bonsai
freeform_multiselect.ml
open! Core open! Bonsai_web open! Bonsai.Let_syntax (** This control is similar to the typeahead control, differing in the fact that it doesn't aim to complete your input. Think of this control as a multi-select that you're free to add random values to. *) let input ~placeholder:placeholder_ ~value:value_ ~extra_attr ~id:id_ ~on_input:on_input_ = Vdom.Node.input ~attr: Vdom.Attr.( extra_attr @ type_ "text" @ create "list" id_ @ placeholder placeholder_ Both Attr.value and Attr.string_property value must be set . The former only affects initial control state while the latter affects the control state whilst the form is being used . initial control state while the latter affects the control state whilst the form is being used. *) @ value value_ @ value_prop value_ @ on_change (fun _ input -> on_input_ input)) () ;; let pills ~selected_options ~on_set_change ~inject_selected_options = let pill option = let remove_option _ = let selected_options = Set.remove selected_options option in Effect.Many [ on_set_change selected_options; inject_selected_options selected_options ] in Vdom.Node.span ~attr: Vdom.Attr.( tabindex 0 @ create "data-value" option @ on_click remove_option @ on_keyup (fun ev -> match Js_of_ocaml.Dom_html.Keyboard_code.of_event ev with | Space | Enter | NumpadEnter | Backspace | Delete -> remove_option ev | _ -> Effect.Ignore)) [ Vdom.Node.text (option ^ " ×") ] in if Set.is_empty selected_options then Vdom.Node.none else Vdom.Node.div ~attr:(Vdom.Attr.class_ "bonsai-web-ui-freeform-multiselect-pills") (Set.to_list selected_options |> List.map ~f:pill) ;; let input ~placeholder ~extra_attr ~split ~id ~selected_options ~on_set_change = (* This state is held internally to force the typeahead to clear the text contents of the input field when an option is selected. *) let%sub select = Bonsai.state (module String) ~default_model:"" in let%arr select, inject_select = select and selected_options, inject_selected_options = selected_options and extra_attr = extra_attr and id = id and on_set_change = on_set_change in let on_input user_input = let maybe_changed_options = split user_input |> String.Set.of_list |> Set.filter ~f:(fun item -> not (String.strip item |> String.is_empty)) |> Set.union selected_options in let ui_events = if Set.equal maybe_changed_options selected_options then [ inject_select user_input ] else [ inject_select ""; on_set_change maybe_changed_options ] in Effect.Many (inject_selected_options maybe_changed_options :: ui_events) in input ~extra_attr ~value:select ~placeholder ~id ~on_input ;; let create ?(extra_attr = Value.return Vdom.Attr.empty) ?(placeholder = "") ?(on_set_change = Value.return (const Effect.Ignore)) ?(split = List.return) () = let%sub selected_options = Bonsai.state (module String.Set) ~default_model:String.Set.empty in let%sub id = Bonsai.path_id in let%sub input = input ~placeholder ~extra_attr ~id ~on_set_change ~split ~selected_options in let%arr selected_options, inject_selected_options = selected_options and input = input and on_set_change = on_set_change in let pills = pills ~selected_options ~on_set_change ~inject_selected_options in selected_options, Vdom.Node.div [ input; pills ], inject_selected_options ;;
null
https://raw.githubusercontent.com/janestreet/bonsai/33e9a58fc55ec12095959dc5ef4fd681021c1083/web_ui/freeform_multiselect/src/freeform_multiselect.ml
ocaml
* This control is similar to the typeahead control, differing in the fact that it doesn't aim to complete your input. Think of this control as a multi-select that you're free to add random values to. This state is held internally to force the typeahead to clear the text contents of the input field when an option is selected.
open! Core open! Bonsai_web open! Bonsai.Let_syntax let input ~placeholder:placeholder_ ~value:value_ ~extra_attr ~id:id_ ~on_input:on_input_ = Vdom.Node.input ~attr: Vdom.Attr.( extra_attr @ type_ "text" @ create "list" id_ @ placeholder placeholder_ Both Attr.value and Attr.string_property value must be set . The former only affects initial control state while the latter affects the control state whilst the form is being used . initial control state while the latter affects the control state whilst the form is being used. *) @ value value_ @ value_prop value_ @ on_change (fun _ input -> on_input_ input)) () ;; let pills ~selected_options ~on_set_change ~inject_selected_options = let pill option = let remove_option _ = let selected_options = Set.remove selected_options option in Effect.Many [ on_set_change selected_options; inject_selected_options selected_options ] in Vdom.Node.span ~attr: Vdom.Attr.( tabindex 0 @ create "data-value" option @ on_click remove_option @ on_keyup (fun ev -> match Js_of_ocaml.Dom_html.Keyboard_code.of_event ev with | Space | Enter | NumpadEnter | Backspace | Delete -> remove_option ev | _ -> Effect.Ignore)) [ Vdom.Node.text (option ^ " ×") ] in if Set.is_empty selected_options then Vdom.Node.none else Vdom.Node.div ~attr:(Vdom.Attr.class_ "bonsai-web-ui-freeform-multiselect-pills") (Set.to_list selected_options |> List.map ~f:pill) ;; let input ~placeholder ~extra_attr ~split ~id ~selected_options ~on_set_change = let%sub select = Bonsai.state (module String) ~default_model:"" in let%arr select, inject_select = select and selected_options, inject_selected_options = selected_options and extra_attr = extra_attr and id = id and on_set_change = on_set_change in let on_input user_input = let maybe_changed_options = split user_input |> String.Set.of_list |> Set.filter ~f:(fun item -> not (String.strip item |> String.is_empty)) |> Set.union selected_options in let ui_events = if Set.equal maybe_changed_options selected_options then [ inject_select user_input ] else [ inject_select ""; on_set_change maybe_changed_options ] in Effect.Many (inject_selected_options maybe_changed_options :: ui_events) in input ~extra_attr ~value:select ~placeholder ~id ~on_input ;; let create ?(extra_attr = Value.return Vdom.Attr.empty) ?(placeholder = "") ?(on_set_change = Value.return (const Effect.Ignore)) ?(split = List.return) () = let%sub selected_options = Bonsai.state (module String.Set) ~default_model:String.Set.empty in let%sub id = Bonsai.path_id in let%sub input = input ~placeholder ~extra_attr ~id ~on_set_change ~split ~selected_options in let%arr selected_options, inject_selected_options = selected_options and input = input and on_set_change = on_set_change in let pills = pills ~selected_options ~on_set_change ~inject_selected_options in selected_options, Vdom.Node.div [ input; pills ], inject_selected_options ;;
ed144ebf5a1f8e63e95d77aa067229cf54ad0359702a826680e6230ffadf57ba
cram2/cram
designator-utils.lisp
;;; Copyright ( c ) 2012 , < > ;;; All rights reserved. ;;; ;;; Redistribution and use in source and binary forms, with or without ;;; modification, are permitted provided that the following conditions are met: ;;; ;;; * Redistributions of source code must retain the above copyright ;;; notice, this list of conditions and the following disclaimer. ;;; * Redistributions in binary form must reproduce the above copyright ;;; notice, this list of conditions and the following disclaimer in the ;;; documentation and/or other materials provided with the distribution. * Neither the name of Willow Garage , Inc. nor the names of its ;;; contributors may be used to endorse or promote products derived from ;;; this software without specific prior written permission. ;;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS " ;;; AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT OWNER OR LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR ;;; CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF ;;; SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN ;;; CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ;;; ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE ;;; POSSIBILITY OF SUCH DAMAGE. ;;; (in-package :cram-robot-interfaces) (defgeneric compute-iks (pose-stamped &key link-name arm robot-state seed-state pose-stamped-frame tcp-in-ee-pose) (:documentation "Computes an inverse kinematics solution (if possible) to position the link `link-name' in the goal pose `pose-stamped' specified in the frame of the pose or `pose-stamped-frame' when given, where only the links in `arm' can be moved to achieve the solution. When given, `robot-state' is the initial pose of robot joints, otherwise TF data is used. `seed-state' is the seed for the solver. When `tcp-in-ee-pose' (i.e. pose of tool center point in end effector frame) is given the goal pose is automatically transformed to take it into account. Returns a ROS JointState message with solution states of the joints in the `arm'.")) (def-fact-group reachability-designators () (<- (reachability-designator ?designator) (desig-prop ?designator (:reachable-for ?robot)) ;; (robot ?robot) ) (<- (visibility-designator ?designator) (desig-prop ?designator (:visible-for ?robot)) ;; (robot ?robot) ) (<- (designator-reach-pose ?designator ?pose ?side) (reachability-designator ?designator) (desig-prop ?designator (:pose ?pose)) (once (-> (desig-prop ?designator (:arm ?side)) (true) (and (robot ?robot) (arm ?robot ?side))))) (<- (designator-reach-pose ?designator ?point ?side) (reachability-designator ?designator) (or (desig-prop ?designator (:object ?object)) (desig-prop ?designator (:obj ?object))) (desig-location-prop ?object ?pose) (once (-> (desig-prop ?designator (:arm ?side)) (true) (and (robot ?robot) (arm ?robot ?side)))) (lisp-fun cl-transforms:origin ?pose ?point)) (<- (designator-reach-pose ?designator ?pose ?side) (reachability-designator ?designator) (desig-prop ?designator (:location ?location)) (once (-> (desig-prop ?designator (:arm ?side)) (true) (and (robot ?robot) (arm ?robot ?side)))) (desig-location-prop ?designator ?pose)) ;; (<- (designator-reach-pose ?designator ?robot-pose ?pose ?side) ;; (reachability-designator ?designator) ;; (desig-prop ?designator (:to :execute)) ;; (desig-prop ?designator (:action ?action)) ;; (trajectory-point ?action ?robot-pose ?pose ?side)) ;; (<- (designator-reach-pose ?designator ?pose ?side) ;; (reachability-designator ?designator) ;; (desig-prop ?designator (:to :execute)) ;; (desig-prop ?designator (:action ?action)) ;; (trajectory-point ?action ?pose ?side)) ) (defun reachability-designator-p (designator) (prolog `(reachability-designator ,designator))) (defun visibility-designator-p (designator) (prolog `(visibility-designator ,designator))) (def-fact-group manipulation-designators () (<- (trajectory-desig? ?desig) (lisp-pred typep ?desig action-designator) (desig-prop ?desig (:type :trajectory))) (<- (constraints-desig? ?desig) (lisp-pred typep ?desig action-designator) (desig-prop ?desig (:type :constraints))))
null
https://raw.githubusercontent.com/cram2/cram/dcb73031ee944d04215bbff9e98b9e8c210ef6c5/cram_common/cram_robot_interfaces/src/designator-utils.lisp
lisp
All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. contributors may be used to endorse or promote products derived from this software without specific prior written permission. AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. (robot ?robot) (robot ?robot) (<- (designator-reach-pose ?designator ?robot-pose ?pose ?side) (reachability-designator ?designator) (desig-prop ?designator (:to :execute)) (desig-prop ?designator (:action ?action)) (trajectory-point ?action ?robot-pose ?pose ?side)) (<- (designator-reach-pose ?designator ?pose ?side) (reachability-designator ?designator) (desig-prop ?designator (:to :execute)) (desig-prop ?designator (:action ?action)) (trajectory-point ?action ?pose ?side))
Copyright ( c ) 2012 , < > * Neither the name of Willow Garage , Inc. nor the names of its THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS " IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT OWNER OR LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN (in-package :cram-robot-interfaces) (defgeneric compute-iks (pose-stamped &key link-name arm robot-state seed-state pose-stamped-frame tcp-in-ee-pose) (:documentation "Computes an inverse kinematics solution (if possible) to position the link `link-name' in the goal pose `pose-stamped' specified in the frame of the pose or `pose-stamped-frame' when given, where only the links in `arm' can be moved to achieve the solution. When given, `robot-state' is the initial pose of robot joints, otherwise TF data is used. `seed-state' is the seed for the solver. When `tcp-in-ee-pose' (i.e. pose of tool center point in end effector frame) is given the goal pose is automatically transformed to take it into account. Returns a ROS JointState message with solution states of the joints in the `arm'.")) (def-fact-group reachability-designators () (<- (reachability-designator ?designator) (desig-prop ?designator (:reachable-for ?robot)) ) (<- (visibility-designator ?designator) (desig-prop ?designator (:visible-for ?robot)) ) (<- (designator-reach-pose ?designator ?pose ?side) (reachability-designator ?designator) (desig-prop ?designator (:pose ?pose)) (once (-> (desig-prop ?designator (:arm ?side)) (true) (and (robot ?robot) (arm ?robot ?side))))) (<- (designator-reach-pose ?designator ?point ?side) (reachability-designator ?designator) (or (desig-prop ?designator (:object ?object)) (desig-prop ?designator (:obj ?object))) (desig-location-prop ?object ?pose) (once (-> (desig-prop ?designator (:arm ?side)) (true) (and (robot ?robot) (arm ?robot ?side)))) (lisp-fun cl-transforms:origin ?pose ?point)) (<- (designator-reach-pose ?designator ?pose ?side) (reachability-designator ?designator) (desig-prop ?designator (:location ?location)) (once (-> (desig-prop ?designator (:arm ?side)) (true) (and (robot ?robot) (arm ?robot ?side)))) (desig-location-prop ?designator ?pose)) ) (defun reachability-designator-p (designator) (prolog `(reachability-designator ,designator))) (defun visibility-designator-p (designator) (prolog `(visibility-designator ,designator))) (def-fact-group manipulation-designators () (<- (trajectory-desig? ?desig) (lisp-pred typep ?desig action-designator) (desig-prop ?desig (:type :trajectory))) (<- (constraints-desig? ?desig) (lisp-pred typep ?desig action-designator) (desig-prop ?desig (:type :constraints))))
9aa5f2c13adaf0631f6a59551797d1ffc4687070990e55065cc11b388c709f38
mrijkeboer/euuid
euuid.erl
%% ------------------------------------------------------------------- %% euuid.erl - Erlang UUID API module %% @author < > 2010 %% @version {@vsn}, {@date}, {@time} @doc Erlang UUID API module . %% @end %% The MIT license . %% Copyright ( c ) 2010 %% %% 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. %% %% ------------------------------------------------------------------- -module(euuid). -author('Martijn Rijkeboer <>'). %% API -export([start/0, stop/0]). -export([format/1]). -export([md5/2, v3/2]). -export([random/0, v4/0]). -export([sha1/2, v5/2]). -export([time_custom/0]). -export([time_mac/0, v1/0]). -export([nil/0, ns_dns/0, ns_url/0, ns_oid/0, ns_x500/0]). %%==================================================================== %% API %%==================================================================== %% ------------------------------------------------------------------- @spec start ( ) - > %% ok | %% {error, Reason} @doc Start the Erlang UUID application . %% @end %% ------------------------------------------------------------------- start() -> application:start(euuid). %% ------------------------------------------------------------------- stop ( ) - > %% ok | %% {error, Reason} @doc Stop the Erlang UUID application . %% @end %% ------------------------------------------------------------------- stop() -> application:stop(euuid). %% ------------------------------------------------------------------- %% @spec time_mac() -> %% UUID @doc Get a new time and MAC based UUID ( RFC4122 Version 1 ) . %% @end %% ------------------------------------------------------------------- time_mac() -> euuid_server:time_mac(). %% ------------------------------------------------------------------- , Name ) - > %% UUID @doc Get a new MD5 name based UUID ( RFC4122 Version 3 ) . %% @end %% ------------------------------------------------------------------- md5(NsUUID, Name) -> euuid_server:md5(NsUUID, Name). %% ------------------------------------------------------------------- random ( ) - > %% UUID @doc Get a new ( pseudo ) random UUID ( RFC4122 Version 4 ) . %% @end %% ------------------------------------------------------------------- random() -> euuid_server:random(). %% ------------------------------------------------------------------- , Name ) - > %% UUID @doc Get a new SHA1 name based UUID ( RFC4122 Version 5 ) . %% @end %% ------------------------------------------------------------------- sha1(NsUUID, Name) -> euuid_server:sha1(NsUUID, Name). %% ------------------------------------------------------------------- time_custom ( ) - > %% UUID @doc Get a new time and MAC based UUID with modified timestamp layout to allow sorting on the UUID 's date of creation . %% @end %% ------------------------------------------------------------------- time_custom() -> euuid_server:time_custom(). %% ------------------------------------------------------------------- %% @spec v1() -> %% UUID @doc Get a new time and MAC based UUID ( RFC4122 Version 1 ) . %% @end %% ------------------------------------------------------------------- v1() -> euuid_server:time_mac(). %% ------------------------------------------------------------------- @spec v3(NsUUID , Name ) - > %% UUID @doc Get a new MD5 name based UUID ( RFC4122 Version 3 ) . %% @end %% ------------------------------------------------------------------- v3(NsUUID, Name) -> euuid_server:md5(NsUUID, Name). %% ------------------------------------------------------------------- %% @spec v4() -> %% UUID @doc Get a new ( pseudo ) random UUID ( RFC4122 Version 4 ) . %% @end %% ------------------------------------------------------------------- v4() -> euuid_server:random(). %% ------------------------------------------------------------------- @spec v5(NsUUID , Name ) - > %% UUID @doc Get a new SHA1 name based UUID ( RFC4122 Version 5 ) . %% @end %% ------------------------------------------------------------------- v5(NsUUID, Name) -> euuid_server:sha1(NsUUID, Name). %% ------------------------------------------------------------------- %% @spec format(UUID) -> UuidStr @doc Format the UUID into string representation . %% @end %% ------------------------------------------------------------------- format(UUID) -> Str = io_lib:format("~8.16.0b-~4.16.0b-~4.16.0b-~2.16.0b~2.16.0b-~12.16.0b", euuid_util:unpack(<<UUID:128>>)), lists:flatten(Str). %% ------------------------------------------------------------------- %% @spec nil() -> %% UUID %% @doc Get the RFC4122 nil UUID. %% @end %% ------------------------------------------------------------------- nil() -> 0. %% ------------------------------------------------------------------- ns_dns ( ) - > %% UUID @doc Get the RFC4122 DNS namespace UUID . %% @end %% ------------------------------------------------------------------- ns_dns() -> 16#6ba7b8109dad11d180b400c04fd430c8. %% ------------------------------------------------------------------- @spec ns_url ( ) - > %% UUID @doc Get the RFC4122 URL namespace UUID . %% @end %% ------------------------------------------------------------------- ns_url() -> 16#6ba7b8119dad11d180b400c04fd430c8. %% ------------------------------------------------------------------- %% @spec ns_oid() -> %% UUID @doc Get the RFC4122 OID namespace UUID . %% @end %% ------------------------------------------------------------------- ns_oid() -> 16#6ba7b8129dad11d180b400c04fd430c8. %% ------------------------------------------------------------------- %% @spec ns_x500() -> %% UUID @doc Get the RFC4122 X500 namespace UUID . %% @end %% ------------------------------------------------------------------- ns_x500() -> 16#6ba7b8149dad11d180b400c04fd430c8.
null
https://raw.githubusercontent.com/mrijkeboer/euuid/f9d435128d7840d55a7b504ab82f5033c381833f/src/euuid.erl
erlang
------------------------------------------------------------------- euuid.erl - Erlang UUID API module @version {@vsn}, {@date}, {@time} @end Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to rights to use, copy, modify, merge, publish, distribute, sublicense, and/or furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ------------------------------------------------------------------- API ==================================================================== API ==================================================================== ------------------------------------------------------------------- ok | {error, Reason} @end ------------------------------------------------------------------- ------------------------------------------------------------------- ok | {error, Reason} @end ------------------------------------------------------------------- ------------------------------------------------------------------- @spec time_mac() -> UUID @end ------------------------------------------------------------------- ------------------------------------------------------------------- UUID @end ------------------------------------------------------------------- ------------------------------------------------------------------- UUID @end ------------------------------------------------------------------- ------------------------------------------------------------------- UUID @end ------------------------------------------------------------------- ------------------------------------------------------------------- UUID @end ------------------------------------------------------------------- ------------------------------------------------------------------- @spec v1() -> UUID @end ------------------------------------------------------------------- ------------------------------------------------------------------- UUID @end ------------------------------------------------------------------- ------------------------------------------------------------------- @spec v4() -> UUID @end ------------------------------------------------------------------- ------------------------------------------------------------------- UUID @end ------------------------------------------------------------------- ------------------------------------------------------------------- @spec format(UUID) -> @end ------------------------------------------------------------------- ------------------------------------------------------------------- @spec nil() -> UUID @doc Get the RFC4122 nil UUID. @end ------------------------------------------------------------------- ------------------------------------------------------------------- UUID @end ------------------------------------------------------------------- ------------------------------------------------------------------- UUID @end ------------------------------------------------------------------- ------------------------------------------------------------------- @spec ns_oid() -> UUID @end ------------------------------------------------------------------- ------------------------------------------------------------------- @spec ns_x500() -> UUID @end -------------------------------------------------------------------
@author < > 2010 @doc Erlang UUID API module . The MIT license . Copyright ( c ) 2010 deal in the Software without restriction , including without limitation the sell copies of the Software , and to permit persons to whom the Software is all copies or substantial portions of the Software . THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING -module(euuid). -author('Martijn Rijkeboer <>'). -export([start/0, stop/0]). -export([format/1]). -export([md5/2, v3/2]). -export([random/0, v4/0]). -export([sha1/2, v5/2]). -export([time_custom/0]). -export([time_mac/0, v1/0]). -export([nil/0, ns_dns/0, ns_url/0, ns_oid/0, ns_x500/0]). @spec start ( ) - > @doc Start the Erlang UUID application . start() -> application:start(euuid). stop ( ) - > @doc Stop the Erlang UUID application . stop() -> application:stop(euuid). @doc Get a new time and MAC based UUID ( RFC4122 Version 1 ) . time_mac() -> euuid_server:time_mac(). , Name ) - > @doc Get a new MD5 name based UUID ( RFC4122 Version 3 ) . md5(NsUUID, Name) -> euuid_server:md5(NsUUID, Name). random ( ) - > @doc Get a new ( pseudo ) random UUID ( RFC4122 Version 4 ) . random() -> euuid_server:random(). , Name ) - > @doc Get a new SHA1 name based UUID ( RFC4122 Version 5 ) . sha1(NsUUID, Name) -> euuid_server:sha1(NsUUID, Name). time_custom ( ) - > @doc Get a new time and MAC based UUID with modified timestamp layout to allow sorting on the UUID 's date of creation . time_custom() -> euuid_server:time_custom(). @doc Get a new time and MAC based UUID ( RFC4122 Version 1 ) . v1() -> euuid_server:time_mac(). @spec v3(NsUUID , Name ) - > @doc Get a new MD5 name based UUID ( RFC4122 Version 3 ) . v3(NsUUID, Name) -> euuid_server:md5(NsUUID, Name). @doc Get a new ( pseudo ) random UUID ( RFC4122 Version 4 ) . v4() -> euuid_server:random(). @spec v5(NsUUID , Name ) - > @doc Get a new SHA1 name based UUID ( RFC4122 Version 5 ) . v5(NsUUID, Name) -> euuid_server:sha1(NsUUID, Name). UuidStr @doc Format the UUID into string representation . format(UUID) -> Str = io_lib:format("~8.16.0b-~4.16.0b-~4.16.0b-~2.16.0b~2.16.0b-~12.16.0b", euuid_util:unpack(<<UUID:128>>)), lists:flatten(Str). nil() -> 0. ns_dns ( ) - > @doc Get the RFC4122 DNS namespace UUID . ns_dns() -> 16#6ba7b8109dad11d180b400c04fd430c8. @spec ns_url ( ) - > @doc Get the RFC4122 URL namespace UUID . ns_url() -> 16#6ba7b8119dad11d180b400c04fd430c8. @doc Get the RFC4122 OID namespace UUID . ns_oid() -> 16#6ba7b8129dad11d180b400c04fd430c8. @doc Get the RFC4122 X500 namespace UUID . ns_x500() -> 16#6ba7b8149dad11d180b400c04fd430c8.
77480115bcfe1cf79ddfbaa4b5f60ee505702687e6ce74208dd64ad6efe331cd
ctford/Idris-Elba-Dev
Transforms.hs
# LANGUAGE PatternGuards # module Idris.Transforms where import Idris.AbsSyntax import Idris.Core.CaseTree import Idris.Core.TT data TTOpt = TermTrans (TT Name -> TT Name) -- term transform | CaseTrans (SC -> SC) -- case expression transform class Transform a where transform :: TTOpt -> a -> a instance Transform (TT Name) where transform o@(TermTrans t) tm = trans t tm where trans t (Bind n b tm) = t $ Bind n (transform o b) (trans t tm) trans t (App f a) = t $ App (trans t f) (trans t a) trans t tm = t tm transform _ tm = tm instance Transform a => Transform (Binder a) where transform t (Let ty v) = Let (transform t ty) (transform t v) transform t b = b { binderTy = transform t (binderTy b) } instance Transform SC where transform o@(CaseTrans t) sc = trans t sc where trans t (Case n alts) = t (Case n (map (transform o) alts)) trans t x = t x transform o@(TermTrans t) sc = trans t sc where trans t (Case n alts) = Case n (map (transform o) alts) trans t (STerm tm) = STerm (t tm) trans t x = x instance Transform CaseAlt where transform o (ConCase n i ns sc) = ConCase n i ns (transform o sc) transform o (ConstCase c sc) = ConstCase c (transform o sc) transform o (DefaultCase sc) = DefaultCase (transform o sc) natTrans = [TermTrans zero, TermTrans suc, CaseTrans natcase] zname = sNS (sUN "Z") ["Nat","Prelude"] sname = sNS (sUN "S") ["Nat","Prelude"] zero :: TT Name -> TT Name zero (P _ n _) | n == zname = Constant (BI 0) zero x = x suc :: TT Name -> TT Name suc (App (P _ s _) a) | s == sname = mkApp (P Ref (sUN "prim__addBigInt") Erased) [Constant (BI 1), a] suc x = x natcase :: SC -> SC natcase = undefined
null
https://raw.githubusercontent.com/ctford/Idris-Elba-Dev/e915e1d6b7a5921ba43d2572a9ad9b980619b8ee/src/Idris/Transforms.hs
haskell
term transform case expression transform
# LANGUAGE PatternGuards # module Idris.Transforms where import Idris.AbsSyntax import Idris.Core.CaseTree import Idris.Core.TT class Transform a where transform :: TTOpt -> a -> a instance Transform (TT Name) where transform o@(TermTrans t) tm = trans t tm where trans t (Bind n b tm) = t $ Bind n (transform o b) (trans t tm) trans t (App f a) = t $ App (trans t f) (trans t a) trans t tm = t tm transform _ tm = tm instance Transform a => Transform (Binder a) where transform t (Let ty v) = Let (transform t ty) (transform t v) transform t b = b { binderTy = transform t (binderTy b) } instance Transform SC where transform o@(CaseTrans t) sc = trans t sc where trans t (Case n alts) = t (Case n (map (transform o) alts)) trans t x = t x transform o@(TermTrans t) sc = trans t sc where trans t (Case n alts) = Case n (map (transform o) alts) trans t (STerm tm) = STerm (t tm) trans t x = x instance Transform CaseAlt where transform o (ConCase n i ns sc) = ConCase n i ns (transform o sc) transform o (ConstCase c sc) = ConstCase c (transform o sc) transform o (DefaultCase sc) = DefaultCase (transform o sc) natTrans = [TermTrans zero, TermTrans suc, CaseTrans natcase] zname = sNS (sUN "Z") ["Nat","Prelude"] sname = sNS (sUN "S") ["Nat","Prelude"] zero :: TT Name -> TT Name zero (P _ n _) | n == zname = Constant (BI 0) zero x = x suc :: TT Name -> TT Name suc (App (P _ s _) a) | s == sname = mkApp (P Ref (sUN "prim__addBigInt") Erased) [Constant (BI 1), a] suc x = x natcase :: SC -> SC natcase = undefined
70ce0fbe234708813bf832c4d9812f607d0cd3f8f2e5ab3627e5ded3cc42c856
PrecursorApp/precursor
permissions.cljs
(ns frontend.components.permissions (:require [frontend.components.common :as common] [frontend.utils :as utils] [frontend.urls :as urls] [frontend.utils.date :refer (date->bucket)]) (:require-macros [sablono.core :refer (html)])) (defn format-access-date [date] (date->bucket date :sentence? true)) ;; TODO: add types to db (defn access-entity-type [access-entity] (cond (or (contains? access-entity :permission/document) (contains? access-entity :permission/team)) (cond (:permission/cust access-entity) :cust-permission (= :permission.reason/github-markdown (:permission/reason access-entity)) :github-readme-permission :else nil) (or (contains? access-entity :access-grant/document) (contains? access-entity :access-grant/team)) :access-grant (or (contains? access-entity :access-request/document) (contains? access-entity :access-request/team)) :access-request :else nil)) TODO : this should call / build somehow (defmulti render-access-entity (fn [entity cast!] (access-entity-type entity))) (defmethod render-access-entity :default [entity cast!] (utils/mlog "Unknown access entity" entity)) (defmethod render-access-entity :github-readme-permission [entity cast!] (html [:div.access-card.make {:key (:db/id entity)} [:div.access-avatar (common/icon :github)] [:div.access-details [:a {:role "button" :href (urls/overlay-path {:db/id (:permission/document entity)} "export") :onClick #(cast! :github-readme-permission-clicked)} [:span {:title "This permission allows read-only access, so that you can embed the doc in a GitHub issue or README."} "GitHub image token"]] [:span.access-status (str "Was created " (format-access-date (:permission/grant-date entity)))]]])) (defmethod render-access-entity :cust-permission [entity cast!] (html [:div.access-card.make {:key (:db/id entity)} [:div.access-avatar [:img.access-avatar-img {:src (utils/gravatar-url (:permission/cust entity))}]] [:div.access-details [:span {:title (:permission/cust entity)} (:permission/cust entity)] [:span.access-status (str "Was granted access " (format-access-date (:permission/grant-date entity)))]]])) (defmethod render-access-entity :access-grant [entity cast!] (html [:div.access-card.make {:key (:db/id entity)} [:div.access-avatar [:img.access-avatar-img {:src (utils/gravatar-url (:access-grant/email entity))}]] [:div.access-details [:span {:title (:access-grant/email entity)} (:access-grant/email entity)] [:span.access-status (str "Was granted access " (format-access-date (:access-grant/grant-date entity)))]]])) (defmethod render-access-entity :access-request [entity cast!] (html [:div.access-card.make {:key (:db/id entity) :class (if (= :access-request.status/denied (:access-request/status entity)) "denied" "requesting")} [:div.access-avatar [:img.access-avatar-img {:src (utils/gravatar-url (:access-request/cust entity))}]] [:div.access-details [:span {:title (:access-request/cust entity)} (:access-request/cust entity)] [:span.access-status (if (= :access-request.status/denied (:access-request/status entity)) (str "Was denied access " (format-access-date (:access-request/deny-date entity))) (str "Requested access " (format-access-date (:access-request/create-date entity))))]] [:div.access-options (when-not (= :access-request.status/denied (:access-request/status entity)) [:button.access-option {:role "button" :class "negative" :title "Decline" :on-click #(cast! :access-request-denied {:request-id (:db/id entity) :doc-id (:access-request/document entity) :team-uuid (:access-request/team entity)})} (common/icon :times)]) [:button.access-option {:role "button" :class "positive" :title "Approve" :on-click #(cast! :access-request-granted {:request-id (:db/id entity) :doc-id (:access-request/document entity) :team-uuid (:access-request/team entity)})} (common/icon :check)]]]))
null
https://raw.githubusercontent.com/PrecursorApp/precursor/30202e40365f6883c4767e423d6299f0d13dc528/src-cljs/frontend/components/permissions.cljs
clojure
TODO: add types to db
(ns frontend.components.permissions (:require [frontend.components.common :as common] [frontend.utils :as utils] [frontend.urls :as urls] [frontend.utils.date :refer (date->bucket)]) (:require-macros [sablono.core :refer (html)])) (defn format-access-date [date] (date->bucket date :sentence? true)) (defn access-entity-type [access-entity] (cond (or (contains? access-entity :permission/document) (contains? access-entity :permission/team)) (cond (:permission/cust access-entity) :cust-permission (= :permission.reason/github-markdown (:permission/reason access-entity)) :github-readme-permission :else nil) (or (contains? access-entity :access-grant/document) (contains? access-entity :access-grant/team)) :access-grant (or (contains? access-entity :access-request/document) (contains? access-entity :access-request/team)) :access-request :else nil)) TODO : this should call / build somehow (defmulti render-access-entity (fn [entity cast!] (access-entity-type entity))) (defmethod render-access-entity :default [entity cast!] (utils/mlog "Unknown access entity" entity)) (defmethod render-access-entity :github-readme-permission [entity cast!] (html [:div.access-card.make {:key (:db/id entity)} [:div.access-avatar (common/icon :github)] [:div.access-details [:a {:role "button" :href (urls/overlay-path {:db/id (:permission/document entity)} "export") :onClick #(cast! :github-readme-permission-clicked)} [:span {:title "This permission allows read-only access, so that you can embed the doc in a GitHub issue or README."} "GitHub image token"]] [:span.access-status (str "Was created " (format-access-date (:permission/grant-date entity)))]]])) (defmethod render-access-entity :cust-permission [entity cast!] (html [:div.access-card.make {:key (:db/id entity)} [:div.access-avatar [:img.access-avatar-img {:src (utils/gravatar-url (:permission/cust entity))}]] [:div.access-details [:span {:title (:permission/cust entity)} (:permission/cust entity)] [:span.access-status (str "Was granted access " (format-access-date (:permission/grant-date entity)))]]])) (defmethod render-access-entity :access-grant [entity cast!] (html [:div.access-card.make {:key (:db/id entity)} [:div.access-avatar [:img.access-avatar-img {:src (utils/gravatar-url (:access-grant/email entity))}]] [:div.access-details [:span {:title (:access-grant/email entity)} (:access-grant/email entity)] [:span.access-status (str "Was granted access " (format-access-date (:access-grant/grant-date entity)))]]])) (defmethod render-access-entity :access-request [entity cast!] (html [:div.access-card.make {:key (:db/id entity) :class (if (= :access-request.status/denied (:access-request/status entity)) "denied" "requesting")} [:div.access-avatar [:img.access-avatar-img {:src (utils/gravatar-url (:access-request/cust entity))}]] [:div.access-details [:span {:title (:access-request/cust entity)} (:access-request/cust entity)] [:span.access-status (if (= :access-request.status/denied (:access-request/status entity)) (str "Was denied access " (format-access-date (:access-request/deny-date entity))) (str "Requested access " (format-access-date (:access-request/create-date entity))))]] [:div.access-options (when-not (= :access-request.status/denied (:access-request/status entity)) [:button.access-option {:role "button" :class "negative" :title "Decline" :on-click #(cast! :access-request-denied {:request-id (:db/id entity) :doc-id (:access-request/document entity) :team-uuid (:access-request/team entity)})} (common/icon :times)]) [:button.access-option {:role "button" :class "positive" :title "Approve" :on-click #(cast! :access-request-granted {:request-id (:db/id entity) :doc-id (:access-request/document entity) :team-uuid (:access-request/team entity)})} (common/icon :check)]]]))
892406818e538dfa487051956164e5f96e9c1c0f59d82a924770113359c06749
kallisti-dev/hs-webdriver
Extension.hs
# LANGUAGE GeneralizedNewtypeDeriving , FlexibleContexts # |Functions and types for working with Google Chrome extensions . module Test.WebDriver.Chrome.Extension ( ChromeExtension , loadExtension , loadRawExtension ) where import Data.ByteString.Lazy as LBS import Data.ByteString.Base64.Lazy as B64 import Data.Text.Lazy import Data.Text.Lazy.Encoding (decodeLatin1) import Data.Aeson import Control.Applicative import Control.Monad.Base import Prelude -- hides some "unused import" warnings |An opaque type representing a Google Chrome extension . Values of this type -- are passed to the 'Test.Webdriver.chromeExtensions' field. newtype ChromeExtension = ChromeExtension Text deriving (Eq, Show, Read, ToJSON, FromJSON) -- |Load a .crx file as a 'ChromeExtension'. loadExtension :: MonadBase IO m => FilePath -> m ChromeExtension loadExtension path = liftBase $ loadRawExtension <$> LBS.readFile path -- |Load raw .crx data as a 'ChromeExtension'. loadRawExtension :: ByteString -> ChromeExtension loadRawExtension = ChromeExtension . decodeLatin1 . B64.encode
null
https://raw.githubusercontent.com/kallisti-dev/hs-webdriver/ea594ce8720c9e11f053b2567f250079f0eac33b/src/Test/WebDriver/Chrome/Extension.hs
haskell
hides some "unused import" warnings are passed to the 'Test.Webdriver.chromeExtensions' field. |Load a .crx file as a 'ChromeExtension'. |Load raw .crx data as a 'ChromeExtension'.
# LANGUAGE GeneralizedNewtypeDeriving , FlexibleContexts # |Functions and types for working with Google Chrome extensions . module Test.WebDriver.Chrome.Extension ( ChromeExtension , loadExtension , loadRawExtension ) where import Data.ByteString.Lazy as LBS import Data.ByteString.Base64.Lazy as B64 import Data.Text.Lazy import Data.Text.Lazy.Encoding (decodeLatin1) import Data.Aeson import Control.Applicative import Control.Monad.Base |An opaque type representing a Google Chrome extension . Values of this type newtype ChromeExtension = ChromeExtension Text deriving (Eq, Show, Read, ToJSON, FromJSON) loadExtension :: MonadBase IO m => FilePath -> m ChromeExtension loadExtension path = liftBase $ loadRawExtension <$> LBS.readFile path loadRawExtension :: ByteString -> ChromeExtension loadRawExtension = ChromeExtension . decodeLatin1 . B64.encode
bfdfd2c16cef0c0731da2d5c6ce78c73c11aae29b6b555de4549dce01234b48d
Erlang-Openid/erljwt
erljwt_sig.erl
-module(erljwt_sig). -include_lib("public_key/include/public_key.hrl"). -export([verify/4, create/3, algo_to_atom/1, algo_to_binary/1]). -define(ALGO_MAPPING, [ { none, <<"none">> , none, undefined}, { rs256, <<"RS256">>, sha256, undefined }, { rs384, <<"RS384">>, sha384, undefined }, { rs512, <<"RS512">>, sha512, undefined }, { es256, <<"ES256">>, sha256, secp256r1 }, { es384, <<"ES384">>, sha384, secp384r1 }, { es512, <<"ES512">>, sha512, secp521r1 }, { hs256, <<"HS256">>, sha256, undefined }, { hs384, <<"HS384">>, sha384, undefined }, { hs512, <<"HS512">>, sha512, undefined } ]). algo_to_atom(Name) -> handle_find_result(lists:keyfind(Name, 2, ?ALGO_MAPPING), 1). algo_to_binary(Atom) -> handle_find_result(lists:keyfind(Atom, 1, ?ALGO_MAPPING), 2). verify(EncSignature, Algo, Payload, #{kty := <<"RSA">>, n := N, e:= E}) when Algo == rs256; Algo == rs384; Algo == rs512-> Signature = erljwt_util:safe_base64_decode(EncSignature), Hash = algo_to_hash(Algo), crypto:verify(rsa, Hash, Payload, Signature, [erljwt_util:base64_to_unsiged(E), erljwt_util:base64_to_unsiged(N)]); verify(EncSignature, Algo, Payload, #{kty := <<"EC">>, x := X0, y := Y0}) when Algo == es256; Algo == es384; Algo == es512-> Signature = erljwt_util:safe_base64_decode(EncSignature), X = erljwt_util:safe_base64_decode(X0), Y = erljwt_util:safe_base64_decode(Y0), Key = <<4:8, X/binary, Y/binary >>, Curve = algo_to_curve(Algo), {R, S} = ec_get_r_s(Signature, Algo), SigValue = #'ECDSA-Sig-Value'{r = binary:decode_unsigned(R), s = binary:decode_unsigned(S)}, Asn1Sig = public_key:der_encode('ECDSA-Sig-Value', SigValue), crypto:verify(ecdsa, algo_to_hash(Algo), Payload, Asn1Sig, [Key, Curve]); verify(Signature, Algo, Payload, SharedKey) when Algo == hs256; Algo == hs384; Algo == hs512 -> Signature =:= create(Algo, Payload, SharedKey); verify(Signature, none, _Payload, _Key) -> Signature =:= <<"">>; verify(_Signature, _Algo, _Payload, Error) when is_atom(Error) -> Error; verify(_Signature, _Algo, _Payload, _Key) -> invalid. -ifdef(OTP_RELEASE). -if(?OTP_RELEASE >= 23). hmac(Algo, Key, Payload) -> crypto:mac(hmac, algo_to_hash(Algo), convert_key(Key), Payload). -else. hmac(Algo, Key, Payload) -> crypto:hmac(algo_to_hash(Algo), convert_key(Key), Payload). -endif. -else. hmac(Algo, Key, Payload) -> crypto:hmac(algo_to_hash(Algo), convert_key(Key), Payload). -endif. create(Algo, Payload, Key) when Algo == rs256; Algo == rs384; Algo == rs512 -> base64url:encode(crypto:sign(rsa, algo_to_hash(Algo), Payload, convert_key(Key))); create(Algo, Payload, Key) when Algo == es256; Algo == es384; Algo == es512 -> Asn1Sig = crypto:sign(ecdsa, algo_to_hash(Algo), Payload, [convert_key(Key), algo_to_curve(Algo)]), #'ECDSA-Sig-Value'{r = R, s = S} = public_key:der_decode('ECDSA-Sig-Value', Asn1Sig), base64url:encode(ec_signature(R, S, Algo)); create(Algo, Payload, Key) when Algo == hs256; Algo == hs384; Algo == hs512 -> base64url:encode(hmac(Algo, Key, Payload)); create(none, _Payload, _Key) -> <<"">>; create(_, _, _) -> alg_not_supported. ec_get_r_s(<<R:32/binary, S:32/binary>>, es256) -> {R, S}; ec_get_r_s(<<R:48/binary, S:48/binary>>, es384) -> {R, S}; ec_get_r_s(<<R:66/binary, S:66/binary>>, es512) -> {R, S}. ec_signature(R, S, es256) -> <<R:256, S:256>>; ec_signature(R, S, es384) -> <<R:384, S:384>>; ec_signature(R, S, es512) -> <<0:7, R:521, 0:7, S:521>>. algo_to_hash(Atom) -> handle_find_result(lists:keyfind(Atom, 1, ?ALGO_MAPPING), 3). algo_to_curve(Atom) -> handle_find_result(lists:keyfind(Atom, 1, ?ALGO_MAPPING), 4). handle_find_result(false, _) -> unknown; handle_find_result(Term, Index) -> element(Index, Term). convert_key(#{kty := <<"oct">>, k := Key}) -> Key; convert_key(#{kty := <<"RSA">>, n := N, e := E, d := D }) -> [erljwt_util:base64_to_unsiged(E), erljwt_util:base64_to_unsiged(N), erljwt_util:base64_to_unsiged(D)]; convert_key(#{kty := <<"EC">>, d := D}) -> erljwt_util:base64_to_unsiged(D).
null
https://raw.githubusercontent.com/Erlang-Openid/erljwt/d2baeecd49c3dd6e41b8511bbf7a35ec995f06cf/src/erljwt_sig.erl
erlang
-module(erljwt_sig). -include_lib("public_key/include/public_key.hrl"). -export([verify/4, create/3, algo_to_atom/1, algo_to_binary/1]). -define(ALGO_MAPPING, [ { none, <<"none">> , none, undefined}, { rs256, <<"RS256">>, sha256, undefined }, { rs384, <<"RS384">>, sha384, undefined }, { rs512, <<"RS512">>, sha512, undefined }, { es256, <<"ES256">>, sha256, secp256r1 }, { es384, <<"ES384">>, sha384, secp384r1 }, { es512, <<"ES512">>, sha512, secp521r1 }, { hs256, <<"HS256">>, sha256, undefined }, { hs384, <<"HS384">>, sha384, undefined }, { hs512, <<"HS512">>, sha512, undefined } ]). algo_to_atom(Name) -> handle_find_result(lists:keyfind(Name, 2, ?ALGO_MAPPING), 1). algo_to_binary(Atom) -> handle_find_result(lists:keyfind(Atom, 1, ?ALGO_MAPPING), 2). verify(EncSignature, Algo, Payload, #{kty := <<"RSA">>, n := N, e:= E}) when Algo == rs256; Algo == rs384; Algo == rs512-> Signature = erljwt_util:safe_base64_decode(EncSignature), Hash = algo_to_hash(Algo), crypto:verify(rsa, Hash, Payload, Signature, [erljwt_util:base64_to_unsiged(E), erljwt_util:base64_to_unsiged(N)]); verify(EncSignature, Algo, Payload, #{kty := <<"EC">>, x := X0, y := Y0}) when Algo == es256; Algo == es384; Algo == es512-> Signature = erljwt_util:safe_base64_decode(EncSignature), X = erljwt_util:safe_base64_decode(X0), Y = erljwt_util:safe_base64_decode(Y0), Key = <<4:8, X/binary, Y/binary >>, Curve = algo_to_curve(Algo), {R, S} = ec_get_r_s(Signature, Algo), SigValue = #'ECDSA-Sig-Value'{r = binary:decode_unsigned(R), s = binary:decode_unsigned(S)}, Asn1Sig = public_key:der_encode('ECDSA-Sig-Value', SigValue), crypto:verify(ecdsa, algo_to_hash(Algo), Payload, Asn1Sig, [Key, Curve]); verify(Signature, Algo, Payload, SharedKey) when Algo == hs256; Algo == hs384; Algo == hs512 -> Signature =:= create(Algo, Payload, SharedKey); verify(Signature, none, _Payload, _Key) -> Signature =:= <<"">>; verify(_Signature, _Algo, _Payload, Error) when is_atom(Error) -> Error; verify(_Signature, _Algo, _Payload, _Key) -> invalid. -ifdef(OTP_RELEASE). -if(?OTP_RELEASE >= 23). hmac(Algo, Key, Payload) -> crypto:mac(hmac, algo_to_hash(Algo), convert_key(Key), Payload). -else. hmac(Algo, Key, Payload) -> crypto:hmac(algo_to_hash(Algo), convert_key(Key), Payload). -endif. -else. hmac(Algo, Key, Payload) -> crypto:hmac(algo_to_hash(Algo), convert_key(Key), Payload). -endif. create(Algo, Payload, Key) when Algo == rs256; Algo == rs384; Algo == rs512 -> base64url:encode(crypto:sign(rsa, algo_to_hash(Algo), Payload, convert_key(Key))); create(Algo, Payload, Key) when Algo == es256; Algo == es384; Algo == es512 -> Asn1Sig = crypto:sign(ecdsa, algo_to_hash(Algo), Payload, [convert_key(Key), algo_to_curve(Algo)]), #'ECDSA-Sig-Value'{r = R, s = S} = public_key:der_decode('ECDSA-Sig-Value', Asn1Sig), base64url:encode(ec_signature(R, S, Algo)); create(Algo, Payload, Key) when Algo == hs256; Algo == hs384; Algo == hs512 -> base64url:encode(hmac(Algo, Key, Payload)); create(none, _Payload, _Key) -> <<"">>; create(_, _, _) -> alg_not_supported. ec_get_r_s(<<R:32/binary, S:32/binary>>, es256) -> {R, S}; ec_get_r_s(<<R:48/binary, S:48/binary>>, es384) -> {R, S}; ec_get_r_s(<<R:66/binary, S:66/binary>>, es512) -> {R, S}. ec_signature(R, S, es256) -> <<R:256, S:256>>; ec_signature(R, S, es384) -> <<R:384, S:384>>; ec_signature(R, S, es512) -> <<0:7, R:521, 0:7, S:521>>. algo_to_hash(Atom) -> handle_find_result(lists:keyfind(Atom, 1, ?ALGO_MAPPING), 3). algo_to_curve(Atom) -> handle_find_result(lists:keyfind(Atom, 1, ?ALGO_MAPPING), 4). handle_find_result(false, _) -> unknown; handle_find_result(Term, Index) -> element(Index, Term). convert_key(#{kty := <<"oct">>, k := Key}) -> Key; convert_key(#{kty := <<"RSA">>, n := N, e := E, d := D }) -> [erljwt_util:base64_to_unsiged(E), erljwt_util:base64_to_unsiged(N), erljwt_util:base64_to_unsiged(D)]; convert_key(#{kty := <<"EC">>, d := D}) -> erljwt_util:base64_to_unsiged(D).
80a84111ae57c354a7b47f59771685b2af737a9f895ed444ac2fc4ad42205989
coq/coq
topfmt.ml
(************************************************************************) (* * The Coq Proof Assistant / The Coq Development Team *) v * Copyright INRIA , CNRS and contributors < O _ _ _ , , * ( see version control and CREDITS file for authors & dates ) \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * (* // * This file is distributed under the terms of the *) * GNU Lesser General Public License Version 2.1 (* * (see LICENSE file for the text of the license) *) (************************************************************************) open Pp (** Pp control also belongs here as the terminal is private to the toplevel *) type pp_global_params = { margin : int; max_indent : int; max_depth : int; ellipsis : string } (* Default parameters of pretty-printing *) let dflt_gp = { margin = 78; max_indent = 50; max_depth = 50; ellipsis = "..." } (* A deeper pretty-printer to print proof scripts *) let deep_gp = { margin = 78; max_indent = 50; max_depth = 10000; ellipsis = "..." } (* set_gp : Format.formatter -> pp_global_params -> unit * set the parameters of a formatter *) let set_gp ft gp = Format.pp_set_margin ft gp.margin ; Format.pp_set_max_indent ft gp.max_indent ; Format.pp_set_max_boxes ft gp.max_depth ; Format.pp_set_ellipsis_text ft gp.ellipsis let set_dflt_gp ft = set_gp ft dflt_gp let get_gp ft = { margin = Format.pp_get_margin ft (); max_indent = Format.pp_get_max_indent ft (); max_depth = Format.pp_get_max_boxes ft (); ellipsis = Format.pp_get_ellipsis_text ft () } (* with_fp : 'a pp_formatter_params -> Format.formatter * returns of formatter for given formatter functions *) let with_fp chan out_function flush_function = let ft = Format.make_formatter out_function flush_function in Format.pp_set_formatter_out_channel ft chan; ft (* Output on a channel ch *) let with_output_to ch = let ft = with_fp ch (output_substring ch) (fun () -> flush ch) in set_gp ft deep_gp; ft let std_ft = ref Format.std_formatter let _ = set_dflt_gp !std_ft let err_ft = ref Format.err_formatter let _ = set_gp !err_ft deep_gp let deep_ft = ref (with_output_to stdout) let _ = set_gp !deep_ft deep_gp (* For parametrization through vernacular *) let default = Format.pp_get_max_boxes !std_ft () let default_margin = Format.pp_get_margin !std_ft () let get_depth_boxes () = Some (Format.pp_get_max_boxes !std_ft ()) let set_depth_boxes v = Format.pp_set_max_boxes !std_ft (match v with None -> default | Some v -> v) let get_margin () = Some (Format.pp_get_margin !std_ft ()) let set_margin v = let v = match v with None -> default_margin | Some v -> v in Format.pp_set_margin Format.str_formatter v; Format.pp_set_margin !std_ft v; Format.pp_set_margin !deep_ft v; Format.pp_set_margin !err_ft v; Heuristic , based on usage : the column on the right of max_indent column is 20 % of width , capped to 30 characters column is 20% of width, capped to 30 characters *) let m = max (64 * v / 100) (v-30) in Format.pp_set_max_indent Format.str_formatter m; Format.pp_set_max_indent !std_ft m; Format.pp_set_max_indent !deep_ft m; Format.pp_set_max_indent !err_ft m (** Console display of feedback *) (** Default tags *) module Tag = struct let error = "message.error" let warning = "message.warning" let debug = "message.debug" end let msgnl_with fmt strm = pp_with fmt (strm ++ fnl ()); Format.pp_print_flush fmt () module Emacs = struct (* Special chars for emacs, to detect warnings inside goal output *) let quote_warning_start = "<warning>" let quote_warning_end = "</warning>" let quote_info_start = "<infomsg>" let quote_info_end = "</infomsg>" let quote_emacs q_start q_end msg = hov 0 (seq [str q_start; brk(0,0); msg; brk(0,0); str q_end]) let quote_warning = quote_emacs quote_warning_start quote_warning_end let quote_info = quote_emacs quote_info_start quote_info_end end let dbg_hdr = tag Tag.debug (str "Debug:") ++ spc () let info_hdr = mt () let warn_hdr = tag Tag.warning (str "Warning:") ++ spc () let err_hdr = tag Tag.error (str "Error:") ++ spc () let make_body quoter info ?pre_hdr s = pr_opt_no_spc (fun x -> x ++ fnl ()) pre_hdr ++ quoter (hov 0 (info ++ s)) (* The empty quoter *) let noq x = x Generic logger let gen_logger dbg warn ?pre_hdr level msg = let open Feedback in match level with | Debug -> msgnl_with !std_ft (make_body dbg dbg_hdr ?pre_hdr msg) | Info -> msgnl_with !std_ft (make_body dbg info_hdr ?pre_hdr msg) | Notice -> msgnl_with !std_ft (make_body noq info_hdr ?pre_hdr msg) | Warning -> Flags.if_warn (fun () -> msgnl_with !err_ft (make_body warn warn_hdr ?pre_hdr msg)) () | Error -> msgnl_with !err_ft (make_body noq err_hdr ?pre_hdr msg) (** Standard loggers *) (* We provide a generic clear_log_backend callback for backends wanting to do cleanup after the print. *) let std_logger_cleanup = ref (fun () -> ()) let std_logger ?pre_hdr level msg = gen_logger (fun x -> x) (fun x -> x) ?pre_hdr level msg; !std_logger_cleanup () * Color logging . Moved from Ppstyle , it may need some more refactoring (* Tag map for terminal style *) let default_tag_map () = let open Terminal in [ (* Local to console toplevel *) "message.error" , make ~bold:true ~fg_color:`WHITE ~bg_color:`RED () ; "message.warning" , make ~bold:true ~fg_color:`WHITE ~bg_color:`YELLOW () ; "message.debug" , make ~bold:true ~fg_color:`WHITE ~bg_color:`MAGENTA () ; "message.prompt" , make ~fg_color:`GREEN () (* Coming from the printer *) ; "constr.evar" , make ~fg_color:`LIGHT_BLUE () ; "constr.keyword" , make ~bold:true () ; "constr.type" , make ~bold:true ~fg_color:`YELLOW () ; "constr.notation" , make ~fg_color:`WHITE () (* ["constr"; "variable"] is not assigned *) ; "constr.reference" , make ~fg_color:`LIGHT_GREEN () ; "constr.path" , make ~fg_color:`LIGHT_MAGENTA () ; "module.definition", make ~bold:true ~fg_color:`LIGHT_RED () ; "module.keyword" , make ~bold:true () ; "tactic.keyword" , make ~bold:true () ; "tactic.primitive" , make ~fg_color:`LIGHT_GREEN () ; "tactic.string" , make ~fg_color:`LIGHT_RED () ; "diff.added" , make ~bg_color:(`RGB(0,141,0)) ~underline:true () ; "diff.removed" , make ~bg_color:(`RGB(170,0,0)) ~underline:true () ; "diff.added.bg" , make ~bg_color:(`RGB(0,91,0)) () ; "diff.removed.bg" , make ~bg_color:(`RGB(91,0,0)) () ] let tag_map = ref CString.Map.empty let init_tag_map styles = let set accu (name, st) = CString.Map.add name st accu in tag_map := List.fold_left set !tag_map styles let default_styles () = init_tag_map (default_tag_map ()) let set_emacs_print_strings () = let open Terminal in let diff = "diff." in List.iter (fun b -> let (name, attrs) = b in if CString.is_sub diff name 0 then tag_map := CString.Map.add name { attrs with prefix = Some (Printf.sprintf "<%s>" name); suffix = Some (Printf.sprintf "</%s>" name) } !tag_map) (CString.Map.bindings !tag_map) let parse_color_config str = let styles = Terminal.parse str in init_tag_map styles let dump_tags () = CString.Map.bindings !tag_map let empty = Terminal.make () let default_style = Terminal.reset_style let get_style tag = try CString.Map.find tag !tag_map with Not_found -> empty;; let get_open_seq tags = let style = List.fold_left (fun a b -> Terminal.merge a (get_style b)) default_style tags in Terminal.eval (Terminal.diff default_style style);; let get_close_seq tags = let style = List.fold_left (fun a b -> Terminal.merge a (get_style b)) default_style tags in Terminal.eval (Terminal.diff style default_style);; let diff_tag_stack = ref [] (* global, just like std_ft *) (** Not thread-safe. We should put a lock somewhere if we print from different threads. Do we? *) let make_style_stack () = (* Default tag is to reset everything *) let style_stack = ref [] in let peek () = match !style_stack with | [] -> default_style (* Anomalous case, but for robustness *) | st :: _ -> st in let open_tag = function | Format.String_tag tag -> let (tpfx, ttag) = split_tag tag in if tpfx = end_pfx then "" else let style = get_style ttag in Merge the current settings and the style being pushed . This allows restoring the previous settings correctly in a pop when both set the same attribute . Example : current settings have red FG , the pushed style has green FG . When popping the style , we should set red FG , not default FG . allows restoring the previous settings correctly in a pop when both set the same attribute. Example: current settings have red FG, the pushed style has green FG. When popping the style, we should set red FG, not default FG. *) let style = Terminal.merge (peek ()) style in let diff = Terminal.diff (peek ()) style in style_stack := style :: !style_stack; if tpfx = start_pfx then diff_tag_stack := ttag :: !diff_tag_stack; Terminal.eval diff | _ -> Terminal.eval default_style in let close_tag = function | Format.String_tag tag -> let (tpfx, _) = split_tag tag in if tpfx = start_pfx then "" else begin if tpfx = end_pfx then diff_tag_stack := (try List.tl !diff_tag_stack with tl -> []); match !style_stack with | [] -> (* Something went wrong, we fallback *) Terminal.eval default_style | cur :: rem -> style_stack := rem; if cur = (peek ()) then "" else if rem = [] then Terminal.reset else Terminal.eval (Terminal.diff cur (peek ())) end | _ -> Terminal.eval default_style in let clear () = style_stack := [] in open_tag, close_tag, clear let make_printing_functions () = let print_prefix ft = function | Format.String_tag tag -> let (tpfx, ttag) = split_tag tag in if tpfx <> end_pfx then let style = get_style ttag in (match style.Terminal.prefix with Some s -> Format.pp_print_as ft 0 s | None -> ()) | _ -> () in let print_suffix ft = function | Format.String_tag tag -> let (tpfx, ttag) = split_tag tag in if tpfx <> start_pfx then let style = get_style ttag in (match style.Terminal.suffix with Some s -> Format.pp_print_as ft 0 s | None -> ()) | _ -> () in print_prefix, print_suffix let init_output_fns () = let reopen_highlight = ref "" in let open Format in let fns = Format.pp_get_formatter_out_functions !std_ft () in let newline () = if !diff_tag_stack <> [] then begin let close = get_close_seq !diff_tag_stack in fns.out_string close 0 (String.length close); reopen_highlight := get_open_seq (List.rev !diff_tag_stack); end; fns.out_string "\n" 0 1 in let string s off n = if !reopen_highlight <> "" && String.trim (String.sub s off n) <> "" then begin fns.out_string !reopen_highlight 0 (String.length !reopen_highlight); reopen_highlight := "" end; fns.out_string s off n in let new_fns = { fns with out_string = string; out_newline = newline } in Format.pp_set_formatter_out_functions !std_ft new_fns;; let init_terminal_output ~color = let open_tag, close_tag, clear_tag = make_style_stack () in let print_prefix, print_suffix = make_printing_functions () in let tag_handler ft = { Format.mark_open_stag = open_tag; Format.mark_close_stag = close_tag; Format.print_open_stag = print_prefix ft; Format.print_close_stag = print_suffix ft; } in if color then (* Use 0-length markers *) begin std_logger_cleanup := clear_tag; init_output_fns (); Format.pp_set_mark_tags !std_ft true; Format.pp_set_mark_tags !err_ft true end else (* Use textual markers *) begin Format.pp_set_print_tags !std_ft true; Format.pp_set_print_tags !err_ft true end; Format.pp_set_formatter_stag_functions !std_ft (tag_handler !std_ft); Format.pp_set_formatter_stag_functions !err_ft (tag_handler !err_ft) (* Rules for emacs: - Debug/info: emacs_quote_info - Warning/Error: emacs_quote_err - Notice: unquoted *) let emacs_logger = gen_logger Emacs.quote_info Emacs.quote_warning (* This is specific to the toplevel *) type execution_phase = | ParsingCommandLine | Initialization | LoadingPrelude | LoadingRcFile | InteractiveLoop | CompilationPhase let default_phase = ref InteractiveLoop let in_phase ~phase f x = let op = !default_phase in default_phase := phase; try let res = f x in default_phase := op; res with exn -> let iexn = Exninfo.capture exn in default_phase := op; Exninfo.iraise iexn let pr_loc loc = Loc.pr loc ++ str ":" let pr_phase ?loc () = match !default_phase, loc with | LoadingRcFile, loc -> For when all errors go through feedback : str " While loading rcfile : " + + Option.cata ( fun loc - > fnl ( ) + + pr_loc loc ) ( mt ( ) ) loc str "While loading rcfile:" ++ Option.cata (fun loc -> fnl () ++ pr_loc loc) (mt ()) loc *) Option.map pr_loc loc | LoadingPrelude, loc -> Some (str "While loading initial state:" ++ Option.cata (fun loc -> fnl () ++ pr_loc loc) (mt ()) loc) | _, Some loc -> Some (pr_loc loc) | ParsingCommandLine, _ | Initialization, _ | CompilationPhase, _ -> None | InteractiveLoop, _ -> (* Note: interactive messages such as "foo is defined" are not located *) None let print_err_exn any = let (e, info) = Exninfo.capture any in let loc = Loc.get_loc info in let pre_hdr = pr_phase ?loc () in let msg = CErrors.iprint (e, info) ++ fnl () in std_logger ?pre_hdr Feedback.Error msg let with_output_to_file fname func input = let channel = open_out (String.concat "." [fname; "out"]) in let old_fmt = !std_ft, !err_ft, !deep_ft in let new_ft = Format.formatter_of_out_channel channel in set_gp new_ft (get_gp !std_ft); std_ft := new_ft; err_ft := new_ft; deep_ft := new_ft; try let output = func input in std_ft := Util.pi1 old_fmt; err_ft := Util.pi2 old_fmt; deep_ft := Util.pi3 old_fmt; Format.pp_print_flush new_ft (); close_out channel; output with reraise -> let reraise = Exninfo.capture reraise in std_ft := Util.pi1 old_fmt; err_ft := Util.pi2 old_fmt; deep_ft := Util.pi3 old_fmt; Format.pp_print_flush new_ft (); close_out channel; Exninfo.iraise reraise (* For coqtop -time, we display the position in the file, and a glimpse of the executed command *) let pr_cmd_header com = let shorten s = if Unicode.utf8_length s > 33 then (Unicode.utf8_sub s 0 30) ^ "..." else s in let noblank s = String.map (fun c -> match c with | ' ' | '\n' | '\t' | '\r' -> '~' | x -> x ) s in let (start,stop) = Option.cata Loc.unloc (0,0) com.CAst.loc in let safe_pr_vernac x = try Ppvernac.pr_vernac x with e -> str (Printexc.to_string e) in let cmd = noblank (shorten (string_of_ppcmds (safe_pr_vernac com))) in str "Chars " ++ int start ++ str " - " ++ int stop ++ str " [" ++ str cmd ++ str "] "
null
https://raw.githubusercontent.com/coq/coq/37e820c1bd5d321cff65285ab7e162b554126d61/vernac/topfmt.ml
ocaml
********************************************************************** * The Coq Proof Assistant / The Coq Development Team // * This file is distributed under the terms of the * (see LICENSE file for the text of the license) ********************************************************************** * Pp control also belongs here as the terminal is private to the toplevel Default parameters of pretty-printing A deeper pretty-printer to print proof scripts set_gp : Format.formatter -> pp_global_params -> unit * set the parameters of a formatter with_fp : 'a pp_formatter_params -> Format.formatter * returns of formatter for given formatter functions Output on a channel ch For parametrization through vernacular * Console display of feedback * Default tags Special chars for emacs, to detect warnings inside goal output The empty quoter * Standard loggers We provide a generic clear_log_backend callback for backends wanting to do cleanup after the print. Tag map for terminal style Local to console toplevel Coming from the printer ["constr"; "variable"] is not assigned global, just like std_ft * Not thread-safe. We should put a lock somewhere if we print from different threads. Do we? Default tag is to reset everything Anomalous case, but for robustness Something went wrong, we fallback Use 0-length markers Use textual markers Rules for emacs: - Debug/info: emacs_quote_info - Warning/Error: emacs_quote_err - Notice: unquoted This is specific to the toplevel Note: interactive messages such as "foo is defined" are not located For coqtop -time, we display the position in the file, and a glimpse of the executed command
v * Copyright INRIA , CNRS and contributors < O _ _ _ , , * ( see version control and CREDITS file for authors & dates ) \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * GNU Lesser General Public License Version 2.1 open Pp type pp_global_params = { margin : int; max_indent : int; max_depth : int; ellipsis : string } let dflt_gp = { margin = 78; max_indent = 50; max_depth = 50; ellipsis = "..." } let deep_gp = { margin = 78; max_indent = 50; max_depth = 10000; ellipsis = "..." } let set_gp ft gp = Format.pp_set_margin ft gp.margin ; Format.pp_set_max_indent ft gp.max_indent ; Format.pp_set_max_boxes ft gp.max_depth ; Format.pp_set_ellipsis_text ft gp.ellipsis let set_dflt_gp ft = set_gp ft dflt_gp let get_gp ft = { margin = Format.pp_get_margin ft (); max_indent = Format.pp_get_max_indent ft (); max_depth = Format.pp_get_max_boxes ft (); ellipsis = Format.pp_get_ellipsis_text ft () } let with_fp chan out_function flush_function = let ft = Format.make_formatter out_function flush_function in Format.pp_set_formatter_out_channel ft chan; ft let with_output_to ch = let ft = with_fp ch (output_substring ch) (fun () -> flush ch) in set_gp ft deep_gp; ft let std_ft = ref Format.std_formatter let _ = set_dflt_gp !std_ft let err_ft = ref Format.err_formatter let _ = set_gp !err_ft deep_gp let deep_ft = ref (with_output_to stdout) let _ = set_gp !deep_ft deep_gp let default = Format.pp_get_max_boxes !std_ft () let default_margin = Format.pp_get_margin !std_ft () let get_depth_boxes () = Some (Format.pp_get_max_boxes !std_ft ()) let set_depth_boxes v = Format.pp_set_max_boxes !std_ft (match v with None -> default | Some v -> v) let get_margin () = Some (Format.pp_get_margin !std_ft ()) let set_margin v = let v = match v with None -> default_margin | Some v -> v in Format.pp_set_margin Format.str_formatter v; Format.pp_set_margin !std_ft v; Format.pp_set_margin !deep_ft v; Format.pp_set_margin !err_ft v; Heuristic , based on usage : the column on the right of max_indent column is 20 % of width , capped to 30 characters column is 20% of width, capped to 30 characters *) let m = max (64 * v / 100) (v-30) in Format.pp_set_max_indent Format.str_formatter m; Format.pp_set_max_indent !std_ft m; Format.pp_set_max_indent !deep_ft m; Format.pp_set_max_indent !err_ft m module Tag = struct let error = "message.error" let warning = "message.warning" let debug = "message.debug" end let msgnl_with fmt strm = pp_with fmt (strm ++ fnl ()); Format.pp_print_flush fmt () module Emacs = struct let quote_warning_start = "<warning>" let quote_warning_end = "</warning>" let quote_info_start = "<infomsg>" let quote_info_end = "</infomsg>" let quote_emacs q_start q_end msg = hov 0 (seq [str q_start; brk(0,0); msg; brk(0,0); str q_end]) let quote_warning = quote_emacs quote_warning_start quote_warning_end let quote_info = quote_emacs quote_info_start quote_info_end end let dbg_hdr = tag Tag.debug (str "Debug:") ++ spc () let info_hdr = mt () let warn_hdr = tag Tag.warning (str "Warning:") ++ spc () let err_hdr = tag Tag.error (str "Error:") ++ spc () let make_body quoter info ?pre_hdr s = pr_opt_no_spc (fun x -> x ++ fnl ()) pre_hdr ++ quoter (hov 0 (info ++ s)) let noq x = x Generic logger let gen_logger dbg warn ?pre_hdr level msg = let open Feedback in match level with | Debug -> msgnl_with !std_ft (make_body dbg dbg_hdr ?pre_hdr msg) | Info -> msgnl_with !std_ft (make_body dbg info_hdr ?pre_hdr msg) | Notice -> msgnl_with !std_ft (make_body noq info_hdr ?pre_hdr msg) | Warning -> Flags.if_warn (fun () -> msgnl_with !err_ft (make_body warn warn_hdr ?pre_hdr msg)) () | Error -> msgnl_with !err_ft (make_body noq err_hdr ?pre_hdr msg) let std_logger_cleanup = ref (fun () -> ()) let std_logger ?pre_hdr level msg = gen_logger (fun x -> x) (fun x -> x) ?pre_hdr level msg; !std_logger_cleanup () * Color logging . Moved from Ppstyle , it may need some more refactoring let default_tag_map () = let open Terminal in [ "message.error" , make ~bold:true ~fg_color:`WHITE ~bg_color:`RED () ; "message.warning" , make ~bold:true ~fg_color:`WHITE ~bg_color:`YELLOW () ; "message.debug" , make ~bold:true ~fg_color:`WHITE ~bg_color:`MAGENTA () ; "message.prompt" , make ~fg_color:`GREEN () ; "constr.evar" , make ~fg_color:`LIGHT_BLUE () ; "constr.keyword" , make ~bold:true () ; "constr.type" , make ~bold:true ~fg_color:`YELLOW () ; "constr.notation" , make ~fg_color:`WHITE () ; "constr.reference" , make ~fg_color:`LIGHT_GREEN () ; "constr.path" , make ~fg_color:`LIGHT_MAGENTA () ; "module.definition", make ~bold:true ~fg_color:`LIGHT_RED () ; "module.keyword" , make ~bold:true () ; "tactic.keyword" , make ~bold:true () ; "tactic.primitive" , make ~fg_color:`LIGHT_GREEN () ; "tactic.string" , make ~fg_color:`LIGHT_RED () ; "diff.added" , make ~bg_color:(`RGB(0,141,0)) ~underline:true () ; "diff.removed" , make ~bg_color:(`RGB(170,0,0)) ~underline:true () ; "diff.added.bg" , make ~bg_color:(`RGB(0,91,0)) () ; "diff.removed.bg" , make ~bg_color:(`RGB(91,0,0)) () ] let tag_map = ref CString.Map.empty let init_tag_map styles = let set accu (name, st) = CString.Map.add name st accu in tag_map := List.fold_left set !tag_map styles let default_styles () = init_tag_map (default_tag_map ()) let set_emacs_print_strings () = let open Terminal in let diff = "diff." in List.iter (fun b -> let (name, attrs) = b in if CString.is_sub diff name 0 then tag_map := CString.Map.add name { attrs with prefix = Some (Printf.sprintf "<%s>" name); suffix = Some (Printf.sprintf "</%s>" name) } !tag_map) (CString.Map.bindings !tag_map) let parse_color_config str = let styles = Terminal.parse str in init_tag_map styles let dump_tags () = CString.Map.bindings !tag_map let empty = Terminal.make () let default_style = Terminal.reset_style let get_style tag = try CString.Map.find tag !tag_map with Not_found -> empty;; let get_open_seq tags = let style = List.fold_left (fun a b -> Terminal.merge a (get_style b)) default_style tags in Terminal.eval (Terminal.diff default_style style);; let get_close_seq tags = let style = List.fold_left (fun a b -> Terminal.merge a (get_style b)) default_style tags in Terminal.eval (Terminal.diff style default_style);; let make_style_stack () = let style_stack = ref [] in let peek () = match !style_stack with | st :: _ -> st in let open_tag = function | Format.String_tag tag -> let (tpfx, ttag) = split_tag tag in if tpfx = end_pfx then "" else let style = get_style ttag in Merge the current settings and the style being pushed . This allows restoring the previous settings correctly in a pop when both set the same attribute . Example : current settings have red FG , the pushed style has green FG . When popping the style , we should set red FG , not default FG . allows restoring the previous settings correctly in a pop when both set the same attribute. Example: current settings have red FG, the pushed style has green FG. When popping the style, we should set red FG, not default FG. *) let style = Terminal.merge (peek ()) style in let diff = Terminal.diff (peek ()) style in style_stack := style :: !style_stack; if tpfx = start_pfx then diff_tag_stack := ttag :: !diff_tag_stack; Terminal.eval diff | _ -> Terminal.eval default_style in let close_tag = function | Format.String_tag tag -> let (tpfx, _) = split_tag tag in if tpfx = start_pfx then "" else begin if tpfx = end_pfx then diff_tag_stack := (try List.tl !diff_tag_stack with tl -> []); match !style_stack with Terminal.eval default_style | cur :: rem -> style_stack := rem; if cur = (peek ()) then "" else if rem = [] then Terminal.reset else Terminal.eval (Terminal.diff cur (peek ())) end | _ -> Terminal.eval default_style in let clear () = style_stack := [] in open_tag, close_tag, clear let make_printing_functions () = let print_prefix ft = function | Format.String_tag tag -> let (tpfx, ttag) = split_tag tag in if tpfx <> end_pfx then let style = get_style ttag in (match style.Terminal.prefix with Some s -> Format.pp_print_as ft 0 s | None -> ()) | _ -> () in let print_suffix ft = function | Format.String_tag tag -> let (tpfx, ttag) = split_tag tag in if tpfx <> start_pfx then let style = get_style ttag in (match style.Terminal.suffix with Some s -> Format.pp_print_as ft 0 s | None -> ()) | _ -> () in print_prefix, print_suffix let init_output_fns () = let reopen_highlight = ref "" in let open Format in let fns = Format.pp_get_formatter_out_functions !std_ft () in let newline () = if !diff_tag_stack <> [] then begin let close = get_close_seq !diff_tag_stack in fns.out_string close 0 (String.length close); reopen_highlight := get_open_seq (List.rev !diff_tag_stack); end; fns.out_string "\n" 0 1 in let string s off n = if !reopen_highlight <> "" && String.trim (String.sub s off n) <> "" then begin fns.out_string !reopen_highlight 0 (String.length !reopen_highlight); reopen_highlight := "" end; fns.out_string s off n in let new_fns = { fns with out_string = string; out_newline = newline } in Format.pp_set_formatter_out_functions !std_ft new_fns;; let init_terminal_output ~color = let open_tag, close_tag, clear_tag = make_style_stack () in let print_prefix, print_suffix = make_printing_functions () in let tag_handler ft = { Format.mark_open_stag = open_tag; Format.mark_close_stag = close_tag; Format.print_open_stag = print_prefix ft; Format.print_close_stag = print_suffix ft; } in if color then begin std_logger_cleanup := clear_tag; init_output_fns (); Format.pp_set_mark_tags !std_ft true; Format.pp_set_mark_tags !err_ft true end else begin Format.pp_set_print_tags !std_ft true; Format.pp_set_print_tags !err_ft true end; Format.pp_set_formatter_stag_functions !std_ft (tag_handler !std_ft); Format.pp_set_formatter_stag_functions !err_ft (tag_handler !err_ft) let emacs_logger = gen_logger Emacs.quote_info Emacs.quote_warning type execution_phase = | ParsingCommandLine | Initialization | LoadingPrelude | LoadingRcFile | InteractiveLoop | CompilationPhase let default_phase = ref InteractiveLoop let in_phase ~phase f x = let op = !default_phase in default_phase := phase; try let res = f x in default_phase := op; res with exn -> let iexn = Exninfo.capture exn in default_phase := op; Exninfo.iraise iexn let pr_loc loc = Loc.pr loc ++ str ":" let pr_phase ?loc () = match !default_phase, loc with | LoadingRcFile, loc -> For when all errors go through feedback : str " While loading rcfile : " + + Option.cata ( fun loc - > fnl ( ) + + pr_loc loc ) ( mt ( ) ) loc str "While loading rcfile:" ++ Option.cata (fun loc -> fnl () ++ pr_loc loc) (mt ()) loc *) Option.map pr_loc loc | LoadingPrelude, loc -> Some (str "While loading initial state:" ++ Option.cata (fun loc -> fnl () ++ pr_loc loc) (mt ()) loc) | _, Some loc -> Some (pr_loc loc) | ParsingCommandLine, _ | Initialization, _ | CompilationPhase, _ -> None | InteractiveLoop, _ -> None let print_err_exn any = let (e, info) = Exninfo.capture any in let loc = Loc.get_loc info in let pre_hdr = pr_phase ?loc () in let msg = CErrors.iprint (e, info) ++ fnl () in std_logger ?pre_hdr Feedback.Error msg let with_output_to_file fname func input = let channel = open_out (String.concat "." [fname; "out"]) in let old_fmt = !std_ft, !err_ft, !deep_ft in let new_ft = Format.formatter_of_out_channel channel in set_gp new_ft (get_gp !std_ft); std_ft := new_ft; err_ft := new_ft; deep_ft := new_ft; try let output = func input in std_ft := Util.pi1 old_fmt; err_ft := Util.pi2 old_fmt; deep_ft := Util.pi3 old_fmt; Format.pp_print_flush new_ft (); close_out channel; output with reraise -> let reraise = Exninfo.capture reraise in std_ft := Util.pi1 old_fmt; err_ft := Util.pi2 old_fmt; deep_ft := Util.pi3 old_fmt; Format.pp_print_flush new_ft (); close_out channel; Exninfo.iraise reraise let pr_cmd_header com = let shorten s = if Unicode.utf8_length s > 33 then (Unicode.utf8_sub s 0 30) ^ "..." else s in let noblank s = String.map (fun c -> match c with | ' ' | '\n' | '\t' | '\r' -> '~' | x -> x ) s in let (start,stop) = Option.cata Loc.unloc (0,0) com.CAst.loc in let safe_pr_vernac x = try Ppvernac.pr_vernac x with e -> str (Printexc.to_string e) in let cmd = noblank (shorten (string_of_ppcmds (safe_pr_vernac com))) in str "Chars " ++ int start ++ str " - " ++ int stop ++ str " [" ++ str cmd ++ str "] "
481de80b381276ce68557eb14cf472046f52d3afc53d76ec3aba212464f7585e
pol-is/polisMath
conv_man.clj
Copyright ( C ) 2012 - present , The Authors . This program is free software : you can redistribute it and/or modify it under the terms of the GNU Affero General Public License , version 3 , as published by the Free Software Foundation . 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 Affero General Public License for more details . You should have received a copy of the GNU Affero General Public License along with this program . If not , see < / > . (ns polismath.conv-man "This is the namesascpe for the " (:require [polismath.math.named-matrix :as nm] [polismath.math.conversation :as conv] [polismath.math.clusters :as clust] [polismath.meta.metrics :as met] [polismath.meta.notify :as notify] [polismath.components.env :as env] [polismath.components.postgres :as db] [polismath.math.corr :as corr] [polismath.utils :as utils] [clojure.core.matrix.impl.ndarray] [clojure.core.async :as async :refer [go go-loop <! >! <!! >!! alts!! alts! chan dropping-buffer put! take!]] [taoensso.timbre :as log] [com.stuartsierra.component :as component] [plumbing.core :as pc] [schema.core :as s] [polismath.components.postgres :as postgres])) ;; Here, we organize things in terms of a conversation manager, which maintains a cache of conversations and routes ;; messages and updates to these conversations. ;; The conversations themselves are organized around conversation actors, which maintain the actual state of the conversation , as well as the message handling machinery ( chans and such ) . ;; Updates to the conversation actors are broken down via a react-to-messages multimethod, which allows for message ;; handling extensibility. ;; Utility update functions ;; ------------------------ (defn prep-bidToPid "Prep function for passing to db/format-as-json-for-db given bidToPid data" [results] {:zid (:zid results) :bidToPid (:bid-to-pid results) :lastVoteTimestamp (:last-vote-timestamp results)}) (defn prep-main "Prep function for passing to db/format-as-json-for-db and on the main polismath collection." [results] (-> results ; REFORMAT BASE CLUSTERS (update-in [:base-clusters] clust/fold-clusters) ; IMPORTANT! Whitelist of keys to be included in json output; used for removing intermediates (assoc :lastVoteTimestamp (:last-vote-timestamp results)) (assoc :lastModTimestamp (:last-mod-timestamp results)) (utils/hash-map-subset #{:base-clusters :group-clusters :subgroup-clusters :in-conv :mod-out :mod-in :meta-tids :lastVoteTimestamp :lastModTimestamp :n :n-cmts :pca :repness :group-aware-consensus :consensus :zid :tids :user-vote-counts :votes-base :group-votes :subgroup-votes :subgroup-repness :comment-priorities}))) ;:subgroup-ptpt-stats}))) (defn columnize ([stats keys] (->> keys (map (fn [k] (let [vals (map (fn [stat] (get stat k)) stats)] [k vals]))) (into {}))) ([stats] (let [keys (-> stats first keys)] (columnize stats keys)))) (defn prep-ptpt-stats [results] {:zid (:zid results) :ptptstats (columnize (:ptpt-stats results)) :lastVoteTimestamp (:last-vote-timestamp results)}) (defn handle-profile-data "For now, just log profile data. Eventually want to send to influxDB and graphite." [{:as conv-man :keys [postgres config]} conv & {:keys [recompute n-votes finish-time] :as extra-data}] (if-let [prof-atom (:profile-data conv)] (let [prof @prof-atom tot (apply + (map second prof)) prof (assoc prof :total tot)] (try (-> prof (assoc :n-ptps (:n conv)) (merge (utils/hash-map-subset conv #{:n-cmts :zid :last-vote-timestamp}) extra-data) (->> (db/upload-math-profile postgres (:zid conv)))) (catch Exception e (log/warn "Unable to submit profile data for zid:" (:zid conv)) (.printStackTrace e))) (log/debug "Profile data for zid" (:zid conv) ": " prof)))) ;; Conversation update functions ;; ============================= ;; XXX This is temporary; should be switching to new spec work in conversation ns (def Conversation "A schema for what valid conversations should look like (WIP)" {:zid s/Int ;; Note: we let all other key-value pairs pass through s/Keyword s/Any}) ;; Should rename this not to conflict with clojure.core/update... poor form (defn conv-update "This function is what actually gets sent to the conv-manager. In addition to the conversation and vote batches up in the channel, we also take an error-callback. Eventually we'll want to pass opts through here as well." [conv-man conv votes] (let [start-time (System/currentTimeMillis) config (:config conv-man) pg (:postgres conv-man)] (log/info "Starting conversation update for zid:" (:zid conv)) ;; Need to expose opts for conv-update through config... XXX (let [updated-conv (conv/conv-update conv votes) zid (:zid updated-conv) finish-time (System/currentTimeMillis) ; If this is a recompute, we'll have either :full or :reboot, ow/ want to send false recompute (or (:recompute conv) false)] (log/info "Finished computng conv-update for zid" zid "in" (- finish-time start-time) "ms") (handle-profile-data conv-man updated-conv :finish-time finish-time :recompute recompute :n-votes (count votes)) ;; Make sure our data has the right shape (when-let [validation-errors (s/check Conversation updated-conv)] ;; XXX Should really be using throw+ (slingshot) here and throutout the code base ;; Also, should put in code for doing smart collapsing of collections... (log/error "Validation error: Conversation value does not match schema for conv:" updated-conv) (throw (Exception. (str "Validation error: Conversation Value does not match schema: " validation-errors)))) ; Return the updated conv updated-conv))) (defn write-conv-updates! [{:as conv-man :keys [postgres]} {:as updated-conv :keys [zid]} math-tick] ;; TODO Really need to extract these writes so that mod updates do whta they're supposed to! And also run in async/thread for better parallelism ; Format and upload main results (async/thread (doseq [[prep-fn upload-fn] [[prep-main db/upload-math-main] ; main math results, for client [prep-bidToPid db/upload-math-bidtopid] ; bidtopid mapping, for server [prep-ptpt-stats db/upload-math-ptptstats]]] (->> updated-conv prep-fn (upload-fn postgres zid math-tick))) (log/info "Finished uploading math results for zid:" zid))) (defn restructure-json-conv [conv] (-> conv (utils/hash-map-subset #{:math_tick :raw-rating-mat :rating-mat :lastVoteTimestamp :mod-out :mod-in :zid :pca :in-conv :n :n-cmts :group-clusters :base-clusters :repness :group-votes :subgroup-clusters :subgroup-votes :subgroup-repness :group-aware-consensus :comment-priorities :meta-tids}) (assoc :last-vote-timestamp (get conv :lastVoteTimestamp) :last-mod-timestamp (get conv :lastModTimestamp)) ; Make sure there is an empty named matrix to operate on (assoc :raw-rating-mat (nm/named-matrix)) ; Update the base clusters to be unfolded (update :base-clusters clust/unfold-clusters) ; Make sure in-conv is a set (update :in-conv set) (update :mod-out set) (update :mod-in set) (update :meta-tids set))) (defn load-or-init "Given a zid, either load a minimal set of information from postgres, or if a new zid, create a new conv" [conv-man zid & {:keys [recompute]}] TODO On recompute should try to preserve in conv and such (log/info "Running load or init") (if-let [conv (and (not recompute) (db/load-conv (:postgres conv-man) zid))] (-> conv ;(->> (tr/trace "load-or-init (about to restructure):")) restructure-json-conv ;(->> (tr/trace "load-or-init (post restructure):")) ;; What the fuck is this all about? Should this really be getting set here? (assoc :recompute :reboot) (assoc :raw-rating-mat (-> (nm/named-matrix) (nm/update-nmat (->> (db/conv-poll (:postgres conv-man) zid 0) (map (fn [vote-row] (mapv (partial get vote-row) [:pid :tid :vote]))))))) (conv/mod-update (db/conv-mod-poll (:postgres conv-man) zid 0))) ; would be nice to have :recompute :initial (assoc (conv/new-conv) :zid zid :recompute :full))) (defn generate-report-data! [{:as conv-man :keys [postgres]} conv math-tick report-data] (log/info "Generating report data for report:" report-data) (let [rid (:rid report-data) tids (map :tid (postgres/query (:postgres conv-man) (postgres/report-tids rid))) corr-mat (corr/compute-corr conv tids)] (async/thread (postgres/insert-correlationmatrix! postgres rid math-tick corr-mat) TODO update to submit usng task type and task bucket (postgres/mark-task-complete! postgres "generate_report_data" rid)))) ;; Message processing functions ;; ---------------------------- (defmacro take-all! [c] "Given a channel, takes all values currently in channel and places in a vector. Must be called within a go block." `(loop [acc# []] (let [[v# ~c] (alts! [~c] :default nil)] (if (not= ~c :default) (recur (conj acc# v#)) acc#)))) (defn take-all!! [c] "Given a channel, takes all values currently in channel and places in a vector. Must be called within a go block." (loop [acc []] (let [[v c] (alts!! [c] :default nil)] (if (not= c :default) (recur (conj acc v)) acc)))) (defn split-batches "This function splits message batches as sent to conv actor up by the first item in batch vector (:votes :moderation) so messages can get processed properly" [messages] (->> messages (group-by :message-type) (pc/map-vals (fn [labeled-batches] (->> labeled-batches (map :message-batch) (flatten)))))) ;; Message processing for conv-actor ;; ================================= ;; Here's the multimethod at the core of the messages the conv actor may act upon. (defmulti react-to-messages (fn [conv-man conv message-type messages] message-type)) (defmethod react-to-messages :votes [conv-man conv _ messages] (conv-update conv-man conv messages)) (defmethod react-to-messages :moderation [conv-man conv _ messages] (conv/mod-update conv messages)) (defmethod react-to-messages :generate_report_data [conv-man conv _ messages] (let [math-tick (or (:math-tick conv) (:math_tick conv))] (doseq [report-task messages] (try (generate-report-data! conv-man conv math-tick report-task) (catch Exception e (log/error e (str "Unable to generate report " (pr-str report-task))))))) ;; explicitly return nil so we don't trigger an update nil) ;; Error handling (defn handle-errors [conv-man conv-actor conv message-type messages update-error start-time] (let [zid (:zid conv-actor) zid-str (str "zid=" zid) retry-chan (:retry-chan conv-actor) notify-message (str "Failed conversation update on " (-> conv-man :config :math-env) " for message-type " message-type " and " zid-str)] (try (let [stack-trace (notify/error-message-body update-error)] (notify/notify-team (:config conv-man) (str "Polismath conv-man error: " message-type) zid notify-message stack-trace)) (catch Exception e (log/error e "Unable to notify team"))) (log/error update-error notify-message) (.printStackTrace update-error) ; Try requeing the votes that failed so that if we get more, they'll get replayed (try (log/info "Re-queueing messages for failed update for" zid-str) (async/go (async/>! retry-chan {:message-type message-type :message-batch messages})) (catch Exception qe (log/error qe (str "MAJOR ERROR! Unable to re-queue votes after conversation update failed for " zid-str)) (.printStackTrace qe))) ; Try to send some failed conversation time metrics, but don't stress if it fails (try (let [end (System/currentTimeMillis) duration (- end start-time)] Update to use MetricSender component XXX (met/send-metric (:metrics conv-man) "math.pca.compute.fail" duration)) (catch Exception e (log/error "Unable to send metrics for failed compute for" zid-str))) ; Try to save conversation state for debugging purposes (try (conv/conv-update-dump conv messages update-error) (catch Exception e (log/error "Unable to perform conv-update dump for" zid-str))))) ;; Wrapper around the multimethod above, which handles errors and such (defn react-to-messages! [conv-man conv-actor message-type messages] (let [start-time (System/currentTimeMillis) {:keys [zid conv retry-chan]} conv-actor update-fn (fn [conv'] (try (if-let [updated-conv (react-to-messages conv-man conv' message-type messages)] (do (let [math-tick (or (:math-tick updated-conv) ;; pass through for report generation (postgres/inc-math-tick (:postgres conv-man) zid))] (write-conv-updates! conv-man updated-conv math-tick)) updated-conv) ;; if nil, don't update, for just side effects conv') (catch Exception e (handle-errors conv-man conv-actor conv' message-type messages e start-time) conv')))] (swap! conv update-fn))) ;; Start the actor (defn go-act! [conv-man conv-actor] (let [{:keys [kill-chan conversations]} conv-man {:keys [zid conv message-chan retry-chan]} conv-actor] (go-loop [] If nil comes through as the first message , then the chan is closed , and we should be done , not continue looping forever (let [[first-msg c] (async/alts! [kill-chan message-chan] :priority true)] (when-not (= c kill-chan) (log/debug "Message chan put in queue-message-batch! for zid:" (:zid first-msg)) ;; If there are any retry messages from a failed recompute, we put them at the front of the message stack. ;; But retry messages only get processed in this way if there are new messages that have come in triggering the first - msg take above , ensuring we do n't just loop forever on a broken message / update . (let [retry-msgs (async/poll! retry-chan) msgs (vec (concat retry-msgs [first-msg] (take-all! message-chan))) ;; Regardless, now we split the messages by message type and process them as below split-msgs (split-batches msgs)] ;; This acts as a whitelist for messages to run, and also an ordering of preference (doseq [message-type [:votes :moderation :generate_report_data]] (when-let [messages (get split-msgs message-type)] (react-to-messages! conv-man conv-actor message-type messages))) (recur))))))) ;; Put the actor together and (defn conv-actor [{:as conv-man :keys [conversations kill-chan config]} zid] (log/info "Starting message batch queue and handler routine for conv zid:" zid) (let [conv (load-or-init conv-man zid :recompute (:recompute config)) _ (log/info "Conversation loaded for conv zid:" zid) ;; Set up our main message chan message-chan (chan 10000) Separate channel for messages that we 've tried to process but that have n't worked for one reason or another ( buffer size not important here ) retry-chan (chan 10) actor {:zid zid :conv (atom conv) :message-chan message-chan :retry-chan retry-chan :conv-man conv-man}] (go-act! conv-man actor) ;; Trigger a conv update as the conv loads, so that state is always consistent (react-to-messages! conv-man actor :votes []) actor)) (defn add-conv-actor-listener! [conv-actor f] (add-watch (:conv conv-actor) ::conv-actor-state-watch (fn [_ _ old-value new-value] (when-not (= old-value new-value) (f new-value))))) ;; At the moment this is mostly used for testing, and I'm not sure that we'll want to keep it long term. But let's see... (defn add-listener! "Adds a watch to the conv-actor for the given zid such that the function f will be called when the given conversation changes or initializes." [conv-man zid f] ;; If the conv-actor has already been created, then we add a watch for its :conv atom (when-let [conv-actor (-> conv-man :conversations deref (get zid))] (add-conv-actor-listener! conv-actor f)) (add-watch (:conversations conv-man) [::conversations-watch zid] (fn [_ _ old-value new-value] If a conv - actor is added for this zid , set the watch now (when-let [new-conv-actor (and (not (get old-value zid)) (get new-value zid))] (add-conv-actor-listener! new-conv-actor f))))) ;; Conversation manager system component ;; ===================================== ;; Puts together the conversation actors into a system component. (defrecord ConversationManager [config postgres metrics conversations kill-chan] component/Lifecycle (start [component] (log/info ">> Starting ConversationManager") (let [conversations (atom {}) kill-chan (async/promise-chan)] (assoc component :conversations conversations :kill-chan kill-chan))) (stop [component] (log/info "<< Stopping ConversationManager") (try ;; Close all our message channels for good measure (log/debug "conversations:" conversations) (go (>! kill-chan :kill)) (doseq [[zid {:keys [message-chan]}] @conversations] (async/close! message-chan)) Not sure , but we might want this for GC (reset! conversations nil) (catch Exception e (log/error e "Unable to stop ConvMan component"))) component)) (defn create-conversation-manager [] (map->ConversationManager {})) ;; How we queue messages up to the conversation manager ;; Need to think about what to do if failed conversations lead to messages piling up in the message queue XXX (defn queue-message-batch! "Queue message batches for a given conversation by zid" [{:as conv-man :keys [conversations config kill-chan]} message-type zid message-batch] (when-not (async/poll! kill-chan) (if-let [{:keys [conv message-chan]} (get @conversations zid)] ;; Then we already have a go loop running for this (>!! message-chan {:message-type message-type :message-batch message-batch}) ;; Then we need to initialize the conversation and set up the conversation channel and go routine (let [conv-actor (conv-actor conv-man zid)] (swap! conversations assoc zid conv-actor) ;; Just call again to make sure the message gets on the chan (using the if-let fork above) :-) (queue-message-batch! conv-man message-type zid message-batch))))) ;; Need to find a good way of making sure these tests don't ever get committed uncommented (comment (require '[clojure.test :as test]) (test/run-tests 'conv-man-tests) :end-comment) :ok
null
https://raw.githubusercontent.com/pol-is/polisMath/dfe233e8c9207c2ce11e1379286ad0cf0f732067/src/polismath/conv_man.clj
clojure
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU Affero General Public License for more details . You should have received a copy of the GNU Affero General Public License along with this program . If not , see < / > . Here, we organize things in terms of a conversation manager, which maintains a cache of conversations and routes messages and updates to these conversations. The conversations themselves are organized around conversation actors, which maintain the actual state of the Updates to the conversation actors are broken down via a react-to-messages multimethod, which allows for message handling extensibility. Utility update functions ------------------------ REFORMAT BASE CLUSTERS IMPORTANT! Whitelist of keys to be included in json output; used for removing intermediates :subgroup-ptpt-stats}))) Conversation update functions ============================= XXX This is temporary; should be switching to new spec work in conversation ns Note: we let all other key-value pairs pass through Should rename this not to conflict with clojure.core/update... poor form Need to expose opts for conv-update through config... XXX If this is a recompute, we'll have either :full or :reboot, ow/ want to send false Make sure our data has the right shape XXX Should really be using throw+ (slingshot) here and throutout the code base Also, should put in code for doing smart collapsing of collections... Return the updated conv TODO Really need to extract these writes so that mod updates do whta they're supposed to! And also run in async/thread for better parallelism Format and upload main results main math results, for client bidtopid mapping, for server Make sure there is an empty named matrix to operate on Update the base clusters to be unfolded Make sure in-conv is a set (->> (tr/trace "load-or-init (about to restructure):")) (->> (tr/trace "load-or-init (post restructure):")) What the fuck is this all about? Should this really be getting set here? would be nice to have :recompute :initial Message processing functions ---------------------------- Message processing for conv-actor ================================= Here's the multimethod at the core of the messages the conv actor may act upon. explicitly return nil so we don't trigger an update Error handling Try requeing the votes that failed so that if we get more, they'll get replayed Try to send some failed conversation time metrics, but don't stress if it fails Try to save conversation state for debugging purposes Wrapper around the multimethod above, which handles errors and such pass through for report generation if nil, don't update, for just side effects Start the actor If there are any retry messages from a failed recompute, we put them at the front of the message stack. But retry messages only get processed in this way if there are new messages that have come in triggering the Regardless, now we split the messages by message type and process them as below This acts as a whitelist for messages to run, and also an ordering of preference Put the actor together and Set up our main message chan Trigger a conv update as the conv loads, so that state is always consistent At the moment this is mostly used for testing, and I'm not sure that we'll want to keep it long term. But let's see... If the conv-actor has already been created, then we add a watch for its :conv atom Conversation manager system component ===================================== Puts together the conversation actors into a system component. Close all our message channels for good measure How we queue messages up to the conversation manager Need to think about what to do if failed conversations lead to messages piling up in the message queue XXX Then we already have a go loop running for this Then we need to initialize the conversation and set up the conversation channel and go routine Just call again to make sure the message gets on the chan (using the if-let fork above) :-) Need to find a good way of making sure these tests don't ever get committed uncommented
(ns polismath.conv-man "This is the namesascpe for the " (:require [polismath.math.named-matrix :as nm] [polismath.math.conversation :as conv] [polismath.math.clusters :as clust] [polismath.meta.metrics :as met] [polismath.meta.notify :as notify] [polismath.components.env :as env] [polismath.components.postgres :as db] [polismath.math.corr :as corr] [polismath.utils :as utils] [clojure.core.matrix.impl.ndarray] [clojure.core.async :as async :refer [go go-loop <! >! <!! >!! alts!! alts! chan dropping-buffer put! take!]] [taoensso.timbre :as log] [com.stuartsierra.component :as component] [plumbing.core :as pc] [schema.core :as s] [polismath.components.postgres :as postgres])) conversation , as well as the message handling machinery ( chans and such ) . (defn prep-bidToPid "Prep function for passing to db/format-as-json-for-db given bidToPid data" [results] {:zid (:zid results) :bidToPid (:bid-to-pid results) :lastVoteTimestamp (:last-vote-timestamp results)}) (defn prep-main "Prep function for passing to db/format-as-json-for-db and on the main polismath collection." [results] (-> results (update-in [:base-clusters] clust/fold-clusters) (assoc :lastVoteTimestamp (:last-vote-timestamp results)) (assoc :lastModTimestamp (:last-mod-timestamp results)) (utils/hash-map-subset #{:base-clusters :group-clusters :subgroup-clusters :in-conv :mod-out :mod-in :meta-tids :lastVoteTimestamp :lastModTimestamp :n :n-cmts :pca :repness :group-aware-consensus :consensus :zid :tids :user-vote-counts :votes-base :group-votes :subgroup-votes :subgroup-repness :comment-priorities}))) (defn columnize ([stats keys] (->> keys (map (fn [k] (let [vals (map (fn [stat] (get stat k)) stats)] [k vals]))) (into {}))) ([stats] (let [keys (-> stats first keys)] (columnize stats keys)))) (defn prep-ptpt-stats [results] {:zid (:zid results) :ptptstats (columnize (:ptpt-stats results)) :lastVoteTimestamp (:last-vote-timestamp results)}) (defn handle-profile-data "For now, just log profile data. Eventually want to send to influxDB and graphite." [{:as conv-man :keys [postgres config]} conv & {:keys [recompute n-votes finish-time] :as extra-data}] (if-let [prof-atom (:profile-data conv)] (let [prof @prof-atom tot (apply + (map second prof)) prof (assoc prof :total tot)] (try (-> prof (assoc :n-ptps (:n conv)) (merge (utils/hash-map-subset conv #{:n-cmts :zid :last-vote-timestamp}) extra-data) (->> (db/upload-math-profile postgres (:zid conv)))) (catch Exception e (log/warn "Unable to submit profile data for zid:" (:zid conv)) (.printStackTrace e))) (log/debug "Profile data for zid" (:zid conv) ": " prof)))) (def Conversation "A schema for what valid conversations should look like (WIP)" {:zid s/Int s/Keyword s/Any}) (defn conv-update "This function is what actually gets sent to the conv-manager. In addition to the conversation and vote batches up in the channel, we also take an error-callback. Eventually we'll want to pass opts through here as well." [conv-man conv votes] (let [start-time (System/currentTimeMillis) config (:config conv-man) pg (:postgres conv-man)] (log/info "Starting conversation update for zid:" (:zid conv)) (let [updated-conv (conv/conv-update conv votes) zid (:zid updated-conv) finish-time (System/currentTimeMillis) recompute (or (:recompute conv) false)] (log/info "Finished computng conv-update for zid" zid "in" (- finish-time start-time) "ms") (handle-profile-data conv-man updated-conv :finish-time finish-time :recompute recompute :n-votes (count votes)) (when-let [validation-errors (s/check Conversation updated-conv)] (log/error "Validation error: Conversation value does not match schema for conv:" updated-conv) (throw (Exception. (str "Validation error: Conversation Value does not match schema: " validation-errors)))) updated-conv))) (defn write-conv-updates! [{:as conv-man :keys [postgres]} {:as updated-conv :keys [zid]} math-tick] (async/thread [prep-ptpt-stats db/upload-math-ptptstats]]] (->> updated-conv prep-fn (upload-fn postgres zid math-tick))) (log/info "Finished uploading math results for zid:" zid))) (defn restructure-json-conv [conv] (-> conv (utils/hash-map-subset #{:math_tick :raw-rating-mat :rating-mat :lastVoteTimestamp :mod-out :mod-in :zid :pca :in-conv :n :n-cmts :group-clusters :base-clusters :repness :group-votes :subgroup-clusters :subgroup-votes :subgroup-repness :group-aware-consensus :comment-priorities :meta-tids}) (assoc :last-vote-timestamp (get conv :lastVoteTimestamp) :last-mod-timestamp (get conv :lastModTimestamp)) (assoc :raw-rating-mat (nm/named-matrix)) (update :base-clusters clust/unfold-clusters) (update :in-conv set) (update :mod-out set) (update :mod-in set) (update :meta-tids set))) (defn load-or-init "Given a zid, either load a minimal set of information from postgres, or if a new zid, create a new conv" [conv-man zid & {:keys [recompute]}] TODO On recompute should try to preserve in conv and such (log/info "Running load or init") (if-let [conv (and (not recompute) (db/load-conv (:postgres conv-man) zid))] (-> conv restructure-json-conv (assoc :recompute :reboot) (assoc :raw-rating-mat (-> (nm/named-matrix) (nm/update-nmat (->> (db/conv-poll (:postgres conv-man) zid 0) (map (fn [vote-row] (mapv (partial get vote-row) [:pid :tid :vote]))))))) (conv/mod-update (db/conv-mod-poll (:postgres conv-man) zid 0))) (assoc (conv/new-conv) :zid zid :recompute :full))) (defn generate-report-data! [{:as conv-man :keys [postgres]} conv math-tick report-data] (log/info "Generating report data for report:" report-data) (let [rid (:rid report-data) tids (map :tid (postgres/query (:postgres conv-man) (postgres/report-tids rid))) corr-mat (corr/compute-corr conv tids)] (async/thread (postgres/insert-correlationmatrix! postgres rid math-tick corr-mat) TODO update to submit usng task type and task bucket (postgres/mark-task-complete! postgres "generate_report_data" rid)))) (defmacro take-all! [c] "Given a channel, takes all values currently in channel and places in a vector. Must be called within a go block." `(loop [acc# []] (let [[v# ~c] (alts! [~c] :default nil)] (if (not= ~c :default) (recur (conj acc# v#)) acc#)))) (defn take-all!! [c] "Given a channel, takes all values currently in channel and places in a vector. Must be called within a go block." (loop [acc []] (let [[v c] (alts!! [c] :default nil)] (if (not= c :default) (recur (conj acc v)) acc)))) (defn split-batches "This function splits message batches as sent to conv actor up by the first item in batch vector (:votes :moderation) so messages can get processed properly" [messages] (->> messages (group-by :message-type) (pc/map-vals (fn [labeled-batches] (->> labeled-batches (map :message-batch) (flatten)))))) (defmulti react-to-messages (fn [conv-man conv message-type messages] message-type)) (defmethod react-to-messages :votes [conv-man conv _ messages] (conv-update conv-man conv messages)) (defmethod react-to-messages :moderation [conv-man conv _ messages] (conv/mod-update conv messages)) (defmethod react-to-messages :generate_report_data [conv-man conv _ messages] (let [math-tick (or (:math-tick conv) (:math_tick conv))] (doseq [report-task messages] (try (generate-report-data! conv-man conv math-tick report-task) (catch Exception e (log/error e (str "Unable to generate report " (pr-str report-task))))))) nil) (defn handle-errors [conv-man conv-actor conv message-type messages update-error start-time] (let [zid (:zid conv-actor) zid-str (str "zid=" zid) retry-chan (:retry-chan conv-actor) notify-message (str "Failed conversation update on " (-> conv-man :config :math-env) " for message-type " message-type " and " zid-str)] (try (let [stack-trace (notify/error-message-body update-error)] (notify/notify-team (:config conv-man) (str "Polismath conv-man error: " message-type) zid notify-message stack-trace)) (catch Exception e (log/error e "Unable to notify team"))) (log/error update-error notify-message) (.printStackTrace update-error) (try (log/info "Re-queueing messages for failed update for" zid-str) (async/go (async/>! retry-chan {:message-type message-type :message-batch messages})) (catch Exception qe (log/error qe (str "MAJOR ERROR! Unable to re-queue votes after conversation update failed for " zid-str)) (.printStackTrace qe))) (try (let [end (System/currentTimeMillis) duration (- end start-time)] Update to use MetricSender component XXX (met/send-metric (:metrics conv-man) "math.pca.compute.fail" duration)) (catch Exception e (log/error "Unable to send metrics for failed compute for" zid-str))) (try (conv/conv-update-dump conv messages update-error) (catch Exception e (log/error "Unable to perform conv-update dump for" zid-str))))) (defn react-to-messages! [conv-man conv-actor message-type messages] (let [start-time (System/currentTimeMillis) {:keys [zid conv retry-chan]} conv-actor update-fn (fn [conv'] (try (if-let [updated-conv (react-to-messages conv-man conv' message-type messages)] (do (postgres/inc-math-tick (:postgres conv-man) zid))] (write-conv-updates! conv-man updated-conv math-tick)) updated-conv) conv') (catch Exception e (handle-errors conv-man conv-actor conv' message-type messages e start-time) conv')))] (swap! conv update-fn))) (defn go-act! [conv-man conv-actor] (let [{:keys [kill-chan conversations]} conv-man {:keys [zid conv message-chan retry-chan]} conv-actor] (go-loop [] If nil comes through as the first message , then the chan is closed , and we should be done , not continue looping forever (let [[first-msg c] (async/alts! [kill-chan message-chan] :priority true)] (when-not (= c kill-chan) (log/debug "Message chan put in queue-message-batch! for zid:" (:zid first-msg)) first - msg take above , ensuring we do n't just loop forever on a broken message / update . (let [retry-msgs (async/poll! retry-chan) msgs (vec (concat retry-msgs [first-msg] (take-all! message-chan))) split-msgs (split-batches msgs)] (doseq [message-type [:votes :moderation :generate_report_data]] (when-let [messages (get split-msgs message-type)] (react-to-messages! conv-man conv-actor message-type messages))) (recur))))))) (defn conv-actor [{:as conv-man :keys [conversations kill-chan config]} zid] (log/info "Starting message batch queue and handler routine for conv zid:" zid) (let [conv (load-or-init conv-man zid :recompute (:recompute config)) _ (log/info "Conversation loaded for conv zid:" zid) message-chan (chan 10000) Separate channel for messages that we 've tried to process but that have n't worked for one reason or another ( buffer size not important here ) retry-chan (chan 10) actor {:zid zid :conv (atom conv) :message-chan message-chan :retry-chan retry-chan :conv-man conv-man}] (go-act! conv-man actor) (react-to-messages! conv-man actor :votes []) actor)) (defn add-conv-actor-listener! [conv-actor f] (add-watch (:conv conv-actor) ::conv-actor-state-watch (fn [_ _ old-value new-value] (when-not (= old-value new-value) (f new-value))))) (defn add-listener! "Adds a watch to the conv-actor for the given zid such that the function f will be called when the given conversation changes or initializes." [conv-man zid f] (when-let [conv-actor (-> conv-man :conversations deref (get zid))] (add-conv-actor-listener! conv-actor f)) (add-watch (:conversations conv-man) [::conversations-watch zid] (fn [_ _ old-value new-value] If a conv - actor is added for this zid , set the watch now (when-let [new-conv-actor (and (not (get old-value zid)) (get new-value zid))] (add-conv-actor-listener! new-conv-actor f))))) (defrecord ConversationManager [config postgres metrics conversations kill-chan] component/Lifecycle (start [component] (log/info ">> Starting ConversationManager") (let [conversations (atom {}) kill-chan (async/promise-chan)] (assoc component :conversations conversations :kill-chan kill-chan))) (stop [component] (log/info "<< Stopping ConversationManager") (try (log/debug "conversations:" conversations) (go (>! kill-chan :kill)) (doseq [[zid {:keys [message-chan]}] @conversations] (async/close! message-chan)) Not sure , but we might want this for GC (reset! conversations nil) (catch Exception e (log/error e "Unable to stop ConvMan component"))) component)) (defn create-conversation-manager [] (map->ConversationManager {})) (defn queue-message-batch! "Queue message batches for a given conversation by zid" [{:as conv-man :keys [conversations config kill-chan]} message-type zid message-batch] (when-not (async/poll! kill-chan) (if-let [{:keys [conv message-chan]} (get @conversations zid)] (>!! message-chan {:message-type message-type :message-batch message-batch}) (let [conv-actor (conv-actor conv-man zid)] (swap! conversations assoc zid conv-actor) (queue-message-batch! conv-man message-type zid message-batch))))) (comment (require '[clojure.test :as test]) (test/run-tests 'conv-man-tests) :end-comment) :ok
a5b0c4450606dd997a00a77a1f2201f87f68386d4f32497f9f7566ed0bbf1005
blindglobe/common-lisp-stat
100-ExploratoryDataAnalysis.lisp
;;; -*- mode: lisp -*- Time - stamp : < 2013 - 07 - 31 07:33:54 tony > Creation : < 2009 - 04 - 19 09:41:09 > ;;; File: basic-eda.lisp Author : < > Copyright : ( c)2009 - - , . See LICENSE.mit in top level ;;; directory for conditions. ;;; Purpose: Example of basic exploratory data analysis in CLS. ;;; What is this talk of 'release'? Klingons do not make software ;;; 'releases'. Our software 'escapes', leaving a bloody trail of ;;; designers and quality assurance people in its wake. (in-package :cls-examples) We assume that the " loading-data.lisp " code has been run , and one ;; now wants to analyze the data loaded into *chickwts-df* ;; ;; Technically, we also want a great deal more for the loading. This will not work unless 00-##.lisp is loaded . Catch-22 ! (load (localized-pathto "examples/00-loadingData.lisp") :verbose t) *chickwts-df* ;;;;;;;;;;;;;;; EVERYTHING BELOW IS BROKEN This is a test philosophy for data analysis from an EDA ;; perspective. It could be expanded to decision support and ;; inferential statistics, but currently is only intended to provide ;; statistically appropriate numerical and visual summaries that are ;; objects that can be manipulated to explore the effect of varying ;; data and metadata. Summarize is the basic EDA tool -- it accepts symbols or lists of ;; symbols, to describe what, when, and how to do it. The resulting ;; data structure has a means for re-invoking the result as well as ;; partial storage of key results (when appropriate) as well as ;; metadata about the results (time / context if provided). ;; numerical: (txt / *ml / , variable / stream / spec'd to file) ;; visual: (static/dynamic, fixed/interactive) (need better term than fixed) ;; context -- using dataset metadata, to drive the resulting summary. ;; dataset metadata: # 1 sampling scheme - ;; retro / prospect collection ;; random, biased, convenience sampling; # 2 purpose of dataset integration / manipulation # 3 sampling / temporal component of variables ;; Create metadata variable graph which provides an initial analysis ;; structure for recording results. (defparameter *chkwt-df-depgraph* (let ((g (make-container 'graph-container ))) (loop for v in (var-list *chickwt-df*) (add-vertex g v)) (loop for (v1 . v2) in (appropriate-pairs-list *chickwt-df*) (add-edge-between-vertexes g v1 v2)))) (defparameter *my-df-smry-num* (summarize *chickwts-df* :type 'numerical :io 'listing) "First numerical summary of *my-df-smry*") (defparameter *my-df-smry-num* (summarize *my-df* :type 'numerical :io 'report-pdf :device '(file "output.pdf")) "First numerical summary of *my-df-smry*") (defparameter *my-df-smry-vis* (summarize *my-df* :type 'visual :io 'interactive :device 'xwin) "visual summary") (defparameter *my-df-smry-vis* (summarize *my-df* :type 'visual :io 'interactive-dynamic) "visual summary") (defparameter *my-df-smry-vis* (summarize *my-df* :type 'visual :io 'static) "visual summary")
null
https://raw.githubusercontent.com/blindglobe/common-lisp-stat/0c657e10a4ee7e8d4ef3737f8c2d4e62abace2d8/examples/100-ExploratoryDataAnalysis.lisp
lisp
-*- mode: lisp -*- File: basic-eda.lisp directory for conditions. Purpose: Example of basic exploratory data analysis in CLS. What is this talk of 'release'? Klingons do not make software 'releases'. Our software 'escapes', leaving a bloody trail of designers and quality assurance people in its wake. now wants to analyze the data loaded into *chickwts-df* Technically, we also want a great deal more for the loading. EVERYTHING BELOW IS BROKEN perspective. It could be expanded to decision support and inferential statistics, but currently is only intended to provide statistically appropriate numerical and visual summaries that are objects that can be manipulated to explore the effect of varying data and metadata. symbols, to describe what, when, and how to do it. The resulting data structure has a means for re-invoking the result as well as partial storage of key results (when appropriate) as well as metadata about the results (time / context if provided). numerical: (txt / *ml / , variable / stream / spec'd to file) visual: (static/dynamic, fixed/interactive) (need better term than fixed) context -- using dataset metadata, to drive the resulting summary. dataset metadata: retro / prospect collection random, biased, convenience sampling; Create metadata variable graph which provides an initial analysis structure for recording results.
Time - stamp : < 2013 - 07 - 31 07:33:54 tony > Creation : < 2009 - 04 - 19 09:41:09 > Author : < > Copyright : ( c)2009 - - , . See LICENSE.mit in top level (in-package :cls-examples) We assume that the " loading-data.lisp " code has been run , and one This will not work unless 00-##.lisp is loaded . Catch-22 ! (load (localized-pathto "examples/00-loadingData.lisp") :verbose t) *chickwts-df* This is a test philosophy for data analysis from an EDA Summarize is the basic EDA tool -- it accepts symbols or lists of # 1 sampling scheme - # 2 purpose of dataset integration / manipulation # 3 sampling / temporal component of variables (defparameter *chkwt-df-depgraph* (let ((g (make-container 'graph-container ))) (loop for v in (var-list *chickwt-df*) (add-vertex g v)) (loop for (v1 . v2) in (appropriate-pairs-list *chickwt-df*) (add-edge-between-vertexes g v1 v2)))) (defparameter *my-df-smry-num* (summarize *chickwts-df* :type 'numerical :io 'listing) "First numerical summary of *my-df-smry*") (defparameter *my-df-smry-num* (summarize *my-df* :type 'numerical :io 'report-pdf :device '(file "output.pdf")) "First numerical summary of *my-df-smry*") (defparameter *my-df-smry-vis* (summarize *my-df* :type 'visual :io 'interactive :device 'xwin) "visual summary") (defparameter *my-df-smry-vis* (summarize *my-df* :type 'visual :io 'interactive-dynamic) "visual summary") (defparameter *my-df-smry-vis* (summarize *my-df* :type 'visual :io 'static) "visual summary")
efefeca58d2d2fb58a9049afbde03e1a4f5bd76647cfb162332e8f547c4bd4f8
solarbit/pool
sbt_app.erl
Copyright 2016 solarbit.cc < > See MIT LICENSE -module(sbt_app). -include("solarbit.hrl"). -behaviour(application). -export([start/2, prep_stop/1, stop/1]). start(normal, []) -> sbt_sup:start_link(). prep_stop(State) -> % notify miners...? State. stop(_State) -> ok.
null
https://raw.githubusercontent.com/solarbit/pool/5576f1b71a469dfa2fcb6b5766667402eacc3860/lib/solarbit/src/sbt_app.erl
erlang
notify miners...?
Copyright 2016 solarbit.cc < > See MIT LICENSE -module(sbt_app). -include("solarbit.hrl"). -behaviour(application). -export([start/2, prep_stop/1, stop/1]). start(normal, []) -> sbt_sup:start_link(). prep_stop(State) -> State. stop(_State) -> ok.
1c99558e65caee433971e25caf04ea4b20c5072f04d073d959285d39a390c288
mudge/php-clj
core.clj
Copyright ( c ) 2014 , ( ) Released under the Eclipse Public License : -v10.html (ns php_clj.core (:require [php_clj.reader :as r] [clojure.string :as s] [ordered.map :refer [ordered-map]])) (declare reader->clj) (declare clj->php) (defn- expect-char [reader expected] (let [actual (r/read-char reader)] (assert (= actual expected) (str "Expected " expected " but got " actual)))) (defn- parse-int [reader] (expect-char reader \:) (-> reader (r/read-until \;) Integer.)) (defn- parse-double [reader] (expect-char reader \:) (-> reader (r/read-until \;) Double.)) (defn- parse-string [reader] (expect-char reader \:) (let [size (Integer. (r/read-until reader \:)) s (do (expect-char reader \") (r/read-str reader size))] (expect-char reader \") (expect-char reader \;) s)) (defn- parse-boolean [reader] (expect-char reader \:) (= "1" (r/read-until reader \;))) (defn- parse-null [reader] (expect-char reader \;) nil) (defn- parse-array [reader] (expect-char reader \:) (let [n-keys (Integer. (r/read-until reader \:)) arr (do (expect-char reader \{) (loop [acc (ordered-map) n n-keys] (if (zero? n) acc (recur (assoc acc (reader->clj reader) (reader->clj reader)) (dec n)))))] (expect-char reader \}) arr)) (defn- one-dimensional-array? [coll] (loop [i 0 indices (keys coll)] (cond (nil? (seq indices)) true (= i (first indices)) (recur (inc i) (next indices)) :else false))) (defn- parse-vector [array] (if (one-dimensional-array? array) (-> array vals vec) array)) (defn- reader->clj [reader] (case (r/read-char reader) \i (parse-int reader) \d (parse-double reader) \s (parse-string reader) \b (parse-boolean reader) \N (parse-null reader) \a (parse-vector (parse-array reader)))) (defn php->clj "Converts serialized PHP into equivalent Clojure data structures. Note that one-dimensional PHP arrays (those with consecutive indices starting at 0 such as array(1, 2, 3)) will be converted to vectors while all others will be converted to ordered maps therefore preserving insertion order. Example: (php->clj \"a:2:{i:0;i:1;i:1;i:2;}\")" [php] (let [reader (r/buffered-input-stream php)] (reader->clj reader))) (defn- encode-string [^String clj] (let [bytes (-> clj .getBytes count)] (str "s:" bytes ":\"" clj "\";"))) (defn- encode-float [clj] (str "d:" clj ";")) (defn- encode-int [clj] (str "i:" clj ";")) (defn- encode-map [clj] (str (reduce (fn [php keyval] (str php (clj->php (key keyval)) (clj->php (val keyval)))) (str "a:" (count clj) ":{") clj) "}")) (defn- encode-collection [clj] (str "a:" (count clj) ":{" (s/join (map-indexed #(str (clj->php %) (clj->php %2)) clj)) "}")) (defn clj->php "Converts Clojure data structures into serialized PHP. Example: (clj->php [1 2 3])" [clj] (cond (map? clj) (encode-map clj) (coll? clj) (encode-collection clj) (string? clj) (encode-string clj) (float? clj) (encode-float clj) (integer? clj) (encode-int clj) (true? clj) "b:1;" (false? clj) "b:0;" (nil? clj) "N;"))
null
https://raw.githubusercontent.com/mudge/php-clj/6a3aa409c8b21d07cb2a32b785432187aa90b4fb/src/php_clj/core.clj
clojure
) Integer.)) ) Double.)) ) ))) )
Copyright ( c ) 2014 , ( ) Released under the Eclipse Public License : -v10.html (ns php_clj.core (:require [php_clj.reader :as r] [clojure.string :as s] [ordered.map :refer [ordered-map]])) (declare reader->clj) (declare clj->php) (defn- expect-char [reader expected] (let [actual (r/read-char reader)] (assert (= actual expected) (str "Expected " expected " but got " actual)))) (defn- parse-int [reader] (expect-char reader \:) (defn- parse-double [reader] (expect-char reader \:) (defn- parse-string [reader] (expect-char reader \:) (let [size (Integer. (r/read-until reader \:)) s (do (expect-char reader \") (r/read-str reader size))] (expect-char reader \") s)) (defn- parse-boolean [reader] (expect-char reader \:) (defn- parse-null [reader] nil) (defn- parse-array [reader] (expect-char reader \:) (let [n-keys (Integer. (r/read-until reader \:)) arr (do (expect-char reader \{) (loop [acc (ordered-map) n n-keys] (if (zero? n) acc (recur (assoc acc (reader->clj reader) (reader->clj reader)) (dec n)))))] (expect-char reader \}) arr)) (defn- one-dimensional-array? [coll] (loop [i 0 indices (keys coll)] (cond (nil? (seq indices)) true (= i (first indices)) (recur (inc i) (next indices)) :else false))) (defn- parse-vector [array] (if (one-dimensional-array? array) (-> array vals vec) array)) (defn- reader->clj [reader] (case (r/read-char reader) \i (parse-int reader) \d (parse-double reader) \s (parse-string reader) \b (parse-boolean reader) \N (parse-null reader) \a (parse-vector (parse-array reader)))) (defn php->clj "Converts serialized PHP into equivalent Clojure data structures. Note that one-dimensional PHP arrays (those with consecutive indices starting at 0 such as array(1, 2, 3)) will be converted to vectors while all others will be converted to ordered maps therefore preserving insertion order. Example: (php->clj \"a:2:{i:0;i:1;i:1;i:2;}\")" [php] (let [reader (r/buffered-input-stream php)] (reader->clj reader))) (defn- encode-string [^String clj] (let [bytes (-> clj .getBytes count)] (str "s:" bytes ":\"" clj "\";"))) (defn- encode-float [clj] (str "d:" clj ";")) (defn- encode-int [clj] (str "i:" clj ";")) (defn- encode-map [clj] (str (reduce (fn [php keyval] (str php (clj->php (key keyval)) (clj->php (val keyval)))) (str "a:" (count clj) ":{") clj) "}")) (defn- encode-collection [clj] (str "a:" (count clj) ":{" (s/join (map-indexed #(str (clj->php %) (clj->php %2)) clj)) "}")) (defn clj->php "Converts Clojure data structures into serialized PHP. Example: (clj->php [1 2 3])" [clj] (cond (map? clj) (encode-map clj) (coll? clj) (encode-collection clj) (string? clj) (encode-string clj) (float? clj) (encode-float clj) (integer? clj) (encode-int clj) (true? clj) "b:1;" (false? clj) "b:0;" (nil? clj) "N;"))
c0ddc39ac3e52c32e31548186d250e4e88edf13562a301f948090459ae0f75f0
coingaming/lnd-client
TH.hs
# LANGUAGE DuplicateRecordFields # # LANGUAGE TemplateHaskell # module LndClient.RPC.TH ( mkRpc, RpcKind (..), ) where import Language.Haskell.TH.Syntax as TH import LndClient.Data.AddHodlInvoice (AddHodlInvoiceRequest (..)) import LndClient.Data.AddInvoice (AddInvoiceRequest (..), AddInvoiceResponse (..)) import LndClient.Data.Channel (Channel (..)) import qualified LndClient.Data.ChannelBackup as Bak import qualified LndClient.Data.ChannelBalance as ChannelBalance import LndClient.Data.ChannelPoint (ChannelPoint (..)) import LndClient.Data.CloseChannel ( ChannelCloseSummary (..), CloseChannelRequest (..), CloseStatusUpdate (..), ) import LndClient.Data.ClosedChannels (ClosedChannelsRequest (..)) import LndClient.Data.FinalizePsbt import LndClient.Data.FundPsbt (FundPsbtRequest, FundPsbtResponse) import qualified LndClient.Data.FundingStateStep as FSS import qualified LndClient.Data.GetInfo as GI import LndClient.Data.HtlcEvent (HtlcEvent (..)) import qualified LndClient.Data.InitWallet as IW import LndClient.Data.Invoice (Invoice (..)) import LndClient.Data.LeaseOutput (LeaseOutputRequest, LeaseOutputResponse) import LndClient.Data.ListChannels (ListChannelsRequest (..)) import LndClient.Data.ListInvoices (ListInvoiceRequest (..), ListInvoiceResponse (..)) import LndClient.Data.ListLeases (ListLeasesRequest, ListLeasesResponse) import LndClient.Data.ListUnspent import LndClient.Data.NewAddress (NewAddressRequest (..), NewAddressResponse (..)) import LndClient.Data.OpenChannel (OpenChannelRequest (..), OpenStatusUpdate (..)) import LndClient.Data.PayReq (PayReq (..)) import LndClient.Data.Payment (Payment (..)) import LndClient.Data.Peer ( ConnectPeerRequest (..), LightningAddress (..), Peer (..), ) import LndClient.Data.PendingChannels (PendingChannelsResponse (..)) import LndClient.Data.PublishTransaction (PublishTransactionRequest, PublishTransactionResponse) import LndClient.Data.ReleaseOutput (ReleaseOutputRequest, ReleaseOutputResponse) import LndClient.Data.SendCoins (SendCoinsRequest, SendCoinsResponse) import LndClient.Data.SendPayment (SendPaymentRequest (..), SendPaymentResponse (..)) import LndClient.Data.SignMessage ( SignMessageRequest (..), SignMessageResponse (..), ) import LndClient.Data.SubscribeChannelEvents (ChannelEventUpdate (..)) import LndClient.Data.SubscribeInvoices ( SubscribeInvoicesRequest (..), ) import LndClient.Data.TrackPayment (TrackPaymentRequest (..)) import qualified LndClient.Data.UnlockWallet as UW import qualified LndClient.Data.VerifyMessage as VM ( VerifyMessageRequest (..), VerifyMessageResponse (..), ) import qualified LndClient.Data.WalletBalance as Wallet import LndClient.Import import LndClient.RPC.Generic import Network.GRPC.HTTP2.ProtoLens (RPC (..)) import qualified Proto.Invoicesrpc.Invoices as LnGRPC import qualified Proto.Lightning as LnGRPC import qualified Proto.Lnrpc.Ln0 as LnGRPC import qualified Proto.Lnrpc.Ln1 as LnGRPC import qualified Proto.Routerrpc.Router as LnGRPC import qualified Proto.Signrpc.Signer as LnGRPC import qualified Proto.Walletrpc.Walletkit as LnGRPC import qualified Proto.Walletunlocker as LnGRPC data RpcKind = RpcSilent | RpcKatip mkRpc :: RpcKind -> Q [Dec] mkRpc k = do m <- VarT <$> newName "m" [d| getInfo :: $(tcc m) => LndEnv -> $(pure m) (Either LndError GI.GetInfoResponse) getInfo env = $(grpcRetry) $ ($(grpcCatchWalletLock) env) $ $(grpcSync) (RPC :: RPC LnGRPC.Lightning "getInfo") env (defMessage :: LnGRPC.GetInfoRequest) getInfoNoUnlock :: $(tcc m) => LndEnv -> $(pure m) (Either LndError GI.GetInfoResponse) getInfoNoUnlock env = $(grpcRetry) $ $(grpcSync) (RPC :: RPC LnGRPC.Lightning "getInfo") env (defMessage :: LnGRPC.GetInfoRequest) initWallet :: $(tcc m) => LndEnv -> $(pure m) (Either LndError ()) initWallet env = do case envLndCipherSeedMnemonic env of Nothing -> pure . Left $ LndEnvError "CipherSeed is required for initWallet" Just seed -> do res <- $(grpcRetry) $ $(grpcSync) (RPC :: RPC LnGRPC.WalletUnlocker "initWallet") env IW.InitWalletRequest { IW.walletPassword = envLndWalletPassword env, IW.cipherSeedMnemonic = seed, IW.aezeedPassphrase = envLndAezeedPassphrase env } if isRight res then waitForGrpc env else return res unlockWallet :: $(tcc m) => LndEnv -> $(pure m) (Either LndError ()) unlockWallet env = do res <- $(grpcRetry) $ $(grpcSync) (RPC :: RPC LnGRPC.WalletUnlocker "unlockWallet") env UW.UnlockWalletRequest { UW.walletPassword = envLndWalletPassword env, UW.recoveryWindow = 100 } if isRight res then waitForGrpc env else return res newAddress :: $(tcc m) => LndEnv -> NewAddressRequest -> $(pure m) (Either LndError NewAddressResponse) newAddress env = $(grpcRetry) . ($(grpcCatchWalletLock) env) . $(grpcSync) (RPC :: RPC LnGRPC.Lightning "newAddress") env addInvoice :: $(tcc m) => LndEnv -> AddInvoiceRequest -> $(pure m) (Either LndError AddInvoiceResponse) addInvoice env = $(grpcRetry) . ($(grpcCatchWalletLock) env) . $(grpcSync) (RPC :: RPC LnGRPC.Lightning "addInvoice") env addHodlInvoice :: $(tcc m) => LndEnv -> AddHodlInvoiceRequest -> $(pure m) (Either LndError PaymentRequest) addHodlInvoice env = $(grpcRetry) . ($(grpcCatchWalletLock) env) . $(grpcSync) (RPC :: RPC LnGRPC.Invoices "addHoldInvoice") env cancelInvoice :: $(tcc m) => LndEnv -> RHash -> $(pure m) (Either LndError ()) cancelInvoice env = $(grpcRetry) . ($(grpcCatchWalletLock) env) . $(grpcSync) (RPC :: RPC LnGRPC.Invoices "cancelInvoice") env settleInvoice :: $(tcc m) => LndEnv -> RPreimage -> $(pure m) (Either LndError ()) settleInvoice env = $(grpcRetry) . ($(grpcCatchWalletLock) env) . $(grpcSync) (RPC :: RPC LnGRPC.Invoices "settleInvoice") env subscribeSingleInvoice :: $(tcc m) => (Invoice -> IO ()) -> LndEnv -> RHash -> $(pure m) (Either LndError ()) subscribeSingleInvoice handler env = ($(grpcCatchWalletLock) env) . $(grpcSubscribe) (RPC :: RPC LnGRPC.Invoices "subscribeSingleInvoice") handler env subscribeSingleInvoiceChan :: $(tcc m) => (req -> RHash) -> Maybe (TChan (req, Invoice)) -> LndEnv -> req -> $(pure m) (Either LndError ()) subscribeSingleInvoiceChan accessor mq env req = do q <- fromMaybeM (atomically newBroadcastTChan) $ pure mq subscribeSingleInvoice (\x -> atomically $ writeTChan q (req, x)) env $ accessor req subscribeInvoices :: $(tcc m) => (Invoice -> IO ()) -> LndEnv -> SubscribeInvoicesRequest -> $(pure m) (Either LndError ()) subscribeInvoices handler env = ($(grpcCatchWalletLock) env) . $(grpcSubscribe) (RPC :: RPC LnGRPC.Lightning "subscribeInvoices") handler env subscribeInvoicesChan :: $(tcc m) => Maybe (TChan (SubscribeInvoicesRequest, Invoice)) -> LndEnv -> SubscribeInvoicesRequest -> $(pure m) (Either LndError ()) subscribeInvoicesChan mq env req = do q <- fromMaybeM (atomically newBroadcastTChan) $ pure mq subscribeInvoices (\x -> atomically $ writeTChan q (req, x)) env req subscribeChannelEvents :: $(tcc m) => (ChannelEventUpdate -> IO ()) -> LndEnv -> $(pure m) (Either LndError ()) subscribeChannelEvents handler env = ($(grpcCatchWalletLock) env) $ $(grpcSubscribe) (RPC :: RPC LnGRPC.Lightning "subscribeChannelEvents") handler env (defMessage :: LnGRPC.ChannelEventSubscription) subscribeChannelEventsChan :: $(tcc m) => Maybe (TChan ((), ChannelEventUpdate)) -> LndEnv -> $(pure m) (Either LndError ()) subscribeChannelEventsChan mq env = do q <- fromMaybeM (atomically newBroadcastTChan) $ pure mq subscribeChannelEvents (\x -> atomically $ writeTChan q ((), x)) env openChannel :: $(tcc m) => (OpenStatusUpdate -> IO ()) -> LndEnv -> OpenChannelRequest -> $(pure m) (Either LndError ()) openChannel handler env = ($(grpcCatchWalletLock) env) . $(grpcSubscribe) (RPC :: RPC LnGRPC.Lightning "openChannel") handler env openChannelSync :: $(tcc m) => LndEnv -> OpenChannelRequest -> $(pure m) (Either LndError ChannelPoint) openChannelSync env = ($(grpcCatchWalletLock) env) . $(grpcSync) (RPC :: RPC LnGRPC.Lightning "openChannelSync") env listChannels :: $(tcc m) => LndEnv -> ListChannelsRequest -> $(pure m) (Either LndError [Channel]) listChannels env = $(grpcRetry) . ($(grpcCatchWalletLock) env) . $(grpcSync) (RPC :: RPC LnGRPC.Lightning "listChannels") env listInvoices :: $(tcc m) => LndEnv -> ListInvoiceRequest -> $(pure m) (Either LndError ListInvoiceResponse) listInvoices env = $(grpcRetry) . ($(grpcCatchWalletLock) env) . $(grpcSync) (RPC :: RPC LnGRPC.Lightning "listInvoices") env closedChannels :: $(tcc m) => LndEnv -> ClosedChannelsRequest -> $(pure m) (Either LndError [ChannelCloseSummary]) closedChannels env = $(grpcRetry) . ($(grpcCatchWalletLock) env) . $(grpcSync) (RPC :: RPC LnGRPC.Lightning "closedChannels") env closeChannel :: $(tcc m) => (CloseStatusUpdate -> IO ()) -> LndEnv -> CloseChannelRequest -> $(pure m) (Either LndError ()) closeChannel handler env = ($(grpcCatchWalletLock) env) . $(grpcSubscribe) (RPC :: RPC LnGRPC.Lightning "closeChannel") handler env listPeers :: $(tcc m) => LndEnv -> $(pure m) (Either LndError [Peer]) listPeers env = $(grpcRetry) $ ($(grpcCatchWalletLock) env) $ $(grpcSync) (RPC :: RPC LnGRPC.Lightning "listPeers") env (defMessage :: LnGRPC.ListPeersRequest) connectPeer :: $(tcc m) => LndEnv -> ConnectPeerRequest -> $(pure m) (Either LndError ()) connectPeer env = $(grpcRetry) . ($(grpcCatchWalletLock) env) . $(grpcSync) (RPC :: RPC LnGRPC.Lightning "connectPeer") env lazyConnectPeer :: $(tcc m) => LndEnv -> ConnectPeerRequest -> $(pure m) (Either LndError ()) lazyConnectPeer env cpr = do eps <- listPeers env case eps of Left e -> return $ Left e Right ps -> if any ((== pk) . pubKey) ps then return $ Right () else connectPeer env cpr where pk = pubkey $ addr cpr sendPayment :: $(tcc m) => LndEnv -> SendPaymentRequest -> $(pure m) (Either LndError SendPaymentResponse) sendPayment env = $(grpcRetry) . ($(grpcCatchWalletLock) env) . $(grpcSync) (RPC :: RPC LnGRPC.Lightning "sendPaymentSync") env fundPsbt :: $(tcc m) => LndEnv -> FundPsbtRequest -> $(pure m) (Either LndError FundPsbtResponse) fundPsbt env = $(grpcRetry) . ($(grpcCatchWalletLock) env) . $(grpcSync) (RPC :: RPC LnGRPC.WalletKit "fundPsbt") env finalizePsbt :: $(tcc m) => LndEnv -> FinalizePsbtRequest -> $(pure m) (Either LndError FinalizePsbtResponse) finalizePsbt env = $(grpcRetry) . ($(grpcCatchWalletLock) env) . $(grpcSync) (RPC :: RPC LnGRPC.WalletKit "finalizePsbt") env publishTransaction :: $(tcc m) => LndEnv -> PublishTransactionRequest -> $(pure m) (Either LndError PublishTransactionResponse) publishTransaction env = $(grpcRetry) . ($(grpcCatchWalletLock) env) . $(grpcSync) (RPC :: RPC LnGRPC.WalletKit "publishTransaction") env listUnspent :: $(tcc m) => LndEnv -> ListUnspentRequest -> $(pure m) (Either LndError ListUnspentResponse) listUnspent env = $(grpcRetry) . ($(grpcCatchWalletLock) env) . $(grpcSync) (RPC :: RPC LnGRPC.WalletKit "listUnspent") env listLeases :: $(tcc m) => LndEnv -> ListLeasesRequest -> $(pure m) (Either LndError ListLeasesResponse) listLeases env = $(grpcRetry) . ($(grpcCatchWalletLock) env) . $(grpcSync) (RPC :: RPC LnGRPC.WalletKit "listLeases") env leaseOutput :: $(tcc m) => LndEnv -> LeaseOutputRequest -> $(pure m) (Either LndError LeaseOutputResponse) leaseOutput env = $(grpcRetry) . ($(grpcCatchWalletLock) env) . $(grpcSync) (RPC :: RPC LnGRPC.WalletKit "leaseOutput") env releaseOutput :: $(tcc m) => LndEnv -> ReleaseOutputRequest -> $(pure m) (Either LndError ReleaseOutputResponse) releaseOutput env = $(grpcRetry) . ($(grpcCatchWalletLock) env) . $(grpcSync) (RPC :: RPC LnGRPC.WalletKit "releaseOutput") env sendCoins :: $(tcc m) => LndEnv -> SendCoinsRequest -> $(pure m) (Either LndError SendCoinsResponse) sendCoins env = ($(grpcCatchWalletLock) env) . $(grpcSync) (RPC :: RPC LnGRPC.Lightning "sendCoins") env subscribeHtlcEvents :: $(tcc m) => (HtlcEvent -> IO ()) -> LndEnv -> $(pure m) (Either LndError ()) subscribeHtlcEvents handler env = ($(grpcCatchWalletLock) env) $ $(grpcSubscribe) (RPC :: RPC LnGRPC.Router "subscribeHtlcEvents") handler env (defMessage :: LnGRPC.SubscribeHtlcEventsRequest) decodePayReq :: $(tcc m) => LndEnv -> PaymentRequest -> $(pure m) (Either LndError PayReq) decodePayReq env = $(grpcRetry) . ($(grpcCatchWalletLock) env) . $(grpcSync) (RPC :: RPC LnGRPC.Lightning "decodePayReq") env lookupInvoice :: $(tcc m) => LndEnv -> RHash -> $(pure m) (Either LndError Invoice) lookupInvoice env = $(grpcRetry) . ($(grpcCatchWalletLock) env) . $(grpcSync) (RPC :: RPC LnGRPC.Lightning "lookupInvoice") env trackPaymentV2 :: $(tcc m) => (Payment -> IO ()) -> LndEnv -> TrackPaymentRequest -> $(pure m) (Either LndError ()) trackPaymentV2 handler env = ($(grpcCatchWalletLock) env) . $(grpcSubscribe) (RPC :: RPC LnGRPC.Router "trackPaymentV2") handler env trackPaymentV2Chan :: $(tcc m) => Maybe (TChan (TrackPaymentRequest, Payment)) -> LndEnv -> TrackPaymentRequest -> $(pure m) (Either LndError ()) trackPaymentV2Chan mc env req = do q <- fromMaybeM (atomically newBroadcastTChan) $ pure mc trackPaymentV2 (\x -> atomically $ writeTChan q (req, x)) env req pendingChannels :: $(tcc m) => LndEnv -> $(pure m) (Either LndError PendingChannelsResponse) pendingChannels env = $(grpcRetry) $ ($(grpcCatchWalletLock) env) $ $(grpcSync) (RPC :: RPC LnGRPC.Lightning "pendingChannels") env (defMessage :: LnGRPC.PendingChannelsRequest) signMessage :: $(tcc m) => LndEnv -> SignMessageRequest -> $(pure m) (Either LndError SignMessageResponse) signMessage env = $(grpcRetry) . ($(grpcCatchWalletLock) env) . $(grpcSync) (RPC :: RPC LnGRPC.Signer "signMessage") env verifyMessage :: $(tcc m) => LndEnv -> VM.VerifyMessageRequest -> $(pure m) (Either LndError VM.VerifyMessageResponse) verifyMessage env = $(grpcRetry) . ($(grpcCatchWalletLock) env) . $(grpcSync) (RPC :: RPC LnGRPC.Signer "verifyMessage") env fundingStateStep :: $(tcc m) => LndEnv -> FSS.FundingStateStepRequest -> $(pure m) (Either LndError ()) fundingStateStep env = $(grpcRetry) . ($(grpcCatchWalletLock) env) . $(grpcSync) (RPC :: RPC LnGRPC.Lightning "fundingStateStep") env exportAllChannelBackups :: $(tcc m) => LndEnv -> $(pure m) (Either LndError [Bak.ChannelBackup]) exportAllChannelBackups env = $(grpcRetry) $ ($(grpcCatchWalletLock) env) $ $(grpcSync) (RPC :: RPC LnGRPC.Lightning "exportAllChannelBackups") env (defMessage :: LnGRPC.ChanBackupExportRequest) exportChannelBackup :: $(tcc m) => LndEnv -> ChannelPoint -> $(pure m) (Either LndError Bak.ChannelBackup) exportChannelBackup env = $(grpcRetry) . ($(grpcCatchWalletLock) env) . $(grpcSync) (RPC :: RPC LnGRPC.Lightning "exportChannelBackup") env restoreChannelBackups :: $(tcc m) => LndEnv -> [Bak.ChannelBackup] -> $(pure m) (Either LndError ()) restoreChannelBackups env = $(grpcRetry) . ($(grpcCatchWalletLock) env) . $(grpcSync) (RPC :: RPC LnGRPC.Lightning "restoreChannelBackups") env walletBalance :: $(tcc m) => LndEnv -> $(pure m) (Either LndError Wallet.WalletBalance) walletBalance env = $(grpcRetry) . ($(grpcCatchWalletLock) env) $ $(grpcSync) (RPC :: RPC LnGRPC.Lightning "walletBalance") env (defMessage :: LnGRPC.WalletBalanceRequest) channelBalance :: $(tcc m) => LndEnv -> $(pure m) (Either LndError ChannelBalance.ChannelBalanceResponse) channelBalance env = $(grpcRetry) . ($(grpcCatchWalletLock) env) $ $(grpcSync) (RPC :: RPC LnGRPC.Lightning "channelBalance") env (defMessage :: LnGRPC.ChannelBalanceRequest) |] where tcc :: TH.Type -> Q TH.Type tcc m = case k of RpcSilent -> [t| ( MonadUnliftIO $(pure m) ) |] RpcKatip -> [t| ( KatipContext $(pure m), MonadUnliftIO $(pure m) ) |] grpcRetry :: Q Exp grpcRetry = case k of RpcSilent -> [e|retrySilent|] RpcKatip -> [e|retryKatip|] grpcSync :: Q Exp grpcSync = case k of RpcSilent -> [e|grpcSyncSilent|] RpcKatip -> [e|grpcSyncKatip|] grpcSubscribe :: Q Exp grpcSubscribe = case k of RpcSilent -> [e|grpcSubscribeSilent|] RpcKatip -> [e|grpcSubscribeKatip|] grpcCatchWalletLock :: Q Exp grpcCatchWalletLock = case k of RpcSilent -> [e|grpcCatchWalletLockSilent|] RpcKatip -> [e|grpcCatchWalletLockKatip|]
null
https://raw.githubusercontent.com/coingaming/lnd-client/dbe701fd030a3562fbbfdd2096cc0b918261f15a/src/LndClient/RPC/TH.hs
haskell
# LANGUAGE DuplicateRecordFields # # LANGUAGE TemplateHaskell # module LndClient.RPC.TH ( mkRpc, RpcKind (..), ) where import Language.Haskell.TH.Syntax as TH import LndClient.Data.AddHodlInvoice (AddHodlInvoiceRequest (..)) import LndClient.Data.AddInvoice (AddInvoiceRequest (..), AddInvoiceResponse (..)) import LndClient.Data.Channel (Channel (..)) import qualified LndClient.Data.ChannelBackup as Bak import qualified LndClient.Data.ChannelBalance as ChannelBalance import LndClient.Data.ChannelPoint (ChannelPoint (..)) import LndClient.Data.CloseChannel ( ChannelCloseSummary (..), CloseChannelRequest (..), CloseStatusUpdate (..), ) import LndClient.Data.ClosedChannels (ClosedChannelsRequest (..)) import LndClient.Data.FinalizePsbt import LndClient.Data.FundPsbt (FundPsbtRequest, FundPsbtResponse) import qualified LndClient.Data.FundingStateStep as FSS import qualified LndClient.Data.GetInfo as GI import LndClient.Data.HtlcEvent (HtlcEvent (..)) import qualified LndClient.Data.InitWallet as IW import LndClient.Data.Invoice (Invoice (..)) import LndClient.Data.LeaseOutput (LeaseOutputRequest, LeaseOutputResponse) import LndClient.Data.ListChannels (ListChannelsRequest (..)) import LndClient.Data.ListInvoices (ListInvoiceRequest (..), ListInvoiceResponse (..)) import LndClient.Data.ListLeases (ListLeasesRequest, ListLeasesResponse) import LndClient.Data.ListUnspent import LndClient.Data.NewAddress (NewAddressRequest (..), NewAddressResponse (..)) import LndClient.Data.OpenChannel (OpenChannelRequest (..), OpenStatusUpdate (..)) import LndClient.Data.PayReq (PayReq (..)) import LndClient.Data.Payment (Payment (..)) import LndClient.Data.Peer ( ConnectPeerRequest (..), LightningAddress (..), Peer (..), ) import LndClient.Data.PendingChannels (PendingChannelsResponse (..)) import LndClient.Data.PublishTransaction (PublishTransactionRequest, PublishTransactionResponse) import LndClient.Data.ReleaseOutput (ReleaseOutputRequest, ReleaseOutputResponse) import LndClient.Data.SendCoins (SendCoinsRequest, SendCoinsResponse) import LndClient.Data.SendPayment (SendPaymentRequest (..), SendPaymentResponse (..)) import LndClient.Data.SignMessage ( SignMessageRequest (..), SignMessageResponse (..), ) import LndClient.Data.SubscribeChannelEvents (ChannelEventUpdate (..)) import LndClient.Data.SubscribeInvoices ( SubscribeInvoicesRequest (..), ) import LndClient.Data.TrackPayment (TrackPaymentRequest (..)) import qualified LndClient.Data.UnlockWallet as UW import qualified LndClient.Data.VerifyMessage as VM ( VerifyMessageRequest (..), VerifyMessageResponse (..), ) import qualified LndClient.Data.WalletBalance as Wallet import LndClient.Import import LndClient.RPC.Generic import Network.GRPC.HTTP2.ProtoLens (RPC (..)) import qualified Proto.Invoicesrpc.Invoices as LnGRPC import qualified Proto.Lightning as LnGRPC import qualified Proto.Lnrpc.Ln0 as LnGRPC import qualified Proto.Lnrpc.Ln1 as LnGRPC import qualified Proto.Routerrpc.Router as LnGRPC import qualified Proto.Signrpc.Signer as LnGRPC import qualified Proto.Walletrpc.Walletkit as LnGRPC import qualified Proto.Walletunlocker as LnGRPC data RpcKind = RpcSilent | RpcKatip mkRpc :: RpcKind -> Q [Dec] mkRpc k = do m <- VarT <$> newName "m" [d| getInfo :: $(tcc m) => LndEnv -> $(pure m) (Either LndError GI.GetInfoResponse) getInfo env = $(grpcRetry) $ ($(grpcCatchWalletLock) env) $ $(grpcSync) (RPC :: RPC LnGRPC.Lightning "getInfo") env (defMessage :: LnGRPC.GetInfoRequest) getInfoNoUnlock :: $(tcc m) => LndEnv -> $(pure m) (Either LndError GI.GetInfoResponse) getInfoNoUnlock env = $(grpcRetry) $ $(grpcSync) (RPC :: RPC LnGRPC.Lightning "getInfo") env (defMessage :: LnGRPC.GetInfoRequest) initWallet :: $(tcc m) => LndEnv -> $(pure m) (Either LndError ()) initWallet env = do case envLndCipherSeedMnemonic env of Nothing -> pure . Left $ LndEnvError "CipherSeed is required for initWallet" Just seed -> do res <- $(grpcRetry) $ $(grpcSync) (RPC :: RPC LnGRPC.WalletUnlocker "initWallet") env IW.InitWalletRequest { IW.walletPassword = envLndWalletPassword env, IW.cipherSeedMnemonic = seed, IW.aezeedPassphrase = envLndAezeedPassphrase env } if isRight res then waitForGrpc env else return res unlockWallet :: $(tcc m) => LndEnv -> $(pure m) (Either LndError ()) unlockWallet env = do res <- $(grpcRetry) $ $(grpcSync) (RPC :: RPC LnGRPC.WalletUnlocker "unlockWallet") env UW.UnlockWalletRequest { UW.walletPassword = envLndWalletPassword env, UW.recoveryWindow = 100 } if isRight res then waitForGrpc env else return res newAddress :: $(tcc m) => LndEnv -> NewAddressRequest -> $(pure m) (Either LndError NewAddressResponse) newAddress env = $(grpcRetry) . ($(grpcCatchWalletLock) env) . $(grpcSync) (RPC :: RPC LnGRPC.Lightning "newAddress") env addInvoice :: $(tcc m) => LndEnv -> AddInvoiceRequest -> $(pure m) (Either LndError AddInvoiceResponse) addInvoice env = $(grpcRetry) . ($(grpcCatchWalletLock) env) . $(grpcSync) (RPC :: RPC LnGRPC.Lightning "addInvoice") env addHodlInvoice :: $(tcc m) => LndEnv -> AddHodlInvoiceRequest -> $(pure m) (Either LndError PaymentRequest) addHodlInvoice env = $(grpcRetry) . ($(grpcCatchWalletLock) env) . $(grpcSync) (RPC :: RPC LnGRPC.Invoices "addHoldInvoice") env cancelInvoice :: $(tcc m) => LndEnv -> RHash -> $(pure m) (Either LndError ()) cancelInvoice env = $(grpcRetry) . ($(grpcCatchWalletLock) env) . $(grpcSync) (RPC :: RPC LnGRPC.Invoices "cancelInvoice") env settleInvoice :: $(tcc m) => LndEnv -> RPreimage -> $(pure m) (Either LndError ()) settleInvoice env = $(grpcRetry) . ($(grpcCatchWalletLock) env) . $(grpcSync) (RPC :: RPC LnGRPC.Invoices "settleInvoice") env subscribeSingleInvoice :: $(tcc m) => (Invoice -> IO ()) -> LndEnv -> RHash -> $(pure m) (Either LndError ()) subscribeSingleInvoice handler env = ($(grpcCatchWalletLock) env) . $(grpcSubscribe) (RPC :: RPC LnGRPC.Invoices "subscribeSingleInvoice") handler env subscribeSingleInvoiceChan :: $(tcc m) => (req -> RHash) -> Maybe (TChan (req, Invoice)) -> LndEnv -> req -> $(pure m) (Either LndError ()) subscribeSingleInvoiceChan accessor mq env req = do q <- fromMaybeM (atomically newBroadcastTChan) $ pure mq subscribeSingleInvoice (\x -> atomically $ writeTChan q (req, x)) env $ accessor req subscribeInvoices :: $(tcc m) => (Invoice -> IO ()) -> LndEnv -> SubscribeInvoicesRequest -> $(pure m) (Either LndError ()) subscribeInvoices handler env = ($(grpcCatchWalletLock) env) . $(grpcSubscribe) (RPC :: RPC LnGRPC.Lightning "subscribeInvoices") handler env subscribeInvoicesChan :: $(tcc m) => Maybe (TChan (SubscribeInvoicesRequest, Invoice)) -> LndEnv -> SubscribeInvoicesRequest -> $(pure m) (Either LndError ()) subscribeInvoicesChan mq env req = do q <- fromMaybeM (atomically newBroadcastTChan) $ pure mq subscribeInvoices (\x -> atomically $ writeTChan q (req, x)) env req subscribeChannelEvents :: $(tcc m) => (ChannelEventUpdate -> IO ()) -> LndEnv -> $(pure m) (Either LndError ()) subscribeChannelEvents handler env = ($(grpcCatchWalletLock) env) $ $(grpcSubscribe) (RPC :: RPC LnGRPC.Lightning "subscribeChannelEvents") handler env (defMessage :: LnGRPC.ChannelEventSubscription) subscribeChannelEventsChan :: $(tcc m) => Maybe (TChan ((), ChannelEventUpdate)) -> LndEnv -> $(pure m) (Either LndError ()) subscribeChannelEventsChan mq env = do q <- fromMaybeM (atomically newBroadcastTChan) $ pure mq subscribeChannelEvents (\x -> atomically $ writeTChan q ((), x)) env openChannel :: $(tcc m) => (OpenStatusUpdate -> IO ()) -> LndEnv -> OpenChannelRequest -> $(pure m) (Either LndError ()) openChannel handler env = ($(grpcCatchWalletLock) env) . $(grpcSubscribe) (RPC :: RPC LnGRPC.Lightning "openChannel") handler env openChannelSync :: $(tcc m) => LndEnv -> OpenChannelRequest -> $(pure m) (Either LndError ChannelPoint) openChannelSync env = ($(grpcCatchWalletLock) env) . $(grpcSync) (RPC :: RPC LnGRPC.Lightning "openChannelSync") env listChannels :: $(tcc m) => LndEnv -> ListChannelsRequest -> $(pure m) (Either LndError [Channel]) listChannels env = $(grpcRetry) . ($(grpcCatchWalletLock) env) . $(grpcSync) (RPC :: RPC LnGRPC.Lightning "listChannels") env listInvoices :: $(tcc m) => LndEnv -> ListInvoiceRequest -> $(pure m) (Either LndError ListInvoiceResponse) listInvoices env = $(grpcRetry) . ($(grpcCatchWalletLock) env) . $(grpcSync) (RPC :: RPC LnGRPC.Lightning "listInvoices") env closedChannels :: $(tcc m) => LndEnv -> ClosedChannelsRequest -> $(pure m) (Either LndError [ChannelCloseSummary]) closedChannels env = $(grpcRetry) . ($(grpcCatchWalletLock) env) . $(grpcSync) (RPC :: RPC LnGRPC.Lightning "closedChannels") env closeChannel :: $(tcc m) => (CloseStatusUpdate -> IO ()) -> LndEnv -> CloseChannelRequest -> $(pure m) (Either LndError ()) closeChannel handler env = ($(grpcCatchWalletLock) env) . $(grpcSubscribe) (RPC :: RPC LnGRPC.Lightning "closeChannel") handler env listPeers :: $(tcc m) => LndEnv -> $(pure m) (Either LndError [Peer]) listPeers env = $(grpcRetry) $ ($(grpcCatchWalletLock) env) $ $(grpcSync) (RPC :: RPC LnGRPC.Lightning "listPeers") env (defMessage :: LnGRPC.ListPeersRequest) connectPeer :: $(tcc m) => LndEnv -> ConnectPeerRequest -> $(pure m) (Either LndError ()) connectPeer env = $(grpcRetry) . ($(grpcCatchWalletLock) env) . $(grpcSync) (RPC :: RPC LnGRPC.Lightning "connectPeer") env lazyConnectPeer :: $(tcc m) => LndEnv -> ConnectPeerRequest -> $(pure m) (Either LndError ()) lazyConnectPeer env cpr = do eps <- listPeers env case eps of Left e -> return $ Left e Right ps -> if any ((== pk) . pubKey) ps then return $ Right () else connectPeer env cpr where pk = pubkey $ addr cpr sendPayment :: $(tcc m) => LndEnv -> SendPaymentRequest -> $(pure m) (Either LndError SendPaymentResponse) sendPayment env = $(grpcRetry) . ($(grpcCatchWalletLock) env) . $(grpcSync) (RPC :: RPC LnGRPC.Lightning "sendPaymentSync") env fundPsbt :: $(tcc m) => LndEnv -> FundPsbtRequest -> $(pure m) (Either LndError FundPsbtResponse) fundPsbt env = $(grpcRetry) . ($(grpcCatchWalletLock) env) . $(grpcSync) (RPC :: RPC LnGRPC.WalletKit "fundPsbt") env finalizePsbt :: $(tcc m) => LndEnv -> FinalizePsbtRequest -> $(pure m) (Either LndError FinalizePsbtResponse) finalizePsbt env = $(grpcRetry) . ($(grpcCatchWalletLock) env) . $(grpcSync) (RPC :: RPC LnGRPC.WalletKit "finalizePsbt") env publishTransaction :: $(tcc m) => LndEnv -> PublishTransactionRequest -> $(pure m) (Either LndError PublishTransactionResponse) publishTransaction env = $(grpcRetry) . ($(grpcCatchWalletLock) env) . $(grpcSync) (RPC :: RPC LnGRPC.WalletKit "publishTransaction") env listUnspent :: $(tcc m) => LndEnv -> ListUnspentRequest -> $(pure m) (Either LndError ListUnspentResponse) listUnspent env = $(grpcRetry) . ($(grpcCatchWalletLock) env) . $(grpcSync) (RPC :: RPC LnGRPC.WalletKit "listUnspent") env listLeases :: $(tcc m) => LndEnv -> ListLeasesRequest -> $(pure m) (Either LndError ListLeasesResponse) listLeases env = $(grpcRetry) . ($(grpcCatchWalletLock) env) . $(grpcSync) (RPC :: RPC LnGRPC.WalletKit "listLeases") env leaseOutput :: $(tcc m) => LndEnv -> LeaseOutputRequest -> $(pure m) (Either LndError LeaseOutputResponse) leaseOutput env = $(grpcRetry) . ($(grpcCatchWalletLock) env) . $(grpcSync) (RPC :: RPC LnGRPC.WalletKit "leaseOutput") env releaseOutput :: $(tcc m) => LndEnv -> ReleaseOutputRequest -> $(pure m) (Either LndError ReleaseOutputResponse) releaseOutput env = $(grpcRetry) . ($(grpcCatchWalletLock) env) . $(grpcSync) (RPC :: RPC LnGRPC.WalletKit "releaseOutput") env sendCoins :: $(tcc m) => LndEnv -> SendCoinsRequest -> $(pure m) (Either LndError SendCoinsResponse) sendCoins env = ($(grpcCatchWalletLock) env) . $(grpcSync) (RPC :: RPC LnGRPC.Lightning "sendCoins") env subscribeHtlcEvents :: $(tcc m) => (HtlcEvent -> IO ()) -> LndEnv -> $(pure m) (Either LndError ()) subscribeHtlcEvents handler env = ($(grpcCatchWalletLock) env) $ $(grpcSubscribe) (RPC :: RPC LnGRPC.Router "subscribeHtlcEvents") handler env (defMessage :: LnGRPC.SubscribeHtlcEventsRequest) decodePayReq :: $(tcc m) => LndEnv -> PaymentRequest -> $(pure m) (Either LndError PayReq) decodePayReq env = $(grpcRetry) . ($(grpcCatchWalletLock) env) . $(grpcSync) (RPC :: RPC LnGRPC.Lightning "decodePayReq") env lookupInvoice :: $(tcc m) => LndEnv -> RHash -> $(pure m) (Either LndError Invoice) lookupInvoice env = $(grpcRetry) . ($(grpcCatchWalletLock) env) . $(grpcSync) (RPC :: RPC LnGRPC.Lightning "lookupInvoice") env trackPaymentV2 :: $(tcc m) => (Payment -> IO ()) -> LndEnv -> TrackPaymentRequest -> $(pure m) (Either LndError ()) trackPaymentV2 handler env = ($(grpcCatchWalletLock) env) . $(grpcSubscribe) (RPC :: RPC LnGRPC.Router "trackPaymentV2") handler env trackPaymentV2Chan :: $(tcc m) => Maybe (TChan (TrackPaymentRequest, Payment)) -> LndEnv -> TrackPaymentRequest -> $(pure m) (Either LndError ()) trackPaymentV2Chan mc env req = do q <- fromMaybeM (atomically newBroadcastTChan) $ pure mc trackPaymentV2 (\x -> atomically $ writeTChan q (req, x)) env req pendingChannels :: $(tcc m) => LndEnv -> $(pure m) (Either LndError PendingChannelsResponse) pendingChannels env = $(grpcRetry) $ ($(grpcCatchWalletLock) env) $ $(grpcSync) (RPC :: RPC LnGRPC.Lightning "pendingChannels") env (defMessage :: LnGRPC.PendingChannelsRequest) signMessage :: $(tcc m) => LndEnv -> SignMessageRequest -> $(pure m) (Either LndError SignMessageResponse) signMessage env = $(grpcRetry) . ($(grpcCatchWalletLock) env) . $(grpcSync) (RPC :: RPC LnGRPC.Signer "signMessage") env verifyMessage :: $(tcc m) => LndEnv -> VM.VerifyMessageRequest -> $(pure m) (Either LndError VM.VerifyMessageResponse) verifyMessage env = $(grpcRetry) . ($(grpcCatchWalletLock) env) . $(grpcSync) (RPC :: RPC LnGRPC.Signer "verifyMessage") env fundingStateStep :: $(tcc m) => LndEnv -> FSS.FundingStateStepRequest -> $(pure m) (Either LndError ()) fundingStateStep env = $(grpcRetry) . ($(grpcCatchWalletLock) env) . $(grpcSync) (RPC :: RPC LnGRPC.Lightning "fundingStateStep") env exportAllChannelBackups :: $(tcc m) => LndEnv -> $(pure m) (Either LndError [Bak.ChannelBackup]) exportAllChannelBackups env = $(grpcRetry) $ ($(grpcCatchWalletLock) env) $ $(grpcSync) (RPC :: RPC LnGRPC.Lightning "exportAllChannelBackups") env (defMessage :: LnGRPC.ChanBackupExportRequest) exportChannelBackup :: $(tcc m) => LndEnv -> ChannelPoint -> $(pure m) (Either LndError Bak.ChannelBackup) exportChannelBackup env = $(grpcRetry) . ($(grpcCatchWalletLock) env) . $(grpcSync) (RPC :: RPC LnGRPC.Lightning "exportChannelBackup") env restoreChannelBackups :: $(tcc m) => LndEnv -> [Bak.ChannelBackup] -> $(pure m) (Either LndError ()) restoreChannelBackups env = $(grpcRetry) . ($(grpcCatchWalletLock) env) . $(grpcSync) (RPC :: RPC LnGRPC.Lightning "restoreChannelBackups") env walletBalance :: $(tcc m) => LndEnv -> $(pure m) (Either LndError Wallet.WalletBalance) walletBalance env = $(grpcRetry) . ($(grpcCatchWalletLock) env) $ $(grpcSync) (RPC :: RPC LnGRPC.Lightning "walletBalance") env (defMessage :: LnGRPC.WalletBalanceRequest) channelBalance :: $(tcc m) => LndEnv -> $(pure m) (Either LndError ChannelBalance.ChannelBalanceResponse) channelBalance env = $(grpcRetry) . ($(grpcCatchWalletLock) env) $ $(grpcSync) (RPC :: RPC LnGRPC.Lightning "channelBalance") env (defMessage :: LnGRPC.ChannelBalanceRequest) |] where tcc :: TH.Type -> Q TH.Type tcc m = case k of RpcSilent -> [t| ( MonadUnliftIO $(pure m) ) |] RpcKatip -> [t| ( KatipContext $(pure m), MonadUnliftIO $(pure m) ) |] grpcRetry :: Q Exp grpcRetry = case k of RpcSilent -> [e|retrySilent|] RpcKatip -> [e|retryKatip|] grpcSync :: Q Exp grpcSync = case k of RpcSilent -> [e|grpcSyncSilent|] RpcKatip -> [e|grpcSyncKatip|] grpcSubscribe :: Q Exp grpcSubscribe = case k of RpcSilent -> [e|grpcSubscribeSilent|] RpcKatip -> [e|grpcSubscribeKatip|] grpcCatchWalletLock :: Q Exp grpcCatchWalletLock = case k of RpcSilent -> [e|grpcCatchWalletLockSilent|] RpcKatip -> [e|grpcCatchWalletLockKatip|]
7c07a0dbb9bc0c27d05803be58615fefc2c1916ee4598b199408d502d32876b9
jgrodziski/keycloak-clojure
google.clj
(ns keycloak.vault.google (:require [clojure.string :as str] [keycloak.vault.protocol :refer [Vault write-secret! read-secret]]) (:import [com.google.cloud.secretmanager.v1 SecretManagerServiceClient ProjectName SecretName SecretPayload SecretVersion Secret Replication Replication$Automatic] [com.google.protobuf ByteString])) (defrecord GoogleSecretManager [project-id] Vault (write-secret! [vault secret-id payload] (if (not (str/blank? payload)) (let [sec-mgr-client (SecretManagerServiceClient/create)] (try (let [ project-name (ProjectName/of project-id) parent-secret (-> (Secret/newBuilder) (.setReplication (doto (Replication/newBuilder) (.setAutomatic (.build (Replication$Automatic/newBuilder))) (.build))) (.build)) created-secret (try (.createSecret sec-mgr-client project-name secret-id parent-secret) (catch com.google.api.gax.rpc.AlreadyExistsException aee (println (format "Secret %s already exist, now add a version with the payload" secret-id)))) secret-payload (-> (SecretPayload/newBuilder) (.setData (ByteString/copyFromUtf8 payload)) (.build)) secret-name (SecretName/of project-id secret-id) added-version (.addSecretVersion sec-mgr-client secret-name secret-payload)] added-version) (finally (.close sec-mgr-client)))) (println (format "payload is nil")))) (read-secret [vault secret-id] (let [sec-mgr-client (SecretManagerServiceClient/create)] (try (let [project-name (ProjectName/of project-id) secret-version (format "projects/%s/secrets/%s/versions/latest" project-id secret-id) version (try (.accessSecretVersion sec-mgr-client secret-version) (catch com.google.api.gax.rpc.NotFoundException nfe (println (format "Secret %s not found" secret-id))))] (println "read-secret" project-id secret-id) (when version (-> version (.getPayload) (.getData) (.toStringUtf8)) )) (finally (.close sec-mgr-client)))))) (comment (def sec-mgr (->GoogleSecretManager "adixe-1168")) (write-secret! sec-mgr "secret-test-2" "yo2") (read-secret sec-mgr "secret-test-3") (setenv "GOOGLE_APPLICATION_CREDENTIALS" "./resources/adixe-1168-fe1fc6bddbbf.json") )
null
https://raw.githubusercontent.com/jgrodziski/keycloak-clojure/39ca9845179fad17fefd60f353578de92dcaec0b/src/keycloak/vault/google.clj
clojure
(ns keycloak.vault.google (:require [clojure.string :as str] [keycloak.vault.protocol :refer [Vault write-secret! read-secret]]) (:import [com.google.cloud.secretmanager.v1 SecretManagerServiceClient ProjectName SecretName SecretPayload SecretVersion Secret Replication Replication$Automatic] [com.google.protobuf ByteString])) (defrecord GoogleSecretManager [project-id] Vault (write-secret! [vault secret-id payload] (if (not (str/blank? payload)) (let [sec-mgr-client (SecretManagerServiceClient/create)] (try (let [ project-name (ProjectName/of project-id) parent-secret (-> (Secret/newBuilder) (.setReplication (doto (Replication/newBuilder) (.setAutomatic (.build (Replication$Automatic/newBuilder))) (.build))) (.build)) created-secret (try (.createSecret sec-mgr-client project-name secret-id parent-secret) (catch com.google.api.gax.rpc.AlreadyExistsException aee (println (format "Secret %s already exist, now add a version with the payload" secret-id)))) secret-payload (-> (SecretPayload/newBuilder) (.setData (ByteString/copyFromUtf8 payload)) (.build)) secret-name (SecretName/of project-id secret-id) added-version (.addSecretVersion sec-mgr-client secret-name secret-payload)] added-version) (finally (.close sec-mgr-client)))) (println (format "payload is nil")))) (read-secret [vault secret-id] (let [sec-mgr-client (SecretManagerServiceClient/create)] (try (let [project-name (ProjectName/of project-id) secret-version (format "projects/%s/secrets/%s/versions/latest" project-id secret-id) version (try (.accessSecretVersion sec-mgr-client secret-version) (catch com.google.api.gax.rpc.NotFoundException nfe (println (format "Secret %s not found" secret-id))))] (println "read-secret" project-id secret-id) (when version (-> version (.getPayload) (.getData) (.toStringUtf8)) )) (finally (.close sec-mgr-client)))))) (comment (def sec-mgr (->GoogleSecretManager "adixe-1168")) (write-secret! sec-mgr "secret-test-2" "yo2") (read-secret sec-mgr "secret-test-3") (setenv "GOOGLE_APPLICATION_CREDENTIALS" "./resources/adixe-1168-fe1fc6bddbbf.json") )
3e34f13649e03cbcecc07d260a3c859b5ac22f74d220d7ed240cde129cef655d
openbadgefactory/salava
db.clj
(ns salava.oauth.db (:require [clojure.tools.logging :as log] [yesql.core :refer [defqueries]] [clojure.java.jdbc :as jdbc] [clojure.set :refer [rename-keys]] [clj-http.client :as http] [buddy.hashers :as hashers] [slingshot.slingshot :refer :all] [salava.core.helper :refer [dump]] [ring.middleware.session.cookie :refer [cookie-store]] [ring.middleware.session :refer [session-response]] [salava.core.util :as u :refer [get-db get-datasource get-site-url get-base-path save-file-from-http-url get-plugins]])) (defqueries "sql/oauth/queries.sql") (defn oauth-request [method url opts] (try (-> {:method method :url url :socket-timeout 30000 :conn-timeout 30000 :content-type :json :as :json} (merge opts) (http/request) (get :body)) (catch Exception ex (log/error "OAuth request failed") (log/error (.toString ex)) (throw+ "oauth/Cannotconnecttoservice")))) (defn access-token [method url opts] (let [response (oauth-request method url opts) access-token (:access_token response)] (when-not access-token TODO : ( log " OAuth request failed " _ ) (throw+ "oauth/Cannotconnecttoservice")) access-token)) (defn oauth-user [ctx url opts parse-fn] (let [user (oauth-request :get url opts)] (if-not user (throw+ "oauth/Cannotconnecttoservice")) (parse-fn ctx user))) (defn remove-oauth-user [ctx user-id service] (delete-oauth-user! {:user_id user-id :service service} (get-db ctx))) (defn remove-oauth-user-all-services [ctx user-id] (delete-oauth-user-all-services! {:user_id user-id} (get-db ctx))) (defn add-oauth-user [ctx user-id oauth-user-id service] (remove-oauth-user ctx user-id service) (insert-oauth-user! {:user_id user-id :oauth_user_id oauth-user-id :service service} (get-db ctx)) user-id) (defn insert-user-terms [ctx user-id status] (let [show-terms? (get-in ctx [:config :core :show-terms?] false)] (when show-terms? (try+ (do (insert-user-terms<! {:user_id user-id :status status} (get-db ctx)) {:status "success" :input status}) (catch Object _ {:status "error" :input status}) )))) (defn create-local-user [ctx oauth-user service] (try+ (let [picture-url (:picture_url oauth-user) profile-picture (if picture-url (save-file-from-http-url ctx (str picture-url))) email_notifications (get-in ctx [:config :user :email-notifications] true) new-user (-> oauth-user (dissoc :oauth_user_id :email :picture_url) (assoc :profile_picture profile-picture :email_notifications email_notifications)) new-user-id (:generated_key (insert-user<! new-user (get-db ctx))) _ (insert-user-email! {:email (:email oauth-user) :user_id new-user-id} (get-db ctx)) _ (add-oauth-user ctx new-user-id (:oauth_user_id oauth-user) service) ] #_new-user-id {:user-id new-user-id :new-user true}) (catch Object _ ;TODO: (log "Could not create user via OAuth" _) (throw+ "oauth/Unexpectederroroccured")))) (defn get-or-create-user [ctx service oauth-user current-user-id] (let [oauth-user-id (:oauth_user_id oauth-user) user-id (select-user-id-by-oauth-user-id-and-service {:oauth_user_id oauth-user-id :service service} (into {:result-set-fn first :row-fn :user_id} (get-db ctx))) {:keys [user_id verified]} (if-not user-id (select-user-id-by-email {:email (:email oauth-user)} (into {:result-set-fn first} (get-db ctx)))) user-id-by-email user_id] (if current-user-id (cond user-id (throw+ "oauth/Accountalreadyregistered") (and user-id-by-email (not= current-user-id user-id-by-email)) (throw+ "oauth/Emailalreadyregistered") (and user-id-by-email (= current-user-id user-id-by-email) (not verified)) (throw+ "oauth/Emailnotverified") :else (add-oauth-user ctx current-user-id oauth-user-id service)) (if user-id user-id (if user-id-by-email (if verified (add-oauth-user ctx user-id-by-email oauth-user-id service) (throw+ "oauth/Facebookemailnotverified")) (create-local-user ctx oauth-user service)))))) (defn login-status [ctx user-id service] (let [oauth-user-id (select-oauth-user-id {:user_id user-id :service service} (into {:result-set-fn first :row-fn :oauth_user_id} (get-db ctx))) password (select-user-password {:id user-id} (into {:result-set-fn first :row-fn :pass} (get-db ctx)))] {:active (boolean oauth-user-id) :no-password? (empty? password)})) (defn update-user-last_login [ctx user-id] (let [last_login (select-oauth-user-last-login {:id user-id} (into {:result-set-fn first :row-fn :last_login} (get-db ctx)))] (when last_login (store-user-last-visited! {:user_id user-id :value last_login} (get-db ctx))) (update-user-last_login! {:id user-id} (get-db ctx)))) (defn get-user-information [ctx user-id] (select-oauth-user-service {:user_id user-id} (into {:row-fn :service} (get-db ctx)))) (defn user-session [ctx user expires] (let [session (-> user (select-keys [:id :role :activated]) (assoc :private (get-in ctx [:config :core :private] false)) (assoc :last-visited (:last_login user)) (assoc :expires (+ (long (/ (System/currentTimeMillis) 1000)) expires))) temp-res (-> {:session {:identity session}} (session-response {} {:store (cookie-store {:key (get-in ctx [:config :core :session :secret])}) :root "/" :cookie-name "oauth2"})) session-str (get-in temp-res [:headers "Set-Cookie"])] (some->> session-str first (re-find #"oauth2=(.+)") last))) (defn authorization-code [ctx client_id user_id code_challenge] (let [auth_code (u/random-token user_id)] (jdbc/with-db-transaction [tx (:connection (get-db ctx))] (delete-oauth2-auth-code! {:user_id user_id :client_id client_id} {:connection tx}) (insert-oauth2-auth-code! {:user_id user_id :client_id client_id :auth_code auth_code :auth_code_challenge code_challenge} {:connection tx})) auth_code)) (defn- challenge-hash [code_verifier] (some->> code_verifier (u/digest "sha256") u/bytes->base64-url)) Expiry time for OAuth access token in seconds . (def token-expires 7200) (defn new-access-token [ctx client_id auth_code code_verifier] (when-let [user (select-oauth2-auth-code-user {:client_id client_id :auth_code auth_code :auth_code_challenge (challenge-hash code_verifier)} (u/get-db-1 ctx))] (let [rtoken (u/random-token auth_code) expires token-expires] (update-oauth2-auth-code! {:client_id client_id :auth_code auth_code :rtoken (hashers/derive rtoken {:alg :bcrypt+sha512})} (get-db ctx)) {:token_id (:token_id user) :access_token (user-session ctx user expires) :refresh_token (str (:id user) "-" rtoken) :token_type "bearer", :expires expires}))) (defn refresh-access-token [ctx client_id [user_id refresh_token]] (let [users (select-oauth2-refresh-token-user {:client_id client_id :user_id user_id} (u/get-db ctx))] (when-let [user (first (filter #(hashers/check refresh_token (:refresh_token %)) users))] (let [out-token (u/random-token refresh_token) enc-token (hashers/derive out-token {:alg :bcrypt+sha512}) expires token-expires] (update-oauth2-refresh-token! {:client_id client_id :id (:token_id user) :user_id (:id user) :rtoken enc-token} (get-db ctx)) {:access_token (user-session ctx user expires) :refresh_token (str (:id user) "-" out-token) :token_type "bearer" :expires expires})))) (defn set-firebase-token [ctx client-id user-id oauth2-id token] (update-oauth2-firebase-token! {:id oauth2-id :client_id client-id :user_id user-id :token token} (get-db ctx)) {:success true}) (defn unauthorize-client [ctx client_id user_id] (delete-oauth2-token! {:client_id client_id :user_id user_id} (get-db ctx)) {:action "unauthorize" :success true})
null
https://raw.githubusercontent.com/openbadgefactory/salava/97f05992406e4dcbe3c4bff75c04378d19606b61/src/clj/salava/oauth/db.clj
clojure
TODO: (log "Could not create user via OAuth" _)
(ns salava.oauth.db (:require [clojure.tools.logging :as log] [yesql.core :refer [defqueries]] [clojure.java.jdbc :as jdbc] [clojure.set :refer [rename-keys]] [clj-http.client :as http] [buddy.hashers :as hashers] [slingshot.slingshot :refer :all] [salava.core.helper :refer [dump]] [ring.middleware.session.cookie :refer [cookie-store]] [ring.middleware.session :refer [session-response]] [salava.core.util :as u :refer [get-db get-datasource get-site-url get-base-path save-file-from-http-url get-plugins]])) (defqueries "sql/oauth/queries.sql") (defn oauth-request [method url opts] (try (-> {:method method :url url :socket-timeout 30000 :conn-timeout 30000 :content-type :json :as :json} (merge opts) (http/request) (get :body)) (catch Exception ex (log/error "OAuth request failed") (log/error (.toString ex)) (throw+ "oauth/Cannotconnecttoservice")))) (defn access-token [method url opts] (let [response (oauth-request method url opts) access-token (:access_token response)] (when-not access-token TODO : ( log " OAuth request failed " _ ) (throw+ "oauth/Cannotconnecttoservice")) access-token)) (defn oauth-user [ctx url opts parse-fn] (let [user (oauth-request :get url opts)] (if-not user (throw+ "oauth/Cannotconnecttoservice")) (parse-fn ctx user))) (defn remove-oauth-user [ctx user-id service] (delete-oauth-user! {:user_id user-id :service service} (get-db ctx))) (defn remove-oauth-user-all-services [ctx user-id] (delete-oauth-user-all-services! {:user_id user-id} (get-db ctx))) (defn add-oauth-user [ctx user-id oauth-user-id service] (remove-oauth-user ctx user-id service) (insert-oauth-user! {:user_id user-id :oauth_user_id oauth-user-id :service service} (get-db ctx)) user-id) (defn insert-user-terms [ctx user-id status] (let [show-terms? (get-in ctx [:config :core :show-terms?] false)] (when show-terms? (try+ (do (insert-user-terms<! {:user_id user-id :status status} (get-db ctx)) {:status "success" :input status}) (catch Object _ {:status "error" :input status}) )))) (defn create-local-user [ctx oauth-user service] (try+ (let [picture-url (:picture_url oauth-user) profile-picture (if picture-url (save-file-from-http-url ctx (str picture-url))) email_notifications (get-in ctx [:config :user :email-notifications] true) new-user (-> oauth-user (dissoc :oauth_user_id :email :picture_url) (assoc :profile_picture profile-picture :email_notifications email_notifications)) new-user-id (:generated_key (insert-user<! new-user (get-db ctx))) _ (insert-user-email! {:email (:email oauth-user) :user_id new-user-id} (get-db ctx)) _ (add-oauth-user ctx new-user-id (:oauth_user_id oauth-user) service) ] #_new-user-id {:user-id new-user-id :new-user true}) (catch Object _ (throw+ "oauth/Unexpectederroroccured")))) (defn get-or-create-user [ctx service oauth-user current-user-id] (let [oauth-user-id (:oauth_user_id oauth-user) user-id (select-user-id-by-oauth-user-id-and-service {:oauth_user_id oauth-user-id :service service} (into {:result-set-fn first :row-fn :user_id} (get-db ctx))) {:keys [user_id verified]} (if-not user-id (select-user-id-by-email {:email (:email oauth-user)} (into {:result-set-fn first} (get-db ctx)))) user-id-by-email user_id] (if current-user-id (cond user-id (throw+ "oauth/Accountalreadyregistered") (and user-id-by-email (not= current-user-id user-id-by-email)) (throw+ "oauth/Emailalreadyregistered") (and user-id-by-email (= current-user-id user-id-by-email) (not verified)) (throw+ "oauth/Emailnotverified") :else (add-oauth-user ctx current-user-id oauth-user-id service)) (if user-id user-id (if user-id-by-email (if verified (add-oauth-user ctx user-id-by-email oauth-user-id service) (throw+ "oauth/Facebookemailnotverified")) (create-local-user ctx oauth-user service)))))) (defn login-status [ctx user-id service] (let [oauth-user-id (select-oauth-user-id {:user_id user-id :service service} (into {:result-set-fn first :row-fn :oauth_user_id} (get-db ctx))) password (select-user-password {:id user-id} (into {:result-set-fn first :row-fn :pass} (get-db ctx)))] {:active (boolean oauth-user-id) :no-password? (empty? password)})) (defn update-user-last_login [ctx user-id] (let [last_login (select-oauth-user-last-login {:id user-id} (into {:result-set-fn first :row-fn :last_login} (get-db ctx)))] (when last_login (store-user-last-visited! {:user_id user-id :value last_login} (get-db ctx))) (update-user-last_login! {:id user-id} (get-db ctx)))) (defn get-user-information [ctx user-id] (select-oauth-user-service {:user_id user-id} (into {:row-fn :service} (get-db ctx)))) (defn user-session [ctx user expires] (let [session (-> user (select-keys [:id :role :activated]) (assoc :private (get-in ctx [:config :core :private] false)) (assoc :last-visited (:last_login user)) (assoc :expires (+ (long (/ (System/currentTimeMillis) 1000)) expires))) temp-res (-> {:session {:identity session}} (session-response {} {:store (cookie-store {:key (get-in ctx [:config :core :session :secret])}) :root "/" :cookie-name "oauth2"})) session-str (get-in temp-res [:headers "Set-Cookie"])] (some->> session-str first (re-find #"oauth2=(.+)") last))) (defn authorization-code [ctx client_id user_id code_challenge] (let [auth_code (u/random-token user_id)] (jdbc/with-db-transaction [tx (:connection (get-db ctx))] (delete-oauth2-auth-code! {:user_id user_id :client_id client_id} {:connection tx}) (insert-oauth2-auth-code! {:user_id user_id :client_id client_id :auth_code auth_code :auth_code_challenge code_challenge} {:connection tx})) auth_code)) (defn- challenge-hash [code_verifier] (some->> code_verifier (u/digest "sha256") u/bytes->base64-url)) Expiry time for OAuth access token in seconds . (def token-expires 7200) (defn new-access-token [ctx client_id auth_code code_verifier] (when-let [user (select-oauth2-auth-code-user {:client_id client_id :auth_code auth_code :auth_code_challenge (challenge-hash code_verifier)} (u/get-db-1 ctx))] (let [rtoken (u/random-token auth_code) expires token-expires] (update-oauth2-auth-code! {:client_id client_id :auth_code auth_code :rtoken (hashers/derive rtoken {:alg :bcrypt+sha512})} (get-db ctx)) {:token_id (:token_id user) :access_token (user-session ctx user expires) :refresh_token (str (:id user) "-" rtoken) :token_type "bearer", :expires expires}))) (defn refresh-access-token [ctx client_id [user_id refresh_token]] (let [users (select-oauth2-refresh-token-user {:client_id client_id :user_id user_id} (u/get-db ctx))] (when-let [user (first (filter #(hashers/check refresh_token (:refresh_token %)) users))] (let [out-token (u/random-token refresh_token) enc-token (hashers/derive out-token {:alg :bcrypt+sha512}) expires token-expires] (update-oauth2-refresh-token! {:client_id client_id :id (:token_id user) :user_id (:id user) :rtoken enc-token} (get-db ctx)) {:access_token (user-session ctx user expires) :refresh_token (str (:id user) "-" out-token) :token_type "bearer" :expires expires})))) (defn set-firebase-token [ctx client-id user-id oauth2-id token] (update-oauth2-firebase-token! {:id oauth2-id :client_id client-id :user_id user-id :token token} (get-db ctx)) {:success true}) (defn unauthorize-client [ctx client_id user_id] (delete-oauth2-token! {:client_id client_id :user_id user_id} (get-db ctx)) {:action "unauthorize" :success true})
ed87a336dbd02064c3c599b1a49cae8b8b1890b0c626ce526719d630498941f6
BrunoBonacci/where
core_test.clj
(ns where.core-test (:use midje.sweet) (:use where.test-util) (:require [midje.util :refer [testable-privates]]) (:require [where.core :refer :all])) (testable-privates where.core f-and f-or) ;; Bootstrapping testing data (bootstrap) (facts "about `where`: with three paraters extractor, comparator, value" ((where :a = 1) {:a 1}) => truthy ((where :a = 1) {:a 2}) => falsey ((where :a = 1) {:b 1}) => falsey ((where :a not= 1) {:b 1}) => truthy ) (facts "about `where`: with nested maps" ((where (comp :b :a) = 1) {:a {:b 1}}) => truthy ((where (comp :b :a) = 1) {:a {:b 2}}) => falsey ((where (comp :b :a) = 1) {:c {:b 1}}) => falsey ((where (comp :b :a) = 1) {:a {:c 1}}) => falsey ) (facts "about `where`: with two paraters comparator, value" ((where = 1) 1) => truthy ((where not= 5) 1) => truthy ((where > 5) 3) => falsey ) (facts "about `where`: stuff you can do with maps" ;; simple map filtering (->> (filter (where :country = "USA") users) (map :country) (into #{})) => #{"USA"} (->> (filter (where :country not= "USA") users) (map :country) (into #{})) =not=> (contains #{"USA"}) (->> (filter (where :age > 18) users) (map :age) (reduce min)) => 19 (->> (filter (where (comp :high :scores) > 9950) users) count) => 4 ) (facts "about `where`: stuff you can do with lists" ;; simple list filtering (filter (where > 5) (range 10)) => [6 7 8 9] (let [square #(* % %)] (filter (where square < 50) (range 10))) => [0 1 2 3 4 5 6 7] ) (facts "about `where`: stuff you can do with sets" ;; simple list filtering (filter (where > 5) #{0 1 2 3 4 5 6 7 8 9} ) => (just [6 7 8 9] :in-any-order) ) (facts "about `where`: wrapping with brachets has the same behaviour of unwrapped" ((where [:a = 1]) {:a 1}) => truthy ((where [:a = 1]) {:a 2}) => falsey ((where [:a = 1]) {:b 1}) => falsey ((where [:a not= 1]) {:b 1}) => truthy ((where [= 1]) 1) => truthy ((where [not= 5]) 1) => truthy ((where [> 5]) 3) => falsey ) (facts "about `where`: composing predicates with logical and" ((where [:and [:a = 1] [:b = 2]]) {:a 1 :b 2}) => truthy ((where [:and [:a = 1] [:b = 2]]) {:a 1 :b 1}) => falsey ((where [:and [:a = 1] [:b = 2]]) {:a 2 :b 2}) => falsey ((where [:and [:a = 1] [:b > 1]]) {:a 1 :b 2}) => truthy ((where [:and [:a = 1] [:b > 1] [:b < 6]]) {:a 1 :b 2}) => truthy ((where [:and [:a = 1] [:b > 1] [:b < 6]]) {:a 1 :b 6}) => falsey (count (filter (where [:and [:country = "Russia"] [:age > 35] [:age < 60]]) users)) => 15 ) (facts "about `where`: composing predicates with logical or" ((where [:or [:a = 1] [:b = 2]]) {:a 1 :b 2}) => truthy ((where [:or [:a = 1] [:b = 2]]) {:a 1 :b 1}) => truthy ((where [:or [:a = 1] [:b = 2]]) {:a 3 :b 2}) => truthy ((where [:or [:a = 1] [:b = 2]]) {:a 0 :b 0}) => falsey ((where [:or [:a = 1] [:b < 1] [:b > 6]]) {:a 1 :b 2}) => truthy ((where [:or [:a = 1] [:b < 1] [:b > 6]]) {:a 2 :b 0}) => truthy ((where [:or [:a = 1] [:b < 1] [:b > 6]]) {:a 2 :b 9}) => truthy ((where [:or [:a = 1] [:b < 1] [:b > 6]]) {:a 2 :b 2}) => falsey ) (facts "about `where`: composing predicates with logical not" ((where [:not [:b = 2]]) {:a 1 :b 3}) => truthy ((where [:not [:b = 3]]) {:a 1 :b 3}) => falsey ((where [:not [:not [:b = 3]]]) {:a 1 :b 3}) => truthy ((where [:not [:b = 2] [:a = 2]]) {:a 1 :b 3}) => (throws IllegalArgumentException) ) (facts "about `where`: composing predicates with both logical operators" (->> (filter (where [:or [:country = "USA"] [:country = "Russia"]]) users) (map :country) (into #{})) => #{"USA" "Russia"} (let [result (filter (where [:and [:or [:country = "USA"] [:country = "Russia"]] [:active = true]]) users)] (->> result (map :country) (into #{})) => #{"USA" "Russia"} (some (complement :active) result) => falsey ) ;; outer AND composition (count (filter (where [:and [:or [:country = "Russia"] [:country = "USA"]] [:age > 35] [:age < 60]]) users)) => 30 ;; outer OR composition (count (filter (where [:or [:and [:age = 35] [:country = "USA"]] [:and [:age > 35] [:age < 55] [:country = "Russia"]]] )users)) => 10 ) (fact "`where`: with DSL unknown operators should throw exception" ((where :unknown-op "target") "value") => (throws IllegalArgumentException)) (tabular (fact "`where`: with DSL operators with strings" ((where ?operator ?target) ?value) => ?result ((where :value ?operator ?target) {:value ?value}) => ?result) ?value ?operator ?target ?result "value" :is? "value" truthy "value1" :is? "value" falsey "value" :is-not? "value" falsey "value1" :is-not? "value" truthy "value" :starts-with? "val" truthy "notval" :starts-with? "value" falsey "VALUE" :starts-with? "val" falsey nil :starts-with? "value" falsey "value" :starts-with? nil falsey "value" :ends-with? "lue" truthy "notval" :ends-with? "value" falsey "VALUE" :ends-with? "lue" falsey nil :ends-with? "value" falsey "value" :ends-with? nil falsey "values" :contains? "lue" truthy "notval" :contains? "value" falsey "VALUE" :contains? "alu" falsey nil :contains? "value" falsey "value" :contains? nil falsey "values" :not-contains? "lue" falsey "notval" :not-contains? "value" truthy nil :not-contains? "value" truthy "value" :not-contains? nil truthy "value 123" :matches? #"\w+ \d+" truthy "value 123" :matches? #"\d+" truthy "value 123" :matches? #"^\d+$" falsey "123" :matches? #"^\d+$" truthy nil :matches? #"^\d+$" falsey "123" :matches? nil falsey "value 123" :matches-exactly? #"\w+ \d+" truthy "value 123" :matches-exactly? #"\d+" falsey "value 123" :matches-exactly? #"^\d+$" falsey "123" :matches-exactly? #"^\d+$" truthy nil :matches-exactly? #"^\d+$" falsey "123" :matches-exactly? nil falsey "value 123" :glob-matches? "*" truthy "v" :glob-matches? "?" truthy "" :glob-matches? "*" truthy "" :glob-matches? "?" falsey "value 123" :glob-matches? "value*" truthy "value 123" :glob-matches? "*value*" truthy "value 123" :glob-matches? "va?ue*123" truthy "value 123" :glob-matches? "va?ue*12" falsey "VALUE 123" :glob-matches? "va?ue*12*" falsey "value 123" :glob-matches? "value?1??" truthy "value.123" :glob-matches? "value.321" falsey "value.123" :glob-matches? "value.1*" truthy "value?123" :glob-matches? "value\\?*" truthy "c*" :glob-matches? "c\\*" truthy "C*" :glob-matches? nil falsey nil :glob-matches? "c*" falsey "value 123" :not-glob-matches? "value?321*" truthy "value 123" :not-glob-matches? "value?123*" falsey ) (tabular (fact "`where`: with DSL operators with numbers" ((where ?operator ?target) ?value) => ?result ((where :value ?operator ?target) {:value ?value}) => ?result) ?value ?operator ?target ?result 42 :between? [35 45] truthy 35 :between? [35 45] truthy 45 :between? [35 45] truthy 34 :between? [35 45] falsey 46 :between? [35 45] falsey nil :between? [35 45] falsey 46 :between? [nil 45] falsey 46 :between? [35 nil] falsey 46 :between? nil falsey 42 :strictly-between? [35 45] truthy 35 :strictly-between? [35 45] falsey 45 :strictly-between? [35 45] falsey 34 :strictly-between? [35 45] falsey 46 :strictly-between? [35 45] falsey nil :strictly-between? [35 45] falsey 46 :strictly-between? [nil 45] falsey 46 :strictly-between? [35 nil] falsey 46 :strictly-between? nil falsey 42 :range? [35 45] truthy 35 :range? [35 45] truthy 45 :range? [35 45] falsey 34 :range? [35 45] falsey 46 :range? [35 45] falsey nil :range? [35 45] falsey 46 :range? [nil 45] falsey 46 :range? [35 nil] falsey 46 :range? nil falsey ) (tabular (fact "`where`: with DSL generic operators" ((where ?operator ?target) ?value) => ?result ((where :value ?operator ?target) {:value ?value}) => ?result) ?value ?operator ?target ?result "v1" :in? ["v1" "v2" "v3"] truthy "v3" :in? ["v1" "v2" "v3"] truthy "not-present" :in? ["v1" "v2" "v3"] falsey "not-present" :in? [] falsey "not-present" :in? nil falsey nil :in? ["v1" "v2" "v3"] falsey nil :in? nil falsey ) (tabular (fact "`where`: with DSL case insensitive operators with strings" ((where ?operator ?target) ?value) => ?result ((where :value ?operator ?target) {:value ?value}) => ?result) ?value ?operator ?target ?result "value" :STARTS-WITH? "val" truthy "notval" :STARTS-WITH? "value" falsey "VALUE" :STARTS-WITH? "val" truthy nil :STARTS-WITH? "value" falsey "value" :STARTS-WITH? nil falsey "value" :ENDS-WITH? "lue" truthy "notval" :ENDS-WITH? "value" falsey "VALUE" :ENDS-WITH? "lue" truthy nil :ENDS-WITH? "value" falsey "value" :ENDS-WITH? nil falsey "values" :CONTAINS? "lue" truthy "notval" :CONTAINS? "value" falsey "VALUE" :CONTAINS? "alu" truthy nil :CONTAINS? "value" falsey "value" :CONTAINS? nil falsey "values" :NOT-CONTAINS? "lue" falsey "values" :NOT-CONTAINS? "LUE" falsey "notval" :NOT-CONTAINS? "value" truthy nil :NOT-CONTAINS? "value" truthy "value" :NOT-CONTAINS? nil truthy "value 123" :MATCHES? #"VAL\w+ \d+" truthy "value 123" :MATCHES? #"\d+" truthy "value 123" :MATCHES? #"^\d+$" falsey "123" :MATCHES? #"^\d+$" truthy nil :MATCHES? #"^\d+$" falsey "123" :MATCHES? nil falsey "value 123" :MATCHES-EXACTLY? #"VAL\w+ \d+" truthy "value 123" :MATCHES-EXACTLY? #"\d+" falsey "value 123" :MATCHES-EXACTLY? #"^\d+$" falsey "123" :MATCHES-EXACTLY? #"^\d+$" truthy nil :MATCHES-EXACTLY? #"^\d+$" falsey "123" :MATCHES-EXACTLY? nil falsey "VALUE 123" :GLOB-MATCHES? "*" truthy "V" :GLOB-MATCHES? "?" truthy "" :GLOB-MATCHES? "*" truthy "" :GLOB-MATCHES? "?" falsey "VALUE 123" :GLOB-MATCHES? "value*" truthy "VALUE 123" :GLOB-MATCHES? "*value*" truthy "VALUE 123" :GLOB-MATCHES? "va?ue*123" truthy "VALUE 123" :GLOB-MATCHES? "va?ue*12" falsey "VALUE 123" :GLOB-MATCHES? "va?ue*12*" truthy "VALUE 123" :GLOB-MATCHES? "value?1??" truthy "VALUE.123" :GLOB-MATCHES? "value.321" falsey "VALUE.123" :GLOB-MATCHES? "value.1*" truthy "VALUE?123" :GLOB-MATCHES? "value\\?*" truthy "C*" :GLOB-MATCHES? "c\\*" truthy "C*" :GLOB-MATCHES? nil falsey nil :GLOB-MATCHES? "c*" falsey "VALUE 123" :NOT-GLOB-MATCHES? "value?321*" truthy "VALUE 123" :NOT-GLOB-MATCHES? "value?123*" falsey "value" :IS? "value" truthy "VALUE" :IS? "value" truthy "value" :IS? "VALUE" truthy nil :IS? "VALUE" falsey "value" :IS? nil falsey "value" :IS? "some" falsey "value" :IS-NOT? "value" falsey "VALUE" :IS-NOT? "value" falsey "value" :IS-NOT? "VALUE" falsey nil :IS-NOT? "VALUE" truthy "value" :IS-NOT? nil truthy "value" :IS-NOT? "some" truthy "value" :IN? ["value" ] truthy "VALUE" :IN? ["value" ] truthy "value" :IN? ["VALUE" ] truthy nil :IN? ["VALUE" ] falsey "value" :IN? [nil ] falsey "value" :IN? ["some" ] falsey "value" :IN? ["some" "wxy"] falsey "value" :IN? ["some" "value"] truthy "value" :NOT-IN? ["some" "wxy"] truthy )
null
https://raw.githubusercontent.com/BrunoBonacci/where/c47dd7760bb8f8d3a52273c262291ae3a48530b3/test/where/core_test.clj
clojure
Bootstrapping testing data simple map filtering simple list filtering simple list filtering outer AND composition outer OR composition
(ns where.core-test (:use midje.sweet) (:use where.test-util) (:require [midje.util :refer [testable-privates]]) (:require [where.core :refer :all])) (testable-privates where.core f-and f-or) (bootstrap) (facts "about `where`: with three paraters extractor, comparator, value" ((where :a = 1) {:a 1}) => truthy ((where :a = 1) {:a 2}) => falsey ((where :a = 1) {:b 1}) => falsey ((where :a not= 1) {:b 1}) => truthy ) (facts "about `where`: with nested maps" ((where (comp :b :a) = 1) {:a {:b 1}}) => truthy ((where (comp :b :a) = 1) {:a {:b 2}}) => falsey ((where (comp :b :a) = 1) {:c {:b 1}}) => falsey ((where (comp :b :a) = 1) {:a {:c 1}}) => falsey ) (facts "about `where`: with two paraters comparator, value" ((where = 1) 1) => truthy ((where not= 5) 1) => truthy ((where > 5) 3) => falsey ) (facts "about `where`: stuff you can do with maps" (->> (filter (where :country = "USA") users) (map :country) (into #{})) => #{"USA"} (->> (filter (where :country not= "USA") users) (map :country) (into #{})) =not=> (contains #{"USA"}) (->> (filter (where :age > 18) users) (map :age) (reduce min)) => 19 (->> (filter (where (comp :high :scores) > 9950) users) count) => 4 ) (facts "about `where`: stuff you can do with lists" (filter (where > 5) (range 10)) => [6 7 8 9] (let [square #(* % %)] (filter (where square < 50) (range 10))) => [0 1 2 3 4 5 6 7] ) (facts "about `where`: stuff you can do with sets" (filter (where > 5) #{0 1 2 3 4 5 6 7 8 9} ) => (just [6 7 8 9] :in-any-order) ) (facts "about `where`: wrapping with brachets has the same behaviour of unwrapped" ((where [:a = 1]) {:a 1}) => truthy ((where [:a = 1]) {:a 2}) => falsey ((where [:a = 1]) {:b 1}) => falsey ((where [:a not= 1]) {:b 1}) => truthy ((where [= 1]) 1) => truthy ((where [not= 5]) 1) => truthy ((where [> 5]) 3) => falsey ) (facts "about `where`: composing predicates with logical and" ((where [:and [:a = 1] [:b = 2]]) {:a 1 :b 2}) => truthy ((where [:and [:a = 1] [:b = 2]]) {:a 1 :b 1}) => falsey ((where [:and [:a = 1] [:b = 2]]) {:a 2 :b 2}) => falsey ((where [:and [:a = 1] [:b > 1]]) {:a 1 :b 2}) => truthy ((where [:and [:a = 1] [:b > 1] [:b < 6]]) {:a 1 :b 2}) => truthy ((where [:and [:a = 1] [:b > 1] [:b < 6]]) {:a 1 :b 6}) => falsey (count (filter (where [:and [:country = "Russia"] [:age > 35] [:age < 60]]) users)) => 15 ) (facts "about `where`: composing predicates with logical or" ((where [:or [:a = 1] [:b = 2]]) {:a 1 :b 2}) => truthy ((where [:or [:a = 1] [:b = 2]]) {:a 1 :b 1}) => truthy ((where [:or [:a = 1] [:b = 2]]) {:a 3 :b 2}) => truthy ((where [:or [:a = 1] [:b = 2]]) {:a 0 :b 0}) => falsey ((where [:or [:a = 1] [:b < 1] [:b > 6]]) {:a 1 :b 2}) => truthy ((where [:or [:a = 1] [:b < 1] [:b > 6]]) {:a 2 :b 0}) => truthy ((where [:or [:a = 1] [:b < 1] [:b > 6]]) {:a 2 :b 9}) => truthy ((where [:or [:a = 1] [:b < 1] [:b > 6]]) {:a 2 :b 2}) => falsey ) (facts "about `where`: composing predicates with logical not" ((where [:not [:b = 2]]) {:a 1 :b 3}) => truthy ((where [:not [:b = 3]]) {:a 1 :b 3}) => falsey ((where [:not [:not [:b = 3]]]) {:a 1 :b 3}) => truthy ((where [:not [:b = 2] [:a = 2]]) {:a 1 :b 3}) => (throws IllegalArgumentException) ) (facts "about `where`: composing predicates with both logical operators" (->> (filter (where [:or [:country = "USA"] [:country = "Russia"]]) users) (map :country) (into #{})) => #{"USA" "Russia"} (let [result (filter (where [:and [:or [:country = "USA"] [:country = "Russia"]] [:active = true]]) users)] (->> result (map :country) (into #{})) => #{"USA" "Russia"} (some (complement :active) result) => falsey ) (count (filter (where [:and [:or [:country = "Russia"] [:country = "USA"]] [:age > 35] [:age < 60]]) users)) => 30 (count (filter (where [:or [:and [:age = 35] [:country = "USA"]] [:and [:age > 35] [:age < 55] [:country = "Russia"]]] )users)) => 10 ) (fact "`where`: with DSL unknown operators should throw exception" ((where :unknown-op "target") "value") => (throws IllegalArgumentException)) (tabular (fact "`where`: with DSL operators with strings" ((where ?operator ?target) ?value) => ?result ((where :value ?operator ?target) {:value ?value}) => ?result) ?value ?operator ?target ?result "value" :is? "value" truthy "value1" :is? "value" falsey "value" :is-not? "value" falsey "value1" :is-not? "value" truthy "value" :starts-with? "val" truthy "notval" :starts-with? "value" falsey "VALUE" :starts-with? "val" falsey nil :starts-with? "value" falsey "value" :starts-with? nil falsey "value" :ends-with? "lue" truthy "notval" :ends-with? "value" falsey "VALUE" :ends-with? "lue" falsey nil :ends-with? "value" falsey "value" :ends-with? nil falsey "values" :contains? "lue" truthy "notval" :contains? "value" falsey "VALUE" :contains? "alu" falsey nil :contains? "value" falsey "value" :contains? nil falsey "values" :not-contains? "lue" falsey "notval" :not-contains? "value" truthy nil :not-contains? "value" truthy "value" :not-contains? nil truthy "value 123" :matches? #"\w+ \d+" truthy "value 123" :matches? #"\d+" truthy "value 123" :matches? #"^\d+$" falsey "123" :matches? #"^\d+$" truthy nil :matches? #"^\d+$" falsey "123" :matches? nil falsey "value 123" :matches-exactly? #"\w+ \d+" truthy "value 123" :matches-exactly? #"\d+" falsey "value 123" :matches-exactly? #"^\d+$" falsey "123" :matches-exactly? #"^\d+$" truthy nil :matches-exactly? #"^\d+$" falsey "123" :matches-exactly? nil falsey "value 123" :glob-matches? "*" truthy "v" :glob-matches? "?" truthy "" :glob-matches? "*" truthy "" :glob-matches? "?" falsey "value 123" :glob-matches? "value*" truthy "value 123" :glob-matches? "*value*" truthy "value 123" :glob-matches? "va?ue*123" truthy "value 123" :glob-matches? "va?ue*12" falsey "VALUE 123" :glob-matches? "va?ue*12*" falsey "value 123" :glob-matches? "value?1??" truthy "value.123" :glob-matches? "value.321" falsey "value.123" :glob-matches? "value.1*" truthy "value?123" :glob-matches? "value\\?*" truthy "c*" :glob-matches? "c\\*" truthy "C*" :glob-matches? nil falsey nil :glob-matches? "c*" falsey "value 123" :not-glob-matches? "value?321*" truthy "value 123" :not-glob-matches? "value?123*" falsey ) (tabular (fact "`where`: with DSL operators with numbers" ((where ?operator ?target) ?value) => ?result ((where :value ?operator ?target) {:value ?value}) => ?result) ?value ?operator ?target ?result 42 :between? [35 45] truthy 35 :between? [35 45] truthy 45 :between? [35 45] truthy 34 :between? [35 45] falsey 46 :between? [35 45] falsey nil :between? [35 45] falsey 46 :between? [nil 45] falsey 46 :between? [35 nil] falsey 46 :between? nil falsey 42 :strictly-between? [35 45] truthy 35 :strictly-between? [35 45] falsey 45 :strictly-between? [35 45] falsey 34 :strictly-between? [35 45] falsey 46 :strictly-between? [35 45] falsey nil :strictly-between? [35 45] falsey 46 :strictly-between? [nil 45] falsey 46 :strictly-between? [35 nil] falsey 46 :strictly-between? nil falsey 42 :range? [35 45] truthy 35 :range? [35 45] truthy 45 :range? [35 45] falsey 34 :range? [35 45] falsey 46 :range? [35 45] falsey nil :range? [35 45] falsey 46 :range? [nil 45] falsey 46 :range? [35 nil] falsey 46 :range? nil falsey ) (tabular (fact "`where`: with DSL generic operators" ((where ?operator ?target) ?value) => ?result ((where :value ?operator ?target) {:value ?value}) => ?result) ?value ?operator ?target ?result "v1" :in? ["v1" "v2" "v3"] truthy "v3" :in? ["v1" "v2" "v3"] truthy "not-present" :in? ["v1" "v2" "v3"] falsey "not-present" :in? [] falsey "not-present" :in? nil falsey nil :in? ["v1" "v2" "v3"] falsey nil :in? nil falsey ) (tabular (fact "`where`: with DSL case insensitive operators with strings" ((where ?operator ?target) ?value) => ?result ((where :value ?operator ?target) {:value ?value}) => ?result) ?value ?operator ?target ?result "value" :STARTS-WITH? "val" truthy "notval" :STARTS-WITH? "value" falsey "VALUE" :STARTS-WITH? "val" truthy nil :STARTS-WITH? "value" falsey "value" :STARTS-WITH? nil falsey "value" :ENDS-WITH? "lue" truthy "notval" :ENDS-WITH? "value" falsey "VALUE" :ENDS-WITH? "lue" truthy nil :ENDS-WITH? "value" falsey "value" :ENDS-WITH? nil falsey "values" :CONTAINS? "lue" truthy "notval" :CONTAINS? "value" falsey "VALUE" :CONTAINS? "alu" truthy nil :CONTAINS? "value" falsey "value" :CONTAINS? nil falsey "values" :NOT-CONTAINS? "lue" falsey "values" :NOT-CONTAINS? "LUE" falsey "notval" :NOT-CONTAINS? "value" truthy nil :NOT-CONTAINS? "value" truthy "value" :NOT-CONTAINS? nil truthy "value 123" :MATCHES? #"VAL\w+ \d+" truthy "value 123" :MATCHES? #"\d+" truthy "value 123" :MATCHES? #"^\d+$" falsey "123" :MATCHES? #"^\d+$" truthy nil :MATCHES? #"^\d+$" falsey "123" :MATCHES? nil falsey "value 123" :MATCHES-EXACTLY? #"VAL\w+ \d+" truthy "value 123" :MATCHES-EXACTLY? #"\d+" falsey "value 123" :MATCHES-EXACTLY? #"^\d+$" falsey "123" :MATCHES-EXACTLY? #"^\d+$" truthy nil :MATCHES-EXACTLY? #"^\d+$" falsey "123" :MATCHES-EXACTLY? nil falsey "VALUE 123" :GLOB-MATCHES? "*" truthy "V" :GLOB-MATCHES? "?" truthy "" :GLOB-MATCHES? "*" truthy "" :GLOB-MATCHES? "?" falsey "VALUE 123" :GLOB-MATCHES? "value*" truthy "VALUE 123" :GLOB-MATCHES? "*value*" truthy "VALUE 123" :GLOB-MATCHES? "va?ue*123" truthy "VALUE 123" :GLOB-MATCHES? "va?ue*12" falsey "VALUE 123" :GLOB-MATCHES? "va?ue*12*" truthy "VALUE 123" :GLOB-MATCHES? "value?1??" truthy "VALUE.123" :GLOB-MATCHES? "value.321" falsey "VALUE.123" :GLOB-MATCHES? "value.1*" truthy "VALUE?123" :GLOB-MATCHES? "value\\?*" truthy "C*" :GLOB-MATCHES? "c\\*" truthy "C*" :GLOB-MATCHES? nil falsey nil :GLOB-MATCHES? "c*" falsey "VALUE 123" :NOT-GLOB-MATCHES? "value?321*" truthy "VALUE 123" :NOT-GLOB-MATCHES? "value?123*" falsey "value" :IS? "value" truthy "VALUE" :IS? "value" truthy "value" :IS? "VALUE" truthy nil :IS? "VALUE" falsey "value" :IS? nil falsey "value" :IS? "some" falsey "value" :IS-NOT? "value" falsey "VALUE" :IS-NOT? "value" falsey "value" :IS-NOT? "VALUE" falsey nil :IS-NOT? "VALUE" truthy "value" :IS-NOT? nil truthy "value" :IS-NOT? "some" truthy "value" :IN? ["value" ] truthy "VALUE" :IN? ["value" ] truthy "value" :IN? ["VALUE" ] truthy nil :IN? ["VALUE" ] falsey "value" :IN? [nil ] falsey "value" :IN? ["some" ] falsey "value" :IN? ["some" "wxy"] falsey "value" :IN? ["some" "value"] truthy "value" :NOT-IN? ["some" "wxy"] truthy )
2496ce661e9b8aa92f70a9bbc64182896879771dd4c310e8f5cedefa87c7da56
wavejumper/boonmee
react_test.clj
(ns boonmee.integration.react-test (:require [clojure.test :refer :all] [clojure.java.io :as io] [clojure.spec.alpha :as s] [boonmee.test-util :refer [with-client request! response!]] [boonmee.protocol])) (def react-resp {:command "completionInfo" :data {:entries [{:kind "const" :kindModifiers "declare" :name "Children" :sortText "0"} {:kind "function" :kindModifiers "declare" :name "cloneElement" :sortText "0"} {:kind "class" :kindModifiers "declare" :name "Component" :sortText "0"} {:kind "function" :kindModifiers "declare" :name "createContext" :sortText "0"} {:kind "function" :kindModifiers "declare" :name "createElement" :sortText "0"} {:kind "function" :kindModifiers "declare" :name "createFactory" :sortText "0"} {:kind "function" :kindModifiers "declare" :name "createRef" :sortText "0"} {:kind "function" :kindModifiers "declare" :name "forwardRef" :sortText "0"} {:kind "const" :kindModifiers "declare" :name "Fragment" :sortText "0"} {:kind "function" :kindModifiers "declare" :name "isValidElement" :sortText "0"} {:kind "function" :kindModifiers "declare" :name "lazy" :sortText "0"} {:kind "function" :kindModifiers "declare" :name "memo" :sortText "0"} {:kind "const" :kindModifiers "declare" :name "Profiler" :sortText "0"} {:kind "class" :kindModifiers "declare" :name "PureComponent" :sortText "0"} {:kind "const" :kindModifiers "declare" :name "StrictMode" :sortText "0"} {:kind "const" :kindModifiers "declare" :name "Suspense" :sortText "0"} {:kind "function" :kindModifiers "declare" :name "useCallback" :sortText "0"} {:kind "function" :kindModifiers "declare" :name "useContext" :sortText "0"} {:kind "function" :kindModifiers "declare" :name "useDebugValue" :sortText "0"} {:kind "function" :kindModifiers "declare" :name "useEffect" :sortText "0"} {:kind "function" :kindModifiers "declare" :name "useImperativeHandle" :sortText "0"} {:kind "function" :kindModifiers "declare" :name "useLayoutEffect" :sortText "0"} {:kind "function" :kindModifiers "declare" :name "useMemo" :sortText "0"} {:kind "function" :kindModifiers "declare" :name "useReducer" :sortText "0"} {:kind "function" :kindModifiers "declare" :name "useRef" :sortText "0"} {:kind "function" :kindModifiers "declare" :name "useState" :sortText "0"} {:kind "const" :kindModifiers "declare" :name "version" :sortText "0"}] :isGlobalCompletion false :isMemberCompletion true :isNewIdentifierLocation false} :interop {:fragments ['useState] :isGlobal false :nextLocation [4 17] :prevLocation [4 1] :sym 'React :usage :method} :requestId "1234567" :success true :type "response"}) (deftest completions--globals (with-client [client {:env "node"}] (testing "react/useState" (let [req {:command "completions" :type "request" :requestId "1234567" :arguments {:file (.getFile (io/resource "react/src/core.cljs")) :projectRoot (.getFile (io/resource "react")) :line 4 :offset 12}}] (is (s/valid? :client/request req)) (request! client req) (let [resp (response! client 60000)] (is (s/valid? :client/response resp)) (is (= resp react-resp)))))))
null
https://raw.githubusercontent.com/wavejumper/boonmee/fc0946568bfc53830717d2b68982872972bd532d/test/boonmee/integration/react_test.clj
clojure
(ns boonmee.integration.react-test (:require [clojure.test :refer :all] [clojure.java.io :as io] [clojure.spec.alpha :as s] [boonmee.test-util :refer [with-client request! response!]] [boonmee.protocol])) (def react-resp {:command "completionInfo" :data {:entries [{:kind "const" :kindModifiers "declare" :name "Children" :sortText "0"} {:kind "function" :kindModifiers "declare" :name "cloneElement" :sortText "0"} {:kind "class" :kindModifiers "declare" :name "Component" :sortText "0"} {:kind "function" :kindModifiers "declare" :name "createContext" :sortText "0"} {:kind "function" :kindModifiers "declare" :name "createElement" :sortText "0"} {:kind "function" :kindModifiers "declare" :name "createFactory" :sortText "0"} {:kind "function" :kindModifiers "declare" :name "createRef" :sortText "0"} {:kind "function" :kindModifiers "declare" :name "forwardRef" :sortText "0"} {:kind "const" :kindModifiers "declare" :name "Fragment" :sortText "0"} {:kind "function" :kindModifiers "declare" :name "isValidElement" :sortText "0"} {:kind "function" :kindModifiers "declare" :name "lazy" :sortText "0"} {:kind "function" :kindModifiers "declare" :name "memo" :sortText "0"} {:kind "const" :kindModifiers "declare" :name "Profiler" :sortText "0"} {:kind "class" :kindModifiers "declare" :name "PureComponent" :sortText "0"} {:kind "const" :kindModifiers "declare" :name "StrictMode" :sortText "0"} {:kind "const" :kindModifiers "declare" :name "Suspense" :sortText "0"} {:kind "function" :kindModifiers "declare" :name "useCallback" :sortText "0"} {:kind "function" :kindModifiers "declare" :name "useContext" :sortText "0"} {:kind "function" :kindModifiers "declare" :name "useDebugValue" :sortText "0"} {:kind "function" :kindModifiers "declare" :name "useEffect" :sortText "0"} {:kind "function" :kindModifiers "declare" :name "useImperativeHandle" :sortText "0"} {:kind "function" :kindModifiers "declare" :name "useLayoutEffect" :sortText "0"} {:kind "function" :kindModifiers "declare" :name "useMemo" :sortText "0"} {:kind "function" :kindModifiers "declare" :name "useReducer" :sortText "0"} {:kind "function" :kindModifiers "declare" :name "useRef" :sortText "0"} {:kind "function" :kindModifiers "declare" :name "useState" :sortText "0"} {:kind "const" :kindModifiers "declare" :name "version" :sortText "0"}] :isGlobalCompletion false :isMemberCompletion true :isNewIdentifierLocation false} :interop {:fragments ['useState] :isGlobal false :nextLocation [4 17] :prevLocation [4 1] :sym 'React :usage :method} :requestId "1234567" :success true :type "response"}) (deftest completions--globals (with-client [client {:env "node"}] (testing "react/useState" (let [req {:command "completions" :type "request" :requestId "1234567" :arguments {:file (.getFile (io/resource "react/src/core.cljs")) :projectRoot (.getFile (io/resource "react")) :line 4 :offset 12}}] (is (s/valid? :client/request req)) (request! client req) (let [resp (response! client 60000)] (is (s/valid? :client/response resp)) (is (= resp react-resp)))))))
49d1d577ba98c9a01007d2b0023e261da80eaf70db5a9e403a06656dc08e1bfc
mbj/stratosphere
StudioEncryptionConfigurationProperty.hs
module Stratosphere.NimbleStudio.Studio.StudioEncryptionConfigurationProperty ( StudioEncryptionConfigurationProperty(..), mkStudioEncryptionConfigurationProperty ) where import qualified Data.Aeson as JSON import qualified Stratosphere.Prelude as Prelude import Stratosphere.Property import Stratosphere.ResourceProperties import Stratosphere.Value data StudioEncryptionConfigurationProperty = StudioEncryptionConfigurationProperty {keyArn :: (Prelude.Maybe (Value Prelude.Text)), keyType :: (Value Prelude.Text)} mkStudioEncryptionConfigurationProperty :: Value Prelude.Text -> StudioEncryptionConfigurationProperty mkStudioEncryptionConfigurationProperty keyType = StudioEncryptionConfigurationProperty {keyType = keyType, keyArn = Prelude.Nothing} instance ToResourceProperties StudioEncryptionConfigurationProperty where toResourceProperties StudioEncryptionConfigurationProperty {..} = ResourceProperties {awsType = "AWS::NimbleStudio::Studio.StudioEncryptionConfiguration", supportsTags = Prelude.False, properties = Prelude.fromList ((Prelude.<>) ["KeyType" JSON..= keyType] (Prelude.catMaybes [(JSON..=) "KeyArn" Prelude.<$> keyArn]))} instance JSON.ToJSON StudioEncryptionConfigurationProperty where toJSON StudioEncryptionConfigurationProperty {..} = JSON.object (Prelude.fromList ((Prelude.<>) ["KeyType" JSON..= keyType] (Prelude.catMaybes [(JSON..=) "KeyArn" Prelude.<$> keyArn]))) instance Property "KeyArn" StudioEncryptionConfigurationProperty where type PropertyType "KeyArn" StudioEncryptionConfigurationProperty = Value Prelude.Text set newValue StudioEncryptionConfigurationProperty {..} = StudioEncryptionConfigurationProperty {keyArn = Prelude.pure newValue, ..} instance Property "KeyType" StudioEncryptionConfigurationProperty where type PropertyType "KeyType" StudioEncryptionConfigurationProperty = Value Prelude.Text set newValue StudioEncryptionConfigurationProperty {..} = StudioEncryptionConfigurationProperty {keyType = newValue, ..}
null
https://raw.githubusercontent.com/mbj/stratosphere/c70f301715425247efcda29af4f3fcf7ec04aa2f/services/nimblestudio/gen/Stratosphere/NimbleStudio/Studio/StudioEncryptionConfigurationProperty.hs
haskell
module Stratosphere.NimbleStudio.Studio.StudioEncryptionConfigurationProperty ( StudioEncryptionConfigurationProperty(..), mkStudioEncryptionConfigurationProperty ) where import qualified Data.Aeson as JSON import qualified Stratosphere.Prelude as Prelude import Stratosphere.Property import Stratosphere.ResourceProperties import Stratosphere.Value data StudioEncryptionConfigurationProperty = StudioEncryptionConfigurationProperty {keyArn :: (Prelude.Maybe (Value Prelude.Text)), keyType :: (Value Prelude.Text)} mkStudioEncryptionConfigurationProperty :: Value Prelude.Text -> StudioEncryptionConfigurationProperty mkStudioEncryptionConfigurationProperty keyType = StudioEncryptionConfigurationProperty {keyType = keyType, keyArn = Prelude.Nothing} instance ToResourceProperties StudioEncryptionConfigurationProperty where toResourceProperties StudioEncryptionConfigurationProperty {..} = ResourceProperties {awsType = "AWS::NimbleStudio::Studio.StudioEncryptionConfiguration", supportsTags = Prelude.False, properties = Prelude.fromList ((Prelude.<>) ["KeyType" JSON..= keyType] (Prelude.catMaybes [(JSON..=) "KeyArn" Prelude.<$> keyArn]))} instance JSON.ToJSON StudioEncryptionConfigurationProperty where toJSON StudioEncryptionConfigurationProperty {..} = JSON.object (Prelude.fromList ((Prelude.<>) ["KeyType" JSON..= keyType] (Prelude.catMaybes [(JSON..=) "KeyArn" Prelude.<$> keyArn]))) instance Property "KeyArn" StudioEncryptionConfigurationProperty where type PropertyType "KeyArn" StudioEncryptionConfigurationProperty = Value Prelude.Text set newValue StudioEncryptionConfigurationProperty {..} = StudioEncryptionConfigurationProperty {keyArn = Prelude.pure newValue, ..} instance Property "KeyType" StudioEncryptionConfigurationProperty where type PropertyType "KeyType" StudioEncryptionConfigurationProperty = Value Prelude.Text set newValue StudioEncryptionConfigurationProperty {..} = StudioEncryptionConfigurationProperty {keyType = newValue, ..}
e37b56419bddaafbcc4a1728c9d71c0847eac2e7f0684941cf85c3496bf76c60
arttuka/reagent-material-ui
man_4_outlined.cljs
(ns reagent-mui.icons.man-4-outlined "Imports @mui/icons-material/Man4Outlined as a Reagent component." (:require-macros [reagent-mui.util :refer [create-svg-icon e]]) (:require [react :as react] ["@mui/material/SvgIcon" :as SvgIcon] [reagent-mui.util])) (def man-4-outlined (create-svg-icon [(e "path" #js {"d" "M13.75 7h-3.5C9.04 7 8.11 8.07 8.27 9.26L10 22h4l1.73-12.74C15.89 8.07 14.96 7 13.75 7z"}) (e "circle" #js {"cx" "12", "cy" "4", "r" "2"})] "Man4Outlined"))
null
https://raw.githubusercontent.com/arttuka/reagent-material-ui/14103a696c41c0eb67fc07fc67cd8799efd88cb9/src/icons/reagent_mui/icons/man_4_outlined.cljs
clojure
(ns reagent-mui.icons.man-4-outlined "Imports @mui/icons-material/Man4Outlined as a Reagent component." (:require-macros [reagent-mui.util :refer [create-svg-icon e]]) (:require [react :as react] ["@mui/material/SvgIcon" :as SvgIcon] [reagent-mui.util])) (def man-4-outlined (create-svg-icon [(e "path" #js {"d" "M13.75 7h-3.5C9.04 7 8.11 8.07 8.27 9.26L10 22h4l1.73-12.74C15.89 8.07 14.96 7 13.75 7z"}) (e "circle" #js {"cx" "12", "cy" "4", "r" "2"})] "Man4Outlined"))
ef0a039776061bb8a1a366e47641d5dc62b89024acfac8e799654e5000b94963
juxt/tick
addon_libs_test.cljc
(ns tick.addon-libs-test (:require [tick.core :as t] [tick.timezone] [tick.locale-en-us] [clojure.test :refer [deftest is testing run-tests] :refer-macros [deftest is testing run-tests]])) (deftest tz-test (is (t/zone "Europe/Berlin"))) (deftest locale-test (is (t/formatter "yyyy-MMM-dd")))
null
https://raw.githubusercontent.com/juxt/tick/7ebf41e9ae96f5ae67ceeabaed8aa7e989269e24/test/tick/addon_libs_test.cljc
clojure
(ns tick.addon-libs-test (:require [tick.core :as t] [tick.timezone] [tick.locale-en-us] [clojure.test :refer [deftest is testing run-tests] :refer-macros [deftest is testing run-tests]])) (deftest tz-test (is (t/zone "Europe/Berlin"))) (deftest locale-test (is (t/formatter "yyyy-MMM-dd")))
e30b8cf3856498923384ae2e0cad08dd53c56245f01c984976f97838ceea7afc
ha-mo-we/Racer
role-structures.lisp
-*- Mode : Lisp ; Syntax : Ansi - Common - Lisp ; Package : RACER ; Base : 10 -*- Copyright ( c ) 1998 - 2014 , , , . ;;; All rights reserved. Racer is distributed under the following BSD 3 - clause license ;;; Redistribution and use in source and binary forms, with or without ;;; modification, are permitted provided that the following conditions are ;;; met: ;;; Redistributions of source code must retain the above copyright notice, ;;; this list of conditions and the following disclaimer. ;;; Redistributions in binary form must reproduce the above copyright ;;; notice, this list of conditions and the following disclaimer in the ;;; documentation and/or other materials provided with the distribution. Neither the name Racer nor the names of its contributors may be used ;;; to endorse or promote products derived from this software without ;;; specific prior written permission. ;;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , ;;; BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND ;;; FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL VOLKER HAARSLEV , RALF MOELLER , NOR FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL ;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE ;;; GOODS OR SERVICES, LOSS OF USE, DATA, OR PROFITS, OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER ;;; IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR ;;; OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ;;; ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. (in-package :racer) (defconstant +top-object-role-symbol+ '*top-object-role* "Used as unique id for symbol-name of the top object role") (defconstant +bottom-object-role-symbol+ '*bottom-object-role* "Used as unique id for symbol-name of the bottom object role") (defconstant +krss-top-object-role-symbol+ 'top-object-role "Used as synonym to *top-object-role*") (defconstant +krss-bottom-object-role-symbol+ 'bottom-object-role "Used as synonym to *bottom-object-role*") (defconstant +top-datatype-role-symbol+ '*top-datatype-role* "Used as unique id for symbol-name of the top datatype role") (defconstant +bottom-datatype-role-symbol+ '*bottom-datatype-role* "Used as unique id for symbol-name of the bottom datatype role") (defconstant +inv-top-datatype-role-symbol+ '*inv-top-datatype-role*) (defconstant +inv-bottom-datatype-role-symbol+ '*inv-bottom-datatype-role*) (defconstant +top-object-role-hash-id+ 4) (defconstant +bottom-object-role-hash-id+ 5) (defconstant +top-datatype-role-hash-id+ 6) (defconstant +bottom-datatype-role-hash-id+ 7) (defconstant +inv-top-datatype-role-hash-id+ 8) (defconstant +inv-bottom-datatype-role-hash-id+ 9) (defparameter *encode-roles-as-transitive* nil) (defparameter *encode-roles-as-reflexive* nil) (defstruct (role-node (:include racer-structure-id) (:conc-name role-) (:predicate role-node-p)) "structure for an internal role or a feature" (name nil) (transitive-p *encode-roles-as-transitive*) (reflexive-p *encode-roles-as-reflexive*) (inverse-internal nil) (feature-p nil) (parents-internal nil) (children-internal nil) (ancestors-internal nil) (has-ancestors-p nil) (feature-ancestors nil) (has-feature-ancestors-p nil) (descendants-internal nil) (internal-conjunction-p nil) (domain-concept nil) (domain-restriction nil) (range-concept nil) (range-restriction nil) (internal-name-p nil) (cd-attribute nil) (synonyms-internal nil) (datatype nil) ; t = used as OWL datatype property, ; 'integer, 'real, 'string = range (annotation-p nil) (gci-dependencies nil) (inverse-feature-p nil) (irreflexive-p nil) (asymmetric-p nil) (symmetric-p nil) (disjoint-roles nil) (compositions nil) (simple-p t) (language-context *dl-empty*) (satisfiability-checked-p nil) ) (race-inline (role-parent-names role-not-transitive-p)) (defun role-parent-names (role) (mapcar #'role-name (role-parents-internal role))) (defmethod print-object :around ((object role-node) stream) (if *print-internals* (print-unreadable-object (object stream :type nil :identity t) (call-next-method)) (call-next-method))) (defmethod print-object ((object role-node) stream) (cond #+:debug ((role-feature-p object) (format stream "~S!" (decode-role object))) #+:debug ((or (role-transitive-p object) (role-compositions object)) (format stream "~S" (decode-role object)) (when (role-compositions object) (format stream "@")) (when (role-transitive-p object) (format stream "+"))) (t (format stream "~S" (decode-role object))))) (defun role-is-satisfiable (role) (let ((domain (role-domain-restriction role)) (range (role-range-restriction role))) (and (or (null domain) (not (is-bottom-concept-p domain))) (or (null range) (not (is-bottom-concept-p range)))))) (defun decode-role (role) (if (role-node-p role) (let ((inverse (role-inverse-internal role))) (if (and (role-internal-name-p role) inverse) (if (role-node-p inverse) `(inv ,(role-name inverse)) `(inv ,inverse)) (role-name role))) role)) (defun role-not-transitive-p (role) (not (role-transitive-p role))) ;;; ====================================================================== (declaim (notinline create-internal-and-role)) #-:cmu (defun create-internal-and-role (tbox role1 role2) (declare (ignore tbox role1 role2)) (if *use-tbox* (error "wrong definition called") (error "this should never happen"))) ;;;=========================================================================== (race-inline (make-top-object-role make-bottom-object-role is-top-object-role-p is-bottom-object-role-p is-predefined-role-p)) (defun make-top-object-role () (let ((role (make-role-node :name +top-object-role-symbol+ :internal-name-p nil :hash-id +top-object-role-hash-id+ :transitive-p t :reflexive-p t :symmetric-p t))) (setf (role-inverse-internal role) role) (setf (role-synonyms-internal role) (list role)) role)) (defun make-bottom-object-role () (let ((role (make-role-node :name +bottom-object-role-symbol+ :internal-name-p nil :hash-id +bottom-object-role-hash-id+ :transitive-p t :reflexive-p nil reflexive - p can not be set to T for unsatisfiable roles ; because otherwise (all r bottom) would expand to bottom :irreflexive-p t :symmetric-p t :asymmetric-p t :satisfiability-checked-p t))) (setf (role-inverse-internal role) role) (setf (role-synonyms-internal role) (list role)) role)) (defun make-top-datatype-role () (let ((role (make-role-node :name +top-datatype-role-symbol+ :internal-name-p nil :hash-id +top-datatype-role-hash-id+ :datatype t :satisfiability-checked-p t)) (inv-role (make-role-node :name (gensym (symbol-name +inv-top-datatype-role-symbol+)) :internal-name-p t :hash-id +inv-top-datatype-role-hash-id+ :satisfiability-checked-p t))) (setf (role-inverse-internal role) inv-role) (setf (role-inverse-internal inv-role) role) (setf (role-synonyms-internal role) (list role)) (setf (role-synonyms-internal inv-role) (list inv-role)) role)) (defun make-bottom-datatype-role () (let ((role (make-role-node :name +bottom-datatype-role-symbol+ :internal-name-p nil :hash-id +bottom-datatype-role-hash-id+ :datatype t :satisfiability-checked-p t)) (inv-role (make-role-node :name (gensym (symbol-name +inv-bottom-datatype-role-symbol+)) :internal-name-p t :hash-id +inv-bottom-datatype-role-hash-id+ :satisfiability-checked-p t))) (setf (role-inverse-internal role) inv-role) (setf (role-inverse-internal inv-role) role) (setf (role-synonyms-internal role) (list role)) (setf (role-synonyms-internal inv-role) (list inv-role)) role)) (race-inline (is-top-object-role-p is-bottom-object-role-p is-top-datatype-role-p is-bottom-datatype-role-p is-predefined-role-p user-defined-role-transitive-p)) (defun is-top-object-role-p (role) (eql (role-hash-id role) +top-object-role-hash-id+)) (defun is-bottom-object-role-p (role) (eql (role-hash-id role) +bottom-object-role-hash-id+)) (defun is-top-datatype-role-p (role) (eql (role-hash-id role) +top-datatype-role-hash-id+)) (defun is-bottom-datatype-role-p (role) (eql (role-hash-id role) +bottom-datatype-role-hash-id+)) (defun is-predefined-role-p (role) (let* ((new-role (if (role-internal-name-p role) (or (role-inverse-internal role) role) role)) (id (role-hash-id new-role))) (or (eql id +top-object-role-hash-id+) (eql id +bottom-object-role-hash-id+) (eql id +top-datatype-role-hash-id+) (eql id +bottom-datatype-role-hash-id+)))) (defun remove-top-object-role (role-list) (loop for role in role-list unless (eql (role-hash-id role) +top-object-role-hash-id+) collect role)) ;;;=========================================================================== (defun user-defined-role-transitive-p (role) (and (role-transitive-p role) (not (is-predefined-role-p role)))) (defun some-user-defined-role-transitive-p (role-list &optional (ignore nil)) (when role-list (loop for role in role-list thereis (and (not (eq role ignore)) (role-transitive-p role) (not (is-predefined-role-p role)))))) (defun find-user-defined-transitive-role (role-list) (when role-list (loop for role in role-list when (and (role-transitive-p role) (not (is-predefined-role-p role))) do (return role)))) (defun user-defined-role-reflexive-p (role) (and (role-reflexive-p role) (not (is-predefined-role-p role)))) (defun user-defined-role-reflexive-feature-p (role) (and (user-defined-role-reflexive-p role) (role-feature-p role)))
null
https://raw.githubusercontent.com/ha-mo-we/Racer/d690841d10015c7a75b1ded393fcf0a33092c4de/source/role-structures.lisp
lisp
Syntax : Ansi - Common - Lisp ; Package : RACER ; Base : 10 -*- All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, LOSS OF USE, DATA, OR PROFITS, OR BUSINESS IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. t = used as OWL datatype property, 'integer, 'real, 'string = range ====================================================================== =========================================================================== because otherwise (all r bottom) would expand to bottom ===========================================================================
Copyright ( c ) 1998 - 2014 , , , . Racer is distributed under the following BSD 3 - clause license Neither the name Racer nor the names of its contributors may be used CONTRIBUTORS " AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , VOLKER HAARSLEV , RALF MOELLER , NOR FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER (in-package :racer) (defconstant +top-object-role-symbol+ '*top-object-role* "Used as unique id for symbol-name of the top object role") (defconstant +bottom-object-role-symbol+ '*bottom-object-role* "Used as unique id for symbol-name of the bottom object role") (defconstant +krss-top-object-role-symbol+ 'top-object-role "Used as synonym to *top-object-role*") (defconstant +krss-bottom-object-role-symbol+ 'bottom-object-role "Used as synonym to *bottom-object-role*") (defconstant +top-datatype-role-symbol+ '*top-datatype-role* "Used as unique id for symbol-name of the top datatype role") (defconstant +bottom-datatype-role-symbol+ '*bottom-datatype-role* "Used as unique id for symbol-name of the bottom datatype role") (defconstant +inv-top-datatype-role-symbol+ '*inv-top-datatype-role*) (defconstant +inv-bottom-datatype-role-symbol+ '*inv-bottom-datatype-role*) (defconstant +top-object-role-hash-id+ 4) (defconstant +bottom-object-role-hash-id+ 5) (defconstant +top-datatype-role-hash-id+ 6) (defconstant +bottom-datatype-role-hash-id+ 7) (defconstant +inv-top-datatype-role-hash-id+ 8) (defconstant +inv-bottom-datatype-role-hash-id+ 9) (defparameter *encode-roles-as-transitive* nil) (defparameter *encode-roles-as-reflexive* nil) (defstruct (role-node (:include racer-structure-id) (:conc-name role-) (:predicate role-node-p)) "structure for an internal role or a feature" (name nil) (transitive-p *encode-roles-as-transitive*) (reflexive-p *encode-roles-as-reflexive*) (inverse-internal nil) (feature-p nil) (parents-internal nil) (children-internal nil) (ancestors-internal nil) (has-ancestors-p nil) (feature-ancestors nil) (has-feature-ancestors-p nil) (descendants-internal nil) (internal-conjunction-p nil) (domain-concept nil) (domain-restriction nil) (range-concept nil) (range-restriction nil) (internal-name-p nil) (cd-attribute nil) (synonyms-internal nil) (annotation-p nil) (gci-dependencies nil) (inverse-feature-p nil) (irreflexive-p nil) (asymmetric-p nil) (symmetric-p nil) (disjoint-roles nil) (compositions nil) (simple-p t) (language-context *dl-empty*) (satisfiability-checked-p nil) ) (race-inline (role-parent-names role-not-transitive-p)) (defun role-parent-names (role) (mapcar #'role-name (role-parents-internal role))) (defmethod print-object :around ((object role-node) stream) (if *print-internals* (print-unreadable-object (object stream :type nil :identity t) (call-next-method)) (call-next-method))) (defmethod print-object ((object role-node) stream) (cond #+:debug ((role-feature-p object) (format stream "~S!" (decode-role object))) #+:debug ((or (role-transitive-p object) (role-compositions object)) (format stream "~S" (decode-role object)) (when (role-compositions object) (format stream "@")) (when (role-transitive-p object) (format stream "+"))) (t (format stream "~S" (decode-role object))))) (defun role-is-satisfiable (role) (let ((domain (role-domain-restriction role)) (range (role-range-restriction role))) (and (or (null domain) (not (is-bottom-concept-p domain))) (or (null range) (not (is-bottom-concept-p range)))))) (defun decode-role (role) (if (role-node-p role) (let ((inverse (role-inverse-internal role))) (if (and (role-internal-name-p role) inverse) (if (role-node-p inverse) `(inv ,(role-name inverse)) `(inv ,inverse)) (role-name role))) role)) (defun role-not-transitive-p (role) (not (role-transitive-p role))) (declaim (notinline create-internal-and-role)) #-:cmu (defun create-internal-and-role (tbox role1 role2) (declare (ignore tbox role1 role2)) (if *use-tbox* (error "wrong definition called") (error "this should never happen"))) (race-inline (make-top-object-role make-bottom-object-role is-top-object-role-p is-bottom-object-role-p is-predefined-role-p)) (defun make-top-object-role () (let ((role (make-role-node :name +top-object-role-symbol+ :internal-name-p nil :hash-id +top-object-role-hash-id+ :transitive-p t :reflexive-p t :symmetric-p t))) (setf (role-inverse-internal role) role) (setf (role-synonyms-internal role) (list role)) role)) (defun make-bottom-object-role () (let ((role (make-role-node :name +bottom-object-role-symbol+ :internal-name-p nil :hash-id +bottom-object-role-hash-id+ :transitive-p t :reflexive-p nil reflexive - p can not be set to T for unsatisfiable roles :irreflexive-p t :symmetric-p t :asymmetric-p t :satisfiability-checked-p t))) (setf (role-inverse-internal role) role) (setf (role-synonyms-internal role) (list role)) role)) (defun make-top-datatype-role () (let ((role (make-role-node :name +top-datatype-role-symbol+ :internal-name-p nil :hash-id +top-datatype-role-hash-id+ :datatype t :satisfiability-checked-p t)) (inv-role (make-role-node :name (gensym (symbol-name +inv-top-datatype-role-symbol+)) :internal-name-p t :hash-id +inv-top-datatype-role-hash-id+ :satisfiability-checked-p t))) (setf (role-inverse-internal role) inv-role) (setf (role-inverse-internal inv-role) role) (setf (role-synonyms-internal role) (list role)) (setf (role-synonyms-internal inv-role) (list inv-role)) role)) (defun make-bottom-datatype-role () (let ((role (make-role-node :name +bottom-datatype-role-symbol+ :internal-name-p nil :hash-id +bottom-datatype-role-hash-id+ :datatype t :satisfiability-checked-p t)) (inv-role (make-role-node :name (gensym (symbol-name +inv-bottom-datatype-role-symbol+)) :internal-name-p t :hash-id +inv-bottom-datatype-role-hash-id+ :satisfiability-checked-p t))) (setf (role-inverse-internal role) inv-role) (setf (role-inverse-internal inv-role) role) (setf (role-synonyms-internal role) (list role)) (setf (role-synonyms-internal inv-role) (list inv-role)) role)) (race-inline (is-top-object-role-p is-bottom-object-role-p is-top-datatype-role-p is-bottom-datatype-role-p is-predefined-role-p user-defined-role-transitive-p)) (defun is-top-object-role-p (role) (eql (role-hash-id role) +top-object-role-hash-id+)) (defun is-bottom-object-role-p (role) (eql (role-hash-id role) +bottom-object-role-hash-id+)) (defun is-top-datatype-role-p (role) (eql (role-hash-id role) +top-datatype-role-hash-id+)) (defun is-bottom-datatype-role-p (role) (eql (role-hash-id role) +bottom-datatype-role-hash-id+)) (defun is-predefined-role-p (role) (let* ((new-role (if (role-internal-name-p role) (or (role-inverse-internal role) role) role)) (id (role-hash-id new-role))) (or (eql id +top-object-role-hash-id+) (eql id +bottom-object-role-hash-id+) (eql id +top-datatype-role-hash-id+) (eql id +bottom-datatype-role-hash-id+)))) (defun remove-top-object-role (role-list) (loop for role in role-list unless (eql (role-hash-id role) +top-object-role-hash-id+) collect role)) (defun user-defined-role-transitive-p (role) (and (role-transitive-p role) (not (is-predefined-role-p role)))) (defun some-user-defined-role-transitive-p (role-list &optional (ignore nil)) (when role-list (loop for role in role-list thereis (and (not (eq role ignore)) (role-transitive-p role) (not (is-predefined-role-p role)))))) (defun find-user-defined-transitive-role (role-list) (when role-list (loop for role in role-list when (and (role-transitive-p role) (not (is-predefined-role-p role))) do (return role)))) (defun user-defined-role-reflexive-p (role) (and (role-reflexive-p role) (not (is-predefined-role-p role)))) (defun user-defined-role-reflexive-feature-p (role) (and (user-defined-role-reflexive-p role) (role-feature-p role)))
0aed11e5a1aa4c20f4baf03a4746c98a96a90c3ab22bf1b6b0c56ca74a48760f
dalaing/little-languages
Pretty.hs
| Copyright : ( c ) , 2016 License : : Stability : experimental Portability : non - portable Pretty printers for types of the NB language . Copyright : (c) Dave Laing, 2016 License : BSD3 Maintainer : Stability : experimental Portability : non-portable Pretty printers for types of the NB language. -} module Type.Pretty ( prettyTypeRules , prettyType ) where -- from 'base' import Data.Foldable (asum) import Data.Maybe (fromMaybe) -- from 'ansi-wl-pprint' import Text.PrettyPrint.ANSI.Leijen (Doc, text) -- local import Common.Pretty (reservedConstructor) import Type (Type (..)) -- $setup > > > import Text . PrettyPrint . > > > let render r w f d = putStr $ displayS ( renderPretty r w ( plain ( f d ) ) ) " " | A pretty printer for ' TyNat ' -- > > > render 0.5 40 ( fromMaybe ( text " ? ? ? " ) . prettyTyNat ) $ TyNat prettyTyNat :: Type -> Maybe Doc prettyTyNat TyNat = Just $ reservedConstructor "Nat" prettyTyNat _ = Nothing -- | A pretty printer for 'TyBool' -- > > > render 0.5 40 ( fromMaybe ( text " ? ? ? " ) . prettyTyBool ) $ TyBool -- Bool prettyTyBool :: Type -> Maybe Doc prettyTyBool TyBool = Just $ reservedConstructor "Bool" prettyTyBool _ = Nothing | The set of pretty printing rules for types of the NB language . prettyTypeRules :: [Type -> Maybe Doc] prettyTypeRules = [ prettyTyNat , prettyTyBool ] | The pretty printer for types of the NB language . -- -- This function is built from the contents of 'prettyTypeRules'. -- It will print "???" if none of the rules apply - which should never happen. -- > > > render 0.5 40 prettyType $ TyNat -- > > > render 0.5 40 prettyType $ TyBool -- Bool prettyType :: Type -> Doc prettyType tm = fromMaybe (text "???") . asum . fmap ($ tm) $ prettyTypeRules
null
https://raw.githubusercontent.com/dalaing/little-languages/9f089f646a5344b8f7178700455a36a755d29b1f/code/nb/src/Type/Pretty.hs
haskell
from 'base' from 'ansi-wl-pprint' local $setup | A pretty printer for 'TyBool' Bool This function is built from the contents of 'prettyTypeRules'. It will print "???" if none of the rules apply - which should never happen. Bool
| Copyright : ( c ) , 2016 License : : Stability : experimental Portability : non - portable Pretty printers for types of the NB language . Copyright : (c) Dave Laing, 2016 License : BSD3 Maintainer : Stability : experimental Portability : non-portable Pretty printers for types of the NB language. -} module Type.Pretty ( prettyTypeRules , prettyType ) where import Data.Foldable (asum) import Data.Maybe (fromMaybe) import Text.PrettyPrint.ANSI.Leijen (Doc, text) import Common.Pretty (reservedConstructor) import Type (Type (..)) > > > import Text . PrettyPrint . > > > let render r w f d = putStr $ displayS ( renderPretty r w ( plain ( f d ) ) ) " " | A pretty printer for ' TyNat ' > > > render 0.5 40 ( fromMaybe ( text " ? ? ? " ) . prettyTyNat ) $ TyNat prettyTyNat :: Type -> Maybe Doc prettyTyNat TyNat = Just $ reservedConstructor "Nat" prettyTyNat _ = Nothing > > > render 0.5 40 ( fromMaybe ( text " ? ? ? " ) . prettyTyBool ) $ TyBool prettyTyBool :: Type -> Maybe Doc prettyTyBool TyBool = Just $ reservedConstructor "Bool" prettyTyBool _ = Nothing | The set of pretty printing rules for types of the NB language . prettyTypeRules :: [Type -> Maybe Doc] prettyTypeRules = [ prettyTyNat , prettyTyBool ] | The pretty printer for types of the NB language . > > > render 0.5 40 prettyType $ TyNat > > > render 0.5 40 prettyType $ TyBool prettyType :: Type -> Doc prettyType tm = fromMaybe (text "???") . asum . fmap ($ tm) $ prettyTypeRules
dc57a98afab30016a4d709c7d564261aa048c6c6966206ab880bb6f42a57b3f5
haskell/cabal
Main.hs
import qualified Data.Map as Map import Data.Map (Map) import Foo main = print $ f (+1) (Map.fromList [(0,1),(2,3)] :: Map Int Int)
null
https://raw.githubusercontent.com/haskell/cabal/55b4ed9f6626613cfd965887bd16f3ffdca1aba6/cabal-testsuite/PackageTests/HaddockArgs/repo/exe-0.1.0.0/Main.hs
haskell
import qualified Data.Map as Map import Data.Map (Map) import Foo main = print $ f (+1) (Map.fromList [(0,1),(2,3)] :: Map Int Int)
9526645e4da6138f8afede00b2d1c236ffafac1a87e5cd2b68bf443e94bf45cc
Helium4Haskell/helium
InstanceEmptyWhere.hs
class PrimaClass a instance PrimaClass Int where
null
https://raw.githubusercontent.com/Helium4Haskell/helium/5928bff479e6f151b4ceb6c69bbc15d71e29eb47/test/typeClassesParse/InstanceEmptyWhere.hs
haskell
class PrimaClass a instance PrimaClass Int where
71f08f1a22ea47359e4be40f666f7e095f39362c26f16378e0683174ebbc9b57
emotiq/emotiq
tx-tests.lisp
;;;; tx-tests.lisp (in-package :cosi-bls-test) ;;;; Accounts and Payments: Some Setup for Hand Testing/Demoing (defstruct (account (:constructor make-account-structure)) name key-pair ; optionally nil public-key private-key address) (defun make-account (user-name) (let* ((key-pair (pbc:make-key-pair user-name)) (public-key (pbc:keying-triple-pkey key-pair)) (private-key (pbc:keying-triple-skey key-pair))) (make-account-structure :name user-name :key-pair key-pair :public-key public-key :private-key private-key :address (cosi/proofs:public-key-to-address public-key)))) (defun make-genesis-account () ;; Currently, the configuration is very simple, as follows: ;; ;; :address-for-coin - bignum representing public key to which to ;; send initial/total coinbase infusion. This is simple the same ;; as the public key of the node, same as :public. ;; :public - bignum representing public key of the node ;; :private - bignum representing private key of the node (let ((config-settings (emotiq/config:setting))) (flet ((config-get (name) (cdr (assoc name config-settings)))) (let* ((address-for-coin (config-get :address-for-coins)) (public-key (config-get :public)) (private-key (config-get :private)) (user-name :genesis)) (unless (equal address-for-coin public-key) compares 2 bignums (setq public-key (make-instance 'pbc:public-key :val public-key)) (setq address-for-coin (cosi/proofs:public-key-to-address public-key)) (setq private-key (make-instance 'pbc:secret-key :val private-key)) (make-account-structure :name user-name :key-pair nil :public-key public-key :private-key private-key :address (cosi/proofs:public-key-to-address public-key)))))) (defvar *all-accounts* '()) (defun get-account (user-name) (cdr (assoc user-name *all-accounts*))) (defun set-account (user-name account) (let ((a (assoc user-name *all-accounts*))) (if a (setf (cdr a) account) (progn (push (cons user-name account) *all-accounts*) account)))) (defsetf get-account set-account) (defparameter *white-space* '(#\space #\tab #\return #\linefeed)) (defvar *keyword-package* (find-package "KEYWORD")) (defun normalize-user-designation (user-designation) (intern (string-upcase (string-trim *white-space* (string user-designation))) *keyword-package*)) ;; Consider: ;; - internal sequence of whitespace, hyphen, or dash => hyphen ;; - require initial alpha or digit - require one or more alpha ;; - reject some, discard some, convert some (defun add-account (user-designation) "Add-account for user-designation, a string or symbol in any package. Return its corresponding account object." (let* ((user-name (normalize-user-designation user-designation)) (account (case user-name (:genesis (make-genesis-account)) (otherwise (make-account user-name))))) (setf (get-account user-name) account) account)) (defun get-account-utxos (user-designation) (let* ((user-name (normalize-user-designation user-designation)) (account? (get-account user-name)) (address? (and account? (account-address account?)))) (and address? (cosi/proofs/newtx:get-utxos-per-account address?)))) (defun make-tx-input-spec (txid index) `(,txid ,index)) (defun make-tx-output-spec (address amount) `(,address ,amount)) (defun make-tx-input-specs (&rest input-specs) (loop for (txid index) in input-specs collect (make-tx-input-spec txid index))) (defun make-tx-output-specs (&rest output-specs) (loop for (address amount) in output-specs collect (make-tx-output-spec address amount))) (defun make-transaction-per-txo-info (from-user-designation txo-info to-user-designation to-amount fee) (destructuring-bind (txo (txid index) amount) txo-info (declare (ignore txo)) (let* ((from-account (get-account (normalize-user-designation from-user-designation))) (to-account (get-account (normalize-user-designation to-user-designation))) change-amount transaction) (when (null from-account) (error "The FROM: user's account designation ~s is unrecognized." from-user-designation)) (when (null to-account) (error "The TO: user's account designation ~s is unrecognized." to-user-designation)) (unless (<= (+ to-amount fee) amount) (error "Not enough coin")) hmmm , currently allow zero change (- amount (+ to-amount fee))) (setq transaction (cosi/proofs/newtx:make-transaction (cosi/proofs/newtx:make-transaction-inputs (make-tx-input-specs `(,txid ,index)) :transaction-type :spend) (cosi/proofs/newtx:make-transaction-outputs (if (zerop change-amount) (make-tx-output-specs `(,(account-address to-account) ,to-amount)) (make-tx-output-specs `(,(account-address to-account) ,to-amount) `(,(account-address from-account) ,change-amount))) :transaction-type :spend) :spend)) (cosi/proofs/newtx:sign-transaction transaction (account-private-key from-account) (account-public-key from-account)) transaction))) (defun init-accounts () (add-account :genesis) (add-account :user-1) (add-account :user-2) (add-account :user-3) some of " Cast of Characters " from and (add-account :alice) (add-account :bob) (add-account :carol) (add-account :dave) (add-account :eve) (add-account :faythe) (add-account :grace) (add-account :mallory) (add-account :trent)) (defun demo-genesis-make-tx () "Make a Spend from the first Genesis UTXO to User-1. Send 50,000 of coin, with 300 as fee, returning rest back to self (Genesis) as change." (let ((first-utxo (first (get-account-utxos :genesis)))) (make-transaction-per-txo-info :genesis first-utxo :user-1 50000 300))) (defun demo-genesis-validate-tx () (let ((tx (demo-genesis-make-tx))) (cosi/proofs/newtx:validate-transaction tx) tx)) ;; Demo script: ;; ( ql : quickload : / startup ) ;; (emotiq:main) ; ; wait a minute ... ( setq cosi - simgen:*current - node * cosi - simgen:*my - node * ) ; must return non - nil ( cosi / proofs / newtx : dump - txs : blockchain t : mempool t ) ;; (init-accounts) ;; (demo-genesis-validate-tx) ( cosi / proofs / newtx : dump - txs : blockchain t : mempool t ) (defun demo-genesis-pay-anyone (to-user-designation amount fee) (let ((utxos (get-account-utxos :genesis))) (loop with needed-amount = (+ amount fee) for utxo in utxos as (nil nil unspent-amount) = utxo when (>= unspent-amount needed-amount) return (let ((tx (make-transaction-per-txo-info :genesis utxo to-user-designation amount fee))) (cosi/proofs/newtx:validate-transaction tx) tx) finally (format t "~%Sorry, could not find a UTXO with enough funds.~%") (return nil)))) Demo script 2 : ;; ( ql : quickload : / startup ) ;; (emotiq:main) ; ; wait a minute ... ( setq cosi - simgen:*current - node * cosi - simgen:*my - node * ) ; must return non - nil ( cosi / proofs / newtx : dump - txs : blockchain t : mempool t ) ;; (init-accounts) ( demo - genesis - pay - anyone : trent 50113 313 ) ( cosi / proofs / newtx : get - balance ( account - address ( get - account : genesis ) ) ) ; may show 0 ( cosi / proofs / newtx : dump - txs : blockchain t : mempool t ) ;; ;; Note: if the transaction sits in the mempool, does not get into a ;; block, get-balance will not consider it. Therefore, balance shows ;; as 0 even after successfully going through. Similarly, trying to ;; spend the output to change address pending in the mempool will not ;; work; will be rejected as a double spend.
null
https://raw.githubusercontent.com/emotiq/emotiq/9af78023f670777895a3dac29a2bbe98e19b6249/src/Cosi-BLS/test/tx-tests.lisp
lisp
tx-tests.lisp Accounts and Payments: Some Setup for Hand Testing/Demoing optionally nil Currently, the configuration is very simple, as follows: :address-for-coin - bignum representing public key to which to send initial/total coinbase infusion. This is simple the same as the public key of the node, same as :public. :public - bignum representing public key of the node :private - bignum representing private key of the node Consider: - internal sequence of whitespace, hyphen, or dash => hyphen - require initial alpha or digit - reject some, discard some, convert some Demo script: (emotiq:main) ; wait a minute ... must return non - nil (init-accounts) (demo-genesis-validate-tx) (emotiq:main) ; wait a minute ... must return non - nil (init-accounts) may show 0 Note: if the transaction sits in the mempool, does not get into a block, get-balance will not consider it. Therefore, balance shows as 0 even after successfully going through. Similarly, trying to spend the output to change address pending in the mempool will not work; will be rejected as a double spend.
(in-package :cosi-bls-test) (defstruct (account (:constructor make-account-structure)) name public-key private-key address) (defun make-account (user-name) (let* ((key-pair (pbc:make-key-pair user-name)) (public-key (pbc:keying-triple-pkey key-pair)) (private-key (pbc:keying-triple-skey key-pair))) (make-account-structure :name user-name :key-pair key-pair :public-key public-key :private-key private-key :address (cosi/proofs:public-key-to-address public-key)))) (defun make-genesis-account () (let ((config-settings (emotiq/config:setting))) (flet ((config-get (name) (cdr (assoc name config-settings)))) (let* ((address-for-coin (config-get :address-for-coins)) (public-key (config-get :public)) (private-key (config-get :private)) (user-name :genesis)) (unless (equal address-for-coin public-key) compares 2 bignums (setq public-key (make-instance 'pbc:public-key :val public-key)) (setq address-for-coin (cosi/proofs:public-key-to-address public-key)) (setq private-key (make-instance 'pbc:secret-key :val private-key)) (make-account-structure :name user-name :key-pair nil :public-key public-key :private-key private-key :address (cosi/proofs:public-key-to-address public-key)))))) (defvar *all-accounts* '()) (defun get-account (user-name) (cdr (assoc user-name *all-accounts*))) (defun set-account (user-name account) (let ((a (assoc user-name *all-accounts*))) (if a (setf (cdr a) account) (progn (push (cons user-name account) *all-accounts*) account)))) (defsetf get-account set-account) (defparameter *white-space* '(#\space #\tab #\return #\linefeed)) (defvar *keyword-package* (find-package "KEYWORD")) (defun normalize-user-designation (user-designation) (intern (string-upcase (string-trim *white-space* (string user-designation))) *keyword-package*)) - require one or more alpha (defun add-account (user-designation) "Add-account for user-designation, a string or symbol in any package. Return its corresponding account object." (let* ((user-name (normalize-user-designation user-designation)) (account (case user-name (:genesis (make-genesis-account)) (otherwise (make-account user-name))))) (setf (get-account user-name) account) account)) (defun get-account-utxos (user-designation) (let* ((user-name (normalize-user-designation user-designation)) (account? (get-account user-name)) (address? (and account? (account-address account?)))) (and address? (cosi/proofs/newtx:get-utxos-per-account address?)))) (defun make-tx-input-spec (txid index) `(,txid ,index)) (defun make-tx-output-spec (address amount) `(,address ,amount)) (defun make-tx-input-specs (&rest input-specs) (loop for (txid index) in input-specs collect (make-tx-input-spec txid index))) (defun make-tx-output-specs (&rest output-specs) (loop for (address amount) in output-specs collect (make-tx-output-spec address amount))) (defun make-transaction-per-txo-info (from-user-designation txo-info to-user-designation to-amount fee) (destructuring-bind (txo (txid index) amount) txo-info (declare (ignore txo)) (let* ((from-account (get-account (normalize-user-designation from-user-designation))) (to-account (get-account (normalize-user-designation to-user-designation))) change-amount transaction) (when (null from-account) (error "The FROM: user's account designation ~s is unrecognized." from-user-designation)) (when (null to-account) (error "The TO: user's account designation ~s is unrecognized." to-user-designation)) (unless (<= (+ to-amount fee) amount) (error "Not enough coin")) hmmm , currently allow zero change (- amount (+ to-amount fee))) (setq transaction (cosi/proofs/newtx:make-transaction (cosi/proofs/newtx:make-transaction-inputs (make-tx-input-specs `(,txid ,index)) :transaction-type :spend) (cosi/proofs/newtx:make-transaction-outputs (if (zerop change-amount) (make-tx-output-specs `(,(account-address to-account) ,to-amount)) (make-tx-output-specs `(,(account-address to-account) ,to-amount) `(,(account-address from-account) ,change-amount))) :transaction-type :spend) :spend)) (cosi/proofs/newtx:sign-transaction transaction (account-private-key from-account) (account-public-key from-account)) transaction))) (defun init-accounts () (add-account :genesis) (add-account :user-1) (add-account :user-2) (add-account :user-3) some of " Cast of Characters " from and (add-account :alice) (add-account :bob) (add-account :carol) (add-account :dave) (add-account :eve) (add-account :faythe) (add-account :grace) (add-account :mallory) (add-account :trent)) (defun demo-genesis-make-tx () "Make a Spend from the first Genesis UTXO to User-1. Send 50,000 of coin, with 300 as fee, returning rest back to self (Genesis) as change." (let ((first-utxo (first (get-account-utxos :genesis)))) (make-transaction-per-txo-info :genesis first-utxo :user-1 50000 300))) (defun demo-genesis-validate-tx () (let ((tx (demo-genesis-make-tx))) (cosi/proofs/newtx:validate-transaction tx) tx)) ( ql : quickload : / startup ) ( cosi / proofs / newtx : dump - txs : blockchain t : mempool t ) ( cosi / proofs / newtx : dump - txs : blockchain t : mempool t ) (defun demo-genesis-pay-anyone (to-user-designation amount fee) (let ((utxos (get-account-utxos :genesis))) (loop with needed-amount = (+ amount fee) for utxo in utxos as (nil nil unspent-amount) = utxo when (>= unspent-amount needed-amount) return (let ((tx (make-transaction-per-txo-info :genesis utxo to-user-designation amount fee))) (cosi/proofs/newtx:validate-transaction tx) tx) finally (format t "~%Sorry, could not find a UTXO with enough funds.~%") (return nil)))) Demo script 2 : ( ql : quickload : / startup ) ( cosi / proofs / newtx : dump - txs : blockchain t : mempool t ) ( demo - genesis - pay - anyone : trent 50113 313 ) ( cosi / proofs / newtx : dump - txs : blockchain t : mempool t )
6684bc6325b34affef76c20250ebf258854deee869b92c3390abcfce9ce971cf
inhabitedtype/ocaml-aws
increaseNodeGroupsInGlobalReplicationGroup.ml
open Types open Aws type input = IncreaseNodeGroupsInGlobalReplicationGroupMessage.t type output = IncreaseNodeGroupsInGlobalReplicationGroupResult.t type error = Errors_internal.t let service = "elasticache" let signature_version = Request.V4 let to_http service region req = let uri = Uri.add_query_params (Uri.of_string (Aws.Util.of_option_exn (Endpoints.url_of service region))) (List.append [ "Version", [ "2015-02-02" ] ; "Action", [ "IncreaseNodeGroupsInGlobalReplicationGroup" ] ] (Util.drop_empty (Uri.query_of_encoded (Query.render (IncreaseNodeGroupsInGlobalReplicationGroupMessage.to_query req))))) in `POST, uri, [] let of_http body = try let xml = Ezxmlm.from_string body in let resp = Util.option_bind (Xml.member "IncreaseNodeGroupsInGlobalReplicationGroupResponse" (snd xml)) (Xml.member "IncreaseNodeGroupsInGlobalReplicationGroupResult") in try Util.or_error (Util.option_bind resp IncreaseNodeGroupsInGlobalReplicationGroupResult.parse) (let open Error in BadResponse { body ; message = "Could not find well formed \ IncreaseNodeGroupsInGlobalReplicationGroupResult." }) with Xml.RequiredFieldMissing msg -> let open Error in `Error (BadResponse { body ; message = "Error parsing IncreaseNodeGroupsInGlobalReplicationGroupResult - missing \ field in body or children: " ^ msg }) with Failure msg -> `Error (let open Error in BadResponse { body; message = "Error parsing xml: " ^ msg }) let parse_error code err = let errors = [] @ Errors_internal.common in match Errors_internal.of_string err with | Some var -> if List.mem var errors && match Errors_internal.to_http_code var with | Some var -> var = code | None -> true then Some var else None | None -> None
null
https://raw.githubusercontent.com/inhabitedtype/ocaml-aws/b6d5554c5d201202b5de8d0b0253871f7b66dab6/libraries/elasticache/lib/increaseNodeGroupsInGlobalReplicationGroup.ml
ocaml
open Types open Aws type input = IncreaseNodeGroupsInGlobalReplicationGroupMessage.t type output = IncreaseNodeGroupsInGlobalReplicationGroupResult.t type error = Errors_internal.t let service = "elasticache" let signature_version = Request.V4 let to_http service region req = let uri = Uri.add_query_params (Uri.of_string (Aws.Util.of_option_exn (Endpoints.url_of service region))) (List.append [ "Version", [ "2015-02-02" ] ; "Action", [ "IncreaseNodeGroupsInGlobalReplicationGroup" ] ] (Util.drop_empty (Uri.query_of_encoded (Query.render (IncreaseNodeGroupsInGlobalReplicationGroupMessage.to_query req))))) in `POST, uri, [] let of_http body = try let xml = Ezxmlm.from_string body in let resp = Util.option_bind (Xml.member "IncreaseNodeGroupsInGlobalReplicationGroupResponse" (snd xml)) (Xml.member "IncreaseNodeGroupsInGlobalReplicationGroupResult") in try Util.or_error (Util.option_bind resp IncreaseNodeGroupsInGlobalReplicationGroupResult.parse) (let open Error in BadResponse { body ; message = "Could not find well formed \ IncreaseNodeGroupsInGlobalReplicationGroupResult." }) with Xml.RequiredFieldMissing msg -> let open Error in `Error (BadResponse { body ; message = "Error parsing IncreaseNodeGroupsInGlobalReplicationGroupResult - missing \ field in body or children: " ^ msg }) with Failure msg -> `Error (let open Error in BadResponse { body; message = "Error parsing xml: " ^ msg }) let parse_error code err = let errors = [] @ Errors_internal.common in match Errors_internal.of_string err with | Some var -> if List.mem var errors && match Errors_internal.to_http_code var with | Some var -> var = code | None -> true then Some var else None | None -> None
07f03379130127840f03485e4357352e65506010fbbcfea8706f4b63f54fc12c
ocsigen/ocaml-eliom
pr6980.ml
type 'a t = [< `Foo | `Bar] as 'a;; type 'a s = [< `Foo | `Bar | `Baz > `Bar] as 'a;; type 'a first = First : 'a second -> ('b t as 'a) first and 'a second = Second : ('b s as 'a) second;; type aux = Aux : 'a t second * ('a -> int) -> aux;; let it : 'a. [< `Bar | `Foo > `Bar ] as 'a = `Bar;; let g (Aux(Second, f)) = f it;;
null
https://raw.githubusercontent.com/ocsigen/ocaml-eliom/497c6707f477cb3086dc6d8124384e74a8c379ae/testsuite/tests/typing-gadts/pr6980.ml
ocaml
type 'a t = [< `Foo | `Bar] as 'a;; type 'a s = [< `Foo | `Bar | `Baz > `Bar] as 'a;; type 'a first = First : 'a second -> ('b t as 'a) first and 'a second = Second : ('b s as 'a) second;; type aux = Aux : 'a t second * ('a -> int) -> aux;; let it : 'a. [< `Bar | `Foo > `Bar ] as 'a = `Bar;; let g (Aux(Second, f)) = f it;;
893df0a1d6f8f7b6111e5432132fd0ec3fbc8068d0873d10c9d14890d9121826
reborg/clojure-essential-reference
2.clj
(.. Thread currentThread getContextClassLoader) # object["clojure.lang . " ] ; < 1 >
null
https://raw.githubusercontent.com/reborg/clojure-essential-reference/9a3eb82024c8e5fbe17412af541c2cd30820c92e/DynamicVariablesintheStandardLibrary/*use-context-classloader*/2.clj
clojure
< 1 >
(.. Thread currentThread getContextClassLoader)
7ad654523cfc5c26a2c34c777d0d468d203ea75ebb47abd88ee93bc54e77d2e6
etrepum/haskell-for-erlangers-2014
common-combinators.hs
-- Function composition (.) :: (b -> c) -> (a -> b) -> a -> c f . g = \x -> f (g x) -- Function application (with a lower precedence) ($) :: (a -> b) -> a -> b f $ x = f x
null
https://raw.githubusercontent.com/etrepum/haskell-for-erlangers-2014/9fb88fd975df4a9eb1975d7ceb8758e6cb52cc36/examples/common-combinators.hs
haskell
Function composition Function application (with a lower precedence)
(.) :: (b -> c) -> (a -> b) -> a -> c f . g = \x -> f (g x) ($) :: (a -> b) -> a -> b f $ x = f x
faeffe78da037497597a547e5fbf190ff4b568bfbfdf1fe51cdbf29f7adb2d9a
RichiH/git-annex
Config.hs
git - annex repository - global config log - - Copyright 2017 < > - - Licensed under the GNU GPL version 3 or higher . - - Copyright 2017 Joey Hess <> - - Licensed under the GNU GPL version 3 or higher. -} module Logs.Config ( ConfigName, ConfigValue, setGlobalConfig, unsetGlobalConfig, getGlobalConfig, loadGlobalConfig, ) where import Annex.Common import Logs import Logs.MapLog import qualified Annex.Branch import qualified Data.Map as M type ConfigName = String type ConfigValue = String setGlobalConfig :: ConfigName -> ConfigValue -> Annex () setGlobalConfig name new = do curr <- getGlobalConfig name when (curr /= Just new) $ setGlobalConfig' name new setGlobalConfig' :: ConfigName -> ConfigValue -> Annex () setGlobalConfig' name new = do c <- liftIO currentVectorClock Annex.Branch.change configLog $ showMapLog id id . changeMapLog c name new . parseGlobalConfig unsetGlobalConfig :: ConfigName -> Annex () unsetGlobalConfig name = do curr <- getGlobalConfig name when (curr /= Nothing) $ setGlobalConfig' name "" -- set to empty string to unset -- Reads the global config log every time. getGlobalConfig :: ConfigName -> Annex (Maybe ConfigValue) getGlobalConfig name = M.lookup name <$> loadGlobalConfig parseGlobalConfig :: String -> MapLog ConfigName ConfigValue parseGlobalConfig = parseMapLog Just Just loadGlobalConfig :: Annex (M.Map ConfigName ConfigValue) loadGlobalConfig = M.filter (not . null) . simpleMap . parseGlobalConfig <$> Annex.Branch.get configLog
null
https://raw.githubusercontent.com/RichiH/git-annex/bbcad2b0af8cd9264d0cb86e6ca126ae626171f3/Logs/Config.hs
haskell
set to empty string to unset Reads the global config log every time.
git - annex repository - global config log - - Copyright 2017 < > - - Licensed under the GNU GPL version 3 or higher . - - Copyright 2017 Joey Hess <> - - Licensed under the GNU GPL version 3 or higher. -} module Logs.Config ( ConfigName, ConfigValue, setGlobalConfig, unsetGlobalConfig, getGlobalConfig, loadGlobalConfig, ) where import Annex.Common import Logs import Logs.MapLog import qualified Annex.Branch import qualified Data.Map as M type ConfigName = String type ConfigValue = String setGlobalConfig :: ConfigName -> ConfigValue -> Annex () setGlobalConfig name new = do curr <- getGlobalConfig name when (curr /= Just new) $ setGlobalConfig' name new setGlobalConfig' :: ConfigName -> ConfigValue -> Annex () setGlobalConfig' name new = do c <- liftIO currentVectorClock Annex.Branch.change configLog $ showMapLog id id . changeMapLog c name new . parseGlobalConfig unsetGlobalConfig :: ConfigName -> Annex () unsetGlobalConfig name = do curr <- getGlobalConfig name when (curr /= Nothing) $ getGlobalConfig :: ConfigName -> Annex (Maybe ConfigValue) getGlobalConfig name = M.lookup name <$> loadGlobalConfig parseGlobalConfig :: String -> MapLog ConfigName ConfigValue parseGlobalConfig = parseMapLog Just Just loadGlobalConfig :: Annex (M.Map ConfigName ConfigValue) loadGlobalConfig = M.filter (not . null) . simpleMap . parseGlobalConfig <$> Annex.Branch.get configLog
0e3663172dbcc9c253cc3815b3c31da0bbb20723b83d2fc8a0d1f30418799988
argp/bap
template.ml
(* T E S T I N G *) open Ast open Big_int_Z open Int64 open Type module D = Debug.Make(struct let name = "Template" and default=`Debug end) open D module type Types = sig type environ type state type result_exp type result_stmt end module Abstract (Typ : Types) = struct type process_exp = Typ.environ -> Typ.state -> Typ.result_exp type process_stmt = Typ.environ -> Typ.state -> Typ.result_stmt module type Exprs = sig val var : Var.t -> process_exp val int : (big_int * typ) -> process_exp val lab : string -> process_exp val ite : (Ast.exp * Ast.exp * Ast.exp) -> process_exp val extract : (big_int * big_int * Ast.exp) -> process_exp val concat : (Ast.exp * Ast.exp) -> process_exp val binop : (binop_type * Ast.exp * Ast.exp) -> process_exp val unop : (unop_type * Ast.exp) -> process_exp val cast : (cast_type * typ * Ast.exp) -> process_exp val lett : (Var.t * Ast.exp * Ast.exp) -> process_exp val load : (Ast.exp * Ast.exp * Ast.exp * typ) -> process_exp val store : (Ast.exp * Ast.exp * Ast.exp * Ast.exp * typ) -> process_exp val unknown : 'a -> process_exp end module type Stmts = sig val move : (Var.t * Ast.exp * Ast.attrs) -> process_stmt val halt : (Ast.exp * Ast.attrs) -> process_stmt val jmp : (Ast.exp * Ast.attrs) -> process_stmt val cjmp : (Ast.exp * Ast.exp * Ast.exp * Ast.attrs) -> process_stmt val assertt : (Ast.exp * Ast.attrs) -> process_stmt val assume : (Ast.exp * Ast.attrs) -> process_stmt val comment : 'a -> process_stmt val label : 'a -> process_stmt val special : (string * Var.defuse option * Ast.attrs) -> process_stmt end module Make(Expr: Exprs)(Stmt: Stmts) = struct let expr = function | Var v -> Expr.var v | Int i -> Expr.int i | Lab l -> Expr.lab l | Ite i -> Expr.ite i | Extract e -> Expr.extract e | Concat c -> Expr.concat c | BinOp b -> Expr.binop b | UnOp u -> Expr.unop u | Cast c -> Expr.cast c | Let l -> Expr.lett l | Load l -> Expr.load l | Store s -> Expr.store s | Unknown u -> Expr.unknown u let stmt = function | Move m -> Stmt.move m | Halt h -> Stmt.halt h | Jmp j -> Stmt.jmp j | CJmp c -> Stmt.cjmp c | Assert a -> Stmt.assertt a | Assume a -> Stmt.assume a | Comment c -> Stmt.comment c | Label l -> Stmt.label l | Special s -> Stmt.special s end end
null
https://raw.githubusercontent.com/argp/bap/2f60a35e822200a1ec50eea3a947a322b45da363/ocaml/template.ml
ocaml
T E S T I N G
open Ast open Big_int_Z open Int64 open Type module D = Debug.Make(struct let name = "Template" and default=`Debug end) open D module type Types = sig type environ type state type result_exp type result_stmt end module Abstract (Typ : Types) = struct type process_exp = Typ.environ -> Typ.state -> Typ.result_exp type process_stmt = Typ.environ -> Typ.state -> Typ.result_stmt module type Exprs = sig val var : Var.t -> process_exp val int : (big_int * typ) -> process_exp val lab : string -> process_exp val ite : (Ast.exp * Ast.exp * Ast.exp) -> process_exp val extract : (big_int * big_int * Ast.exp) -> process_exp val concat : (Ast.exp * Ast.exp) -> process_exp val binop : (binop_type * Ast.exp * Ast.exp) -> process_exp val unop : (unop_type * Ast.exp) -> process_exp val cast : (cast_type * typ * Ast.exp) -> process_exp val lett : (Var.t * Ast.exp * Ast.exp) -> process_exp val load : (Ast.exp * Ast.exp * Ast.exp * typ) -> process_exp val store : (Ast.exp * Ast.exp * Ast.exp * Ast.exp * typ) -> process_exp val unknown : 'a -> process_exp end module type Stmts = sig val move : (Var.t * Ast.exp * Ast.attrs) -> process_stmt val halt : (Ast.exp * Ast.attrs) -> process_stmt val jmp : (Ast.exp * Ast.attrs) -> process_stmt val cjmp : (Ast.exp * Ast.exp * Ast.exp * Ast.attrs) -> process_stmt val assertt : (Ast.exp * Ast.attrs) -> process_stmt val assume : (Ast.exp * Ast.attrs) -> process_stmt val comment : 'a -> process_stmt val label : 'a -> process_stmt val special : (string * Var.defuse option * Ast.attrs) -> process_stmt end module Make(Expr: Exprs)(Stmt: Stmts) = struct let expr = function | Var v -> Expr.var v | Int i -> Expr.int i | Lab l -> Expr.lab l | Ite i -> Expr.ite i | Extract e -> Expr.extract e | Concat c -> Expr.concat c | BinOp b -> Expr.binop b | UnOp u -> Expr.unop u | Cast c -> Expr.cast c | Let l -> Expr.lett l | Load l -> Expr.load l | Store s -> Expr.store s | Unknown u -> Expr.unknown u let stmt = function | Move m -> Stmt.move m | Halt h -> Stmt.halt h | Jmp j -> Stmt.jmp j | CJmp c -> Stmt.cjmp c | Assert a -> Stmt.assertt a | Assume a -> Stmt.assume a | Comment c -> Stmt.comment c | Label l -> Stmt.label l | Special s -> Stmt.special s end end
cc6c56e41c80d29167c6680ac4fc8b759d8714aefd229a80bbea53e74da787aa
c-cube/ocaml-containers
t_byte_buffer.ml
module T = (val Containers_testlib.make ~__FILE__ ()) include T open CCByte_buffer;; t @@ fun () -> let b = create () in is_empty b ;; t @@ fun () -> let b = create ~cap:32 () in is_empty b ;; t @@ fun () -> let b = create () in length b = 0 ;; t @@ fun () -> let b = create ~cap:32 () in length b = 0 let test_count = 2_500 open QCheck type op = | Add_char of char | Add_string of string | Get_contents | Get of int | Clear | Shrink_to of int | Set of int * char let spf = Printf.sprintf let str_op = function | Add_char c -> spf "add_char %C" c | Add_string s -> spf "add_string %S" s | Get_contents -> "contents" | Get i -> spf "get %d" i | Clear -> "clear" | Shrink_to n -> spf "shrink %d" n | Set (i, c) -> spf "set %d %C" i c let gen_op size : (_ * _) Gen.t = let open Gen in let base = if size > 0 then [ (1, 0 -- size >|= fun x -> Get x, size); ( 1, 0 -- size >>= fun x -> printable >|= fun c -> Set (x, c), size ); (1, 0 -- size >|= fun x -> Shrink_to x, x); ] else [] in frequency (base @ [ 1, return (Get_contents, size); 1, return (Clear, 0); (3, printable >|= fun c -> Add_char c, size + 1); ( 1, string_size (0 -- 100) ~gen:printable >|= fun s -> Add_string s, size + String.length s ); ]) let rec gen_l acc sz n = let open Gen in if n = 0 then return (List.rev acc) else gen_op sz >>= fun (op, sz) -> gen_l (op :: acc) sz (n - 1) let gen : op list Gen.t = Gen.sized (gen_l [] 0) let is_valid ops = let rec loop sz = function | [] -> true | Add_char _ :: tl -> loop (sz + 1) tl | Clear :: tl -> loop 0 tl | Add_string s :: tl -> loop (sz + String.length s) tl | (Get n | Set (n, _)) :: tl -> n < sz && loop sz tl | Get_contents :: tl -> loop sz tl | Shrink_to x :: tl -> x <= sz && loop x tl in loop 0 ops let shrink_op = Iter.( function | Get_contents | Clear -> empty | Get n -> Shrink.int n >|= fun n -> Get n | Add_char c -> Shrink.char c >|= fun c -> Add_char c | Add_string s -> Shrink.string s >|= fun s -> Add_string s | Shrink_to n -> Shrink.int n >|= fun n -> Shrink_to n | Set (n, c) -> Shrink.int n >|= (fun n -> Set (n, c)) <+> (Shrink.char c >|= fun c -> Set (n, c))) let arb = make gen ~print:(Print.list str_op) ~shrink:Shrink.(filter is_valid @@ list ~shrink:shrink_op) exception Nope of string let prop_consistent ops = let buf = ref "" in let b = create ~cap:32 () in let run_op op = match op with | Get i -> assert (String.length !buf = length b); let c1 = !buf.[i] in let c2 = get b i in if c1 <> c2 then raise (Nope (spf "c1=%C, c2=%C" c1 c2)) | Get_contents -> let s1 = !buf in let s2 = contents b in if s1 <> s2 then raise (Nope (spf "s1=%S, s2=%S" s1 s2)) | Add_char c -> buf := !buf ^ String.make 1 c; add_char b c | Add_string s -> buf := !buf ^ s; append_string b s | Clear -> buf := ""; clear b | Shrink_to n -> buf := String.sub !buf 0 n; shrink_to b n | Set (n, c) -> (let b' = Bytes.of_string !buf in Bytes.set b' n c; buf := Bytes.unsafe_to_string b'); set b n c in assume (is_valid ops); try List.iter run_op ops; true with Nope str -> Test.fail_reportf "consistent ops failed:\n%s" str ;; q arb (fun ops -> prop_consistent ops)
null
https://raw.githubusercontent.com/c-cube/ocaml-containers/69f2805f1073c4ebd1063bbd58380d17e62f6324/tests/core/t_byte_buffer.ml
ocaml
module T = (val Containers_testlib.make ~__FILE__ ()) include T open CCByte_buffer;; t @@ fun () -> let b = create () in is_empty b ;; t @@ fun () -> let b = create ~cap:32 () in is_empty b ;; t @@ fun () -> let b = create () in length b = 0 ;; t @@ fun () -> let b = create ~cap:32 () in length b = 0 let test_count = 2_500 open QCheck type op = | Add_char of char | Add_string of string | Get_contents | Get of int | Clear | Shrink_to of int | Set of int * char let spf = Printf.sprintf let str_op = function | Add_char c -> spf "add_char %C" c | Add_string s -> spf "add_string %S" s | Get_contents -> "contents" | Get i -> spf "get %d" i | Clear -> "clear" | Shrink_to n -> spf "shrink %d" n | Set (i, c) -> spf "set %d %C" i c let gen_op size : (_ * _) Gen.t = let open Gen in let base = if size > 0 then [ (1, 0 -- size >|= fun x -> Get x, size); ( 1, 0 -- size >>= fun x -> printable >|= fun c -> Set (x, c), size ); (1, 0 -- size >|= fun x -> Shrink_to x, x); ] else [] in frequency (base @ [ 1, return (Get_contents, size); 1, return (Clear, 0); (3, printable >|= fun c -> Add_char c, size + 1); ( 1, string_size (0 -- 100) ~gen:printable >|= fun s -> Add_string s, size + String.length s ); ]) let rec gen_l acc sz n = let open Gen in if n = 0 then return (List.rev acc) else gen_op sz >>= fun (op, sz) -> gen_l (op :: acc) sz (n - 1) let gen : op list Gen.t = Gen.sized (gen_l [] 0) let is_valid ops = let rec loop sz = function | [] -> true | Add_char _ :: tl -> loop (sz + 1) tl | Clear :: tl -> loop 0 tl | Add_string s :: tl -> loop (sz + String.length s) tl | (Get n | Set (n, _)) :: tl -> n < sz && loop sz tl | Get_contents :: tl -> loop sz tl | Shrink_to x :: tl -> x <= sz && loop x tl in loop 0 ops let shrink_op = Iter.( function | Get_contents | Clear -> empty | Get n -> Shrink.int n >|= fun n -> Get n | Add_char c -> Shrink.char c >|= fun c -> Add_char c | Add_string s -> Shrink.string s >|= fun s -> Add_string s | Shrink_to n -> Shrink.int n >|= fun n -> Shrink_to n | Set (n, c) -> Shrink.int n >|= (fun n -> Set (n, c)) <+> (Shrink.char c >|= fun c -> Set (n, c))) let arb = make gen ~print:(Print.list str_op) ~shrink:Shrink.(filter is_valid @@ list ~shrink:shrink_op) exception Nope of string let prop_consistent ops = let buf = ref "" in let b = create ~cap:32 () in let run_op op = match op with | Get i -> assert (String.length !buf = length b); let c1 = !buf.[i] in let c2 = get b i in if c1 <> c2 then raise (Nope (spf "c1=%C, c2=%C" c1 c2)) | Get_contents -> let s1 = !buf in let s2 = contents b in if s1 <> s2 then raise (Nope (spf "s1=%S, s2=%S" s1 s2)) | Add_char c -> buf := !buf ^ String.make 1 c; add_char b c | Add_string s -> buf := !buf ^ s; append_string b s | Clear -> buf := ""; clear b | Shrink_to n -> buf := String.sub !buf 0 n; shrink_to b n | Set (n, c) -> (let b' = Bytes.of_string !buf in Bytes.set b' n c; buf := Bytes.unsafe_to_string b'); set b n c in assume (is_valid ops); try List.iter run_op ops; true with Nope str -> Test.fail_reportf "consistent ops failed:\n%s" str ;; q arb (fun ops -> prop_consistent ops)
1f68bb0eda957bd8bb0a9716048c608758b333a31c6140255fa2b19c068e281b
nboldi/c-parser-in-haskell
PosOps.hs
{-# LANGUAGE DeriveDataTypeable #-} -- | Operations on source positions module Text.Parsec.PosOps where import Text.Parsec import Text.Parsec.Pos import Data.Function import Data.Data import Debug.Trace -- * Utils on source positions | Shows a source position in a : col@ format , omitting file name . shortShow :: SourcePos -> String shortShow sp = show (sourceLine sp) ++ ":" ++ show (sourceColumn sp) -- | Initial position in the same file as initPosIn :: SourcePos -> SourcePos initPosIn sp = initialPos (sourceName sp) takeToPos' sp = takeToPos sp (initPosIn sp) dropToPos' sp = dropToPos sp (initPosIn sp) takeToPos :: SourcePos -> SourcePos -> String -> (SourcePos, String) takeToPos to curr (c:s) | curr < to = let (endPos, res) = takeToPos to (updatePosChar curr c) s in (endPos, c : res) takeToPos to curr s = (curr, []) dropToPos :: SourcePos -> SourcePos -> String -> (SourcePos, String) dropToPos to curr (c:s) | curr < to = dropToPos to (updatePosChar curr c) s dropToPos to curr s = (curr, s) -- * Source Ranges -- | A range of characters in a source file given by a begin and an end position. data SourceRange = SourceRange { srcRangeBegin :: SourcePos , srcRangeEnd :: SourcePos } deriving (Eq, Ord, Typeable, Data) instance Show SourceRange where show sr = show (srcRangeBegin sr) ++ " -- " ++ show (srcRangeEnd sr) -- | Shows a range in a @line:col-line:col@ format shortShowRng :: SourceRange -> String shortShowRng sr = shortShow (srcRangeBegin sr) ++ "-" ++ shortShow (srcRangeEnd sr) | Creates a source range between two source positions srcRange :: SourcePos -> SourcePos -> SourceRange srcRange pos0 pos1 = if pos0 < pos1 then SourceRange pos0 pos1 else SourceRange pos1 pos0 -- | True, if a source range is completely inside another range rangeInside :: SourceRange -> SourceRange -> Bool (SourceRange from1 to1) `rangeInside` (SourceRange from2 to2) = from2 <= from1 && to1 <= to2 && from2 < to1 -- | True, if a source range is completely inside another range rangeStrictInside :: SourceRange -> SourceRange -> Bool (SourceRange from1 to1) `rangeStrictInside` (SourceRange from2 to2) = from2 <= from1 && to1 <= to2 && (from2 < from1 || to1 < to2) | True , two source ranges overlap rangeOverlaps :: SourceRange -> SourceRange -> Bool (SourceRange from1 to1) `rangeOverlaps` (SourceRange from2 to2) = (from1 <= from2 && from2 <= to1) || (from1 <= to2 && to2 <= to1) | The smallest range that contains the two given range . srcRngUnion :: SourceRange -> SourceRange -> SourceRange srcRngUnion sr1 sr2 = SourceRange ((min `on` srcRangeBegin) sr1 sr2) ((max `on` srcRangeEnd) sr1 sr2) | Returns a range that has the same size as the given range but starts from file position of zero . rngFromStart :: SourceRange -> SourceRange rngFromStart rng = rangeRelativelyTo rng (srcRangeBegin rng) -- | Returns an empty range at the beginning of the given range. rngStartAsRange :: SourceRange -> SourceRange rngStartAsRange (SourceRange begin _) = SourceRange begin begin -- | Returns an empty range at the end of the given range. rngEndAsRange :: SourceRange -> SourceRange rngEndAsRange (SourceRange _ end) = SourceRange end end -- | True, iff the range is empty emptyRange :: SourceRange -> Bool emptyRange (SourceRange begin end) = (begin == end) -- | Addition on source positions. offsetedBy :: SourcePos -> SourcePos -> SourcePos sp1 `offsetedBy` sp2 = newPos (sourceName sp1) (sourceLine sp1 + sourceLine sp2 - 1) (if sourceLine sp2 == 1 then sourceColumn sp1 + sourceColumn sp2 - 1 else sourceColumn sp2) -- | Substraction on source positions. relativelyTo :: SourcePos -> SourcePos -> SourcePos sp1 `relativelyTo` sp2 = let newLine = sourceLine sp1 - sourceLine sp2 + 1 in newPos (sourceName sp1) newLine (if newLine == 1 then sourceColumn sp1 - sourceColumn sp2 + 1 else sourceColumn sp1) -- | Gets a source range, with a specified position substracted from beginning and end. rangeRelativelyTo :: SourceRange -> SourcePos -> SourceRange sr `rangeRelativelyTo` sp = rangeMapBoth (`relativelyTo` sp) sr -- | Applies a function on source positions to both begin and end of range rangeMapBoth :: (SourcePos -> SourcePos) -> SourceRange -> SourceRange rangeMapBoth f (SourceRange sp0 sp1) = SourceRange (f sp0) (f sp1) -- | Takes a substring indicated by a source range from the contents of the file takeSourceRange :: SourceRange -> String -> String takeSourceRange (SourceRange from to) s = let init = (initialPos (sourceName from)) (startPos,startsAtPos) = dropToPos from init s in snd $ takeToPos to startPos startsAtPos
null
https://raw.githubusercontent.com/nboldi/c-parser-in-haskell/1a92132e7d1b984cf93ec89d6836cc804257b57d/Text/Parsec/PosOps.hs
haskell
# LANGUAGE DeriveDataTypeable # | Operations on source positions * Utils on source positions | Initial position in the same file as * Source Ranges | A range of characters in a source file given by a begin and an end position. | Shows a range in a @line:col-line:col@ format | True, if a source range is completely inside another range | True, if a source range is completely inside another range | Returns an empty range at the beginning of the given range. | Returns an empty range at the end of the given range. | True, iff the range is empty | Addition on source positions. | Substraction on source positions. | Gets a source range, with a specified position substracted from beginning and end. | Applies a function on source positions to both begin and end of range | Takes a substring indicated by a source range from the contents of the file
module Text.Parsec.PosOps where import Text.Parsec import Text.Parsec.Pos import Data.Function import Data.Data import Debug.Trace | Shows a source position in a : col@ format , omitting file name . shortShow :: SourcePos -> String shortShow sp = show (sourceLine sp) ++ ":" ++ show (sourceColumn sp) initPosIn :: SourcePos -> SourcePos initPosIn sp = initialPos (sourceName sp) takeToPos' sp = takeToPos sp (initPosIn sp) dropToPos' sp = dropToPos sp (initPosIn sp) takeToPos :: SourcePos -> SourcePos -> String -> (SourcePos, String) takeToPos to curr (c:s) | curr < to = let (endPos, res) = takeToPos to (updatePosChar curr c) s in (endPos, c : res) takeToPos to curr s = (curr, []) dropToPos :: SourcePos -> SourcePos -> String -> (SourcePos, String) dropToPos to curr (c:s) | curr < to = dropToPos to (updatePosChar curr c) s dropToPos to curr s = (curr, s) data SourceRange = SourceRange { srcRangeBegin :: SourcePos , srcRangeEnd :: SourcePos } deriving (Eq, Ord, Typeable, Data) instance Show SourceRange where show sr = show (srcRangeBegin sr) ++ " -- " ++ show (srcRangeEnd sr) shortShowRng :: SourceRange -> String shortShowRng sr = shortShow (srcRangeBegin sr) ++ "-" ++ shortShow (srcRangeEnd sr) | Creates a source range between two source positions srcRange :: SourcePos -> SourcePos -> SourceRange srcRange pos0 pos1 = if pos0 < pos1 then SourceRange pos0 pos1 else SourceRange pos1 pos0 rangeInside :: SourceRange -> SourceRange -> Bool (SourceRange from1 to1) `rangeInside` (SourceRange from2 to2) = from2 <= from1 && to1 <= to2 && from2 < to1 rangeStrictInside :: SourceRange -> SourceRange -> Bool (SourceRange from1 to1) `rangeStrictInside` (SourceRange from2 to2) = from2 <= from1 && to1 <= to2 && (from2 < from1 || to1 < to2) | True , two source ranges overlap rangeOverlaps :: SourceRange -> SourceRange -> Bool (SourceRange from1 to1) `rangeOverlaps` (SourceRange from2 to2) = (from1 <= from2 && from2 <= to1) || (from1 <= to2 && to2 <= to1) | The smallest range that contains the two given range . srcRngUnion :: SourceRange -> SourceRange -> SourceRange srcRngUnion sr1 sr2 = SourceRange ((min `on` srcRangeBegin) sr1 sr2) ((max `on` srcRangeEnd) sr1 sr2) | Returns a range that has the same size as the given range but starts from file position of zero . rngFromStart :: SourceRange -> SourceRange rngFromStart rng = rangeRelativelyTo rng (srcRangeBegin rng) rngStartAsRange :: SourceRange -> SourceRange rngStartAsRange (SourceRange begin _) = SourceRange begin begin rngEndAsRange :: SourceRange -> SourceRange rngEndAsRange (SourceRange _ end) = SourceRange end end emptyRange :: SourceRange -> Bool emptyRange (SourceRange begin end) = (begin == end) offsetedBy :: SourcePos -> SourcePos -> SourcePos sp1 `offsetedBy` sp2 = newPos (sourceName sp1) (sourceLine sp1 + sourceLine sp2 - 1) (if sourceLine sp2 == 1 then sourceColumn sp1 + sourceColumn sp2 - 1 else sourceColumn sp2) relativelyTo :: SourcePos -> SourcePos -> SourcePos sp1 `relativelyTo` sp2 = let newLine = sourceLine sp1 - sourceLine sp2 + 1 in newPos (sourceName sp1) newLine (if newLine == 1 then sourceColumn sp1 - sourceColumn sp2 + 1 else sourceColumn sp1) rangeRelativelyTo :: SourceRange -> SourcePos -> SourceRange sr `rangeRelativelyTo` sp = rangeMapBoth (`relativelyTo` sp) sr rangeMapBoth :: (SourcePos -> SourcePos) -> SourceRange -> SourceRange rangeMapBoth f (SourceRange sp0 sp1) = SourceRange (f sp0) (f sp1) takeSourceRange :: SourceRange -> String -> String takeSourceRange (SourceRange from to) s = let init = (initialPos (sourceName from)) (startPos,startsAtPos) = dropToPos from init s in snd $ takeToPos to startPos startsAtPos
84b3a7b23033a54a29f51ef535549750c27429ddbfc904cf69cb47b8cb4ee53f
bruz/hotframeworks
utils.clj
(ns hotframeworks.utils) (defn average [values] (let [sum (reduce + values) number (count values)] (if (= 0 number) 0 (int (/ sum number)))))
null
https://raw.githubusercontent.com/bruz/hotframeworks/629aa8f3cd7556479ea5cd7720d8b06ee4926ae4/src/hotframeworks/utils.clj
clojure
(ns hotframeworks.utils) (defn average [values] (let [sum (reduce + values) number (count values)] (if (= 0 number) 0 (int (/ sum number)))))
091edc176a0e0e16182e248cb982e4b7fd22fe80d418125c1a94d09e54a4d112
fakedata-haskell/fakedata
TrTextSpec.hs
# LANGUAGE ScopedTypeVariables # {-# LANGUAGE OverloadedStrings #-} module TrTextSpec where import Data.Text (Text) import qualified Data.Text as T import Faker hiding (defaultFakerSettings) import qualified Faker.Address as FA import Faker.Combinators (listOf) import qualified Faker.Company as CO import qualified Faker.Commerce as CE import qualified Faker.Internet as IN import qualified Faker.Name as NA import qualified Faker.PhoneNumber as PH import qualified Faker.Book as BO import qualified Faker.Lorem as LO import qualified Faker.Game.Pokemon as PO import qualified Faker.Appliance as AP import qualified Faker.Measurement as ME import qualified Faker.Compass as CE import qualified Faker.Coin as CO import qualified Faker.Color as CL import qualified Faker.Gender as GE import qualified Faker.Vehicle as VE import qualified Faker.Food as FO import qualified Faker.Team as TE import qualified Faker.Job as JO import qualified Faker.University as UN import Test.Hspec import TestImport isText :: Text -> Bool isText x = T.length x >= 1 isTexts :: [Text] -> Bool isTexts xs = and $ map isText xs locale :: Text locale = "tr" fakerSettings :: FakerSettings fakerSettings = setLocale locale defaultFakerSettings verifyDistributeFakes :: [Fake Text] -> IO [Bool] verifyDistributeFakes funs = do let fs :: [IO [Text]] = map (generateWithSettings fakerSettings) $ map (listOf 100) funs gs :: [IO Bool] = map (\f -> isTexts <$> f) fs sequence gs spec :: Spec spec = do describe "TextSpec" $ do it "validates tr locale" $ do let functions :: [Fake Text] = [ NA.firstName , NA.lastName , NA.prefix , NA.name , NA.nameWithMiddle , IN.freeEmail , IN.domainSuffix , PH.formats , FA.city , FA.country , BO.title , BO.author , BO.publisher ] bools <- verifyDistributeFakes functions (and bools) `shouldBe` True
null
https://raw.githubusercontent.com/fakedata-haskell/fakedata/e6fbc16cfa27b2d17aa449ea8140788196ca135b/test/TrTextSpec.hs
haskell
# LANGUAGE OverloadedStrings #
# LANGUAGE ScopedTypeVariables # module TrTextSpec where import Data.Text (Text) import qualified Data.Text as T import Faker hiding (defaultFakerSettings) import qualified Faker.Address as FA import Faker.Combinators (listOf) import qualified Faker.Company as CO import qualified Faker.Commerce as CE import qualified Faker.Internet as IN import qualified Faker.Name as NA import qualified Faker.PhoneNumber as PH import qualified Faker.Book as BO import qualified Faker.Lorem as LO import qualified Faker.Game.Pokemon as PO import qualified Faker.Appliance as AP import qualified Faker.Measurement as ME import qualified Faker.Compass as CE import qualified Faker.Coin as CO import qualified Faker.Color as CL import qualified Faker.Gender as GE import qualified Faker.Vehicle as VE import qualified Faker.Food as FO import qualified Faker.Team as TE import qualified Faker.Job as JO import qualified Faker.University as UN import Test.Hspec import TestImport isText :: Text -> Bool isText x = T.length x >= 1 isTexts :: [Text] -> Bool isTexts xs = and $ map isText xs locale :: Text locale = "tr" fakerSettings :: FakerSettings fakerSettings = setLocale locale defaultFakerSettings verifyDistributeFakes :: [Fake Text] -> IO [Bool] verifyDistributeFakes funs = do let fs :: [IO [Text]] = map (generateWithSettings fakerSettings) $ map (listOf 100) funs gs :: [IO Bool] = map (\f -> isTexts <$> f) fs sequence gs spec :: Spec spec = do describe "TextSpec" $ do it "validates tr locale" $ do let functions :: [Fake Text] = [ NA.firstName , NA.lastName , NA.prefix , NA.name , NA.nameWithMiddle , IN.freeEmail , IN.domainSuffix , PH.formats , FA.city , FA.country , BO.title , BO.author , BO.publisher ] bools <- verifyDistributeFakes functions (and bools) `shouldBe` True
f0fa51e3705803581e4d4fe4a3726d10e50d604271b05bb4161815e9d0f2710f
mentat-collective/JSXGraph.cljs
sci_extensions.cljs
(ns jsxgraph.sci-extensions (:require [jsxgraph.sci])) # # SCI Customization (jsxgraph.sci/install!)
null
https://raw.githubusercontent.com/mentat-collective/JSXGraph.cljs/83ce94fdd54326dd3a355e283a3a216d08cc2801/dev/jsxgraph/sci_extensions.cljs
clojure
(ns jsxgraph.sci-extensions (:require [jsxgraph.sci])) # # SCI Customization (jsxgraph.sci/install!)
9de246c3d92dc914414b4171f580b2d60dde36b74fa6eb2df0fc1a0dcd14231f
pflanze/chj-schemelib
svg.scm
Copyright 2013 - 2020 by < > ;;; This file is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License ( GPL ) as published by the Free Software Foundation , either version 2 of the License , or ;;; (at your option) any later version. (require easy oo-util ;; part of easy, though? 2d-shape color dsssl cj-sxml cj-sxml-serializer (tempfile tempfile-incremental-at) (cj-functional-2 =>) (cj-path path-string?)) (export (generic 2d-shape.svg-fragment) (class svg) showsvg showsvg* #!optional (enum fit)) (def. (real.svg-string x) (let* ((integertostring (lambda (x) (number.string (if (exact? x) x (inexact->exact x)))))) (if (integer? x) (integertostring x) (let ((x* (inexact.round-at (exact->inexact x) 4))) (if (integer? x*) (integertostring x*) (number.string x*)))))) (TEST > (real.svg-string 0) "0" > (real.svg-string -0.99999999999) "-1" > (real.svg-string 2/3) ".6667" no need to add leading zero : ;; #DataTypeNumber > (real.svg-string -2/3) "-.6667" > (real.svg-string -4/3) "-1.3333" > (real.svg-string -4.) "-4" > (real.svg-string -0.) "0") (def (optionS/default optionsS default-options) ;; yep optionsS, not optionS, XX naming wrong further down. (lambda (f) (or (and optionsS (improper-any f optionsS)) (and default-options (f default-options))))) (def default-2d-point-colors (colors (colorstring "blue") (colorstring "blue"))) (def. (2d-point.svg-fragment shape fit #!optional optionS) (let ((p (fit shape)) (getopt (optionS/default optionS default-2d-point-colors))) `(circle (@ (cx ,(.svg-string (.x p))) (cy ,(.svg-string (.y p))) (r ,(or (getopt .maybe-stroke-width) 1.5)) (stroke ,(.html-colorstring (getopt .maybe-stroke-color))) (stroke-width 0) (fill ,(.html-colorstring (getopt .maybe-fill-color))))))) (def (_svg-point command p last?) (list command " " (.svg-string (.x p)) " " (.svg-string (.y p)) (if last? #f " "))) (def (_svg-point* maybe-command p) (let ((cont (list (.svg-string (.x p)) "," (.svg-string (.y p))))) (if maybe-command (cons* maybe-command " " cont) cont))) (def default-2d-line-color (colorstring "black")) (def. (2d-line.svg-fragment shape fit #!optional optionS) (let-2d-line ((from to) shape) (let ((getopt (optionS/default optionS default-2d-line-color))) `(path (@ (d ,(cons (_svg-point "M" (fit from) #f) (_svg-point "L" (fit to) #t))) (stroke ,(.html-colorstring (getopt .maybe-stroke-color))) (stroke-width ,(or (getopt .maybe-stroke-width) 1))))))) (def default-2d-path-colors (colors (colorstring "black") (colorstring "green"))) (def. (2d-path.svg-fragment shape fit #!optional optionS) (let ((ps (map fit (.points shape))) (getopt (optionS/default optionS default-2d-path-colors))) (let-pair ((p0 ps*) ps) `(path (@ (d ,(list (_svg-point* "M" p0) " " (list-join (map (C _svg-point* #f _) ps*) " ") (if (.closed? shape) " z" ""))) (stroke ,(.html-colorstring (getopt .maybe-stroke-color))) (stroke-width ,(or (getopt .maybe-stroke-width) 1)) (fill ,(.html-colorstring (getopt .maybe-fill-color)))))))) (TEST > (def p (2d-path (list (2d-point 1 7) (2d-point 2 9)) #t)) > (.svg-fragment p identity) (path (@ (d (("M" " " "1" "," "7") " " (("2" "," "9")) " z")) (stroke "black") (stroke-width 1) (fill "green"))) > (.svg-fragment p identity (colorstring "yellow")) (path (@ (d (("M" " " "1" "," "7") " " (("2" "," "9")) " z")) (stroke "yellow") (stroke-width 1) (fill "yellow"))) > (.svg-fragment p identity (paint stroke-width: 5 fill-color: (colorstring "white"))) (path (@ (d (("M" " " "1" "," "7") " " (("2" "," "9")) " z")) (stroke "black") (stroke-width 5) (fill "white"))) > (.svg-fragment p identity (paint fill-color: (rgb01l 0 0.5 1))) (path (@ (d (("M" " " "1" "," "7") " " (("2" "," "9")) " z")) (stroke "black") (stroke-width 1) (fill "#00BCFF")))) ;; insert SVG code verbatim (jclass (svg-fragment [sxml-element? value]) (def-method (svg-fragment shape fit #!optional optionS) ;; simply ignore the arguments? value) ;; and those 2d-shape methods that are required for operation ;; in svg.scm (def-method (min+maxs/prev v min+max) ;; simply be invisible? XX totally unsafe and bad. min+max)) (def default-2d-square-colors (colors (colorstring "black") (colorstring "none"))) (def. (2d-square.svg-fragment shape fit #!optional optionS) (let ((getopt (optionS/default optionS default-2d-square-colors))) `(path (@ (d ,(let* ((ps (.points shape)) (p0 (car ps))) (cons (_svg-point "M" (fit p0) #f) (fold-right (lambda (p r) (cons (_svg-point "L" (fit p) #f) r)) (_svg-point "L" (fit p0) #t) (cdr ps))))) (stroke ,(.html-colorstring (getopt .maybe-stroke-color))) (stroke-width ,(or (getopt .maybe-stroke-width) "1")) (fill ,(.html-colorstring (getopt .maybe-fill-color))))))) (defclass (svg [2d-point? size] [2d-window? window] ;; 2d-window into the shapes data shapes ;; flat list of shapes; no grouping supported (yet?) #!key [(maybe color?) background-color] ([real? border] 5)) (defmethod (sxml s) (let* ((borderpoint (2d-point border border)) (fit (let. ((mi range) window) (let* ((stretch (../ size range))) (lambda (p) (.+ (..* (.- p mi) stretch) borderpoint)))))) `(svg (@ (xmlns "") (xmlns:xlink "") (height ,(integer-ceiling (+ (.y size) (* 2 border)))) (width ,(integer-ceiling (+ (.x size) (* 2 border)))) ,(and background-color `(style ,(string-append "background-color: " (.html-colorstring background-color) ";")))) display from imagemagick 8:6.7.7.10 - 5 ignores any style ;; etc. attributes of the svg element that set the bgcolor, ;; thus: ,(and background-color `(rect (@ (width "100%") (height "100%") (fill ,(.html-colorstring background-color))))) ,(map ;;stream-map (lambda (shape) (if (painted? shape) (let-painted ((optionS shape) shape) (.svg-fragment shape fit optionS)) (.svg-fragment shape fit))) shapes)))) (defmethod (sxml-file s [path-string? path]) (sxml>>pretty-xml-file (.sxml s) path))) (def svg-path-generate (tempfile-incremental-at "out-" ".svg")) (def use-eog-if-possible? #f) (def svg-viewer (let ((els (lambda () (letv ((out s) (backtick "which" "display")) (if (zero? s) ;; oddly need to force output size (list out "-resize" "800x800") #f))))) (if use-eog-if-possible? (letv ((out s) (backtick "which" "eog")) (if (zero? s) (list out) (els))) (els)))) (def default-svg-size (2d-point 800 800)) (defenum fit within clip stretch) (def (_fit-to-props fit size) (let ((targetprops (.x/y size))) (xcase fit ((within) (C .fit-to-proportions _ targetprops #f)) ((clip) (C .fit-to-proportions _ targetprops #t)) ((stretch) identity)))) ;; with auto-scaling/cropping to the given size (def (showsvg shapes . options) (let ((fit (-> fit? (dsssl-ref options fit: 'within))) (size (dsssl-ref options size: default-svg-size)) (path (or (dsssl-ref options path: #f) (svg-path-generate))) (options (=> options (dsssl-delete fit:) (dsssl-delete size:) (dsssl-delete path:)))) ah want regenerate stream(s ) maybe ? not cache ? well . how to say . (let (p0 (.start (car (force shapes)))) (let-pair ((mi ma) (stream-fold-left .min+maxs/prev (cons p0 p0) shapes)) (let* ((usage-window (2d-window mi ma)) (cont (lambda (size window) (.sxml-file (apply svg size window shapes options)))) (cont-size (lambda (size) (cont size usage-window))) (cont-fit (lambda (size) (cont size ((_fit-to-props fit size) usage-window))))) (if (partial-2d-point? size) (xcase (.partial-kind size) ((full) (cont-fit (.2d-point size))) ;; In partial cases, |fit| is ignored. ;; (Should the program instead require ;; the user to give a 'partial ;; ('complete-size, 'calculate-size) ;; fit value and save the dispatching ;; here?) ((x-given) (let. ((x) size) (cont-size (2d-point x (/ x (.x/y usage-window)))))) ((y-given) (let. ((y) size) (cont-size (2d-point (* y (.x/y usage-window)) y)))) ((empty) (error "given size has neither x nor y"))) (cont-fit size))) (future (apply xsystem `(,@svg-viewer "--" ,path))) path)))) ;; with manual scaling/cropping XX copy - paste (def (showsvg* size window shapes . options) (let (path (or (dsssl-ref options path: #f) (svg-path-generate))) (.sxml-file (apply svg size window shapes (=> options (dsssl-delete path:))) path) (future (apply xsystem `(,@svg-viewer "--" ,path))) path))
null
https://raw.githubusercontent.com/pflanze/chj-schemelib/59ff8476e39f207c2f1d807cfc9670581c8cedd3/svg.scm
scheme
This file is free software; you can redistribute it and/or modify (at your option) any later version. part of easy, though? #DataTypeNumber yep optionsS, not optionS, XX naming wrong further down. insert SVG code verbatim simply ignore the arguments? and those 2d-shape methods that are required for operation in svg.scm simply be invisible? XX totally unsafe and bad. 2d-window into the shapes data flat list of shapes; no grouping supported (yet?) etc. attributes of the svg element that set the bgcolor, thus: stream-map oddly need to force output size with auto-scaling/cropping to the given size In partial cases, |fit| is ignored. (Should the program instead require the user to give a 'partial ('complete-size, 'calculate-size) fit value and save the dispatching here?) with manual scaling/cropping
Copyright 2013 - 2020 by < > it under the terms of the GNU General Public License ( GPL ) as published by the Free Software Foundation , either version 2 of the License , or (require easy 2d-shape color dsssl cj-sxml cj-sxml-serializer (tempfile tempfile-incremental-at) (cj-functional-2 =>) (cj-path path-string?)) (export (generic 2d-shape.svg-fragment) (class svg) showsvg showsvg* #!optional (enum fit)) (def. (real.svg-string x) (let* ((integertostring (lambda (x) (number.string (if (exact? x) x (inexact->exact x)))))) (if (integer? x) (integertostring x) (let ((x* (inexact.round-at (exact->inexact x) 4))) (if (integer? x*) (integertostring x*) (number.string x*)))))) (TEST > (real.svg-string 0) "0" > (real.svg-string -0.99999999999) "-1" > (real.svg-string 2/3) ".6667" no need to add leading zero : > (real.svg-string -2/3) "-.6667" > (real.svg-string -4/3) "-1.3333" > (real.svg-string -4.) "-4" > (real.svg-string -0.) "0") (def (optionS/default optionsS default-options) (lambda (f) (or (and optionsS (improper-any f optionsS)) (and default-options (f default-options))))) (def default-2d-point-colors (colors (colorstring "blue") (colorstring "blue"))) (def. (2d-point.svg-fragment shape fit #!optional optionS) (let ((p (fit shape)) (getopt (optionS/default optionS default-2d-point-colors))) `(circle (@ (cx ,(.svg-string (.x p))) (cy ,(.svg-string (.y p))) (r ,(or (getopt .maybe-stroke-width) 1.5)) (stroke ,(.html-colorstring (getopt .maybe-stroke-color))) (stroke-width 0) (fill ,(.html-colorstring (getopt .maybe-fill-color))))))) (def (_svg-point command p last?) (list command " " (.svg-string (.x p)) " " (.svg-string (.y p)) (if last? #f " "))) (def (_svg-point* maybe-command p) (let ((cont (list (.svg-string (.x p)) "," (.svg-string (.y p))))) (if maybe-command (cons* maybe-command " " cont) cont))) (def default-2d-line-color (colorstring "black")) (def. (2d-line.svg-fragment shape fit #!optional optionS) (let-2d-line ((from to) shape) (let ((getopt (optionS/default optionS default-2d-line-color))) `(path (@ (d ,(cons (_svg-point "M" (fit from) #f) (_svg-point "L" (fit to) #t))) (stroke ,(.html-colorstring (getopt .maybe-stroke-color))) (stroke-width ,(or (getopt .maybe-stroke-width) 1))))))) (def default-2d-path-colors (colors (colorstring "black") (colorstring "green"))) (def. (2d-path.svg-fragment shape fit #!optional optionS) (let ((ps (map fit (.points shape))) (getopt (optionS/default optionS default-2d-path-colors))) (let-pair ((p0 ps*) ps) `(path (@ (d ,(list (_svg-point* "M" p0) " " (list-join (map (C _svg-point* #f _) ps*) " ") (if (.closed? shape) " z" ""))) (stroke ,(.html-colorstring (getopt .maybe-stroke-color))) (stroke-width ,(or (getopt .maybe-stroke-width) 1)) (fill ,(.html-colorstring (getopt .maybe-fill-color)))))))) (TEST > (def p (2d-path (list (2d-point 1 7) (2d-point 2 9)) #t)) > (.svg-fragment p identity) (path (@ (d (("M" " " "1" "," "7") " " (("2" "," "9")) " z")) (stroke "black") (stroke-width 1) (fill "green"))) > (.svg-fragment p identity (colorstring "yellow")) (path (@ (d (("M" " " "1" "," "7") " " (("2" "," "9")) " z")) (stroke "yellow") (stroke-width 1) (fill "yellow"))) > (.svg-fragment p identity (paint stroke-width: 5 fill-color: (colorstring "white"))) (path (@ (d (("M" " " "1" "," "7") " " (("2" "," "9")) " z")) (stroke "black") (stroke-width 5) (fill "white"))) > (.svg-fragment p identity (paint fill-color: (rgb01l 0 0.5 1))) (path (@ (d (("M" " " "1" "," "7") " " (("2" "," "9")) " z")) (stroke "black") (stroke-width 1) (fill "#00BCFF")))) (jclass (svg-fragment [sxml-element? value]) (def-method (svg-fragment shape fit #!optional optionS) value) (def-method (min+maxs/prev v min+max) min+max)) (def default-2d-square-colors (colors (colorstring "black") (colorstring "none"))) (def. (2d-square.svg-fragment shape fit #!optional optionS) (let ((getopt (optionS/default optionS default-2d-square-colors))) `(path (@ (d ,(let* ((ps (.points shape)) (p0 (car ps))) (cons (_svg-point "M" (fit p0) #f) (fold-right (lambda (p r) (cons (_svg-point "L" (fit p) #f) r)) (_svg-point "L" (fit p0) #t) (cdr ps))))) (stroke ,(.html-colorstring (getopt .maybe-stroke-color))) (stroke-width ,(or (getopt .maybe-stroke-width) "1")) (fill ,(.html-colorstring (getopt .maybe-fill-color))))))) (defclass (svg [2d-point? size] #!key [(maybe color?) background-color] ([real? border] 5)) (defmethod (sxml s) (let* ((borderpoint (2d-point border border)) (fit (let. ((mi range) window) (let* ((stretch (../ size range))) (lambda (p) (.+ (..* (.- p mi) stretch) borderpoint)))))) `(svg (@ (xmlns "") (xmlns:xlink "") (height ,(integer-ceiling (+ (.y size) (* 2 border)))) (width ,(integer-ceiling (+ (.x size) (* 2 border)))) ,(and background-color `(style ,(string-append "background-color: " (.html-colorstring background-color) ";")))) display from imagemagick 8:6.7.7.10 - 5 ignores any style ,(and background-color `(rect (@ (width "100%") (height "100%") (fill ,(.html-colorstring background-color))))) (lambda (shape) (if (painted? shape) (let-painted ((optionS shape) shape) (.svg-fragment shape fit optionS)) (.svg-fragment shape fit))) shapes)))) (defmethod (sxml-file s [path-string? path]) (sxml>>pretty-xml-file (.sxml s) path))) (def svg-path-generate (tempfile-incremental-at "out-" ".svg")) (def use-eog-if-possible? #f) (def svg-viewer (let ((els (lambda () (letv ((out s) (backtick "which" "display")) (if (zero? s) (list out "-resize" "800x800") #f))))) (if use-eog-if-possible? (letv ((out s) (backtick "which" "eog")) (if (zero? s) (list out) (els))) (els)))) (def default-svg-size (2d-point 800 800)) (defenum fit within clip stretch) (def (_fit-to-props fit size) (let ((targetprops (.x/y size))) (xcase fit ((within) (C .fit-to-proportions _ targetprops #f)) ((clip) (C .fit-to-proportions _ targetprops #t)) ((stretch) identity)))) (def (showsvg shapes . options) (let ((fit (-> fit? (dsssl-ref options fit: 'within))) (size (dsssl-ref options size: default-svg-size)) (path (or (dsssl-ref options path: #f) (svg-path-generate))) (options (=> options (dsssl-delete fit:) (dsssl-delete size:) (dsssl-delete path:)))) ah want regenerate stream(s ) maybe ? not cache ? well . how to say . (let (p0 (.start (car (force shapes)))) (let-pair ((mi ma) (stream-fold-left .min+maxs/prev (cons p0 p0) shapes)) (let* ((usage-window (2d-window mi ma)) (cont (lambda (size window) (.sxml-file (apply svg size window shapes options)))) (cont-size (lambda (size) (cont size usage-window))) (cont-fit (lambda (size) (cont size ((_fit-to-props fit size) usage-window))))) (if (partial-2d-point? size) (xcase (.partial-kind size) ((full) (cont-fit (.2d-point size))) ((x-given) (let. ((x) size) (cont-size (2d-point x (/ x (.x/y usage-window)))))) ((y-given) (let. ((y) size) (cont-size (2d-point (* y (.x/y usage-window)) y)))) ((empty) (error "given size has neither x nor y"))) (cont-fit size))) (future (apply xsystem `(,@svg-viewer "--" ,path))) path)))) XX copy - paste (def (showsvg* size window shapes . options) (let (path (or (dsssl-ref options path: #f) (svg-path-generate))) (.sxml-file (apply svg size window shapes (=> options (dsssl-delete path:))) path) (future (apply xsystem `(,@svg-viewer "--" ,path))) path))
e858c9c0d21487963d25c4920cb5dafc7dfe016e8dd7dba7bf5474072d2e99f5
aistrate/Okasaki
PairingHeap.hs
# LANGUAGE FlexibleInstances , MultiParamTypeClasses # module PairingHeap (module Heap, PairingHeap(..)) where import Heap data PairingHeap a = E | T a [PairingHeap a] deriving (Eq, Show) mergePairs [] = E mergePairs [h] = h mergePairs (h1 : h2 : hs) = merge (merge h1 h2) (mergePairs hs) instance Ord a => Heap PairingHeap a where empty = E isEmpty E = True isEmpty _ = False insert x h = merge (T x []) h merge h E = h merge E h = h merge h1@(T x hs1) h2@(T y hs2) = if x < y then T x (h2:hs1) else T y (h1:hs2) findMin E = error "PairingHeap.findMin: empty heap" findMin (T x hs) = x deleteMin E = error "PairingHeap.deleteMin: empty heap" deleteMin (T x hs) = mergePairs hs
null
https://raw.githubusercontent.com/aistrate/Okasaki/cc1473c81d053483bb5e327409346da7fda10fb4/MyCode/Ch05/PairingHeap.hs
haskell
# LANGUAGE FlexibleInstances , MultiParamTypeClasses # module PairingHeap (module Heap, PairingHeap(..)) where import Heap data PairingHeap a = E | T a [PairingHeap a] deriving (Eq, Show) mergePairs [] = E mergePairs [h] = h mergePairs (h1 : h2 : hs) = merge (merge h1 h2) (mergePairs hs) instance Ord a => Heap PairingHeap a where empty = E isEmpty E = True isEmpty _ = False insert x h = merge (T x []) h merge h E = h merge E h = h merge h1@(T x hs1) h2@(T y hs2) = if x < y then T x (h2:hs1) else T y (h1:hs2) findMin E = error "PairingHeap.findMin: empty heap" findMin (T x hs) = x deleteMin E = error "PairingHeap.deleteMin: empty heap" deleteMin (T x hs) = mergePairs hs
1a2a8a115008005c2cf268c1b0a5b3e715d79a1a2ef54319f1f2a90ba4cb2093
magnusjonsson/tidder-icfpc-2008
evector.scm
(module evector mzscheme (require "extensible-vector.scm") (provide (all-from "extensible-vector.scm")))
null
https://raw.githubusercontent.com/magnusjonsson/tidder-icfpc-2008/84d68fd9ac358c38e7eff99117d9cdfa86c1864a/libraries/scheme/evector/evector.scm
scheme
(module evector mzscheme (require "extensible-vector.scm") (provide (all-from "extensible-vector.scm")))
45aae30c4c8d1710ab85dbd5c8fd723da05ea89c558240fba6e6e748c81cbe06
anurudhp/CPHaskell
d.hs
import Control.Arrow ((>>>)) import Data.Bool (bool) main :: IO () main = interact $ lines >>> drop 1 >>> map (words >>> map read) >>> process >>> map (bool "NO" "YES") >>> unlines process :: [[Int]] -> [Bool] process [] = [] process (_:xs:xss) = solve xs : process xss solve :: [Int] -> Bool solve xs = minimum pre >= 0 && minimum suf >= 0 where gaps = zipWith (-) (tail xs) xs decs = map (min 0) gaps pre = scanl (+) (head xs) decs suf = zipWith (-) xs pre
null
https://raw.githubusercontent.com/anurudhp/CPHaskell/01ae8dde6aab4f6ddfebd122ded0b42779dd16f1/contests/codeforces/1443/d.hs
haskell
import Control.Arrow ((>>>)) import Data.Bool (bool) main :: IO () main = interact $ lines >>> drop 1 >>> map (words >>> map read) >>> process >>> map (bool "NO" "YES") >>> unlines process :: [[Int]] -> [Bool] process [] = [] process (_:xs:xss) = solve xs : process xss solve :: [Int] -> Bool solve xs = minimum pre >= 0 && minimum suf >= 0 where gaps = zipWith (-) (tail xs) xs decs = map (min 0) gaps pre = scanl (+) (head xs) decs suf = zipWith (-) xs pre
193859eff392b504ce3b1e28c0f13bf2e55224eeac4dbbbe41e10a03cdc81ebb
bloomberg/blpapi-hs
Service.hs
| Module : Finance . Blpapi . Service Description : Schema Types for request / response and subscriptions Copyright : Bloomberg Finance L.P. License : MIT Maintainer : Stability : experimental Portability : * nix , windows All API data is associated with a ' Service ' . A service object is obtained from a Session and contains zero or more ' Operations ' . A service can be a provider service ( can generate API data ) or a consumer service . Module : Finance.Blpapi.Service Description : Schema Types for request/response and subscriptions Copyright : Bloomberg Finance L.P. License : MIT Maintainer : Stability : experimental Portability : *nix, windows All API data is associated with a 'Service'. A service object is obtained from a Session and contains zero or more 'Operations'. A service can be a provider service (can generate API data) or a consumer service. -} module Finance.Blpapi.Service where import qualified Finance.Blpapi.Types as T -- | This data type defines a service which provides access to API data. -- -- A 'Service' is obtained from a 'Session' and contains the 'Operation's -- (each of which contains its own 'SchemaDefinition') and the -- 'SchemaDefinition' for Events which this 'Service' may produce. -- -- All API data is associated with a service. Before accessing API data -- using either request-reply or subscription, the appropriate 'Service' -- must be 'opened' and, if necessary, authorized. -- Once a Service has been successfully opened in a Session it remains -- accessible until the Session is terminated. data Service = Service { -- | The service name serviceName :: !String, -- | The service description serviceDescription :: !String, -- | The service name used to authorize this service serviceAuthorizationServiceName :: !String, -- | The list of supported operations serviceOperations :: ![Operation], -- | The schema which defines the 'Event's which will be -- delivered when subscription is successful serviceEventDefinitions :: ![SchemaDefinition] } deriving (Show, Eq, Ord) -- | This data type represents an operation that can be performed on -- a service data Operation = Operation { -- | The name of the operation operationName :: !String, -- | The description of the operation operationDescription :: !String, -- | The schema which determines the request structure operationRequestSchema :: !SchemaDefinition, -- | The schema for this list of responses that are tied to -- this operation operationResponseSchema :: ![SchemaDefinition] } deriving (Show, Eq, Ord) -- | This data type represents the definition of an individual field within a -- schema type. An element is defined by an identifier/name, a type, and the -- number of values of that type that may be associated with the -- identifier/name. In addition, this class offers access to meta data -- providing a description and deprecation status for the field. -- -- An optional element has 'schemaDefMinValues == 0'. -- -- A mandatory element has 'schemaDefMinValues >= 1'. -- -- An element that must contain a single value has ' schemaDefMinValues = = schemaDefMaxValues = = 1 ' . -- An element containing an array has ' schemaDefMaxValues > 1 ' . data SchemaDefinition = SchemaDefinition { -- | The nsame of schema definition schemaDefName :: !String, -- | The description schemaDefDescription :: !String, -- | The schema status schemaDefStatus :: !SchemaStatus, -- | The list of alternate names schemaDefAlternateNames :: ![String], -- | The minimun values of occurences of this Element schemaDefMinValues :: !Int, -- | The maximum values of occurences of this Element schemaDefMaxValues :: !Int, -- | The definition of the type schemaDefTypeDefinition :: !SchemaTypeDefinition } deriving (Show, Eq, Ord) -- This data type in addition to the type's structure also provides the -- metadata containing a description and deprecation status data SchemaTypeDefinition = SchemaTypeDefinition { schemaTypeName :: String, scehmaTypeDescription :: String, schemaTypeStatus :: SchemaStatus, schemaTypeDefinition :: TypeDefinition } deriving (Show, Eq, Ord) -- | Enumeration of the possible deprection statuses of the schema element -- or type data SchemaStatus -- | This item is current and may appear in Messages = SchemaActive -- | This item is current and may appear in Messages but will be removed -- in due course | SchemaDeprecated -- | This item is not current and will not appear in Messages | SchemaInactive -- | This item is expected to be deprecated in the future; clients are -- advised to migrate away from use of this item. | SchemaPendingDeprecation deriving (Show, Eq, Enum, Ord) -- |Represents the value of a schema enumeration constant. data Constant = | The symbolic name of the constantName :: !String, | The description of the constantDescripton :: !String, -- | The status of the schema constantStatus :: !SchemaStatus, | The underlying value of the constantValue :: !T.Value } deriving (Show, Eq, Ord) -- | Represents a list schema enumeration constant data ConstantList = ConstantList { -- | The 'ConstantList' name constantListName :: !String, -- | The description constantListDescription :: !String, -- | The status defined by the schema constantListStatus :: !SchemaStatus, | The list of constantListValues :: ![Constant] } deriving (Show, Eq, Ord) -- | This data type is a representation of a "type" that can be used -- within a schema, including both simple atomic types (integers, dates, -- strings, etc.) as well as "complex" types defined a sequences of or -- choice among a collection (named) elements, each of which is in turn -- described by another type. data TypeDefinition = TypeDefinitionSequence { sequenceDefinition :: [SchemaDefinition] } | TypeDefinitionChoice { choiceDefinition :: [SchemaDefinition] } | TypeDefinitionBool | TypeDefinitionChar | TypeDefinitionByte | TypeDefinitionInt32 | TypeDefinitionInt64 | TypeDefinitionFloat32 | TypeDefinitionFloat64 | TypeDefinitionString | TypeDefinitionByteArray | TypeDefinitionDate | TypeDefinitionTime | TypeDefinitionDateTime | TypeDefinitionEnum { constantList :: ConstantList } deriving (Show, Eq, Ord)
null
https://raw.githubusercontent.com/bloomberg/blpapi-hs/a4bdff86f3febcf8b06cbc70466c8abc177b973a/src/Finance/Blpapi/Service.hs
haskell
| This data type defines a service which provides access to API data. A 'Service' is obtained from a 'Session' and contains the 'Operation's (each of which contains its own 'SchemaDefinition') and the 'SchemaDefinition' for Events which this 'Service' may produce. All API data is associated with a service. Before accessing API data using either request-reply or subscription, the appropriate 'Service' must be 'opened' and, if necessary, authorized. accessible until the Session is terminated. | The service name | The service description | The service name used to authorize this service | The list of supported operations | The schema which defines the 'Event's which will be delivered when subscription is successful | This data type represents an operation that can be performed on a service | The name of the operation | The description of the operation | The schema which determines the request structure | The schema for this list of responses that are tied to this operation | This data type represents the definition of an individual field within a schema type. An element is defined by an identifier/name, a type, and the number of values of that type that may be associated with the identifier/name. In addition, this class offers access to meta data providing a description and deprecation status for the field. An optional element has 'schemaDefMinValues == 0'. A mandatory element has 'schemaDefMinValues >= 1'. An element that must contain a single value has | The nsame of schema definition | The description | The schema status | The list of alternate names | The minimun values of occurences of this Element | The maximum values of occurences of this Element | The definition of the type This data type in addition to the type's structure also provides the metadata containing a description and deprecation status | Enumeration of the possible deprection statuses of the schema element or type | This item is current and may appear in Messages | This item is current and may appear in Messages but will be removed in due course | This item is not current and will not appear in Messages | This item is expected to be deprecated in the future; clients are advised to migrate away from use of this item. |Represents the value of a schema enumeration constant. | The status of the schema | Represents a list schema enumeration constant | The 'ConstantList' name | The description | The status defined by the schema | This data type is a representation of a "type" that can be used within a schema, including both simple atomic types (integers, dates, strings, etc.) as well as "complex" types defined a sequences of or choice among a collection (named) elements, each of which is in turn described by another type.
| Module : Finance . Blpapi . Service Description : Schema Types for request / response and subscriptions Copyright : Bloomberg Finance L.P. License : MIT Maintainer : Stability : experimental Portability : * nix , windows All API data is associated with a ' Service ' . A service object is obtained from a Session and contains zero or more ' Operations ' . A service can be a provider service ( can generate API data ) or a consumer service . Module : Finance.Blpapi.Service Description : Schema Types for request/response and subscriptions Copyright : Bloomberg Finance L.P. License : MIT Maintainer : Stability : experimental Portability : *nix, windows All API data is associated with a 'Service'. A service object is obtained from a Session and contains zero or more 'Operations'. A service can be a provider service (can generate API data) or a consumer service. -} module Finance.Blpapi.Service where import qualified Finance.Blpapi.Types as T Once a Service has been successfully opened in a Session it remains data Service = serviceName :: !String, serviceDescription :: !String, serviceAuthorizationServiceName :: !String, serviceOperations :: ![Operation], serviceEventDefinitions :: ![SchemaDefinition] } deriving (Show, Eq, Ord) data Operation = operationName :: !String, operationDescription :: !String, operationRequestSchema :: !SchemaDefinition, operationResponseSchema :: ![SchemaDefinition] } deriving (Show, Eq, Ord) ' schemaDefMinValues = = schemaDefMaxValues = = 1 ' . An element containing an array has ' schemaDefMaxValues > 1 ' . data SchemaDefinition = schemaDefName :: !String, schemaDefDescription :: !String, schemaDefStatus :: !SchemaStatus, schemaDefAlternateNames :: ![String], schemaDefMinValues :: !Int, schemaDefMaxValues :: !Int, schemaDefTypeDefinition :: !SchemaTypeDefinition } deriving (Show, Eq, Ord) data SchemaTypeDefinition = SchemaTypeDefinition { schemaTypeName :: String, scehmaTypeDescription :: String, schemaTypeStatus :: SchemaStatus, schemaTypeDefinition :: TypeDefinition } deriving (Show, Eq, Ord) data SchemaStatus = SchemaActive | SchemaDeprecated | SchemaInactive | SchemaPendingDeprecation deriving (Show, Eq, Enum, Ord) data Constant = | The symbolic name of the constantName :: !String, | The description of the constantDescripton :: !String, constantStatus :: !SchemaStatus, | The underlying value of the constantValue :: !T.Value } deriving (Show, Eq, Ord) data ConstantList = constantListName :: !String, constantListDescription :: !String, constantListStatus :: !SchemaStatus, | The list of constantListValues :: ![Constant] } deriving (Show, Eq, Ord) data TypeDefinition = TypeDefinitionSequence { sequenceDefinition :: [SchemaDefinition] } | TypeDefinitionChoice { choiceDefinition :: [SchemaDefinition] } | TypeDefinitionBool | TypeDefinitionChar | TypeDefinitionByte | TypeDefinitionInt32 | TypeDefinitionInt64 | TypeDefinitionFloat32 | TypeDefinitionFloat64 | TypeDefinitionString | TypeDefinitionByteArray | TypeDefinitionDate | TypeDefinitionTime | TypeDefinitionDateTime | TypeDefinitionEnum { constantList :: ConstantList } deriving (Show, Eq, Ord)
92c4ba6ba9df2785124119ce9cc83409f3858dad2b4893f8672c00365fc490a5
mejgun/haskell-tdlib
BankCardActionOpenUrl.hs
{-# LANGUAGE OverloadedStrings #-} -- | module TD.Data.BankCardActionOpenUrl where import qualified Data.Aeson as A import qualified Data.Aeson.Types as T import qualified Utils as U -- | | Describes an action associated with a bank card number @text Action text @url The URL to be opened BankCardActionOpenUrl { -- | url :: Maybe String, -- | text :: Maybe String } deriving (Eq) instance Show BankCardActionOpenUrl where show BankCardActionOpenUrl { url = url_, text = text_ } = "BankCardActionOpenUrl" ++ U.cc [ U.p "url" url_, U.p "text" text_ ] instance T.FromJSON BankCardActionOpenUrl where parseJSON v@(T.Object obj) = do t <- obj A..: "@type" :: T.Parser String case t of "bankCardActionOpenUrl" -> parseBankCardActionOpenUrl v _ -> mempty where parseBankCardActionOpenUrl :: A.Value -> T.Parser BankCardActionOpenUrl parseBankCardActionOpenUrl = A.withObject "BankCardActionOpenUrl" $ \o -> do url_ <- o A..:? "url" text_ <- o A..:? "text" return $ BankCardActionOpenUrl {url = url_, text = text_} parseJSON _ = mempty instance T.ToJSON BankCardActionOpenUrl where toJSON BankCardActionOpenUrl { url = url_, text = text_ } = A.object [ "@type" A..= T.String "bankCardActionOpenUrl", "url" A..= url_, "text" A..= text_ ]
null
https://raw.githubusercontent.com/mejgun/haskell-tdlib/beb6635177d7626b70fd909b1d89f2156a992cd2/src/TD/Data/BankCardActionOpenUrl.hs
haskell
# LANGUAGE OverloadedStrings # | | | |
module TD.Data.BankCardActionOpenUrl where import qualified Data.Aeson as A import qualified Data.Aeson.Types as T import qualified Utils as U | Describes an action associated with a bank card number @text Action text @url The URL to be opened BankCardActionOpenUrl url :: Maybe String, text :: Maybe String } deriving (Eq) instance Show BankCardActionOpenUrl where show BankCardActionOpenUrl { url = url_, text = text_ } = "BankCardActionOpenUrl" ++ U.cc [ U.p "url" url_, U.p "text" text_ ] instance T.FromJSON BankCardActionOpenUrl where parseJSON v@(T.Object obj) = do t <- obj A..: "@type" :: T.Parser String case t of "bankCardActionOpenUrl" -> parseBankCardActionOpenUrl v _ -> mempty where parseBankCardActionOpenUrl :: A.Value -> T.Parser BankCardActionOpenUrl parseBankCardActionOpenUrl = A.withObject "BankCardActionOpenUrl" $ \o -> do url_ <- o A..:? "url" text_ <- o A..:? "text" return $ BankCardActionOpenUrl {url = url_, text = text_} parseJSON _ = mempty instance T.ToJSON BankCardActionOpenUrl where toJSON BankCardActionOpenUrl { url = url_, text = text_ } = A.object [ "@type" A..= T.String "bankCardActionOpenUrl", "url" A..= url_, "text" A..= text_ ]
4e720b5eea85e48b13cfeea50946cd5e83dfb99a794156530421f5fb9c515c33
emilaxelsson/syntactic
Tuple.hs
# LANGUAGE TemplateHaskell # # LANGUAGE UndecidableInstances # -- | 'Syntactic' instances for tuples module Language.Syntactic.Sugar.Tuple where import Language.Syntactic import Language.Syntactic.Functional.Tuple import Language.Syntactic.Functional.Tuple.TH instance ( Syntactic a , Syntactic b , Tuple :<: Domain a , Domain a ~ Domain b ) => Syntactic (a,b) where type Domain (a,b) = Domain a type Internal (a,b) = (Internal a, Internal b) desugar (a,b) = inj Pair :$ desugar a :$ desugar b sugar ab = (sugar $ inj Fst :$ ab, sugar $ inj Snd :$ ab) -- `desugar` and `sugar` can be seen as applying the eta-rule for pairs. -- <-cafe/2016-April/123639.html> deriveSyntacticForTuples (const []) id [] 15
null
https://raw.githubusercontent.com/emilaxelsson/syntactic/c51258ed96d4e9704e5842ce15667e7d3e5b77d7/src/Language/Syntactic/Sugar/Tuple.hs
haskell
| 'Syntactic' instances for tuples `desugar` and `sugar` can be seen as applying the eta-rule for pairs. <-cafe/2016-April/123639.html>
# LANGUAGE TemplateHaskell # # LANGUAGE UndecidableInstances # module Language.Syntactic.Sugar.Tuple where import Language.Syntactic import Language.Syntactic.Functional.Tuple import Language.Syntactic.Functional.Tuple.TH instance ( Syntactic a , Syntactic b , Tuple :<: Domain a , Domain a ~ Domain b ) => Syntactic (a,b) where type Domain (a,b) = Domain a type Internal (a,b) = (Internal a, Internal b) desugar (a,b) = inj Pair :$ desugar a :$ desugar b sugar ab = (sugar $ inj Fst :$ ab, sugar $ inj Snd :$ ab) deriveSyntacticForTuples (const []) id [] 15
aced3b3ce5c057081e060b4feaceac9f0f95ec0136e9bcb862f342f90bb02e42
huangz1990/SICP-answers
28-expmod.scm
28-expmod.scm (load "28-nontrivial-square-root.scm") (define (expmod base exp m) (cond ((= exp 0) 1) ((nontrivial-square-root? base m) ; 新增 0) ; ((even? exp) (remainder (square (expmod base (/ exp 2) m)) m)) (else (remainder (* base (expmod base (- exp 1) m)) m))))
null
https://raw.githubusercontent.com/huangz1990/SICP-answers/15e3475003ef10eb738cf93c1932277bc56bacbe/chp1/code/28-expmod.scm
scheme
新增
28-expmod.scm (load "28-nontrivial-square-root.scm") (define (expmod base exp m) (cond ((= exp 0) 1) ((even? exp) (remainder (square (expmod base (/ exp 2) m)) m)) (else (remainder (* base (expmod base (- exp 1) m)) m))))
d8469bd003d385015407dc99845f118e4191478567ff535d38a802b08e350de6
kizzx2/haskell-qrcode
QRCode.hs
-- | -- Module : Codec.Binary.QRCode -- License : BSD3 -- -- Maintainer : -- Stability : Experimental -- Portability : Portable -- An evolving QR Code encoder ( and future decoder ) in pure Haskell . -- Currently supports encoding ' Numeric ' , ' Alphanumeric ' , and ' EightBit ' data . -- -- Example -- -- > encode (fromJust $ version 1) M Alphanumeric "hello world" module Codec.Binary.QRCode ( -- * Operations encode , toArray , width -- * Data Constructors , version -- * Data Types , Matrix , Module(..) , Mode(Numeric, Alphanumeric, EightBit) , ErrorLevel(..) , Version ) where import Codec.Binary.QRCode.Utils import Codec.Binary.QRCode.Spec import Codec.Binary.QRCode.Placement import Codec.Binary.QRCode.Masks import Codec.Binary.QRCode.Blocks import Codec.Binary.QRCode.Matrix import qualified Codec.Binary.QRCode.Modes.Numeric as N import qualified Codec.Binary.QRCode.Modes.Alphanumeric as A import qualified Codec.Binary.QRCode.Modes.EightBit as E import qualified Codec.Binary.QRCode.FormatInfo as F import qualified Codec.Binary.QRCode.VersionInfo as V import Control.Monad.Reader -- | Returns 'Nothing' if the input is invalid for the 'Mode' specified. encode :: Version -> ErrorLevel -> Mode -> String -> Maybe Matrix encode ver ecl mode input = inputEncode ver input >>= return . encode' ver ecl where inputEncode = case mode of Numeric -> N.encode Alphanumeric -> A.encode EightBit -> E.encode Kanji -> undefined encode' :: Version -> ErrorLevel -> BitStream -> Matrix encode' ver ecl encodedInput = final' where bitstream = interleave ver ecl encodedInput modules = toModules bitstream (matrix,maskRef) = runReader (mask modules) ver format = F.encode ecl maskRef ver' = V.encode ver final = qrmApplyFormatInfo ver matrix format final' = qrmApplyVersionInfo ver final ver' -- | The number of modules per side. width :: Matrix -> Int width = qrmWidth | Valid version number is /[1 , 40]/ version :: Int -> Maybe Version version n | n >= 1 && n <= 40 = Just (Version n) | otherwise = Nothing
null
https://raw.githubusercontent.com/kizzx2/haskell-qrcode/be06628d4cb77381c55a788c11c1695ebe432c28/Codec/Binary/QRCode.hs
haskell
| Module : Codec.Binary.QRCode License : BSD3 Maintainer : Stability : Experimental Portability : Portable Example > encode (fromJust $ version 1) M Alphanumeric "hello world" * Operations * Data Constructors * Data Types | Returns 'Nothing' if the input is invalid for the 'Mode' specified. | The number of modules per side.
An evolving QR Code encoder ( and future decoder ) in pure Haskell . Currently supports encoding ' Numeric ' , ' Alphanumeric ' , and ' EightBit ' data . module Codec.Binary.QRCode ( encode , toArray , width , version , Matrix , Module(..) , Mode(Numeric, Alphanumeric, EightBit) , ErrorLevel(..) , Version ) where import Codec.Binary.QRCode.Utils import Codec.Binary.QRCode.Spec import Codec.Binary.QRCode.Placement import Codec.Binary.QRCode.Masks import Codec.Binary.QRCode.Blocks import Codec.Binary.QRCode.Matrix import qualified Codec.Binary.QRCode.Modes.Numeric as N import qualified Codec.Binary.QRCode.Modes.Alphanumeric as A import qualified Codec.Binary.QRCode.Modes.EightBit as E import qualified Codec.Binary.QRCode.FormatInfo as F import qualified Codec.Binary.QRCode.VersionInfo as V import Control.Monad.Reader encode :: Version -> ErrorLevel -> Mode -> String -> Maybe Matrix encode ver ecl mode input = inputEncode ver input >>= return . encode' ver ecl where inputEncode = case mode of Numeric -> N.encode Alphanumeric -> A.encode EightBit -> E.encode Kanji -> undefined encode' :: Version -> ErrorLevel -> BitStream -> Matrix encode' ver ecl encodedInput = final' where bitstream = interleave ver ecl encodedInput modules = toModules bitstream (matrix,maskRef) = runReader (mask modules) ver format = F.encode ecl maskRef ver' = V.encode ver final = qrmApplyFormatInfo ver matrix format final' = qrmApplyVersionInfo ver final ver' width :: Matrix -> Int width = qrmWidth | Valid version number is /[1 , 40]/ version :: Int -> Maybe Version version n | n >= 1 && n <= 40 = Just (Version n) | otherwise = Nothing
bcb774f6ce8eafe8caaf948a2c2950d2c9f328a4b07205674ee8ddb413a19110
lilactown/punk
web.cljs
(ns punk.adapter.web (:require [goog.object :as gobj] [punk.core :as punk] [frame.core :as f] [cljs.tools.reader.edn :as edn] [cljs.tagged-literals] [clojure.core.async :as a])) (defonce in-chan (a/chan)) (defonce out-chan (a/chan)) ;; Handles incoming events from the UI and passes them to the user-space frame (defonce event-loop (a/go-loop [] (let [ev (a/<! out-chan)] (punk/dispatch (edn/read-string {:readers {;; 'js (with-meta identity {:punk/literal-tag 'js}) 'inst cljs.tagged-literals/read-inst 'uuid cljs.tagged-literals/read-uuid 'queue cljs.tagged-literals/read-queue} :default tagged-literal} ev)) (recur)))) (defonce subscribers (atom #{})) (defonce subscriber-loop (a/go-loop [] (let [ev (a/<! in-chan)] (doseq [sub-handler @subscribers] (sub-handler ev)) (recur)))) (f/reg-fx punk/frame :emit (fn [v] (a/put! in-chan (pr-str v)))) (def in-stream #js {:subscribe #(swap! subscribers conj %) :unsubscribe #(swap! subscribers disj %)}) (def out-stream #js {:put (fn [v] (a/put! out-chan v))}) (defn start-ui! [opts] (let [start! (gobj/getValueByKeys js/window "punk" "ui" "core" "start_BANG_") container (. js/document getElementById "punk")] (punk/remove-taps!) (punk/add-taps!) (start! container in-stream out-stream (pr-str opts)))) ;; ;; ---- Defaults ---- ;; (def default-script "@v0.0.7/ui/dist/js/main.js" ;; ":8701/main.js" ) (def default-css ["+Sans+Pro" "@v0.0.7/ui/dist/css/grid-layout.css" "@v0.0.7/ui/dist/css/resizable.css" "@v0.0.7/ui/dist/css/punk.css"]) (defn ^{:export true} start ([] (start nil)) ([opts] (let [default-opts {:ui/script default-script :ui/css default-css} opts-with-defaults (merge default-opts opts) {:keys [ui/script ui/css]} opts-with-defaults] (if (. js/document getElementById "punk") (start-ui! opts-with-defaults) first time running (let [new-container (. js/document createElement "div") script-tag (. js/document createElement "script")] ;; script tag (. script-tag setAttribute "src" script) (set! (.-onload ^js script-tag) (fn [] (start-ui! opts-with-defaults))) (-> js/document .-body (.appendChild script-tag)) ;; css (doseq [sheet css] (let [link-tag (. js/document createElement "link")] (. link-tag setAttribute "rel" "stylesheet") (. link-tag setAttribute "type" "text/css") (. link-tag setAttribute "href" sheet) (-> js/document .-body (.appendChild link-tag)))) ;; container (. new-container setAttribute "id" "punk") (-> js/document .-body (.appendChild new-container)) new-container)))))
null
https://raw.githubusercontent.com/lilactown/punk/0c6e529429837c00958d41e09fd672f49778dedf/adapter-web/src/punk/adapter/web.cljs
clojure
Handles incoming events from the UI and passes them to the user-space frame 'js (with-meta identity {:punk/literal-tag 'js}) ---- Defaults ---- ":8701/main.js" script tag css container
(ns punk.adapter.web (:require [goog.object :as gobj] [punk.core :as punk] [frame.core :as f] [cljs.tools.reader.edn :as edn] [cljs.tagged-literals] [clojure.core.async :as a])) (defonce in-chan (a/chan)) (defonce out-chan (a/chan)) (defonce event-loop (a/go-loop [] (let [ev (a/<! out-chan)] (punk/dispatch (edn/read-string 'inst cljs.tagged-literals/read-inst 'uuid cljs.tagged-literals/read-uuid 'queue cljs.tagged-literals/read-queue} :default tagged-literal} ev)) (recur)))) (defonce subscribers (atom #{})) (defonce subscriber-loop (a/go-loop [] (let [ev (a/<! in-chan)] (doseq [sub-handler @subscribers] (sub-handler ev)) (recur)))) (f/reg-fx punk/frame :emit (fn [v] (a/put! in-chan (pr-str v)))) (def in-stream #js {:subscribe #(swap! subscribers conj %) :unsubscribe #(swap! subscribers disj %)}) (def out-stream #js {:put (fn [v] (a/put! out-chan v))}) (defn start-ui! [opts] (let [start! (gobj/getValueByKeys js/window "punk" "ui" "core" "start_BANG_") container (. js/document getElementById "punk")] (punk/remove-taps!) (punk/add-taps!) (start! container in-stream out-stream (pr-str opts)))) (def default-script "@v0.0.7/ui/dist/js/main.js" ) (def default-css ["+Sans+Pro" "@v0.0.7/ui/dist/css/grid-layout.css" "@v0.0.7/ui/dist/css/resizable.css" "@v0.0.7/ui/dist/css/punk.css"]) (defn ^{:export true} start ([] (start nil)) ([opts] (let [default-opts {:ui/script default-script :ui/css default-css} opts-with-defaults (merge default-opts opts) {:keys [ui/script ui/css]} opts-with-defaults] (if (. js/document getElementById "punk") (start-ui! opts-with-defaults) first time running (let [new-container (. js/document createElement "div") script-tag (. js/document createElement "script")] (. script-tag setAttribute "src" script) (set! (.-onload ^js script-tag) (fn [] (start-ui! opts-with-defaults))) (-> js/document .-body (.appendChild script-tag)) (doseq [sheet css] (let [link-tag (. js/document createElement "link")] (. link-tag setAttribute "rel" "stylesheet") (. link-tag setAttribute "type" "text/css") (. link-tag setAttribute "href" sheet) (-> js/document .-body (.appendChild link-tag)))) (. new-container setAttribute "id" "punk") (-> js/document .-body (.appendChild new-container)) new-container)))))
59e5c4aa2f1bd482adb377811a17da87c2cafb28f0f24e21f8d07f598dd57566
snmsts/cl-langserver
clasp.lisp
;;;; -*- indent-tabs-mode: nil -*- ;;; slynk-clasp.lisp --- SLIME backend for CLASP . ;;; ;;; This code has been placed in the Public Domain. All warranties ;;; are disclaimed. ;;; Administrivia (defpackage :ls-clasp (:use cl ls-backend)) (in-package ls-clasp) (defmacro cslime-log (fmt &rest fmt-args) `(format t ,fmt ,@fmt-args)) ;; Hard dependencies. (eval-when (:compile-toplevel :load-toplevel :execute) (require 'sockets)) ;; Soft dependencies. (eval-when (:compile-toplevel :load-toplevel :execute) (when (probe-file "sys:profile.fas") (require :profile) (pushnew :profile *features*)) (when (probe-file "sys:serve-event") (require :serve-event) (pushnew :serve-event *features*))) (declaim (optimize (debug 3))) ;;; Slynk-mop (eval-when (:compile-toplevel :load-toplevel :execute) (import-ls-mop-symbols :clos `(:eql-specializer :eql-specializer-object :generic-function-declarations :specializer-direct-methods ,@(unless (fboundp 'clos:compute-applicable-methods-using-classes) '(:compute-applicable-methods-using-classes))))) (defimplementation gray-package-name () "GRAY") ;;;; TCP Server (defimplementation preferred-communication-style () CLASP does not provide threads yet . ECLs slynk implementation says that CLOS is not thread safe and ;; I use ECLs CLOS implementation - this is a worry for the future. nil ) (defun resolve-hostname (name) (car (sb-bsd-sockets:host-ent-addresses (sb-bsd-sockets:get-host-by-name name)))) (defimplementation create-socket (host port &key backlog) (let ((socket (make-instance 'sb-bsd-sockets:inet-socket :type :stream :protocol :tcp))) (setf (sb-bsd-sockets:sockopt-reuse-address socket) t) (sb-bsd-sockets:socket-bind socket (resolve-hostname host) port) (sb-bsd-sockets:socket-listen socket (or backlog 5)) socket)) (defimplementation local-port (socket) (nth-value 1 (sb-bsd-sockets:socket-name socket))) (defimplementation close-socket (socket) (sb-bsd-sockets:socket-close socket)) (defimplementation accept-connection (socket &key external-format buffering timeout) (declare (ignore timeout)) (sb-bsd-sockets:socket-make-stream (accept socket) :output t :input t :buffering (ecase buffering ((t) :full) ((nil) :none) (:line :line)) :element-type (if external-format 'character '(unsigned-byte 8)) :external-format external-format)) (defun accept (socket) "Like socket-accept, but retry on EAGAIN." (loop (handler-case (return (sb-bsd-sockets:socket-accept socket)) (sb-bsd-sockets:interrupted-error ())))) (defimplementation socket-fd (socket) (etypecase socket (fixnum socket) (two-way-stream (socket-fd (two-way-stream-input-stream socket))) (sb-bsd-sockets:socket (sb-bsd-sockets:socket-file-descriptor socket)) (file-stream (si:file-stream-fd socket)))) (defvar *external-format-to-coding-system* '((:latin-1 "latin-1" "latin-1-unix" "iso-latin-1-unix" "iso-8859-1" "iso-8859-1-unix") (:utf-8 "utf-8" "utf-8-unix"))) (defun external-format (coding-system) (or (car (rassoc-if (lambda (x) (member coding-system x :test #'equal)) *external-format-to-coding-system*)) (find coding-system (ext:all-encodings) :test #'string-equal))) (defimplementation find-external-format (coding-system) #+unicode (external-format coding-system) Without unicode support , CLASP uses the one - byte encoding of the underlying OS , and will barf on anything except : . We return NIL here for known encodings , so ;; SLYNK:CREATE-SERVER will barf. #-unicode (let ((xf (external-format coding-system))) (if (member xf '(:utf-8)) nil :default))) ;;;; Unix Integration If CLASP is built with thread support , it 'll spawn a helper thread ;;; executing the SIGINT handler. We do not want to BREAK into that ;;; helper but into the main thread, though. This is coupled with the current choice of NIL as communication - style in so far as CLASP 's main - thread is also the Slime 's REPL thread . #+clasp-working (defimplementation call-with-user-break-handler (real-handler function) (let ((old-handler #'si:terminal-interrupt)) (setf (symbol-function 'si:terminal-interrupt) (make-interrupt-handler real-handler)) (unwind-protect (funcall function) (setf (symbol-function 'si:terminal-interrupt) old-handler)))) #+threads (defun make-interrupt-handler (real-handler) (let ((main-thread (find 'si:top-level (mp:all-processes) :key #'mp:process-name))) #'(lambda (&rest args) (declare (ignore args)) (mp:interrupt-process main-thread real-handler)))) #-threads (defun make-interrupt-handler (real-handler) #'(lambda (&rest args) (declare (ignore args)) (funcall real-handler))) (defimplementation getpid () (si:getpid)) (defimplementation set-default-directory (directory) adapts * DEFAULT - PATHNAME - DEFAULTS * . (default-directory)) (defimplementation default-directory () (namestring (ext:getcwd))) (defimplementation quit-lisp () (core:quit)) Instead of busy waiting with communication - style NIL , use select ( ) ;;; on the sockets' streams. #+serve-event (progn (defun poll-streams (streams timeout) (let* ((serve-event::*descriptor-handlers* (copy-list serve-event::*descriptor-handlers*)) (active-fds '()) (fd-stream-alist (loop for s in streams for fd = (socket-fd s) collect (cons fd s) do (serve-event:add-fd-handler fd :input #'(lambda (fd) (push fd active-fds)))))) (serve-event:serve-event timeout) (loop for fd in active-fds collect (cdr (assoc fd fd-stream-alist))))) (defimplementation wait-for-input (streams &optional timeout) (assert (member timeout '(nil t))) (loop (cond ((check-slime-interrupts) (return :interrupt)) (timeout (return (poll-streams streams 0))) (t (when-let (ready (poll-streams streams 0.2)) (return ready)))))) ) ; #+serve-event (progn ... #-serve-event (defimplementation wait-for-input (streams &optional timeout) (assert (member timeout '(nil t))) (loop (cond ((check-slime-interrupts) (return :interrupt)) (timeout (return (remove-if-not #'listen streams))) (t (let ((ready (remove-if-not #'listen streams))) (if ready (return ready)) (sleep 0.1)))))) ;;;; Compilation (defvar *buffer-name* nil) (defvar *buffer-start-position*) (defun signal-compiler-condition (&rest args) (apply #'signal 'compiler-condition args)) #-clasp-bytecmp (defun handle-compiler-message (condition) CLASP emits lots of noise in compiler - notes , like " Invoking ;; external command". (unless (typep condition 'c::compiler-note) (signal-compiler-condition :original-condition condition :message (princ-to-string condition) :severity (etypecase condition (cmp:compiler-fatal-error :error) (cmp:compiler-error :error) (error :error) (style-warning :style-warning) (warning :warning)) :location (condition-location condition)))) #-clasp-bytecmp (defun condition-location (condition) (let ((file (cmp:compiler-message-file condition)) (position (cmp:compiler-message-file-position condition))) (if (and position (not (minusp position))) (if *buffer-name* (make-buffer-location *buffer-name* *buffer-start-position* position) (make-file-location file position)) (make-error-location "No location found.")))) (defimplementation call-with-compilation-hooks (function) (funcall function)) #|| #-clasp-bytecmp (handler-bind ((c:compiler-message #'handle-compiler-message)) (funcall function))) ||# (defimplementation slynk-compile-file (input-file output-file load-p external-format &key policy) (declare (ignore policy)) (format t "Compiling file input-file = ~a output-file = ~a~%" input-file output-file) ;; Ignore the output-file and generate our own (let ((tmp-output-file (compile-file-pathname (si:mkstemp "TMP:clasp-slynk-compile-file-")))) (format t "Using tmp-output-file: ~a~%" tmp-output-file) (multiple-value-bind (fasl warnings-p failure-p) (with-compilation-hooks () (compile-file input-file :output-file tmp-output-file :external-format external-format)) (values fasl warnings-p (or failure-p (when load-p (not (load fasl)))))))) (defvar *tmpfile-map* (make-hash-table :test #'equal)) (defun note-buffer-tmpfile (tmp-file buffer-name) EXT : COMPILED - FUNCTION - FILE below will return a namestring . (let ((tmp-namestring (namestring (truename tmp-file)))) (setf (gethash tmp-namestring *tmpfile-map*) buffer-name) tmp-namestring)) (defun tmpfile-to-buffer (tmp-file) (gethash tmp-file *tmpfile-map*)) (defimplementation slynk-compile-string (string &key buffer position filename policy) (declare (ignore policy)) (with-compilation-hooks () (let ((*buffer-name* buffer) ; for compilation hooks (*buffer-start-position* position)) (let ((tmp-file (si:mkstemp "TMP:clasp-slynk-tmpfile-")) (fasl-file) (warnings-p) (failure-p)) (unwind-protect (with-open-file (tmp-stream tmp-file :direction :output :if-exists :supersede) (write-string string tmp-stream) (finish-output tmp-stream) (multiple-value-setq (fasl-file warnings-p failure-p) (let ((truename (or filename (note-buffer-tmpfile tmp-file buffer)))) (compile-file tmp-file :source-debug-namestring truename :source-debug-offset (1- position))))) (when fasl-file (load fasl-file)) (when (probe-file tmp-file) (delete-file tmp-file)) (when fasl-file (delete-file fasl-file))) (not failure-p))))) ;;;; Documentation (defimplementation arglist (name) (multiple-value-bind (arglist foundp) (core:function-lambda-list name) ;; Uses bc-split (if foundp arglist :not-available))) (defimplementation function-name (f) (typecase f (generic-function (clos::generic-function-name f)) (function (ext:compiled-function-name f)))) FIXME (defimplementation macroexpand-all (form &optional env) (declare (ignore env)) (macroexpand form)) (defimplementation describe-symbol-for-emacs (symbol) (let ((result '())) (flet ((frob (type boundp) (when (funcall boundp symbol) (let ((doc (describe-definition symbol type))) (setf result (list* type doc result)))))) (frob :VARIABLE #'boundp) (frob :FUNCTION #'fboundp) (frob :CLASS (lambda (x) (find-class x nil)))) result)) (defimplementation describe-definition (name type) (case type (:variable (documentation name 'variable)) (:function (documentation name 'function)) (:class (documentation name 'class)) (t nil))) (defimplementation type-specifier-p (symbol) (or (subtypep nil symbol) (not (eq (type-specifier-arglist symbol) :not-available)))) ;;; Debugging (eval-when (:compile-toplevel :load-toplevel :execute) (import '(si::*break-env* si::*ihs-top* si::*ihs-current* si::*ihs-base* #+frs si::*frs-base* #+frs si::*frs-top* si::*tpl-commands* si::*tpl-level* #+frs si::frs-top si::ihs-top si::ihs-fun si::ihs-env #+frs si::sch-frs-base si::set-break-env si::set-current-ihs si::tpl-commands))) (defun make-invoke-debugger-hook (hook) (when hook #'(lambda (condition old-hook) ;; Regard *debugger-hook* if set by user. (if *debugger-hook* nil ; decline, *DEBUGGER-HOOK* will be tried next. (funcall hook condition old-hook))))) (defimplementation install-debugger-globally (function) (setq *debugger-hook* function) (setq ext:*invoke-debugger-hook* (make-invoke-debugger-hook function)) ) (defimplementation call-with-debugger-hook (hook fun) (let ((*debugger-hook* hook) (ext:*invoke-debugger-hook* (make-invoke-debugger-hook hook))) (funcall fun)) ) (defvar *backtrace* '()) ;;; Commented out; it's not clear this is a good way of doing it. In ;;; particular because it makes errors stemming from this file harder to debug , and given the " young " age of CLASP 's slynk backend , that 's ;;; a bad idea. ;; (defun in-slynk-package-p (x) ;; (and ;; (symbolp x) ;; (member (symbol-package x) ( list : slynk ) ;; #.(find-package ls-backend) ;; #.(ignore-errors (find-package :slynk-mop)) ;; #.(ignore-errors (find-package :ls-loader)))) ;; t)) ;; (defun is-slynk-source-p (name) ( setf name ( pathname name ) ) ;; (pathname-match-p ;; name ;; (make-pathname :defaults ls-loader::*source-directory* ;; :name (pathname-name name) ;; :type (pathname-type name) ;; :version (pathname-version name)))) ;; (defun is-ignorable-fun-p (x) ;; (or ;; (in-slynk-package-p (frame-name x)) ;; (multiple-value-bind (file position) ;; (ignore-errors (si::bc-file (car x))) ;; (declare (ignore position)) ;; (if file (is-slynk-source-p file))))) (defimplementation call-with-debugging-environment (debugger-loop-fn) (declare (type function debugger-loop-fn)) (let* ((*ihs-top* (or #+#.(ls-backend:with-symbol '*stack-top-hint* 'core) core:*stack-top-hint* (ihs-top))) (*ihs-current* *ihs-top*) #+frs (*frs-base* (or (sch-frs-base *frs-top* *ihs-base*) (1+ (frs-top)))) #+frs (*frs-top* (frs-top)) (*tpl-level* (1+ *tpl-level*)) (*backtrace* (loop for ihs from 0 below *ihs-top* collect (list (si::ihs-fun ihs) (si::ihs-env ihs) ihs)))) (declare (special *ihs-current*)) #+frs (loop for f from *frs-base* until *frs-top* do (let ((i (- (si::frs-ihs f) *ihs-base* 1))) (when (plusp i) (let* ((x (elt *backtrace* i)) (name (si::frs-tag f))) (unless (si::fixnump name) (push name (third x))))))) (setf *backtrace* (nreverse *backtrace*)) (set-break-env) (set-current-ihs) (let ((*ihs-base* *ihs-top*)) (funcall debugger-loop-fn)))) (defimplementation compute-backtrace (start end) (subseq *backtrace* start (and (numberp end) (min end (length *backtrace*))))) (defun frame-name (frame) (let ((x (first frame))) (if (symbolp x) x (function-name x)))) (defun frame-function (frame-number) (let ((x (first (elt *backtrace* frame-number)))) (etypecase x (symbol (and (fboundp x) (fdefinition x))) (function x)))) (defimplementation print-frame (frame stream) (format stream "(~s~{ ~s~})" (function-name (first frame)) #+#.(ls-backend:with-symbol 'ihs-arguments 'core) (coerce (core:ihs-arguments (third frame)) 'list) #-#.(ls-backend:with-symbol 'ihs-arguments 'core) nil)) (defimplementation frame-source-location (frame-number) (source-location (frame-function frame-number))) #+clasp-working (defimplementation frame-catch-tags (frame-number) (third (elt *backtrace* frame-number))) (defun ihs-frame-id (frame-number) (- (core:ihs-top) frame-number)) (defimplementation frame-locals (frame-number) (let* ((frame (elt *backtrace* frame-number)) (env (second frame)) (locals (loop for x = env then (core:get-parent-environment x) while x nconc (loop for name across (core:environment-debug-names x) for value across (core:environment-debug-values x) collect (list :name name :id 0 :value value))))) (nconc (loop for arg across (core:ihs-arguments (third frame)) for i from 0 collect (list :name (intern (format nil "ARG~d" i) #.*package*) :id 0 :value arg)) locals))) (defimplementation frame-var-value (frame-number var-number) (let* ((frame (elt *backtrace* frame-number)) (env (second frame)) (args (core:ihs-arguments (third frame)))) (if (< var-number (length args)) (svref args var-number) (elt (frame-locals frame-number) var-number)))) #+clasp-working (defimplementation disassemble-frame (frame-number) (let ((fun (frame-function frame-number))) (disassemble fun))) (defimplementation eval-in-frame (form frame-number) (let ((env (second (elt *backtrace* frame-number)))) (core:compile-form-and-eval-with-env form env))) #+clasp-working (defimplementation gdb-initial-commands () These signals are used by the GC . #+linux '("handle SIGPWR noprint nostop" "handle SIGXCPU noprint nostop")) #+clasp-working (defimplementation command-line-args () (loop for n from 0 below (si:argc) collect (si:argv n))) ;;;; Inspector ;;; FIXME: Would be nice if it was possible to inspect objects ;;; implemented in C. ;;;; Definitions (defun make-file-location (file file-position) File positions in CL start at 0 , but Emacs ' buffer positions start at 1 . We specify (: ) because the positions comming from CLASP point at right after the toplevel form appearing before the actual target toplevel form ; (: ) will DTRT in that case . (make-location `(:file ,(namestring (translate-logical-pathname file))) `(:position ,(1+ file-position)) `(:align t))) (defun make-buffer-location (buffer-name start-position &optional (offset 0)) (make-location `(:buffer ,buffer-name) `(:offset ,start-position ,offset) `(:align t))) (defimplementation find-definitions (name) (let ((annotations (core:get-annotation name 'si::location :all))) (cond (annotations (loop for annotation in annotations collect (destructuring-bind (dspec file . pos) annotation `(,dspec ,(make-file-location file pos))))) (t (mapcan #'(lambda (type) (find-definitions-by-type name type)) (classify-definition-name name)))))) (defun classify-definition-name (name) (let ((types '())) (when (fboundp name) (cond ((special-operator-p name) (push :special-operator types)) ((macro-function name) (push :macro types)) ((typep (fdefinition name) 'generic-function) (push :generic-function types)) ((si:mangle-name name t) (push :c-function types)) (t (push :lisp-function types)))) (when (boundp name) (cond ((constantp name) (push :constant types)) (t (push :global-variable types)))) types)) (defun find-definitions-by-type (name type) (ecase type (:lisp-function (when-let (loc (source-location (fdefinition name))) (list `((defun ,name) ,loc)))) (:c-function (when-let (loc (source-location (fdefinition name))) (list `((c-source ,name) ,loc)))) (:generic-function (loop for method in (clos:generic-function-methods (fdefinition name)) for specs = (clos:method-specializers method) for loc = (source-location method) when loc collect `((defmethod ,name ,specs) ,loc))) (:macro (when-let (loc (source-location (macro-function name))) (list `((defmacro ,name) ,loc)))) (:constant (when-let (loc (source-location name)) (list `((defconstant ,name) ,loc)))) (:global-variable (when-let (loc (source-location name)) (list `((defvar ,name) ,loc)))) (:special-operator))) ;;; FIXME: There ought to be a better way. (eval-when (:compile-toplevel :load-toplevel :execute) (defun c-function-name-p (name) (and (symbolp name) (si:mangle-name name t) t)) (defun c-function-p (object) (and (functionp object) (let ((fn-name (function-name object))) (and fn-name (c-function-name-p fn-name)))))) (deftype c-function () `(satisfies c-function-p)) (defun source-location (object) (converting-errors-to-error-location (typecase object (function (multiple-value-bind (file pos) (ext:compiled-function-file object) (cond ((not file) (return-from source-location nil)) ((tmpfile-to-buffer file) (make-buffer-location (tmpfile-to-buffer file) pos)) (t (assert (probe-file file)) (assert (not (minusp pos))) (make-file-location file pos))))) (method FIXME : This will always return NIL at the moment ; CLASP does not ;; store debug information for methods yet. (source-location (clos:method-function object)))))) (defimplementation find-source-location (object) (or (source-location object) (make-error-location "Source definition of ~S not found." object))) ;;;; Profiling #+profile (progn (defimplementation profile (fname) (when fname (eval `(profile:profile ,fname)))) (defimplementation unprofile (fname) (when fname (eval `(profile:unprofile ,fname)))) (defimplementation unprofile-all () (profile:unprofile-all) "All functions unprofiled.") (defimplementation profile-report () (profile:report)) (defimplementation profile-reset () (profile:reset) "Reset profiling counters.") (defimplementation profiled-functions () (profile:profile)) (defimplementation profile-package (package callers methods) (declare (ignore callers methods)) (eval `(profile:profile ,(package-name (find-package package))))) ) ; #+profile (progn ... ;;;; Threads #+threads (progn (defvar *thread-id-counter* 0) (defparameter *thread-id-map* (make-hash-table)) (defvar *thread-id-map-lock* (mp:make-lock :name "thread id map lock")) (defimplementation spawn (fn &key name) (mp:process-run-function name fn)) (defimplementation thread-id (target-thread) (block thread-id (mp:with-lock (*thread-id-map-lock*) Does - THREAD have an i d already ? (maphash (lambda (id thread-pointer) (let ((thread (si:weak-pointer-value thread-pointer))) (cond ((not thread) (remhash id *thread-id-map*)) ((eq thread target-thread) (return-from thread-id id))))) *thread-id-map*) ;; TARGET-THREAD not found in *THREAD-ID-MAP* (let ((id (incf *thread-id-counter*)) (thread-pointer (si:make-weak-pointer target-thread))) (setf (gethash id *thread-id-map*) thread-pointer) id)))) (defimplementation find-thread (id) (mp:with-lock (*thread-id-map-lock*) (let* ((thread-ptr (gethash id *thread-id-map*)) (thread (and thread-ptr (si:weak-pointer-value thread-ptr)))) (unless thread (remhash id *thread-id-map*)) thread))) (defimplementation thread-name (thread) (mp:process-name thread)) (defimplementation thread-status (thread) (if (mp:process-active-p thread) "RUNNING" "STOPPED")) (defimplementation make-lock (&key name) (mp:make-lock :name name :recursive t)) (defimplementation call-with-lock-held (lock function) (declare (type function function)) (mp:with-lock (lock) (funcall function))) (defimplementation current-thread () mp:*current-process*) (defimplementation all-threads () (mp:all-processes)) (defimplementation interrupt-thread (thread fn) (mp:interrupt-process thread fn)) (defimplementation kill-thread (thread) (mp:process-kill thread)) (defimplementation thread-alive-p (thread) (mp:process-active-p thread)) (defvar *mailbox-lock* (mp:make-lock :name "mailbox lock")) (defvar *mailboxes* (list)) (declaim (type list *mailboxes*)) (defstruct (mailbox (:conc-name mailbox.)) thread (mutex (mp:make-lock)) (cvar (mp:make-condition-variable)) (queue '() :type list)) (defun mailbox (thread) "Return THREAD's mailbox." (mp:with-lock (*mailbox-lock*) (or (find thread *mailboxes* :key #'mailbox.thread) (let ((mb (make-mailbox :thread thread))) (push mb *mailboxes*) mb)))) (defimplementation send (thread message) (let* ((mbox (mailbox thread)) (mutex (mailbox.mutex mbox))) (mp:with-lock (mutex) (setf (mailbox.queue mbox) (nconc (mailbox.queue mbox) (list message))) (mp:condition-variable-broadcast (mailbox.cvar mbox))))) (defimplementation receive-if (test &optional timeout) (let* ((mbox (mailbox (current-thread))) (mutex (mailbox.mutex mbox))) (assert (or (not timeout) (eq timeout t))) (loop (check-slime-interrupts) (mp:with-lock (mutex) (let* ((q (mailbox.queue mbox)) (tail (member-if test q))) (when tail (setf (mailbox.queue mbox) (nconc (ldiff q tail) (cdr tail))) (return (car tail)))) (when (eq timeout t) (return (values nil t))) (mp:condition-variable-timedwait (mailbox.cvar mbox) mutex 0.2))))) ) ; #+threads (progn ...
null
https://raw.githubusercontent.com/snmsts/cl-langserver/3b1246a5d0bd58459e7a64708f820bf718cf7175/src/backend/impls/clasp.lisp
lisp
-*- indent-tabs-mode: nil -*- This code has been placed in the Public Domain. All warranties are disclaimed. Hard dependencies. Soft dependencies. Slynk-mop TCP Server I use ECLs CLOS implementation - this is a worry for the future. SLYNK:CREATE-SERVER will barf. Unix Integration executing the SIGINT handler. We do not want to BREAK into that helper but into the main thread, though. This is coupled with the on the sockets' streams. #+serve-event (progn ... Compilation external command". #-clasp-bytecmp (handler-bind ((c:compiler-message #'handle-compiler-message)) (funcall function))) Ignore the output-file and generate our own for compilation hooks Documentation Uses bc-split Debugging Regard *debugger-hook* if set by user. decline, *DEBUGGER-HOOK* will be tried next. Commented out; it's not clear this is a good way of doing it. In particular because it makes errors stemming from this file harder a bad idea. (defun in-slynk-package-p (x) (and (symbolp x) (member (symbol-package x) #.(find-package ls-backend) #.(ignore-errors (find-package :slynk-mop)) #.(ignore-errors (find-package :ls-loader)))) t)) (defun is-slynk-source-p (name) (pathname-match-p name (make-pathname :defaults ls-loader::*source-directory* :name (pathname-name name) :type (pathname-type name) :version (pathname-version name)))) (defun is-ignorable-fun-p (x) (or (in-slynk-package-p (frame-name x)) (multiple-value-bind (file position) (ignore-errors (si::bc-file (car x))) (declare (ignore position)) (if file (is-slynk-source-p file))))) Inspector FIXME: Would be nice if it was possible to inspect objects implemented in C. Definitions (: ) will DTRT in that case . FIXME: There ought to be a better way. CLASP does not store debug information for methods yet. Profiling #+profile (progn ... Threads TARGET-THREAD not found in *THREAD-ID-MAP* #+threads (progn ...
slynk-clasp.lisp --- SLIME backend for CLASP . Administrivia (defpackage :ls-clasp (:use cl ls-backend)) (in-package ls-clasp) (defmacro cslime-log (fmt &rest fmt-args) `(format t ,fmt ,@fmt-args)) (eval-when (:compile-toplevel :load-toplevel :execute) (require 'sockets)) (eval-when (:compile-toplevel :load-toplevel :execute) (when (probe-file "sys:profile.fas") (require :profile) (pushnew :profile *features*)) (when (probe-file "sys:serve-event") (require :serve-event) (pushnew :serve-event *features*))) (declaim (optimize (debug 3))) (eval-when (:compile-toplevel :load-toplevel :execute) (import-ls-mop-symbols :clos `(:eql-specializer :eql-specializer-object :generic-function-declarations :specializer-direct-methods ,@(unless (fboundp 'clos:compute-applicable-methods-using-classes) '(:compute-applicable-methods-using-classes))))) (defimplementation gray-package-name () "GRAY") (defimplementation preferred-communication-style () CLASP does not provide threads yet . ECLs slynk implementation says that CLOS is not thread safe and nil ) (defun resolve-hostname (name) (car (sb-bsd-sockets:host-ent-addresses (sb-bsd-sockets:get-host-by-name name)))) (defimplementation create-socket (host port &key backlog) (let ((socket (make-instance 'sb-bsd-sockets:inet-socket :type :stream :protocol :tcp))) (setf (sb-bsd-sockets:sockopt-reuse-address socket) t) (sb-bsd-sockets:socket-bind socket (resolve-hostname host) port) (sb-bsd-sockets:socket-listen socket (or backlog 5)) socket)) (defimplementation local-port (socket) (nth-value 1 (sb-bsd-sockets:socket-name socket))) (defimplementation close-socket (socket) (sb-bsd-sockets:socket-close socket)) (defimplementation accept-connection (socket &key external-format buffering timeout) (declare (ignore timeout)) (sb-bsd-sockets:socket-make-stream (accept socket) :output t :input t :buffering (ecase buffering ((t) :full) ((nil) :none) (:line :line)) :element-type (if external-format 'character '(unsigned-byte 8)) :external-format external-format)) (defun accept (socket) "Like socket-accept, but retry on EAGAIN." (loop (handler-case (return (sb-bsd-sockets:socket-accept socket)) (sb-bsd-sockets:interrupted-error ())))) (defimplementation socket-fd (socket) (etypecase socket (fixnum socket) (two-way-stream (socket-fd (two-way-stream-input-stream socket))) (sb-bsd-sockets:socket (sb-bsd-sockets:socket-file-descriptor socket)) (file-stream (si:file-stream-fd socket)))) (defvar *external-format-to-coding-system* '((:latin-1 "latin-1" "latin-1-unix" "iso-latin-1-unix" "iso-8859-1" "iso-8859-1-unix") (:utf-8 "utf-8" "utf-8-unix"))) (defun external-format (coding-system) (or (car (rassoc-if (lambda (x) (member coding-system x :test #'equal)) *external-format-to-coding-system*)) (find coding-system (ext:all-encodings) :test #'string-equal))) (defimplementation find-external-format (coding-system) #+unicode (external-format coding-system) Without unicode support , CLASP uses the one - byte encoding of the underlying OS , and will barf on anything except : . We return NIL here for known encodings , so #-unicode (let ((xf (external-format coding-system))) (if (member xf '(:utf-8)) nil :default))) If CLASP is built with thread support , it 'll spawn a helper thread current choice of NIL as communication - style in so far as CLASP 's main - thread is also the Slime 's REPL thread . #+clasp-working (defimplementation call-with-user-break-handler (real-handler function) (let ((old-handler #'si:terminal-interrupt)) (setf (symbol-function 'si:terminal-interrupt) (make-interrupt-handler real-handler)) (unwind-protect (funcall function) (setf (symbol-function 'si:terminal-interrupt) old-handler)))) #+threads (defun make-interrupt-handler (real-handler) (let ((main-thread (find 'si:top-level (mp:all-processes) :key #'mp:process-name))) #'(lambda (&rest args) (declare (ignore args)) (mp:interrupt-process main-thread real-handler)))) #-threads (defun make-interrupt-handler (real-handler) #'(lambda (&rest args) (declare (ignore args)) (funcall real-handler))) (defimplementation getpid () (si:getpid)) (defimplementation set-default-directory (directory) adapts * DEFAULT - PATHNAME - DEFAULTS * . (default-directory)) (defimplementation default-directory () (namestring (ext:getcwd))) (defimplementation quit-lisp () (core:quit)) Instead of busy waiting with communication - style NIL , use select ( ) #+serve-event (progn (defun poll-streams (streams timeout) (let* ((serve-event::*descriptor-handlers* (copy-list serve-event::*descriptor-handlers*)) (active-fds '()) (fd-stream-alist (loop for s in streams for fd = (socket-fd s) collect (cons fd s) do (serve-event:add-fd-handler fd :input #'(lambda (fd) (push fd active-fds)))))) (serve-event:serve-event timeout) (loop for fd in active-fds collect (cdr (assoc fd fd-stream-alist))))) (defimplementation wait-for-input (streams &optional timeout) (assert (member timeout '(nil t))) (loop (cond ((check-slime-interrupts) (return :interrupt)) (timeout (return (poll-streams streams 0))) (t (when-let (ready (poll-streams streams 0.2)) (return ready)))))) #-serve-event (defimplementation wait-for-input (streams &optional timeout) (assert (member timeout '(nil t))) (loop (cond ((check-slime-interrupts) (return :interrupt)) (timeout (return (remove-if-not #'listen streams))) (t (let ((ready (remove-if-not #'listen streams))) (if ready (return ready)) (sleep 0.1)))))) (defvar *buffer-name* nil) (defvar *buffer-start-position*) (defun signal-compiler-condition (&rest args) (apply #'signal 'compiler-condition args)) #-clasp-bytecmp (defun handle-compiler-message (condition) CLASP emits lots of noise in compiler - notes , like " Invoking (unless (typep condition 'c::compiler-note) (signal-compiler-condition :original-condition condition :message (princ-to-string condition) :severity (etypecase condition (cmp:compiler-fatal-error :error) (cmp:compiler-error :error) (error :error) (style-warning :style-warning) (warning :warning)) :location (condition-location condition)))) #-clasp-bytecmp (defun condition-location (condition) (let ((file (cmp:compiler-message-file condition)) (position (cmp:compiler-message-file-position condition))) (if (and position (not (minusp position))) (if *buffer-name* (make-buffer-location *buffer-name* *buffer-start-position* position) (make-file-location file position)) (make-error-location "No location found.")))) (defimplementation call-with-compilation-hooks (function) (funcall function)) (defimplementation slynk-compile-file (input-file output-file load-p external-format &key policy) (declare (ignore policy)) (format t "Compiling file input-file = ~a output-file = ~a~%" input-file output-file) (let ((tmp-output-file (compile-file-pathname (si:mkstemp "TMP:clasp-slynk-compile-file-")))) (format t "Using tmp-output-file: ~a~%" tmp-output-file) (multiple-value-bind (fasl warnings-p failure-p) (with-compilation-hooks () (compile-file input-file :output-file tmp-output-file :external-format external-format)) (values fasl warnings-p (or failure-p (when load-p (not (load fasl)))))))) (defvar *tmpfile-map* (make-hash-table :test #'equal)) (defun note-buffer-tmpfile (tmp-file buffer-name) EXT : COMPILED - FUNCTION - FILE below will return a namestring . (let ((tmp-namestring (namestring (truename tmp-file)))) (setf (gethash tmp-namestring *tmpfile-map*) buffer-name) tmp-namestring)) (defun tmpfile-to-buffer (tmp-file) (gethash tmp-file *tmpfile-map*)) (defimplementation slynk-compile-string (string &key buffer position filename policy) (declare (ignore policy)) (with-compilation-hooks () (*buffer-start-position* position)) (let ((tmp-file (si:mkstemp "TMP:clasp-slynk-tmpfile-")) (fasl-file) (warnings-p) (failure-p)) (unwind-protect (with-open-file (tmp-stream tmp-file :direction :output :if-exists :supersede) (write-string string tmp-stream) (finish-output tmp-stream) (multiple-value-setq (fasl-file warnings-p failure-p) (let ((truename (or filename (note-buffer-tmpfile tmp-file buffer)))) (compile-file tmp-file :source-debug-namestring truename :source-debug-offset (1- position))))) (when fasl-file (load fasl-file)) (when (probe-file tmp-file) (delete-file tmp-file)) (when fasl-file (delete-file fasl-file))) (not failure-p))))) (defimplementation arglist (name) (multiple-value-bind (arglist foundp) (if foundp arglist :not-available))) (defimplementation function-name (f) (typecase f (generic-function (clos::generic-function-name f)) (function (ext:compiled-function-name f)))) FIXME (defimplementation macroexpand-all (form &optional env) (declare (ignore env)) (macroexpand form)) (defimplementation describe-symbol-for-emacs (symbol) (let ((result '())) (flet ((frob (type boundp) (when (funcall boundp symbol) (let ((doc (describe-definition symbol type))) (setf result (list* type doc result)))))) (frob :VARIABLE #'boundp) (frob :FUNCTION #'fboundp) (frob :CLASS (lambda (x) (find-class x nil)))) result)) (defimplementation describe-definition (name type) (case type (:variable (documentation name 'variable)) (:function (documentation name 'function)) (:class (documentation name 'class)) (t nil))) (defimplementation type-specifier-p (symbol) (or (subtypep nil symbol) (not (eq (type-specifier-arglist symbol) :not-available)))) (eval-when (:compile-toplevel :load-toplevel :execute) (import '(si::*break-env* si::*ihs-top* si::*ihs-current* si::*ihs-base* #+frs si::*frs-base* #+frs si::*frs-top* si::*tpl-commands* si::*tpl-level* #+frs si::frs-top si::ihs-top si::ihs-fun si::ihs-env #+frs si::sch-frs-base si::set-break-env si::set-current-ihs si::tpl-commands))) (defun make-invoke-debugger-hook (hook) (when hook #'(lambda (condition old-hook) (if *debugger-hook* (funcall hook condition old-hook))))) (defimplementation install-debugger-globally (function) (setq *debugger-hook* function) (setq ext:*invoke-debugger-hook* (make-invoke-debugger-hook function)) ) (defimplementation call-with-debugger-hook (hook fun) (let ((*debugger-hook* hook) (ext:*invoke-debugger-hook* (make-invoke-debugger-hook hook))) (funcall fun)) ) (defvar *backtrace* '()) to debug , and given the " young " age of CLASP 's slynk backend , that 's ( list : slynk ) ( setf name ( pathname name ) ) (defimplementation call-with-debugging-environment (debugger-loop-fn) (declare (type function debugger-loop-fn)) (let* ((*ihs-top* (or #+#.(ls-backend:with-symbol '*stack-top-hint* 'core) core:*stack-top-hint* (ihs-top))) (*ihs-current* *ihs-top*) #+frs (*frs-base* (or (sch-frs-base *frs-top* *ihs-base*) (1+ (frs-top)))) #+frs (*frs-top* (frs-top)) (*tpl-level* (1+ *tpl-level*)) (*backtrace* (loop for ihs from 0 below *ihs-top* collect (list (si::ihs-fun ihs) (si::ihs-env ihs) ihs)))) (declare (special *ihs-current*)) #+frs (loop for f from *frs-base* until *frs-top* do (let ((i (- (si::frs-ihs f) *ihs-base* 1))) (when (plusp i) (let* ((x (elt *backtrace* i)) (name (si::frs-tag f))) (unless (si::fixnump name) (push name (third x))))))) (setf *backtrace* (nreverse *backtrace*)) (set-break-env) (set-current-ihs) (let ((*ihs-base* *ihs-top*)) (funcall debugger-loop-fn)))) (defimplementation compute-backtrace (start end) (subseq *backtrace* start (and (numberp end) (min end (length *backtrace*))))) (defun frame-name (frame) (let ((x (first frame))) (if (symbolp x) x (function-name x)))) (defun frame-function (frame-number) (let ((x (first (elt *backtrace* frame-number)))) (etypecase x (symbol (and (fboundp x) (fdefinition x))) (function x)))) (defimplementation print-frame (frame stream) (format stream "(~s~{ ~s~})" (function-name (first frame)) #+#.(ls-backend:with-symbol 'ihs-arguments 'core) (coerce (core:ihs-arguments (third frame)) 'list) #-#.(ls-backend:with-symbol 'ihs-arguments 'core) nil)) (defimplementation frame-source-location (frame-number) (source-location (frame-function frame-number))) #+clasp-working (defimplementation frame-catch-tags (frame-number) (third (elt *backtrace* frame-number))) (defun ihs-frame-id (frame-number) (- (core:ihs-top) frame-number)) (defimplementation frame-locals (frame-number) (let* ((frame (elt *backtrace* frame-number)) (env (second frame)) (locals (loop for x = env then (core:get-parent-environment x) while x nconc (loop for name across (core:environment-debug-names x) for value across (core:environment-debug-values x) collect (list :name name :id 0 :value value))))) (nconc (loop for arg across (core:ihs-arguments (third frame)) for i from 0 collect (list :name (intern (format nil "ARG~d" i) #.*package*) :id 0 :value arg)) locals))) (defimplementation frame-var-value (frame-number var-number) (let* ((frame (elt *backtrace* frame-number)) (env (second frame)) (args (core:ihs-arguments (third frame)))) (if (< var-number (length args)) (svref args var-number) (elt (frame-locals frame-number) var-number)))) #+clasp-working (defimplementation disassemble-frame (frame-number) (let ((fun (frame-function frame-number))) (disassemble fun))) (defimplementation eval-in-frame (form frame-number) (let ((env (second (elt *backtrace* frame-number)))) (core:compile-form-and-eval-with-env form env))) #+clasp-working (defimplementation gdb-initial-commands () These signals are used by the GC . #+linux '("handle SIGPWR noprint nostop" "handle SIGXCPU noprint nostop")) #+clasp-working (defimplementation command-line-args () (loop for n from 0 below (si:argc) collect (si:argv n))) (defun make-file-location (file file-position) File positions in CL start at 0 , but Emacs ' buffer positions start at 1 . We specify (: ) because the positions comming from CLASP point at right after the toplevel form appearing before (make-location `(:file ,(namestring (translate-logical-pathname file))) `(:position ,(1+ file-position)) `(:align t))) (defun make-buffer-location (buffer-name start-position &optional (offset 0)) (make-location `(:buffer ,buffer-name) `(:offset ,start-position ,offset) `(:align t))) (defimplementation find-definitions (name) (let ((annotations (core:get-annotation name 'si::location :all))) (cond (annotations (loop for annotation in annotations collect (destructuring-bind (dspec file . pos) annotation `(,dspec ,(make-file-location file pos))))) (t (mapcan #'(lambda (type) (find-definitions-by-type name type)) (classify-definition-name name)))))) (defun classify-definition-name (name) (let ((types '())) (when (fboundp name) (cond ((special-operator-p name) (push :special-operator types)) ((macro-function name) (push :macro types)) ((typep (fdefinition name) 'generic-function) (push :generic-function types)) ((si:mangle-name name t) (push :c-function types)) (t (push :lisp-function types)))) (when (boundp name) (cond ((constantp name) (push :constant types)) (t (push :global-variable types)))) types)) (defun find-definitions-by-type (name type) (ecase type (:lisp-function (when-let (loc (source-location (fdefinition name))) (list `((defun ,name) ,loc)))) (:c-function (when-let (loc (source-location (fdefinition name))) (list `((c-source ,name) ,loc)))) (:generic-function (loop for method in (clos:generic-function-methods (fdefinition name)) for specs = (clos:method-specializers method) for loc = (source-location method) when loc collect `((defmethod ,name ,specs) ,loc))) (:macro (when-let (loc (source-location (macro-function name))) (list `((defmacro ,name) ,loc)))) (:constant (when-let (loc (source-location name)) (list `((defconstant ,name) ,loc)))) (:global-variable (when-let (loc (source-location name)) (list `((defvar ,name) ,loc)))) (:special-operator))) (eval-when (:compile-toplevel :load-toplevel :execute) (defun c-function-name-p (name) (and (symbolp name) (si:mangle-name name t) t)) (defun c-function-p (object) (and (functionp object) (let ((fn-name (function-name object))) (and fn-name (c-function-name-p fn-name)))))) (deftype c-function () `(satisfies c-function-p)) (defun source-location (object) (converting-errors-to-error-location (typecase object (function (multiple-value-bind (file pos) (ext:compiled-function-file object) (cond ((not file) (return-from source-location nil)) ((tmpfile-to-buffer file) (make-buffer-location (tmpfile-to-buffer file) pos)) (t (assert (probe-file file)) (assert (not (minusp pos))) (make-file-location file pos))))) (method (source-location (clos:method-function object)))))) (defimplementation find-source-location (object) (or (source-location object) (make-error-location "Source definition of ~S not found." object))) #+profile (progn (defimplementation profile (fname) (when fname (eval `(profile:profile ,fname)))) (defimplementation unprofile (fname) (when fname (eval `(profile:unprofile ,fname)))) (defimplementation unprofile-all () (profile:unprofile-all) "All functions unprofiled.") (defimplementation profile-report () (profile:report)) (defimplementation profile-reset () (profile:reset) "Reset profiling counters.") (defimplementation profiled-functions () (profile:profile)) (defimplementation profile-package (package callers methods) (declare (ignore callers methods)) (eval `(profile:profile ,(package-name (find-package package))))) #+threads (progn (defvar *thread-id-counter* 0) (defparameter *thread-id-map* (make-hash-table)) (defvar *thread-id-map-lock* (mp:make-lock :name "thread id map lock")) (defimplementation spawn (fn &key name) (mp:process-run-function name fn)) (defimplementation thread-id (target-thread) (block thread-id (mp:with-lock (*thread-id-map-lock*) Does - THREAD have an i d already ? (maphash (lambda (id thread-pointer) (let ((thread (si:weak-pointer-value thread-pointer))) (cond ((not thread) (remhash id *thread-id-map*)) ((eq thread target-thread) (return-from thread-id id))))) *thread-id-map*) (let ((id (incf *thread-id-counter*)) (thread-pointer (si:make-weak-pointer target-thread))) (setf (gethash id *thread-id-map*) thread-pointer) id)))) (defimplementation find-thread (id) (mp:with-lock (*thread-id-map-lock*) (let* ((thread-ptr (gethash id *thread-id-map*)) (thread (and thread-ptr (si:weak-pointer-value thread-ptr)))) (unless thread (remhash id *thread-id-map*)) thread))) (defimplementation thread-name (thread) (mp:process-name thread)) (defimplementation thread-status (thread) (if (mp:process-active-p thread) "RUNNING" "STOPPED")) (defimplementation make-lock (&key name) (mp:make-lock :name name :recursive t)) (defimplementation call-with-lock-held (lock function) (declare (type function function)) (mp:with-lock (lock) (funcall function))) (defimplementation current-thread () mp:*current-process*) (defimplementation all-threads () (mp:all-processes)) (defimplementation interrupt-thread (thread fn) (mp:interrupt-process thread fn)) (defimplementation kill-thread (thread) (mp:process-kill thread)) (defimplementation thread-alive-p (thread) (mp:process-active-p thread)) (defvar *mailbox-lock* (mp:make-lock :name "mailbox lock")) (defvar *mailboxes* (list)) (declaim (type list *mailboxes*)) (defstruct (mailbox (:conc-name mailbox.)) thread (mutex (mp:make-lock)) (cvar (mp:make-condition-variable)) (queue '() :type list)) (defun mailbox (thread) "Return THREAD's mailbox." (mp:with-lock (*mailbox-lock*) (or (find thread *mailboxes* :key #'mailbox.thread) (let ((mb (make-mailbox :thread thread))) (push mb *mailboxes*) mb)))) (defimplementation send (thread message) (let* ((mbox (mailbox thread)) (mutex (mailbox.mutex mbox))) (mp:with-lock (mutex) (setf (mailbox.queue mbox) (nconc (mailbox.queue mbox) (list message))) (mp:condition-variable-broadcast (mailbox.cvar mbox))))) (defimplementation receive-if (test &optional timeout) (let* ((mbox (mailbox (current-thread))) (mutex (mailbox.mutex mbox))) (assert (or (not timeout) (eq timeout t))) (loop (check-slime-interrupts) (mp:with-lock (mutex) (let* ((q (mailbox.queue mbox)) (tail (member-if test q))) (when tail (setf (mailbox.queue mbox) (nconc (ldiff q tail) (cdr tail))) (return (car tail)))) (when (eq timeout t) (return (values nil t))) (mp:condition-variable-timedwait (mailbox.cvar mbox) mutex 0.2)))))
58f89dd0617d7a545a4943667b9e638b6b64d0b08b9a8176f4390b1cbbb53357
input-output-hk/cardano-wallet
Primitive.hs
# LANGUAGE DataKinds # # LANGUAGE FlexibleInstances # # LANGUAGE QuasiQuotes # # LANGUAGE ScopedTypeVariables # # LANGUAGE TypeApplications # # LANGUAGE ViewPatterns # # OPTIONS_GHC -Wno - orphans # -- | Copyright : © 2018 - 2022 IOHK -- License: Apache-2.0 module Cardano.Wallet.Api.Types.Primitive () where import Prelude import Cardano.Api ( TxMetadataJsonSchema (..) , displayError , metadataFromJson , metadataToJson ) import Cardano.Pool.Metadata.Types ( StakePoolMetadataHash, StakePoolMetadataUrl ) import Cardano.Pool.Types ( PoolId, PoolOwner, decodePoolIdBech32, encodePoolIdBech32 ) import Cardano.Wallet.Api.Aeson ( eitherToParser ) import Cardano.Wallet.Api.Hex ( fromHexText, hexText ) import Cardano.Wallet.Api.Lib.ApiT ( ApiT (..), fromTextApiT, toTextApiT ) import Cardano.Wallet.Api.Types.Key ( parseBech32 ) import Cardano.Wallet.Primitive.AddressDerivation ( DerivationIndex, RewardAccount ) import Cardano.Wallet.Primitive.Passphrase.Types ( Passphrase (..), PassphraseMaxLength (..), PassphraseMinLength (..) ) import Cardano.Wallet.Primitive.Types ( EpochNo (..) , NonWalletCertificate (..) , SlotInEpoch (..) , SlotNo (..) , unsafeEpochNo ) import Cardano.Wallet.Primitive.Types.Address ( Address (..) ) import Cardano.Wallet.Primitive.Types.Coin ( Coin (..), coinFromQuantity, coinToQuantity ) import Cardano.Wallet.Primitive.Types.Hash ( Hash (..) ) import Cardano.Wallet.Primitive.Types.Tx.Constraints ( coinIsValidForTxOut, txOutMaxCoin ) import Cardano.Wallet.Primitive.Types.Tx.Tx ( TxMetadata (..), TxScriptValidity ) import Cardano.Wallet.Primitive.Types.Tx.TxIn ( TxIn (..) ) import Cardano.Wallet.Shelley.Network.Discriminant ( DecodeAddress (..) , DecodeStakeAddress (..) , EncodeAddress (..) , EncodeStakeAddress (..) ) import Cardano.Wallet.Transaction ( AnyScript (NativeScript, PlutusScript), PlutusScriptInfo (..) ) import Cardano.Wallet.Util ( ShowFmt (..) ) import Codec.Binary.Bech32 ( dataPartFromBytes ) import Codec.Binary.Bech32.TH ( humanReadablePart ) import Control.Monad ( when, (>=>) ) import Data.Aeson ( FromJSON (parseJSON) , KeyValue (..) , Options (..) , ToJSON (toJSON) , Value (..) , camelTo2 , genericParseJSON , genericToJSON , object , withObject , withText , (.!=) , (.:) , (.:?) , (.=) ) import Data.Aeson.Types ( prependFailure ) import Data.Bifunctor ( Bifunctor (..) ) import Data.Proxy ( Proxy (..) ) import Data.Quantity ( Quantity (..) ) import Data.Text.Class ( FromText (..), ToText (..) ) import Data.Word ( Word32, Word64 ) import Data.Word.Odd ( Word31 ) import qualified Cardano.Wallet.Primitive.Types as W import qualified Cardano.Wallet.Primitive.Types.TokenBundle as W import qualified Cardano.Wallet.Primitive.Types.TokenMap as W import qualified Cardano.Wallet.Primitive.Types.TokenPolicy as W import qualified Codec.Binary.Bech32 as Bech32 import qualified Data.Aeson.Types as Aeson import qualified Data.ByteString as BS instance ToJSON (ApiT DerivationIndex) where toJSON = toTextApiT instance FromJSON (ApiT DerivationIndex) where parseJSON = fromTextApiT "DerivationIndex" instance (PassphraseMaxLength purpose, PassphraseMinLength purpose) => FromJSON (ApiT (Passphrase purpose)) where parseJSON = fromTextApiT "Passphrase" instance ToJSON (ApiT (Passphrase purpose)) where toJSON = toTextApiT instance FromJSON (ApiT W.TokenPolicyId) where parseJSON = fromTextApiT "PolicyId" instance ToJSON (ApiT W.TokenPolicyId) where toJSON = toTextApiT instance FromJSON (ApiT PlutusScriptInfo) where parseJSON = (fmap. fmap) ApiT $ parseJSON >=> eitherToParser . bimap ShowFmt PlutusScriptInfo . fromText instance ToJSON (ApiT PlutusScriptInfo) where toJSON (ApiT (PlutusScriptInfo v)) = toJSON $ toText v instance FromJSON (ApiT AnyScript) where parseJSON = (fmap . fmap) ApiT . withObject "AnyScript" $ \obj -> do scriptType <- obj .:? "script_type" case (scriptType :: Maybe String) of Just t | t == "plutus" -> PlutusScript . getApiT <$> obj .: "language_version" Just t | t == "native" -> NativeScript <$> obj .: "script" _ -> fail "AnyScript needs either 'native' or 'plutus' in 'script_type'" instance ToJSON (ApiT AnyScript) where toJSON (ApiT anyScript) = case anyScript of NativeScript s -> object [ "script_type" .= String "native" , "script" .= toJSON s ] PlutusScript v -> object [ "script_type" .= String "plutus" , "language_version" .= toJSON (ApiT v) ] instance FromJSON (ApiT W.TokenName) where parseJSON = withText "AssetName" (fmap (ApiT . W.UnsafeTokenName) . eitherToParser . fromHexText) instance ToJSON (ApiT W.TokenName) where toJSON = toJSON . hexText . W.unTokenName . getApiT instance FromJSON (ApiT W.TokenFingerprint) where parseJSON = fromTextApiT "TokenFingerprint" instance ToJSON (ApiT W.TokenFingerprint) where toJSON = toTextApiT instance FromJSON (ApiT EpochNo) where parseJSON = fmap (ApiT . unsafeEpochNo) . parseJSON instance ToJSON (ApiT EpochNo) where toJSON (ApiT (EpochNo en)) = toJSON $ fromIntegral @Word31 @Word32 en instance FromJSON (ApiT SlotInEpoch) where parseJSON = fmap (ApiT . SlotInEpoch) . parseJSON instance ToJSON (ApiT SlotInEpoch) where toJSON (ApiT (SlotInEpoch sn)) = toJSON sn instance FromJSON (ApiT SlotNo) where parseJSON = fmap (ApiT . SlotNo) . parseJSON instance ToJSON (ApiT SlotNo) where toJSON (ApiT (SlotNo sn)) = toJSON sn instance FromJSON (ApiT W.TokenMap) where parseJSON = fmap (ApiT . W.getFlat) . parseJSON instance ToJSON (ApiT W.TokenMap) where toJSON = toJSON . W.Flat . getApiT instance ToJSON (ApiT W.TokenBundle) where -- TODO: consider other structures toJSON (ApiT (W.TokenBundle c ts)) = object [ "amount" .= coinToQuantity @Word c , "assets" .= toJSON (ApiT ts) ] instance FromJSON (ApiT W.TokenBundle) where -- TODO: reject unknown fields parseJSON = withObject "Value " $ \v -> prependFailure "parsing Value failed, " $ fmap ApiT $ W.TokenBundle <$> (v .: "amount" >>= validateCoin) <*> fmap getApiT (v .: "assets" .!= mempty) where validateCoin :: Quantity "lovelace" Word64 -> Aeson.Parser Coin validateCoin (coinFromQuantity -> c) | coinIsValidForTxOut c = pure c | otherwise = fail $ "invalid coin value: value has to be lower than or equal to " <> show (unCoin txOutMaxCoin) <> " lovelace." instance FromJSON (ApiT TxIn) where parseJSON = withObject "TxIn" $ \v -> ApiT <$> (TxIn <$> fmap getApiT (v .: "id") <*> v .: "index") instance ToJSON (ApiT TxIn) where toJSON (ApiT (TxIn txid ix)) = object [ "id" .= toJSON (ApiT txid) , "index" .= toJSON ix ] instance FromJSON (ApiT (Hash "Tx")) where parseJSON = fromTextApiT "Tx Hash" instance ToJSON (ApiT (Hash "Tx")) where toJSON = toTextApiT instance FromJSON (ApiT TxScriptValidity) where parseJSON = fmap ApiT . genericParseJSON Aeson.defaultOptions { constructorTagModifier = camelTo2 '_' . drop 8 } instance ToJSON (ApiT TxScriptValidity) where toJSON = genericToJSON Aeson.defaultOptions { constructorTagModifier = camelTo2 '_' . drop 8 } . getApiT instance {-# OVERLAPS #-} DecodeAddress n => FromJSON (ApiT Address, Proxy n) where parseJSON x = do let proxy = Proxy @n addr <- parseJSON x >>= eitherToParser . bimap ShowFmt ApiT . decodeAddress @n return (addr, proxy) instance {-# OVERLAPS #-} EncodeAddress n => ToJSON (ApiT Address, Proxy n) where toJSON (addr, _) = toJSON . encodeAddress @n . getApiT $ addr instance {-# OVERLAPS #-} (DecodeStakeAddress n) => FromJSON (ApiT RewardAccount, Proxy n) where parseJSON x = do let proxy = Proxy @n acct <- parseJSON x >>= eitherToParser . bimap ShowFmt ApiT . decodeStakeAddress @n return (acct, proxy) instance {-# OVERLAPS #-} EncodeStakeAddress n => ToJSON (ApiT RewardAccount, Proxy n) where toJSON (acct, _) = toJSON . encodeStakeAddress @n . getApiT $ acct instance FromJSON (ApiT PoolId) where parseJSON = parseJSON >=> eitherToParser . bimap ShowFmt ApiT . decodePoolIdBech32 instance ToJSON (ApiT PoolId) where toJSON = toJSON . encodePoolIdBech32 . getApiT instance FromJSON (ApiT StakePoolMetadataHash) where parseJSON = fromTextApiT "ApiT StakePoolMetadataHash" instance ToJSON (ApiT StakePoolMetadataHash) where toJSON = toTextApiT instance FromJSON (ApiT PoolOwner) where parseJSON = fromTextApiT "ApiT PoolOwner" instance ToJSON (ApiT PoolOwner) where toJSON = toTextApiT instance FromJSON (ApiT StakePoolMetadataUrl) where parseJSON = fromTextApiT "ApiT StakePoolMetadataUrl" instance ToJSON (ApiT StakePoolMetadataUrl) where toJSON = toTextApiT instance FromJSON (ApiT W.NonWalletCertificate) where parseJSON val | val == object ["certificate_type" .= String "mir"] = pure $ ApiT MIRCertificate | val == object ["certificate_type" .= String "genesis"] = pure $ ApiT GenesisCertificate | otherwise = fail "expected object with key 'certificate_type' and value either 'mir' or 'genesis'" instance ToJSON (ApiT W.NonWalletCertificate) where toJSON (ApiT cert) = object ["certificate_type" .= String (toText cert)] instance FromJSON (ApiT TxMetadata) where parseJSON = fmap ApiT . either (fail . displayError) pure . metadataFromJson TxMetadataJsonDetailedSchema instance ToJSON (ApiT TxMetadata) where toJSON = metadataToJson TxMetadataJsonDetailedSchema . getApiT instance FromJSON (ApiT (Hash "ScriptIntegrity")) where parseJSON value = do (hrp, bytes) <- parseJSON value >>= parseBech32 "Malformed policy key" when (hrp /= [humanReadablePart|script_data|]) $ fail "expected a bech32 script_data hash" when (BS.length bytes /= 32) $ fail "expected a bech32 script_data hash of 32 bytes" pure $ ApiT $ Hash bytes instance ToJSON (ApiT (Hash "ScriptIntegrity")) where toJSON (ApiT (Hash hashed')) = toJSON $ Bech32.encodeLenient [humanReadablePart|script_data|] $ dataPartFromBytes hashed' instance FromJSON (ApiT (Hash "ExtraSignature")) where parseJSON value = do (hrp, bytes) <- parseJSON value >>= parseBech32 "Malformed policy key" when (hrp /= [humanReadablePart|req_signer_vkh|]) $ fail "expected a bech32 req_signer_vkh hash" when (BS.length bytes /= 28) $ fail "expected a bech32 req_signer_vkh hash of 28 bytes" pure $ ApiT $ Hash bytes instance ToJSON (ApiT (Hash "ExtraSignature")) where toJSON (ApiT (Hash hashed')) = toJSON $ Bech32.encodeLenient [humanReadablePart|req_signer_vkh|] $ dataPartFromBytes hashed'
null
https://raw.githubusercontent.com/input-output-hk/cardano-wallet/18bc22ad0932e4e8b1b6eafee5edf99ac57126af/lib/wallet/api/http/Cardano/Wallet/Api/Types/Primitive.hs
haskell
| License: Apache-2.0 TODO: consider other structures TODO: reject unknown fields # OVERLAPS # # OVERLAPS # # OVERLAPS # # OVERLAPS #
# LANGUAGE DataKinds # # LANGUAGE FlexibleInstances # # LANGUAGE QuasiQuotes # # LANGUAGE ScopedTypeVariables # # LANGUAGE TypeApplications # # LANGUAGE ViewPatterns # # OPTIONS_GHC -Wno - orphans # Copyright : © 2018 - 2022 IOHK module Cardano.Wallet.Api.Types.Primitive () where import Prelude import Cardano.Api ( TxMetadataJsonSchema (..) , displayError , metadataFromJson , metadataToJson ) import Cardano.Pool.Metadata.Types ( StakePoolMetadataHash, StakePoolMetadataUrl ) import Cardano.Pool.Types ( PoolId, PoolOwner, decodePoolIdBech32, encodePoolIdBech32 ) import Cardano.Wallet.Api.Aeson ( eitherToParser ) import Cardano.Wallet.Api.Hex ( fromHexText, hexText ) import Cardano.Wallet.Api.Lib.ApiT ( ApiT (..), fromTextApiT, toTextApiT ) import Cardano.Wallet.Api.Types.Key ( parseBech32 ) import Cardano.Wallet.Primitive.AddressDerivation ( DerivationIndex, RewardAccount ) import Cardano.Wallet.Primitive.Passphrase.Types ( Passphrase (..), PassphraseMaxLength (..), PassphraseMinLength (..) ) import Cardano.Wallet.Primitive.Types ( EpochNo (..) , NonWalletCertificate (..) , SlotInEpoch (..) , SlotNo (..) , unsafeEpochNo ) import Cardano.Wallet.Primitive.Types.Address ( Address (..) ) import Cardano.Wallet.Primitive.Types.Coin ( Coin (..), coinFromQuantity, coinToQuantity ) import Cardano.Wallet.Primitive.Types.Hash ( Hash (..) ) import Cardano.Wallet.Primitive.Types.Tx.Constraints ( coinIsValidForTxOut, txOutMaxCoin ) import Cardano.Wallet.Primitive.Types.Tx.Tx ( TxMetadata (..), TxScriptValidity ) import Cardano.Wallet.Primitive.Types.Tx.TxIn ( TxIn (..) ) import Cardano.Wallet.Shelley.Network.Discriminant ( DecodeAddress (..) , DecodeStakeAddress (..) , EncodeAddress (..) , EncodeStakeAddress (..) ) import Cardano.Wallet.Transaction ( AnyScript (NativeScript, PlutusScript), PlutusScriptInfo (..) ) import Cardano.Wallet.Util ( ShowFmt (..) ) import Codec.Binary.Bech32 ( dataPartFromBytes ) import Codec.Binary.Bech32.TH ( humanReadablePart ) import Control.Monad ( when, (>=>) ) import Data.Aeson ( FromJSON (parseJSON) , KeyValue (..) , Options (..) , ToJSON (toJSON) , Value (..) , camelTo2 , genericParseJSON , genericToJSON , object , withObject , withText , (.!=) , (.:) , (.:?) , (.=) ) import Data.Aeson.Types ( prependFailure ) import Data.Bifunctor ( Bifunctor (..) ) import Data.Proxy ( Proxy (..) ) import Data.Quantity ( Quantity (..) ) import Data.Text.Class ( FromText (..), ToText (..) ) import Data.Word ( Word32, Word64 ) import Data.Word.Odd ( Word31 ) import qualified Cardano.Wallet.Primitive.Types as W import qualified Cardano.Wallet.Primitive.Types.TokenBundle as W import qualified Cardano.Wallet.Primitive.Types.TokenMap as W import qualified Cardano.Wallet.Primitive.Types.TokenPolicy as W import qualified Codec.Binary.Bech32 as Bech32 import qualified Data.Aeson.Types as Aeson import qualified Data.ByteString as BS instance ToJSON (ApiT DerivationIndex) where toJSON = toTextApiT instance FromJSON (ApiT DerivationIndex) where parseJSON = fromTextApiT "DerivationIndex" instance (PassphraseMaxLength purpose, PassphraseMinLength purpose) => FromJSON (ApiT (Passphrase purpose)) where parseJSON = fromTextApiT "Passphrase" instance ToJSON (ApiT (Passphrase purpose)) where toJSON = toTextApiT instance FromJSON (ApiT W.TokenPolicyId) where parseJSON = fromTextApiT "PolicyId" instance ToJSON (ApiT W.TokenPolicyId) where toJSON = toTextApiT instance FromJSON (ApiT PlutusScriptInfo) where parseJSON = (fmap. fmap) ApiT $ parseJSON >=> eitherToParser . bimap ShowFmt PlutusScriptInfo . fromText instance ToJSON (ApiT PlutusScriptInfo) where toJSON (ApiT (PlutusScriptInfo v)) = toJSON $ toText v instance FromJSON (ApiT AnyScript) where parseJSON = (fmap . fmap) ApiT . withObject "AnyScript" $ \obj -> do scriptType <- obj .:? "script_type" case (scriptType :: Maybe String) of Just t | t == "plutus" -> PlutusScript . getApiT <$> obj .: "language_version" Just t | t == "native" -> NativeScript <$> obj .: "script" _ -> fail "AnyScript needs either 'native' or 'plutus' in 'script_type'" instance ToJSON (ApiT AnyScript) where toJSON (ApiT anyScript) = case anyScript of NativeScript s -> object [ "script_type" .= String "native" , "script" .= toJSON s ] PlutusScript v -> object [ "script_type" .= String "plutus" , "language_version" .= toJSON (ApiT v) ] instance FromJSON (ApiT W.TokenName) where parseJSON = withText "AssetName" (fmap (ApiT . W.UnsafeTokenName) . eitherToParser . fromHexText) instance ToJSON (ApiT W.TokenName) where toJSON = toJSON . hexText . W.unTokenName . getApiT instance FromJSON (ApiT W.TokenFingerprint) where parseJSON = fromTextApiT "TokenFingerprint" instance ToJSON (ApiT W.TokenFingerprint) where toJSON = toTextApiT instance FromJSON (ApiT EpochNo) where parseJSON = fmap (ApiT . unsafeEpochNo) . parseJSON instance ToJSON (ApiT EpochNo) where toJSON (ApiT (EpochNo en)) = toJSON $ fromIntegral @Word31 @Word32 en instance FromJSON (ApiT SlotInEpoch) where parseJSON = fmap (ApiT . SlotInEpoch) . parseJSON instance ToJSON (ApiT SlotInEpoch) where toJSON (ApiT (SlotInEpoch sn)) = toJSON sn instance FromJSON (ApiT SlotNo) where parseJSON = fmap (ApiT . SlotNo) . parseJSON instance ToJSON (ApiT SlotNo) where toJSON (ApiT (SlotNo sn)) = toJSON sn instance FromJSON (ApiT W.TokenMap) where parseJSON = fmap (ApiT . W.getFlat) . parseJSON instance ToJSON (ApiT W.TokenMap) where toJSON = toJSON . W.Flat . getApiT instance ToJSON (ApiT W.TokenBundle) where toJSON (ApiT (W.TokenBundle c ts)) = object [ "amount" .= coinToQuantity @Word c , "assets" .= toJSON (ApiT ts) ] instance FromJSON (ApiT W.TokenBundle) where parseJSON = withObject "Value " $ \v -> prependFailure "parsing Value failed, " $ fmap ApiT $ W.TokenBundle <$> (v .: "amount" >>= validateCoin) <*> fmap getApiT (v .: "assets" .!= mempty) where validateCoin :: Quantity "lovelace" Word64 -> Aeson.Parser Coin validateCoin (coinFromQuantity -> c) | coinIsValidForTxOut c = pure c | otherwise = fail $ "invalid coin value: value has to be lower than or equal to " <> show (unCoin txOutMaxCoin) <> " lovelace." instance FromJSON (ApiT TxIn) where parseJSON = withObject "TxIn" $ \v -> ApiT <$> (TxIn <$> fmap getApiT (v .: "id") <*> v .: "index") instance ToJSON (ApiT TxIn) where toJSON (ApiT (TxIn txid ix)) = object [ "id" .= toJSON (ApiT txid) , "index" .= toJSON ix ] instance FromJSON (ApiT (Hash "Tx")) where parseJSON = fromTextApiT "Tx Hash" instance ToJSON (ApiT (Hash "Tx")) where toJSON = toTextApiT instance FromJSON (ApiT TxScriptValidity) where parseJSON = fmap ApiT . genericParseJSON Aeson.defaultOptions { constructorTagModifier = camelTo2 '_' . drop 8 } instance ToJSON (ApiT TxScriptValidity) where toJSON = genericToJSON Aeson.defaultOptions { constructorTagModifier = camelTo2 '_' . drop 8 } . getApiT where parseJSON x = do let proxy = Proxy @n addr <- parseJSON x >>= eitherToParser . bimap ShowFmt ApiT . decodeAddress @n return (addr, proxy) where toJSON (addr, _) = toJSON . encodeAddress @n . getApiT $ addr => FromJSON (ApiT RewardAccount, Proxy n) where parseJSON x = do let proxy = Proxy @n acct <- parseJSON x >>= eitherToParser . bimap ShowFmt ApiT . decodeStakeAddress @n return (acct, proxy) => ToJSON (ApiT RewardAccount, Proxy n) where toJSON (acct, _) = toJSON . encodeStakeAddress @n . getApiT $ acct instance FromJSON (ApiT PoolId) where parseJSON = parseJSON >=> eitherToParser . bimap ShowFmt ApiT . decodePoolIdBech32 instance ToJSON (ApiT PoolId) where toJSON = toJSON . encodePoolIdBech32 . getApiT instance FromJSON (ApiT StakePoolMetadataHash) where parseJSON = fromTextApiT "ApiT StakePoolMetadataHash" instance ToJSON (ApiT StakePoolMetadataHash) where toJSON = toTextApiT instance FromJSON (ApiT PoolOwner) where parseJSON = fromTextApiT "ApiT PoolOwner" instance ToJSON (ApiT PoolOwner) where toJSON = toTextApiT instance FromJSON (ApiT StakePoolMetadataUrl) where parseJSON = fromTextApiT "ApiT StakePoolMetadataUrl" instance ToJSON (ApiT StakePoolMetadataUrl) where toJSON = toTextApiT instance FromJSON (ApiT W.NonWalletCertificate) where parseJSON val | val == object ["certificate_type" .= String "mir"] = pure $ ApiT MIRCertificate | val == object ["certificate_type" .= String "genesis"] = pure $ ApiT GenesisCertificate | otherwise = fail "expected object with key 'certificate_type' and value either 'mir' or 'genesis'" instance ToJSON (ApiT W.NonWalletCertificate) where toJSON (ApiT cert) = object ["certificate_type" .= String (toText cert)] instance FromJSON (ApiT TxMetadata) where parseJSON = fmap ApiT . either (fail . displayError) pure . metadataFromJson TxMetadataJsonDetailedSchema instance ToJSON (ApiT TxMetadata) where toJSON = metadataToJson TxMetadataJsonDetailedSchema . getApiT instance FromJSON (ApiT (Hash "ScriptIntegrity")) where parseJSON value = do (hrp, bytes) <- parseJSON value >>= parseBech32 "Malformed policy key" when (hrp /= [humanReadablePart|script_data|]) $ fail "expected a bech32 script_data hash" when (BS.length bytes /= 32) $ fail "expected a bech32 script_data hash of 32 bytes" pure $ ApiT $ Hash bytes instance ToJSON (ApiT (Hash "ScriptIntegrity")) where toJSON (ApiT (Hash hashed')) = toJSON $ Bech32.encodeLenient [humanReadablePart|script_data|] $ dataPartFromBytes hashed' instance FromJSON (ApiT (Hash "ExtraSignature")) where parseJSON value = do (hrp, bytes) <- parseJSON value >>= parseBech32 "Malformed policy key" when (hrp /= [humanReadablePart|req_signer_vkh|]) $ fail "expected a bech32 req_signer_vkh hash" when (BS.length bytes /= 28) $ fail "expected a bech32 req_signer_vkh hash of 28 bytes" pure $ ApiT $ Hash bytes instance ToJSON (ApiT (Hash "ExtraSignature")) where toJSON (ApiT (Hash hashed')) = toJSON $ Bech32.encodeLenient [humanReadablePart|req_signer_vkh|] $ dataPartFromBytes hashed'
379e38a71ba45127cc339c04b4092f5be95f7197771282b76667493a81cba3d6
kayceesrk/httpaf
httpaf.mli
---------------------------------------------------------------------------- Copyright ( c ) 2016 Inhabited Type LLC . All rights reserved . Redistribution and use in source and binary forms , with or without modification , are permitted provided that the following conditions are met : 1 . Redistributions of source code must retain the above copyright notice , this list of conditions and the following disclaimer . 2 . Redistributions in binary form must reproduce the above copyright notice , this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution . 3 . Neither the name of the author nor the names of his contributors may be used to endorse or promote products derived from this software without specific prior written permission . THIS SOFTWARE IS PROVIDED BY THE CONTRIBUTORS ` ` AS IS '' AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT LIMITED TO , THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED . IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE , DATA , OR PROFITS ; OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING NEGLIGENCE OR OTHERWISE ) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE , EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE . ---------------------------------------------------------------------------- Copyright (c) 2016 Inhabited Type LLC. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the author nor the names of his contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ----------------------------------------------------------------------------*) * Http / af is a high - performance , memory - efficient , and scalable web server for OCaml . It implements the HTTP 1.1 specification with respect to parsing , serialization , and connection pipelining . For compatibility , http / af respects the imperatives of the [ Connection ] header when handling HTTP 1.0 connections . To use this library effectively , the user must be familiar with the HTTP 1.1 specification , and the basic principles of memory management and vectorized IO . for OCaml. It implements the HTTP 1.1 specification with respect to parsing, serialization, and connection pipelining. For compatibility, http/af respects the imperatives of the [Connection] header when handling HTTP 1.0 connections. To use this library effectively, the user must be familiar with the HTTP 1.1 specification, and the basic principles of memory management and vectorized IO. *) open Result * { 2 Basic HTTP Types } (** Protocol Version HTTP uses a "<major>.<minor>" numbering scheme to indicate versions of the protocol. The protocol version as a whole indicates the sender's conformance with the set of requirements laid out in that version's corresponding specification of HTTP. See {{:#section-2.6} RFC7230§2.6} for more details. *) module Version : sig type t = { major : int (** The major protocol number. *) ; minor : int (** The minor protocol number. *) } val compare : t -> t -> int val to_string : t -> string val of_string : string -> t val pp_hum : Format.formatter -> t -> unit end (** Request Method The request method token is the primary source of request semantics; it indicates the purpose for which the client has made this request and what is expected by the client as a successful result. See {{:#section-4} RFC7231§4} for more detials. *) module Method : sig type standard = [ | `GET * { { : #section-4.3.1 } RFC7231§4.3.1 } . Safe , Cacheable . | `HEAD * { { : #section-4.3.2 } RFC7231§4.3.2 } . Safe , Cacheable . | `POST * { { : #section-4.3.3 } RFC7231§4.3.3 } . Cacheable . | `PUT (** {{:#section-4.3.4} RFC7231§4.3.4}. Idempotent. *) | `DELETE (** {{:#section-4.3.5} RFC7231§4.3.5}. Idempotent. *) | `CONNECT (** {{:#section-4.3.6} RFC7231§4.3.6}. *) | `OPTIONS (** {{:#section-4.3.7} RFC7231§4.3.7}. Safe.*) | `TRACE (** {{:#section-4.3.8} RFC7231§4.3.8}. Safe.*) ] type t = [ | standard | `Other of string * Methods defined outside of RFC7231 , or custom methods . ] val is_safe : standard -> bool (** Request methods are considered "safe" if their defined semantics are essentially read-only; i.e., the client does not request, and does not expect, any state change on the origin server as a result of applying a safe method to a target resource. Likewise, reasonable use of a safe method is not expected to cause any harm, loss of property, or unusual burden on the origin server. See {{:#section-4.2.1} RFC7231§4.2.1} for more details. *) val is_cacheable : standard -> bool * Request methods can be defined as " cacheable " to indicate that responses to them are allowed to be stored for future reuse . See { { : } } for more details . to them are allowed to be stored for future reuse. See {{:} RFC7234} for more details. *) val is_idempotent : standard -> bool * A request method is considered " idempotent " if the intended effect on the server of multiple identical requests with that method is the same as the effect for a single such request . Of the request methods defined by this specification , PUT , DELETE , and safe request methods are idempotent . See { { : #section-4.2.2 } RFC7231§4.2.2 } for more details . the server of multiple identical requests with that method is the same as the effect for a single such request. Of the request methods defined by this specification, PUT, DELETE, and safe request methods are idempotent. See {{:#section-4.2.2} RFC7231§4.2.2} for more details. *) val to_string : t -> string val of_string : string -> t val pp_hum : Format.formatter -> t -> unit end * Response Status Codes The status - code element is a three - digit integer code giving the result of the attempt to understand and satisfy the request . See { { : #section-6 } RFC7231§6 } for more details . The status-code element is a three-digit integer code giving the result of the attempt to understand and satisfy the request. See {{:#section-6} RFC7231§6} for more details. *) module Status : sig type informational = [ | `Continue | `Switching_protocols ] * The 1xx ( Informational ) class of status code indicates an interim response for communicating connection status or request progress prior to completing the requested action and sending a final response . See { { : #section-6.2 } RFC7231§6.2 } for more details . response for communicating connection status or request progress prior to completing the requested action and sending a final response. See {{:#section-6.2} RFC7231§6.2} for more details. *) type successful = [ | `OK | `Created | `Accepted | `Non_authoritative_information | `No_content | `Reset_content | `Partial_content ] * The 2xx ( Successful ) class of status code indicates that the client 's request was successfully received , understood , and accepted . See { { : #section-6.3 } RFC7231§6.3 } for more details . request was successfully received, understood, and accepted. See {{:#section-6.3} RFC7231§6.3} for more details. *) type redirection = [ | `Multiple_choices | `Moved_permanently | `Found | `See_other | `Not_modified | `Use_proxy | `Temporary_redirect ] * The ( Redirection ) class of status code indicates that further action needs to be taken by the user agent in order to fulfill the request . See { { : #section-6.4 } RFC7231§6.4 } for more details . action needs to be taken by the user agent in order to fulfill the request. See {{:#section-6.4} RFC7231§6.4} for more details. *) type client_error = [ | `Bad_request | `Unauthorized | `Payment_required | `Forbidden | `Not_found | `Method_not_allowed | `Not_acceptable | `Proxy_authentication_required | `Request_timeout | `Conflict | `Gone | `Length_required | `Precondition_failed | `Request_entity_too_large | `Request_uri_too_long | `Unsupported_media_type | `Requested_range_not_satisfiable | `Expectation_failed | `Upgrade_required | `I_m_a_teapot | `Enhance_your_calm ] * The 4xx ( Client Error ) class of status code indicates that the client seems to have erred . See { { : } RFC7231§6.5 } for more details . seems to have erred. See {{:#section-6.5} RFC7231§6.5} for more details. *) type server_error = [ | `Internal_server_error | `Not_implemented | `Bad_gateway | `Service_unavailable | `Gateway_timeout | `Http_version_not_supported ] * The 5xx ( Server Error ) class of status code indicates that the server is aware that it has erred or is incapable of performing the requested method . See { { : #section-6.6 } RFC7231§6.6 } for more details . aware that it has erred or is incapable of performing the requested method. See {{:#section-6.6} RFC7231§6.6} for more details. *) type standard = [ | informational | successful | redirection | client_error | server_error ] * The status codes defined in the HTTP 1.1 RFCs type t = [ | standard | `Code of int ] (** The standard codes along with support for custom codes. *) val default_reason_phrase : standard -> string * [ default_reason_phrase standard ] is the example reason phrase provided by for the [ standard ] status code . The RFC allows servers to use reason phrases besides these in responses . by RFC7231 for the [standard] status code. The RFC allows servers to use reason phrases besides these in responses. *) val to_code : t -> int (** [to_code t] is the integer representation of [t]. *) val of_code : int -> t * [ of_code i ] is the [ t ] representation of [ i ] . [ of_code ] raises [ Failure ] if [ i ] is not a positive three - digit number . if [i] is not a positive three-digit number. *) val unsafe_of_code : int -> t (** [unsafe_of_code i] is equivalent to [of_code i], except it accepts any positive code, regardless of the number of digits it has. On negative codes, it will still raise [Failure]. *) val is_informational : t -> bool (** [is_informational t] is true iff [t] belongs to the Informational class of status codes. *) val is_successful : t -> bool (** [is_successful t] is true iff [t] belongs to the Successful class of status codes. *) val is_redirection : t -> bool * [ is_redirection t ] is true iff [ t ] belongs to the Redirection class of status codes . status codes. *) val is_client_error : t -> bool (** [is_client_error t] is true iff [t] belongs to the Client Error class of status codes. *) val is_server_error : t -> bool (** [is_server_error t] is true iff [t] belongs to the Server Error class of status codes. *) val is_error : t -> bool (** [is_server_error t] is true iff [t] belongs to the Client Error or Server Error class of status codes. *) val to_string : t -> string val of_string : string -> t val pp_hum : Format.formatter -> t -> unit end * Header Each header field consists of a case - insensitive { b field name } and a { b field value } . The order in which header fields { i with differing field names } are received is not significant . However , it is good practice to send header fields that contain control data first so that implementations can decide when not to handle a message as early as possible . A sender MUST NOT generate multiple header fields with the same field name in a message unless either the entire field value for that header field is defined as a comma - separated list or the header field is a well - known exception , e.g. , [ Set - Cookie ] . A recipient combine multiple header fields with the same field name into one " field - name : field - value " pair , without changing the semantics of the message , by appending each subsequent field value to the combined field value in order , separated by a comma . { i The order in which header fields with the same field name are received is therefore significant to the interpretation of the combined field value } ; a proxy MUST NOT change the order of these field values when forwarding a message . { i Note . } Unless otherwise specified , all operations preserve header field order and all reference to equality on names is assumed to be case - insensitive . See { { : #section-3.2 } RFC7230§3.2 } for more details . Each header field consists of a case-insensitive {b field name} and a {b field value}. The order in which header fields {i with differing field names} are received is not significant. However, it is good practice to send header fields that contain control data first so that implementations can decide when not to handle a message as early as possible. A sender MUST NOT generate multiple header fields with the same field name in a message unless either the entire field value for that header field is defined as a comma-separated list or the header field is a well-known exception, e.g., [Set-Cookie]. A recipient MAY combine multiple header fields with the same field name into one "field-name: field-value" pair, without changing the semantics of the message, by appending each subsequent field value to the combined field value in order, separated by a comma. {i The order in which header fields with the same field name are received is therefore significant to the interpretation of the combined field value}; a proxy MUST NOT change the order of these field values when forwarding a message. {i Note.} Unless otherwise specified, all operations preserve header field order and all reference to equality on names is assumed to be case-insensitive. See {{:#section-3.2} RFC7230§3.2} for more details. *) module Headers : sig type t type name = string (** The type of a case-insensitive header name. *) type value = string (** The type of a header value. *) (** {3 Constructor} *) val empty : t (** [empty] is the empty collection of header fields. *) val of_list : (name * value) list -> t (** [of_list assoc] is a collection of header fields defined by the association list [assoc]. [of_list] assumes the order of header fields in [assoc] is the intended transmission order. The following equations should hold: {ul {- [to_list (of_list lst) = lst] } {- [get (of_list [("k", "v1"); ("k", "v2")]) "k" = Some "v2"]. }} *) val of_rev_list : (name * value) list -> t (** [of_list assoc] is a collection of header fields defined by the association list [assoc]. [of_list] assumes the order of header fields in [assoc] is the {i reverse} of the intended trasmission order. The following equations should hold: {ul {- [to_list (of__rev_list lst) = List.rev lst] } {- [get (of_list [("k", "v1"); ("k", "v2")]) "k" = Some "v1"]. }} *) val to_list : t -> (name * value) list (** [to_list t] is the assocition list of header fields contained in [t] in transmission order. *) val to_rev_list : t -> (name * value) list (** [to_rev_list t] is the association list of header fields contained in [t] in {i reverse} transmission order. *) val add : t -> name -> value -> t (** [add t name value] is a collection of header fields that is the same as [t] except with [(name, value)] added at the beginning of the trasmission order. The following equations should hold: {ul {- [get (add t name value) name = Some value] }} *) val add_unless_exists : t -> name -> value -> t (** [add_unless_exists t name value] is a collection of header fields that is the same as [t] if [t] already inclues [name], and otherwise is equivalent to [add t name value]. *) val add_list : t -> (name * value) list -> t (** [add_list t assoc] is a collection of header fields that is the same as [t] except with all the header fields in [assoc] added to the beginning of the transmission order. *) val add_multi : t -> (name * value list) list -> t (** [add_multi t headers] *) val remove : t -> name -> t (** [remove t name] is a collection of header fields that contains all the header fields of [t] except those that have a header-field name that are equal to [name]. If [t] contains multiple header fields whose name is [name], they will all be removed. *) val replace : t -> name -> value -> t (** {3 Destructors} *) val mem : t -> name -> bool (** [mem t name] is true iff [t] includes a header field with a name that is equal to [name]. *) val get : t -> name -> value option val get_multi : t -> name -> value list * { 3 Iteration } val iter : f:(name -> value -> unit) -> t -> unit val fold : f:(name -> value -> 'a -> 'a) -> init:'a -> t -> 'a * { 3 Utilities } val to_string : t -> string val pp_hum : Format.formatter -> t -> unit end * { 2 Message Types } (** Request A client-initiated HTTP message. *) module Request : sig type t = { meth : Method.t ; target : string ; version : Version.t ; headers : Headers.t } val create * default is HTTP 1.1 -> ?headers:Headers.t (** default is {!Headers.empty} *) -> Method.t -> string -> t val body_length : t -> [ | `Fixed of Int64.t | `Chunked | `Error of [`Bad_request] ] * [ t ] is the length of the message body accompanying [ t ] . It is an error to generate a request with a close - delimited message body . See { { : #section-3.3.3 } RFC7230§3.3.3 } for more details . an error to generate a request with a close-delimited message body. See {{:#section-3.3.3} RFC7230§3.3.3} for more details. *) val persistent_connection : ?proxy:bool -> t -> bool * [ persistent_connection ? proxy t ] indicates whether the connection for [ t ] can be reused for multiple requests and responses . If the calling code is acting as a proxy , it should pass [ ~proxy : true ] . See { { : #section-6.3 } RFC7230§6.3 for more details . can be reused for multiple requests and responses. If the calling code is acting as a proxy, it should pass [~proxy:true]. See {{:#section-6.3} RFC7230§6.3 for more details. *) val pp_hum : Format.formatter -> t -> unit end (** Response A server-generated message to a {Request}. *) module Response : sig type t = { version : Version.t ; status : Status.t ; reason : string ; headers : Headers.t } val create : ?reason:string (** default is determined by {!Status.default_reason_phrase} *) * default is HTTP 1.1 -> ?headers:Headers.t (** default is {!Headers.empty} *) -> Status.t -> t val body_length : ?proxy:bool -> request_method:Method.standard -> t -> [ | `Fixed of Int64.t | `Chunked | `Close_delimited | `Error of [`Bad_request | `Bad_gateway | `Internal_server_error ] ] * [ ? proxy ~request_method t ] is the length of the message body accompanying [ t ] assuming it is a response to a request whose method was [ request_method ] . If the calling code is acting as a proxy , it should pass [ ~proxy : true ] . This optional parameter only affects error reporting . See { { : #section-3.3.3 } RFC7230§3.3.3 } for more details . accompanying [t] assuming it is a response to a request whose method was [request_method]. If the calling code is acting as a proxy, it should pass [~proxy:true]. This optional parameter only affects error reporting. See {{:#section-3.3.3} RFC7230§3.3.3} for more details. *) val persistent_connection : ?proxy:bool -> t -> bool * [ persistent_connection ? proxy t ] indicates whether the connection for [ t ] can be reused for multiple requests and responses . If the calling code is acting as a proxy , it should pass [ ~proxy : true ] . See { { : #section-6.3 } RFC7230§6.3 for more details . can be reused for multiple requests and responses. If the calling code is acting as a proxy, it should pass [~proxy:true]. See {{:#section-6.3} RFC7230§6.3 for more details. *) val pp_hum : Format.formatter -> t -> unit end module Bigstring : sig type t = (char, Bigarray.int8_unsigned_elt, Bigarray.c_layout) Bigarray.Array1.t val create : int -> t val of_string : ?off:int -> ?len:int -> string -> t val length : t -> int val get : t -> int -> char val unsafe_get : t -> int -> char val set : t -> int -> char -> unit val unsafe_set : t -> int -> char -> unit val sub : off:int -> ?len:int -> t -> t val copy : ?off:int -> ?len:int -> t -> string val blit : t -> int -> t -> int -> int -> unit val blit_from_string : string -> int -> t -> int -> int -> unit val blit_from_bytes : Bytes.t -> int -> t -> int -> int -> unit end * module IOVec : sig type buffer = [ `String of string | `Bytes of Bytes.t | `Bigstring of Bigstring.t ] as 'a constraint 'a = Faraday.buffer type 'a t = 'a Faraday.iovec = { buffer : 'a ; off : int ; len : int } val length : _ t -> int val lengthv : _ t list -> int val shift : 'a t -> int -> 'a t val shiftv : 'a t list -> int -> 'a t list end (** Message Body *) module Body : sig type 'mode t module R : sig type phantom type nonrec t = phantom t end module W : sig type phantom type nonrec t = phantom t end val write_string : W.t -> ?off:int -> ?len:int -> string -> unit (** [write_string w ?off ?len str] copies [str] into an internal buffer. If possible, this write will be combined with previous and/or subsequent writes before transmission. *) val write_bigstring : W.t -> ?off:int -> ?len:int -> Bigstring.t -> unit (** [write_bigstring w ?off ?len bs] copies [bs] into an internal buffer. If possible, this write will be combined with previous and/or subsequent writes before transmission. *) val schedule_string : W.t -> ?off:int -> ?len:int -> string -> unit (** [schedule_string w ?off ?len str] schedules [str] to be transmitted at the next opportunity, without performing a copy. *) val schedule_bigstring : W.t -> ?off:int -> ?len:int -> Bigstring.t -> unit (** [schedule_bigstring w ?off ?len bs] schedules [bs] to be transmitted at the next opportunity without performing a copy. [bs] should not be modified until a subsequent call to {!flush} has successfully completed. *) val flush : W.t -> (unit -> unit) -> unit (** [flush t f] *) val schedule_read : R.t -> readv:(IOVec.buffer IOVec.t list -> 'a * int) -> result:([`Eof | `Ok of 'a] -> unit) -> unit * [ schedule_read r ~readv ] val close : _ t -> unit (** [close t] closes [t], causing subsequent read or write calls to raise. *) val is_closed : _ t -> bool (** [is_closed t] is true if {close} has been called on [t] and [false] otherwise. A closed [t] may still have pending output. *) end module Connection : sig module Config : sig type t = * Default is [ 4096 ] * Default is [ 4096 ] } val default : t (** [default] is a configuration record with all parameters set to their default values. *) end type t type handler = Request.t -> Body.R.t -> (Response.t -> Body.W.t) -> unit val create : ?config:Config.t -> handler -> t (** [create ?config handler] creates a connection handler that will service individual requests with [handler]. *) val next_read_operation : t -> [ | `Read of Bigstring.t | `Yield | `Close of (unit, [Status.t | `Parse of string list * string]) result ] val report_read_result : t -> [`Ok of int | `Eof] -> unit val yield_reader : t -> (unit -> unit) -> unit val next_write_operation : t -> [ | `Write of IOVec.buffer IOVec.t list | `Yield | `Close of int ] val report_write_result : t -> [`Ok of int | `Closed] -> unit val yield_writer : t -> (unit -> unit) -> unit val shutdown_reader : t -> unit val shutdown : t -> unit val state : t -> [ `Running | `Closed_input | `Closed ] (** [state t] is the state of the connection's input and output processors. A connection's input processor may be closed while it's output processor is still running (corresponding to the [`Closed_input] state), but the output processor can never be closed while in the input processor is open. *) end
null
https://raw.githubusercontent.com/kayceesrk/httpaf/791593e0f576a54a6eb37534abde2df60a8370e8/lib/httpaf.mli
ocaml
* Protocol Version HTTP uses a "<major>.<minor>" numbering scheme to indicate versions of the protocol. The protocol version as a whole indicates the sender's conformance with the set of requirements laid out in that version's corresponding specification of HTTP. See {{:#section-2.6} RFC7230§2.6} for more details. * The major protocol number. * The minor protocol number. * Request Method The request method token is the primary source of request semantics; it indicates the purpose for which the client has made this request and what is expected by the client as a successful result. See {{:#section-4} RFC7231§4} for more detials. * {{:#section-4.3.4} RFC7231§4.3.4}. Idempotent. * {{:#section-4.3.5} RFC7231§4.3.5}. Idempotent. * {{:#section-4.3.6} RFC7231§4.3.6}. * {{:#section-4.3.7} RFC7231§4.3.7}. Safe. * {{:#section-4.3.8} RFC7231§4.3.8}. Safe. * Request methods are considered "safe" if their defined semantics are essentially read-only; i.e., the client does not request, and does not expect, any state change on the origin server as a result of applying a safe method to a target resource. Likewise, reasonable use of a safe method is not expected to cause any harm, loss of property, or unusual burden on the origin server. See {{:#section-4.2.1} RFC7231§4.2.1} for more details. * The standard codes along with support for custom codes. * [to_code t] is the integer representation of [t]. * [unsafe_of_code i] is equivalent to [of_code i], except it accepts any positive code, regardless of the number of digits it has. On negative codes, it will still raise [Failure]. * [is_informational t] is true iff [t] belongs to the Informational class of status codes. * [is_successful t] is true iff [t] belongs to the Successful class of status codes. * [is_client_error t] is true iff [t] belongs to the Client Error class of status codes. * [is_server_error t] is true iff [t] belongs to the Server Error class of status codes. * [is_server_error t] is true iff [t] belongs to the Client Error or Server Error class of status codes. * The type of a case-insensitive header name. * The type of a header value. * {3 Constructor} * [empty] is the empty collection of header fields. * [of_list assoc] is a collection of header fields defined by the association list [assoc]. [of_list] assumes the order of header fields in [assoc] is the intended transmission order. The following equations should hold: {ul {- [to_list (of_list lst) = lst] } {- [get (of_list [("k", "v1"); ("k", "v2")]) "k" = Some "v2"]. }} * [of_list assoc] is a collection of header fields defined by the association list [assoc]. [of_list] assumes the order of header fields in [assoc] is the {i reverse} of the intended trasmission order. The following equations should hold: {ul {- [to_list (of__rev_list lst) = List.rev lst] } {- [get (of_list [("k", "v1"); ("k", "v2")]) "k" = Some "v1"]. }} * [to_list t] is the assocition list of header fields contained in [t] in transmission order. * [to_rev_list t] is the association list of header fields contained in [t] in {i reverse} transmission order. * [add t name value] is a collection of header fields that is the same as [t] except with [(name, value)] added at the beginning of the trasmission order. The following equations should hold: {ul {- [get (add t name value) name = Some value] }} * [add_unless_exists t name value] is a collection of header fields that is the same as [t] if [t] already inclues [name], and otherwise is equivalent to [add t name value]. * [add_list t assoc] is a collection of header fields that is the same as [t] except with all the header fields in [assoc] added to the beginning of the transmission order. * [add_multi t headers] * [remove t name] is a collection of header fields that contains all the header fields of [t] except those that have a header-field name that are equal to [name]. If [t] contains multiple header fields whose name is [name], they will all be removed. * {3 Destructors} * [mem t name] is true iff [t] includes a header field with a name that is equal to [name]. * Request A client-initiated HTTP message. * default is {!Headers.empty} * Response A server-generated message to a {Request}. * default is determined by {!Status.default_reason_phrase} * default is {!Headers.empty} * Message Body * [write_string w ?off ?len str] copies [str] into an internal buffer. If possible, this write will be combined with previous and/or subsequent writes before transmission. * [write_bigstring w ?off ?len bs] copies [bs] into an internal buffer. If possible, this write will be combined with previous and/or subsequent writes before transmission. * [schedule_string w ?off ?len str] schedules [str] to be transmitted at the next opportunity, without performing a copy. * [schedule_bigstring w ?off ?len bs] schedules [bs] to be transmitted at the next opportunity without performing a copy. [bs] should not be modified until a subsequent call to {!flush} has successfully completed. * [flush t f] * [close t] closes [t], causing subsequent read or write calls to raise. * [is_closed t] is true if {close} has been called on [t] and [false] otherwise. A closed [t] may still have pending output. * [default] is a configuration record with all parameters set to their default values. * [create ?config handler] creates a connection handler that will service individual requests with [handler]. * [state t] is the state of the connection's input and output processors. A connection's input processor may be closed while it's output processor is still running (corresponding to the [`Closed_input] state), but the output processor can never be closed while in the input processor is open.
---------------------------------------------------------------------------- Copyright ( c ) 2016 Inhabited Type LLC . All rights reserved . Redistribution and use in source and binary forms , with or without modification , are permitted provided that the following conditions are met : 1 . Redistributions of source code must retain the above copyright notice , this list of conditions and the following disclaimer . 2 . Redistributions in binary form must reproduce the above copyright notice , this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution . 3 . Neither the name of the author nor the names of his contributors may be used to endorse or promote products derived from this software without specific prior written permission . THIS SOFTWARE IS PROVIDED BY THE CONTRIBUTORS ` ` AS IS '' AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT LIMITED TO , THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED . IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE , DATA , OR PROFITS ; OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING NEGLIGENCE OR OTHERWISE ) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE , EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE . ---------------------------------------------------------------------------- Copyright (c) 2016 Inhabited Type LLC. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the author nor the names of his contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ----------------------------------------------------------------------------*) * Http / af is a high - performance , memory - efficient , and scalable web server for OCaml . It implements the HTTP 1.1 specification with respect to parsing , serialization , and connection pipelining . For compatibility , http / af respects the imperatives of the [ Connection ] header when handling HTTP 1.0 connections . To use this library effectively , the user must be familiar with the HTTP 1.1 specification , and the basic principles of memory management and vectorized IO . for OCaml. It implements the HTTP 1.1 specification with respect to parsing, serialization, and connection pipelining. For compatibility, http/af respects the imperatives of the [Connection] header when handling HTTP 1.0 connections. To use this library effectively, the user must be familiar with the HTTP 1.1 specification, and the basic principles of memory management and vectorized IO. *) open Result * { 2 Basic HTTP Types } module Version : sig type t = } val compare : t -> t -> int val to_string : t -> string val of_string : string -> t val pp_hum : Format.formatter -> t -> unit end module Method : sig type standard = [ | `GET * { { : #section-4.3.1 } RFC7231§4.3.1 } . Safe , Cacheable . | `HEAD * { { : #section-4.3.2 } RFC7231§4.3.2 } . Safe , Cacheable . | `POST * { { : #section-4.3.3 } RFC7231§4.3.3 } . Cacheable . | `PUT | `DELETE | `CONNECT | `OPTIONS | `TRACE ] type t = [ | standard | `Other of string * Methods defined outside of RFC7231 , or custom methods . ] val is_safe : standard -> bool val is_cacheable : standard -> bool * Request methods can be defined as " cacheable " to indicate that responses to them are allowed to be stored for future reuse . See { { : } } for more details . to them are allowed to be stored for future reuse. See {{:} RFC7234} for more details. *) val is_idempotent : standard -> bool * A request method is considered " idempotent " if the intended effect on the server of multiple identical requests with that method is the same as the effect for a single such request . Of the request methods defined by this specification , PUT , DELETE , and safe request methods are idempotent . See { { : #section-4.2.2 } RFC7231§4.2.2 } for more details . the server of multiple identical requests with that method is the same as the effect for a single such request. Of the request methods defined by this specification, PUT, DELETE, and safe request methods are idempotent. See {{:#section-4.2.2} RFC7231§4.2.2} for more details. *) val to_string : t -> string val of_string : string -> t val pp_hum : Format.formatter -> t -> unit end * Response Status Codes The status - code element is a three - digit integer code giving the result of the attempt to understand and satisfy the request . See { { : #section-6 } RFC7231§6 } for more details . The status-code element is a three-digit integer code giving the result of the attempt to understand and satisfy the request. See {{:#section-6} RFC7231§6} for more details. *) module Status : sig type informational = [ | `Continue | `Switching_protocols ] * The 1xx ( Informational ) class of status code indicates an interim response for communicating connection status or request progress prior to completing the requested action and sending a final response . See { { : #section-6.2 } RFC7231§6.2 } for more details . response for communicating connection status or request progress prior to completing the requested action and sending a final response. See {{:#section-6.2} RFC7231§6.2} for more details. *) type successful = [ | `OK | `Created | `Accepted | `Non_authoritative_information | `No_content | `Reset_content | `Partial_content ] * The 2xx ( Successful ) class of status code indicates that the client 's request was successfully received , understood , and accepted . See { { : #section-6.3 } RFC7231§6.3 } for more details . request was successfully received, understood, and accepted. See {{:#section-6.3} RFC7231§6.3} for more details. *) type redirection = [ | `Multiple_choices | `Moved_permanently | `Found | `See_other | `Not_modified | `Use_proxy | `Temporary_redirect ] * The ( Redirection ) class of status code indicates that further action needs to be taken by the user agent in order to fulfill the request . See { { : #section-6.4 } RFC7231§6.4 } for more details . action needs to be taken by the user agent in order to fulfill the request. See {{:#section-6.4} RFC7231§6.4} for more details. *) type client_error = [ | `Bad_request | `Unauthorized | `Payment_required | `Forbidden | `Not_found | `Method_not_allowed | `Not_acceptable | `Proxy_authentication_required | `Request_timeout | `Conflict | `Gone | `Length_required | `Precondition_failed | `Request_entity_too_large | `Request_uri_too_long | `Unsupported_media_type | `Requested_range_not_satisfiable | `Expectation_failed | `Upgrade_required | `I_m_a_teapot | `Enhance_your_calm ] * The 4xx ( Client Error ) class of status code indicates that the client seems to have erred . See { { : } RFC7231§6.5 } for more details . seems to have erred. See {{:#section-6.5} RFC7231§6.5} for more details. *) type server_error = [ | `Internal_server_error | `Not_implemented | `Bad_gateway | `Service_unavailable | `Gateway_timeout | `Http_version_not_supported ] * The 5xx ( Server Error ) class of status code indicates that the server is aware that it has erred or is incapable of performing the requested method . See { { : #section-6.6 } RFC7231§6.6 } for more details . aware that it has erred or is incapable of performing the requested method. See {{:#section-6.6} RFC7231§6.6} for more details. *) type standard = [ | informational | successful | redirection | client_error | server_error ] * The status codes defined in the HTTP 1.1 RFCs type t = [ | standard | `Code of int ] val default_reason_phrase : standard -> string * [ default_reason_phrase standard ] is the example reason phrase provided by for the [ standard ] status code . The RFC allows servers to use reason phrases besides these in responses . by RFC7231 for the [standard] status code. The RFC allows servers to use reason phrases besides these in responses. *) val to_code : t -> int val of_code : int -> t * [ of_code i ] is the [ t ] representation of [ i ] . [ of_code ] raises [ Failure ] if [ i ] is not a positive three - digit number . if [i] is not a positive three-digit number. *) val unsafe_of_code : int -> t val is_informational : t -> bool val is_successful : t -> bool val is_redirection : t -> bool * [ is_redirection t ] is true iff [ t ] belongs to the Redirection class of status codes . status codes. *) val is_client_error : t -> bool val is_server_error : t -> bool val is_error : t -> bool val to_string : t -> string val of_string : string -> t val pp_hum : Format.formatter -> t -> unit end * Header Each header field consists of a case - insensitive { b field name } and a { b field value } . The order in which header fields { i with differing field names } are received is not significant . However , it is good practice to send header fields that contain control data first so that implementations can decide when not to handle a message as early as possible . A sender MUST NOT generate multiple header fields with the same field name in a message unless either the entire field value for that header field is defined as a comma - separated list or the header field is a well - known exception , e.g. , [ Set - Cookie ] . A recipient combine multiple header fields with the same field name into one " field - name : field - value " pair , without changing the semantics of the message , by appending each subsequent field value to the combined field value in order , separated by a comma . { i The order in which header fields with the same field name are received is therefore significant to the interpretation of the combined field value } ; a proxy MUST NOT change the order of these field values when forwarding a message . { i Note . } Unless otherwise specified , all operations preserve header field order and all reference to equality on names is assumed to be case - insensitive . See { { : #section-3.2 } RFC7230§3.2 } for more details . Each header field consists of a case-insensitive {b field name} and a {b field value}. The order in which header fields {i with differing field names} are received is not significant. However, it is good practice to send header fields that contain control data first so that implementations can decide when not to handle a message as early as possible. A sender MUST NOT generate multiple header fields with the same field name in a message unless either the entire field value for that header field is defined as a comma-separated list or the header field is a well-known exception, e.g., [Set-Cookie]. A recipient MAY combine multiple header fields with the same field name into one "field-name: field-value" pair, without changing the semantics of the message, by appending each subsequent field value to the combined field value in order, separated by a comma. {i The order in which header fields with the same field name are received is therefore significant to the interpretation of the combined field value}; a proxy MUST NOT change the order of these field values when forwarding a message. {i Note.} Unless otherwise specified, all operations preserve header field order and all reference to equality on names is assumed to be case-insensitive. See {{:#section-3.2} RFC7230§3.2} for more details. *) module Headers : sig type t type name = string type value = string val empty : t val of_list : (name * value) list -> t val of_rev_list : (name * value) list -> t val to_list : t -> (name * value) list val to_rev_list : t -> (name * value) list val add : t -> name -> value -> t val add_unless_exists : t -> name -> value -> t val add_list : t -> (name * value) list -> t val add_multi : t -> (name * value list) list -> t val remove : t -> name -> t val replace : t -> name -> value -> t val mem : t -> name -> bool val get : t -> name -> value option val get_multi : t -> name -> value list * { 3 Iteration } val iter : f:(name -> value -> unit) -> t -> unit val fold : f:(name -> value -> 'a -> 'a) -> init:'a -> t -> 'a * { 3 Utilities } val to_string : t -> string val pp_hum : Format.formatter -> t -> unit end * { 2 Message Types } module Request : sig type t = { meth : Method.t ; target : string ; version : Version.t ; headers : Headers.t } val create * default is HTTP 1.1 -> Method.t -> string -> t val body_length : t -> [ | `Fixed of Int64.t | `Chunked | `Error of [`Bad_request] ] * [ t ] is the length of the message body accompanying [ t ] . It is an error to generate a request with a close - delimited message body . See { { : #section-3.3.3 } RFC7230§3.3.3 } for more details . an error to generate a request with a close-delimited message body. See {{:#section-3.3.3} RFC7230§3.3.3} for more details. *) val persistent_connection : ?proxy:bool -> t -> bool * [ persistent_connection ? proxy t ] indicates whether the connection for [ t ] can be reused for multiple requests and responses . If the calling code is acting as a proxy , it should pass [ ~proxy : true ] . See { { : #section-6.3 } RFC7230§6.3 for more details . can be reused for multiple requests and responses. If the calling code is acting as a proxy, it should pass [~proxy:true]. See {{:#section-6.3} RFC7230§6.3 for more details. *) val pp_hum : Format.formatter -> t -> unit end module Response : sig type t = { version : Version.t ; status : Status.t ; reason : string ; headers : Headers.t } val create * default is HTTP 1.1 -> Status.t -> t val body_length : ?proxy:bool -> request_method:Method.standard -> t -> [ | `Fixed of Int64.t | `Chunked | `Close_delimited | `Error of [`Bad_request | `Bad_gateway | `Internal_server_error ] ] * [ ? proxy ~request_method t ] is the length of the message body accompanying [ t ] assuming it is a response to a request whose method was [ request_method ] . If the calling code is acting as a proxy , it should pass [ ~proxy : true ] . This optional parameter only affects error reporting . See { { : #section-3.3.3 } RFC7230§3.3.3 } for more details . accompanying [t] assuming it is a response to a request whose method was [request_method]. If the calling code is acting as a proxy, it should pass [~proxy:true]. This optional parameter only affects error reporting. See {{:#section-3.3.3} RFC7230§3.3.3} for more details. *) val persistent_connection : ?proxy:bool -> t -> bool * [ persistent_connection ? proxy t ] indicates whether the connection for [ t ] can be reused for multiple requests and responses . If the calling code is acting as a proxy , it should pass [ ~proxy : true ] . See { { : #section-6.3 } RFC7230§6.3 for more details . can be reused for multiple requests and responses. If the calling code is acting as a proxy, it should pass [~proxy:true]. See {{:#section-6.3} RFC7230§6.3 for more details. *) val pp_hum : Format.formatter -> t -> unit end module Bigstring : sig type t = (char, Bigarray.int8_unsigned_elt, Bigarray.c_layout) Bigarray.Array1.t val create : int -> t val of_string : ?off:int -> ?len:int -> string -> t val length : t -> int val get : t -> int -> char val unsafe_get : t -> int -> char val set : t -> int -> char -> unit val unsafe_set : t -> int -> char -> unit val sub : off:int -> ?len:int -> t -> t val copy : ?off:int -> ?len:int -> t -> string val blit : t -> int -> t -> int -> int -> unit val blit_from_string : string -> int -> t -> int -> int -> unit val blit_from_bytes : Bytes.t -> int -> t -> int -> int -> unit end * module IOVec : sig type buffer = [ `String of string | `Bytes of Bytes.t | `Bigstring of Bigstring.t ] as 'a constraint 'a = Faraday.buffer type 'a t = 'a Faraday.iovec = { buffer : 'a ; off : int ; len : int } val length : _ t -> int val lengthv : _ t list -> int val shift : 'a t -> int -> 'a t val shiftv : 'a t list -> int -> 'a t list end module Body : sig type 'mode t module R : sig type phantom type nonrec t = phantom t end module W : sig type phantom type nonrec t = phantom t end val write_string : W.t -> ?off:int -> ?len:int -> string -> unit val write_bigstring : W.t -> ?off:int -> ?len:int -> Bigstring.t -> unit val schedule_string : W.t -> ?off:int -> ?len:int -> string -> unit val schedule_bigstring : W.t -> ?off:int -> ?len:int -> Bigstring.t -> unit val flush : W.t -> (unit -> unit) -> unit val schedule_read : R.t -> readv:(IOVec.buffer IOVec.t list -> 'a * int) -> result:([`Eof | `Ok of 'a] -> unit) -> unit * [ schedule_read r ~readv ] val close : _ t -> unit val is_closed : _ t -> bool end module Connection : sig module Config : sig type t = * Default is [ 4096 ] * Default is [ 4096 ] } val default : t end type t type handler = Request.t -> Body.R.t -> (Response.t -> Body.W.t) -> unit val create : ?config:Config.t -> handler -> t val next_read_operation : t -> [ | `Read of Bigstring.t | `Yield | `Close of (unit, [Status.t | `Parse of string list * string]) result ] val report_read_result : t -> [`Ok of int | `Eof] -> unit val yield_reader : t -> (unit -> unit) -> unit val next_write_operation : t -> [ | `Write of IOVec.buffer IOVec.t list | `Yield | `Close of int ] val report_write_result : t -> [`Ok of int | `Closed] -> unit val yield_writer : t -> (unit -> unit) -> unit val shutdown_reader : t -> unit val shutdown : t -> unit val state : t -> [ `Running | `Closed_input | `Closed ] end
036c1945824226c988d1413100edb230d715c925569eb5df71d57981bb95ff34
discus-lang/salt
Pretty.hs
module Salt.Core.Codec.Text.Pretty ( module Salt.Core.Codec.Text.Pretty.Base , module Salt.Core.Codec.Text.Pretty.Term , module Salt.Core.Codec.Text.Pretty.Type , module Salt.Data.Pretty) where import Salt.Core.Codec.Text.Pretty.Base import Salt.Core.Codec.Text.Pretty.Term import Salt.Core.Codec.Text.Pretty.Type import Salt.Data.Pretty
null
https://raw.githubusercontent.com/discus-lang/salt/33c14414ac7e238fdbd8161971b8b8ac67fff569/src/salt/Salt/Core/Codec/Text/Pretty.hs
haskell
module Salt.Core.Codec.Text.Pretty ( module Salt.Core.Codec.Text.Pretty.Base , module Salt.Core.Codec.Text.Pretty.Term , module Salt.Core.Codec.Text.Pretty.Type , module Salt.Data.Pretty) where import Salt.Core.Codec.Text.Pretty.Base import Salt.Core.Codec.Text.Pretty.Term import Salt.Core.Codec.Text.Pretty.Type import Salt.Data.Pretty
8f04c0d04321c06fe90a902a14d11586b049e66bf77b5c2522663ba6792238f1
Operational-Transformation/ot.hs
ClientServerTests.hs
# LANGUAGE MultiParamTypeClasses , FlexibleInstances , BangPatterns # module Control.OperationalTransformation.ClientServerTests ( tests ) where import Control.OperationalTransformation import Control.OperationalTransformation.Client import Control.OperationalTransformation.Server import Data.Maybe (fromJust) import Control.OperationalTransformation.Text.Gen (genOperation) import Test.Framework import Test.Framework.Providers.QuickCheck2 import Test.QuickCheck hiding (reason) import Test.QuickCheck.Property type Queue a = [a] emptyQueue :: Queue a emptyQueue = [] appendQueue :: a -> Queue a -> Queue a appendQueue a q = q ++ [a] type ClientId = Int data ExtendedClient doc op = ExtendedClient { clientId :: !ClientId , clientRevision :: !Revision , clientSendQueue :: Queue (Revision, op) , clientReceiveQueue :: Queue (Maybe op) , clientDoc :: !doc , clientState :: !(ClientState op) } deriving (Show) prop_client_server :: (Eq doc, Arbitrary doc, OTSystem doc op, OTComposableOperation op) => (doc -> Gen op) -> Property prop_client_server genOp = property $ do doc <- arbitrary let server = initialServerState doc clients = createClients doc $ take numClients [1..] (server', clients') <- simulate numActions server clients return $ if not (all isSynchronized clients') then property $ failed { reason = "some clients are not synchronized" } else let ServerState _ doc' _ = server' in if all ((== doc') . clientDoc) clients' then property True else property $ failed { reason = "client documents did not converge" } where numClients, numActions :: Int numClients = 2 numActions = 100 firstRevision = 0 createClients doc = map $ \n -> ExtendedClient { clientId = n , clientRevision = firstRevision , clientSendQueue = emptyQueue , clientReceiveQueue = emptyQueue , clientDoc = doc , clientState = initialClientState } simulate !n !server !clients = do clientN <- choose (0, length clients - 1) actionN <- choose (0, 2) :: Gen Int let client = clients !! clientN (server', clients') <- case actionN of 0 | canReceive client -> do let client' = receiveClient client return (server, replace clientN client' clients) 1 | canSend client -> do let ((rev, op), client') = sendClient client Right (op', (), server') = applyOperation server rev op () clients' = replace clientN client' clients clients'' = broadcast (clientId client) op' clients' return (server', clients'') _ | n < 0 -> return (server, clients) | otherwise -> do client' <- editClient client return (server, replace clientN client' clients) if n > 0 || any (\c -> canReceive c || canSend c) clients' then simulate (n-1) server' clients' else return (server', clients') replace 0 e (_:xs) = e:xs replace n e (x:xs) = x:(replace (n-1) e xs) replace _ _ [] = error "replacing empty list" canReceive = not . null . clientReceiveQueue canSend = not . null . clientSendQueue receiveClient client = case clientReceiveQueue client of [] -> error "empty receive queue" msg:ops -> let client' = client { clientReceiveQueue = ops , clientRevision = clientRevision client + 1 } in case msg of Nothing -> case fromJust $ serverAck (clientState client') of (Just op, clientState') -> client' { clientState = clientState' , clientSendQueue = appendQueue (clientRevision client', op) (clientSendQueue client') } (Nothing, clientState') -> client' { clientState = clientState' } Just op -> case applyServer (clientState client) op of Left err -> error $ "should not happen: " ++ err Right (op', clientState') -> case apply op' (clientDoc client') of Left err -> error $ "apply failed: " ++ err Right doc' -> client' { clientState = clientState', clientDoc = doc' } sendClient client = case clientSendQueue client of [] -> error "empty send queue" op:ops -> (op, client { clientSendQueue = ops }) editClient client = do op <- genOp $ clientDoc client let doc' = fromRight $ apply op $ clientDoc client (shouldSend, state') = fromRight $ applyClient (clientState client) op client' = client { clientState = state', clientDoc = doc' } return $ if shouldSend then client' { clientSendQueue = appendQueue (clientRevision client', op) (clientSendQueue client) } else client' fromRight (Right a) = a fromRight (Left err) = error err broadcast creator op = map $ \client -> let msg = if creator == clientId client then Nothing else Just op in client { clientReceiveQueue = appendQueue msg (clientReceiveQueue client) } isSynchronized client = case clientState client of ClientSynchronized -> True _ -> False tests :: Test tests = testGroup "Control.OperationalTransformation.ClientServerTests" [ testProperty "prop_client_server" $ prop_client_server genOperation ]
null
https://raw.githubusercontent.com/Operational-Transformation/ot.hs/4a0ca8f1e3f59fd8ce0e6cfd95633940d4e22f88/test/Control/OperationalTransformation/ClientServerTests.hs
haskell
# LANGUAGE MultiParamTypeClasses , FlexibleInstances , BangPatterns # module Control.OperationalTransformation.ClientServerTests ( tests ) where import Control.OperationalTransformation import Control.OperationalTransformation.Client import Control.OperationalTransformation.Server import Data.Maybe (fromJust) import Control.OperationalTransformation.Text.Gen (genOperation) import Test.Framework import Test.Framework.Providers.QuickCheck2 import Test.QuickCheck hiding (reason) import Test.QuickCheck.Property type Queue a = [a] emptyQueue :: Queue a emptyQueue = [] appendQueue :: a -> Queue a -> Queue a appendQueue a q = q ++ [a] type ClientId = Int data ExtendedClient doc op = ExtendedClient { clientId :: !ClientId , clientRevision :: !Revision , clientSendQueue :: Queue (Revision, op) , clientReceiveQueue :: Queue (Maybe op) , clientDoc :: !doc , clientState :: !(ClientState op) } deriving (Show) prop_client_server :: (Eq doc, Arbitrary doc, OTSystem doc op, OTComposableOperation op) => (doc -> Gen op) -> Property prop_client_server genOp = property $ do doc <- arbitrary let server = initialServerState doc clients = createClients doc $ take numClients [1..] (server', clients') <- simulate numActions server clients return $ if not (all isSynchronized clients') then property $ failed { reason = "some clients are not synchronized" } else let ServerState _ doc' _ = server' in if all ((== doc') . clientDoc) clients' then property True else property $ failed { reason = "client documents did not converge" } where numClients, numActions :: Int numClients = 2 numActions = 100 firstRevision = 0 createClients doc = map $ \n -> ExtendedClient { clientId = n , clientRevision = firstRevision , clientSendQueue = emptyQueue , clientReceiveQueue = emptyQueue , clientDoc = doc , clientState = initialClientState } simulate !n !server !clients = do clientN <- choose (0, length clients - 1) actionN <- choose (0, 2) :: Gen Int let client = clients !! clientN (server', clients') <- case actionN of 0 | canReceive client -> do let client' = receiveClient client return (server, replace clientN client' clients) 1 | canSend client -> do let ((rev, op), client') = sendClient client Right (op', (), server') = applyOperation server rev op () clients' = replace clientN client' clients clients'' = broadcast (clientId client) op' clients' return (server', clients'') _ | n < 0 -> return (server, clients) | otherwise -> do client' <- editClient client return (server, replace clientN client' clients) if n > 0 || any (\c -> canReceive c || canSend c) clients' then simulate (n-1) server' clients' else return (server', clients') replace 0 e (_:xs) = e:xs replace n e (x:xs) = x:(replace (n-1) e xs) replace _ _ [] = error "replacing empty list" canReceive = not . null . clientReceiveQueue canSend = not . null . clientSendQueue receiveClient client = case clientReceiveQueue client of [] -> error "empty receive queue" msg:ops -> let client' = client { clientReceiveQueue = ops , clientRevision = clientRevision client + 1 } in case msg of Nothing -> case fromJust $ serverAck (clientState client') of (Just op, clientState') -> client' { clientState = clientState' , clientSendQueue = appendQueue (clientRevision client', op) (clientSendQueue client') } (Nothing, clientState') -> client' { clientState = clientState' } Just op -> case applyServer (clientState client) op of Left err -> error $ "should not happen: " ++ err Right (op', clientState') -> case apply op' (clientDoc client') of Left err -> error $ "apply failed: " ++ err Right doc' -> client' { clientState = clientState', clientDoc = doc' } sendClient client = case clientSendQueue client of [] -> error "empty send queue" op:ops -> (op, client { clientSendQueue = ops }) editClient client = do op <- genOp $ clientDoc client let doc' = fromRight $ apply op $ clientDoc client (shouldSend, state') = fromRight $ applyClient (clientState client) op client' = client { clientState = state', clientDoc = doc' } return $ if shouldSend then client' { clientSendQueue = appendQueue (clientRevision client', op) (clientSendQueue client) } else client' fromRight (Right a) = a fromRight (Left err) = error err broadcast creator op = map $ \client -> let msg = if creator == clientId client then Nothing else Just op in client { clientReceiveQueue = appendQueue msg (clientReceiveQueue client) } isSynchronized client = case clientState client of ClientSynchronized -> True _ -> False tests :: Test tests = testGroup "Control.OperationalTransformation.ClientServerTests" [ testProperty "prop_client_server" $ prop_client_server genOperation ]
aed7f37aa15dbc646b6106d5a7690ca81131137243e361947a1e6e211a9ecc84
xvw/preface
free_selective.mli
(** A [Free selective] allows you to build a {e rigid} {!module:Preface_specs.Selective} from a given {!module:Preface_specs.Functor}. *) (** Such {!module:Preface_specs.selective} is equipped with and additional function for [promoting] values from the underlying {!module:Preface_specs.Functor} into the [Free selective] and a [Natural transformations] for transforming the value of the [Free selective] to an other {!module:Preface_specs.Selective} or to a {!module:Preface_specs.Monoid}. *) * { 2 Note about complexity } Although free constructs are elegant , they introduce an execution cost due to the recursive nature of defining the type of a [ Free Selective ] . There are { e cheaper } encodings but they are not , for the moment , available in Preface . Although free constructs are elegant, they introduce an execution cost due to the recursive nature of defining the type of a [Free Selective]. There are {e cheaper} encodings but they are not, for the moment, available in Preface. *) (** {1 Structure anatomy} *) (** The natural transformation for [Free Selective] to [Selective]. *) module type TO_SELECTIVE = sig type 'a t * The type held by the [ Free Selective ] . type 'a f (** The type held by the {!module:Preface_specs.Functor}. *) type 'a selective (** The type held by the [Selective]. *) type natural_transformation = { transform : 'a. 'a f -> 'a selective } val run : natural_transformation -> 'a t -> 'a selective (** Run the natural transformation over the [Free selective]. *) end (** The natural transformation for [Free Selective] to [Monoid]. *) module type TO_MONOID = sig type 'a t (** The type held by the [Free selective]. *) type 'a f (** The type held by the {!module:Preface_specs.Functor}. *) type monoid * The type held by the [ Monoid ] . type natural_transformation = { transform : 'a. 'a f -> monoid } val run : natural_transformation -> 'a t -> monoid (** Run the natural transformation over the [Free selective]. *) end (** The [Free selective] API without the {!module:Preface_specs.Selective} API. *) module type CORE = sig type 'a f (** The type held by the {!module:Preface_specs.Functor}. *) (** The type held by the [Free selective]. *) type _ t = | Pure : 'a -> 'a t | Select : ('a, 'b) Either.t t * ('a -> 'b) f -> 'b t val promote : 'a f -> 'a t (** Promote a value from the {!module:Preface_specs.Functor} into the [Free selective]. *) (** The natural transformation from a [Free selective] to an other {!module:Preface_specs.Selective}. *) module To_selective (Selective : Selective.CORE) : TO_SELECTIVE with type 'a t := 'a t and type 'a f := 'a f and type 'a selective := 'a Selective.t (** The natural transformation from a [Free selective] to a {!module:Preface_specs.Monoid}. *) module To_monoid (Monoid : Monoid.CORE) : TO_MONOID with type 'a t := 'a t and type 'a f := 'a f and type monoid := Monoid.t end (** {1 Complete API} *) (** The complete interface of a [Free selective]. *) module type API = sig include CORE * @inline * { 1 Selective API } A [ Free selective ] is also a { ! module : Preface_specs . Selective } . A [Free selective] is also a {!module:Preface_specs.Selective}. *) include Selective.API with type 'a t := 'a t * @inline end * { 1 Additional references } - { { : documentation of a Selective Application Functor } - { { : -functors.pdf } Selective Applicative Functors } - {{:} Haskell's documentation of a Selective Application Functor} - {{:-functors.pdf} Selective Applicative Functors} *)
null
https://raw.githubusercontent.com/xvw/preface/d6424579efdc91744414db2ca6541eb9469ac1a8/lib/preface_specs/free_selective.mli
ocaml
* A [Free selective] allows you to build a {e rigid} {!module:Preface_specs.Selective} from a given {!module:Preface_specs.Functor}. * Such {!module:Preface_specs.selective} is equipped with and additional function for [promoting] values from the underlying {!module:Preface_specs.Functor} into the [Free selective] and a [Natural transformations] for transforming the value of the [Free selective] to an other {!module:Preface_specs.Selective} or to a {!module:Preface_specs.Monoid}. * {1 Structure anatomy} * The natural transformation for [Free Selective] to [Selective]. * The type held by the {!module:Preface_specs.Functor}. * The type held by the [Selective]. * Run the natural transformation over the [Free selective]. * The natural transformation for [Free Selective] to [Monoid]. * The type held by the [Free selective]. * The type held by the {!module:Preface_specs.Functor}. * Run the natural transformation over the [Free selective]. * The [Free selective] API without the {!module:Preface_specs.Selective} API. * The type held by the {!module:Preface_specs.Functor}. * The type held by the [Free selective]. * Promote a value from the {!module:Preface_specs.Functor} into the [Free selective]. * The natural transformation from a [Free selective] to an other {!module:Preface_specs.Selective}. * The natural transformation from a [Free selective] to a {!module:Preface_specs.Monoid}. * {1 Complete API} * The complete interface of a [Free selective].
* { 2 Note about complexity } Although free constructs are elegant , they introduce an execution cost due to the recursive nature of defining the type of a [ Free Selective ] . There are { e cheaper } encodings but they are not , for the moment , available in Preface . Although free constructs are elegant, they introduce an execution cost due to the recursive nature of defining the type of a [Free Selective]. There are {e cheaper} encodings but they are not, for the moment, available in Preface. *) module type TO_SELECTIVE = sig type 'a t * The type held by the [ Free Selective ] . type 'a f type 'a selective type natural_transformation = { transform : 'a. 'a f -> 'a selective } val run : natural_transformation -> 'a t -> 'a selective end module type TO_MONOID = sig type 'a t type 'a f type monoid * The type held by the [ Monoid ] . type natural_transformation = { transform : 'a. 'a f -> monoid } val run : natural_transformation -> 'a t -> monoid end module type CORE = sig type 'a f type _ t = | Pure : 'a -> 'a t | Select : ('a, 'b) Either.t t * ('a -> 'b) f -> 'b t val promote : 'a f -> 'a t module To_selective (Selective : Selective.CORE) : TO_SELECTIVE with type 'a t := 'a t and type 'a f := 'a f and type 'a selective := 'a Selective.t module To_monoid (Monoid : Monoid.CORE) : TO_MONOID with type 'a t := 'a t and type 'a f := 'a f and type monoid := Monoid.t end module type API = sig include CORE * @inline * { 1 Selective API } A [ Free selective ] is also a { ! module : Preface_specs . Selective } . A [Free selective] is also a {!module:Preface_specs.Selective}. *) include Selective.API with type 'a t := 'a t * @inline end * { 1 Additional references } - { { : documentation of a Selective Application Functor } - { { : -functors.pdf } Selective Applicative Functors } - {{:} Haskell's documentation of a Selective Application Functor} - {{:-functors.pdf} Selective Applicative Functors} *)
63fe06cda31e79f14f8d3f5db00834ef7faad954b6845e2c3ac02358aeb8e0e2
c-cube/funarith
Simplex.ml
copyright ( c ) 2014 - 2018 , , copyright (c) 2014-2018, Guillaume Bury, Simon Cruanes *) OPTIMS : * - distinguish separate systems ( that do not interact ) , such as in { 1 < = 3x = 3y < = 2 ; z < = 3 } ? * - Implement cuts ? * - distinguish separate systems (that do not interact), such as in { 1 <= 3x = 3y <= 2; z <= 3} ? * - Implement gomorry cuts ? *) open Containers module type VAR = Linear_expr_intf.VAR module type FRESH = Linear_expr_intf.FRESH module type VAR_GEN = Linear_expr_intf.VAR_GEN module type S = Simplex_intf.S module type S_FULL = Simplex_intf.S_FULL module Vec = CCVector module Matrix : sig type 'a t val create : unit -> 'a t val get : 'a t -> int -> int -> 'a val set : 'a t -> int -> int -> 'a -> unit val get_row : 'a t -> int -> 'a Vec.vector val copy : 'a t -> 'a t val n_row : _ t -> int val n_col : _ t -> int val push_row : 'a t -> 'a -> unit (* new row, filled with element *) val push_col : 'a t -> 'a -> unit (* new column, filled with element *) (**/**) val check_invariants : _ t -> bool (**/**) end = struct type 'a t = { mutable n_col: int; (* num of columns *) tab: 'a Vec.vector Vec.vector; } let[@inline] create() : _ = {tab=Vec.create(); n_col=0} let[@inline] get m i j = Vec.get (Vec.get m.tab i) j let[@inline] get_row m i = Vec.get m.tab i let[@inline] set (m:_ t) i j x = Vec.set (Vec.get m.tab i) j x let[@inline] copy m = {m with tab=Vec.map Vec.copy m.tab} let[@inline] n_row m = Vec.length m.tab let[@inline] n_col m = m.n_col let push_row m x = Vec.push m.tab (Vec.make (n_col m) x) let push_col m x = m.n_col <- m.n_col + 1; Vec.iter (fun row -> Vec.push row x) m.tab let check_invariants m = Vec.for_all (fun r -> Vec.length r = n_col m) m.tab end (* use non-polymorphic comparison ops *) open Int.Infix (* Simplex Implementation *) module Make_inner(Q : Rat.S)(Var: VAR)(VMap : CCMap.S with type key=Var.t) = struct module Q = Q module Var_map = VMap module M = Var_map (* Exceptions *) exception Unsat of Var.t exception AbsurdBounds of Var.t exception NoneSuitable type var = Var.t type basic_var = var type nbasic_var = var type erat = { base: Q.t; (* reference number *) eps_factor: Q.t; (* coefficient for epsilon, the infinitesimal *) } (** Epsilon-rationals, used for strict bounds *) module Erat = struct type t = erat let zero : t = {base=Q.zero; eps_factor=Q.zero} let[@inline] make base eps_factor : t = {base; eps_factor} let[@inline] base t = t.base let[@inline] eps_factor t = t.eps_factor let[@inline] mul k e = Q.(make (k * e.base) (k * e.eps_factor)) let[@inline] sum e1 e2 = Q.(make (e1.base + e2.base) (e1.eps_factor + e2.eps_factor)) let[@inline] compare e1 e2 = match Q.compare e1.base e2.base with | 0 -> Q.compare e1.eps_factor e2.eps_factor | x -> x let lt a b = compare a b < 0 let gt a b = compare a b > 0 let[@inline] min x y = if compare x y <= 0 then x else y let[@inline] max x y = if compare x y >= 0 then x else y let[@inline] evaluate (epsilon:Q.t) (e:t) : Q.t = Q.(e.base + epsilon * e.eps_factor) let pp out e = if Q.equal Q.zero (eps_factor e) then Q.pp out (base e) else Format.fprintf out "(@[<h>%a + @<1>ε * %a@])" Q.pp (base e) Q.pp (eps_factor e) end let str_of_var = Format.to_string Var.pp let str_of_erat = Format.to_string Erat.pp let str_of_q = Format.to_string Q.pp type t = { tab : Q.t Matrix.t; (* the matrix of coefficients *) basic : basic_var Vec.vector; (* basic variables *) nbasic : nbasic_var Vec.vector; (* non basic variables *) mutable assign : Erat.t M.t; (* assignments *) mutable bounds : (Erat.t * Erat.t) M.t; (* (lower, upper) bounds for variables *) mutable idx_basic : int M.t; (* basic var -> its index in [basic] *) mutable idx_nbasic : int M.t; (* non basic var -> its index in [nbasic] *) } type cert = { cert_var: var; cert_expr: (Q.t * var) list; } type res = | Solution of Q.t Var_map.t | Unsatisfiable of cert let create () : t = { tab = Matrix.create (); basic = Vec.create (); nbasic = Vec.create (); assign = M.empty; bounds = M.empty; idx_basic = M.empty; idx_nbasic = M.empty; } let copy t = { tab = Matrix.copy t.tab; basic = Vec.copy t.basic; nbasic = Vec.copy t.nbasic; assign = t.assign; bounds = t.bounds; idx_nbasic = t.idx_nbasic; idx_basic = t.idx_basic; } let index_basic (t:t) (x:basic_var) : int = match M.find x t.idx_basic with | n -> n | exception Not_found -> -1 let index_nbasic (t:t) (x:nbasic_var) : int = match M.find x t.idx_nbasic with | n -> n | exception Not_found -> -1 let[@inline] mem_basic (t:t) (x:var) : bool = M.mem x t.idx_basic let[@inline] mem_nbasic (t:t) (x:var) : bool = M.mem x t.idx_nbasic (* check invariants, for test purposes *) let check_invariants (t:t) : bool = Matrix.check_invariants t.tab && Vec.for_all (fun v -> mem_basic t v) t.basic && Vec.for_all (fun v -> mem_nbasic t v) t.nbasic && Vec.for_all (fun v -> not (mem_nbasic t v)) t.basic && Vec.for_all (fun v -> not (mem_basic t v)) t.nbasic && Vec.for_all (fun v -> Var_map.mem v t.assign) t.nbasic && Vec.for_all (fun v -> not (Var_map.mem v t.assign)) t.basic && true (* find the definition of the basic variable [x], as a linear combination of non basic variables *) let find_expr_basic_opt t (x:var) : Q.t Vec.vector option = begin match index_basic t x with | -1 -> None | i -> Some (Matrix.get_row t.tab i) end let find_expr_basic t (x:basic_var) : Q.t Vec.vector = match find_expr_basic_opt t x with | None -> assert false | Some e -> e build the expression [ y = \sum_i ( if x_i = y then 1 else 0)·x_i ] let find_expr_nbasic t (x:nbasic_var) : Q.t Vec.vector = Vec.map (fun y -> if Var.compare x y = 0 then Q.one else Q.zero) t.nbasic (* TODO: avoid double lookup in maps *) (* find expression of [x] *) let find_expr_total (t:t) (x:var) : Q.t Vec.vector = if mem_basic t x then find_expr_basic t x else ( assert (mem_nbasic t x); find_expr_nbasic t x ) (* compute value of basic variable. It can be computed by using [x]'s definition in terms of nbasic variables, which have values *) let value_basic (t:t) (x:basic_var) : Erat.t = assert (mem_basic t x); let res = ref Erat.zero in let expr = find_expr_basic t x in for i = 0 to Vec.length expr - 1 do let val_nbasic_i = try M.find (Vec.get t.nbasic i) t.assign with Not_found -> assert false in res := Erat.sum !res (Erat.mul (Vec.get expr i) val_nbasic_i) done; !res (* extract a value for [x] *) let[@inline] value (t:t) (x:var) : Erat.t = try M.find x t.assign (* nbasic variables are assigned *) with Not_found -> value_basic t x (* trivial bounds *) let empty_bounds : Erat.t * Erat.t = Q.(Erat.make minus_inf zero, Erat.make inf zero) (* find bounds of [x] *) let[@inline] get_bounds (t:t) (x:var) : Erat.t * Erat.t = try M.find x t.bounds with Not_found -> empty_bounds (* is [value x] within the bounds for [x]? *) let is_within_bounds (t:t) (x:var) : bool * Erat.t = let v = value t x in let low, upp = get_bounds t x in if Erat.compare v low < 0 then false, low else if Erat.compare v upp > 0 then false, upp else true, v add nbasic variables let add_vars (t:t) (l:var list) : unit = add new variable to idx and array for nbasic , removing duplicates and variables already present and variables already present *) let idx_nbasic, _, l = List.fold_left (fun ((idx_nbasic, offset, l) as acc) x -> if mem_basic t x then acc else if M.mem x idx_nbasic then acc else ( (* allocate new index for [x] *) M.add x offset idx_nbasic, offset+1, x::l )) (t.idx_nbasic, Vec.length t.nbasic, []) l in (* add new columns to the matrix *) let old_dim = Matrix.n_col t.tab in List.iter (fun _ -> Matrix.push_col t.tab Q.zero) l; assert (old_dim + List.length l = Matrix.n_col t.tab); Vec.append_list t.nbasic (List.rev l); (* assign these variables *) t.assign <- List.fold_left (fun acc y -> M.add y Erat.zero acc) t.assign l; t.idx_nbasic <- idx_nbasic; () (* define basic variable [x] by [eq] in [t] *) let add_eq (t:t) (x, eq : basic_var * _ list) : unit = if mem_basic t x || mem_nbasic t x then ( invalid_arg (Format.sprintf "Variable `%a` already defined." Var.pp x); ); add_vars t (List.map snd eq); (* add [x] as a basic var *) t.idx_basic <- M.add x (Vec.length t.basic) t.idx_basic; Vec.push t.basic x; (* add new row for defining [x] *) assert (Matrix.n_col t.tab > 0); Matrix.push_row t.tab Q.zero; let row_i = Matrix.n_row t.tab - 1 in assert (row_i >= 0); (* now put into the row the coefficients corresponding to [eq], expanding basic variables to their definition *) List.iter (fun (c, x) -> let expr = find_expr_total t x in assert (Vec.length expr = Matrix.n_col t.tab); Vec.iteri (fun j c' -> if not (Q.equal Q.zero c') then ( Matrix.set t.tab row_i j Q.(Matrix.get t.tab row_i j + c * c') )) expr) eq; () (* add bounds to [x] in [t] *) let add_bound_aux (t:t) (x:var) (low:Erat.t) (upp:Erat.t) : unit = add_vars t [x]; let l, u = get_bounds t x in t.bounds <- M.add x (Erat.max l low, Erat.min u upp) t.bounds let add_bounds (t:t) ?strict_lower:(slow=false) ?strict_upper:(supp=false) (x, l, u) : unit = let e1 = if slow then Q.one else Q.zero in let e2 = if supp then Q.neg Q.one else Q.zero in add_bound_aux t x (Erat.make l e1) (Erat.make u e2); if mem_nbasic t x then ( let b, v = is_within_bounds t x in if not b then ( t.assign <- M.add x v t.assign; ) ) let add_lower_bound t ?strict x l = add_bounds t ?strict_lower:strict (x,l,Q.inf) let add_upper_bound t ?strict x u = add_bounds t ?strict_upper:strict (x,Q.minus_inf,u) (* full assignment *) let full_assign (t:t) : (var * Erat.t) Iter.t = Iter.append (Vec.to_iter t.nbasic) (Vec.to_iter t.basic) |> Iter.map (fun x -> x, value t x) let[@inline] min x y = if Q.compare x y < 0 then x else y (* Find an epsilon that is small enough for finding a solution, yet it must be positive. {!Erat.t} values are used to turn strict bounds ([X > 0]) into non-strict bounds ([X >= 0 + ε]), because the simplex algorithm only deals with non-strict bounds. When a solution is found, we need to turn {!Erat.t} into {!Q.t} by finding a rational value that is small enough that it will fit into all the intervals of [t]. This rational will be the actual value of [ε]. *) let solve_epsilon (t:t) : Q.t = let emax = M.fold (fun x ({base=low;eps_factor=e_low}, {base=upp;eps_factor=e_upp}) emax -> let {base=v; eps_factor=e_v} = value t x in (* lower bound *) let emax = if Q.compare low Q.minus_inf > 0 && Q.compare e_v e_low < 0 then min emax Q.((low - v) / (e_v - e_low)) else emax in (* upper bound *) if Q.compare upp Q.inf < 0 && Q.compare e_v e_upp > 0 then min emax Q.((upp - v) / (e_v - e_upp)) else emax) t.bounds Q.inf in if Q.compare emax Q.one >= 0 then Q.one else emax let get_full_assign_seq (t:t) : _ Iter.t = let e = solve_epsilon t in let f = Erat.evaluate e in full_assign t |> Iter.map (fun (x,v) -> x, f v) let get_full_assign t : Q.t Var_map.t = Var_map.of_iter (get_full_assign_seq t) (* Find nbasic variable suitable for pivoting with [x]. A nbasic variable [y] is suitable if it "goes into the right direction" (its coefficient in the definition of [x] is of the adequate sign) and if it hasn't reached its bound in this direction. precondition: [x] is a basic variable whose value in current assignment is outside its bounds We return the smallest (w.r.t Var.compare) suitable variable. This is important for termination. *) let find_suitable_nbasic_for_pivot (t:t) (x:basic_var) : nbasic_var * Q.t = assert (mem_basic t x); let _, v = is_within_bounds t x in let b = Erat.compare (value t x) v < 0 in is nbasic var [ y ] , with [ a ] in definition of [ x ] , suitable ? let test (y:nbasic_var) (a:Q.t) : bool = assert (mem_nbasic t y); let v = value t y in let low, upp = get_bounds t y in if b then ( (Erat.lt v upp && Q.compare a Q.zero > 0) || (Erat.gt v low && Q.compare a Q.zero < 0) ) else ( (Erat.gt v low && Q.compare a Q.zero > 0) || (Erat.lt v upp && Q.compare a Q.zero < 0) ) in let nbasic_vars = t.nbasic in let expr = find_expr_basic t x in (* find best suitable variable *) let rec aux i = if i = Vec.length nbasic_vars then ( assert (i = Vec.length expr); None ) else ( let y = Vec.get nbasic_vars i in let a = Vec.get expr i in if test y a then ( (* see if other variables are better suited *) begin match aux (i+1) with | None -> Some (y,a) | Some (z, _) as res_tail -> if Var.compare y z <= 0 then Some (y,a) else res_tail end ) else ( aux (i+1) ) ) in begin match aux 0 with | Some res -> res | None -> raise NoneSuitable end (* pivot to exchange [x] and [y] *) let pivot (t:t) (x:basic_var) (y:nbasic_var) (a:Q.t) : unit = (* swap values ([x] becomes assigned) *) let val_x = value t x in t.assign <- t.assign |> M.remove y |> M.add x val_x; Matrixrix Pivot operation let kx = index_basic t x in let ky = index_nbasic t y in for j = 0 to Vec.length t.nbasic - 1 do if Var.compare y (Vec.get t.nbasic j) = 0 then ( Matrix.set t.tab kx j Q.(one / a) ) else ( Matrix.set t.tab kx j Q.(neg (Matrix.get t.tab kx j) / a) ) done; for i = 0 to Vec.length t.basic - 1 do if i <> kx then ( let c = Matrix.get t.tab i ky in Matrix.set t.tab i ky Q.zero; for j = 0 to Vec.length t.nbasic - 1 do Matrix.set t.tab i j Q.(Matrix.get t.tab i j + c * Matrix.get t.tab kx j) done ) done; Switch x and y in basic and nbasic vars Vec.set t.basic kx y; Vec.set t.nbasic ky x; t.idx_basic <- t.idx_basic |> M.remove x |> M.add y kx; t.idx_nbasic <- t.idx_nbasic |> M.remove y |> M.add x ky; () (* find minimum element of [arr] (wrt [cmp]) that satisfies predicate [f] *) let find_min_filter ~cmp (f:'a -> bool) (arr:('a,_) Vec.t) : 'a option = find the first element that satisfies [ f ] let rec aux_find_first i = if i = Vec.length arr then None else ( let x = Vec.get arr i in if f x then aux_compare_with x (i+1) else aux_find_first (i+1) ) (* find if any element of [l] satisfies [f] and is smaller than [x] *) and aux_compare_with x i = if i = Vec.length arr then Some x else ( let y = Vec.get arr i in let best = if f y && cmp y x < 0 then y else x in aux_compare_with best (i+1) ) in aux_find_first 0 (* check bounds *) let check_bounds (t:t) : unit = M.iter (fun x (l, u) -> if Erat.gt l u then raise (AbsurdBounds x)) t.bounds (* actual solving algorithm *) let solve_aux (t:t) : unit = check_bounds t; (* select the smallest basic variable that is not satisfied in the current assignment. *) let rec aux_select_basic_var () = match find_min_filter ~cmp:Var.compare (fun x -> not (fst (is_within_bounds t x))) t.basic with | Some x -> aux_pivot_on_basic x | None -> () (* remove the basic variable *) and aux_pivot_on_basic x = let _b, v = is_within_bounds t x in assert (not _b); match find_suitable_nbasic_for_pivot t x with | y, a -> (* exchange [x] and [y] by pivoting *) pivot t x y a; (* assign [x], now a nbasic variable, to the faulty bound [v] *) t.assign <- M.add x v t.assign; (* next iteration *) aux_select_basic_var () | exception NoneSuitable -> raise (Unsat x) in aux_select_basic_var (); () (* main method for the user to call *) let solve (t:t) : res = try solve_aux t; Solution (get_full_assign t) with | Unsat x -> let cert_expr = List.combine (Vec.to_list (find_expr_basic t x)) (Vec.to_list t.nbasic) in Unsatisfiable { cert_var=x; cert_expr; } | AbsurdBounds x -> Unsatisfiable { cert_var=x; cert_expr=[]; } add [ c·x ] to [ m ] let add_expr_ (x:var) (c:Q.t) (m:Q.t M.t) = let c' = M.get_or ~default:Q.zero x m in let c' = Q.(c + c') in if Q.equal Q.zero c' then M.remove x m else M.add x c' m (* dereference basic variables from [c·x], and add the result to [m] *) let rec deref_var_ t x c m = match find_expr_basic_opt t x with | None -> add_expr_ x c m | Some expr_x -> let m = ref m in Vec.iteri (fun i c_i -> let y_i = Vec.get t.nbasic i in m := deref_var_ t y_i Q.(c * c_i) !m) expr_x; !m (* maybe invert bounds, if [c < 0] *) let scale_bounds c (l,u) : erat * erat = match Q.compare c Q.zero with | 0 -> Erat.zero, Erat.zero | n when n<0 -> Erat.mul c u, Erat.mul c l | _ -> Erat.mul c l, Erat.mul c u let check_cert (t:t) (c:cert) = let x = c.cert_var in let low_x, up_x = get_bounds t x in begin match c.cert_expr with | [] -> if Erat.compare low_x up_x > 0 then `Ok else `Bad_bounds (str_of_erat low_x, str_of_erat up_x) | expr -> let e0 = deref_var_ t x (Q.neg Q.one) M.empty in (* compute bounds for the expression [c.cert_expr], and also compute [c.cert_expr - x] to check if it's 0] *) let low, up, expr_minus_x = List.fold_left (fun (l,u,expr_minus_x) (c, y) -> let ly, uy = scale_bounds c (get_bounds t y) in assert (Erat.compare ly uy <= 0); let expr_minus_x = deref_var_ t y c expr_minus_x in Erat.sum l ly, Erat.sum u uy, expr_minus_x) (Erat.zero, Erat.zero, e0) expr in (* check that the expanded expression is [x], and that one of the bounds on [x] is incompatible with bounds of [c.cert_expr] *) if M.is_empty expr_minus_x then ( if Erat.compare low_x up > 0 || Erat.compare up_x low < 0 then `Ok else `Bad_bounds (str_of_erat low, str_of_erat up) ) else `Diff_not_0 expr_minus_x end (* printer *) let matrix_pp_width = ref 8 let fmt_head = format_of_string "|%*s|| " let fmt_cell = format_of_string "%*s| " let pp_cert out (c:cert) = match c.cert_expr with | [] -> Format.fprintf out "(@[inconsistent-bounds %a@])" Var.pp c.cert_var | _ -> let pp_pair = Format.(hvbox ~i:2 @@ pair ~sep:(return "@ * ") Q.pp Var.pp) in Format.fprintf out "(@[<hv>cert@ :var %a@ :linexp %a@])" Var.pp c.cert_var Format.(within "[" "]" @@ hvbox @@ list ~sep:(return "@ + ") pp_pair) c.cert_expr let pp_mat out t = let open Format in fprintf out "@[<v>"; (* header *) fprintf out fmt_head !matrix_pp_width ""; Vec.iter (fun x -> fprintf out fmt_cell !matrix_pp_width (str_of_var x)) t.nbasic; fprintf out "@,"; (* rows *) for i=0 to Matrix.n_row t.tab-1 do if i>0 then fprintf out "@,"; let v = Vec.get t.basic i in fprintf out fmt_head !matrix_pp_width (str_of_var v); let row = Matrix.get_row t.tab i in Vec.iter (fun q -> fprintf out fmt_cell !matrix_pp_width (str_of_q q)) row; done; fprintf out "@]" let pp_assign = let open Format in let pp_pair = within "(" ")" @@ hvbox @@ pair ~sep:(return "@ := ") Var.pp Erat.pp in map Var_map.to_seq @@ within "(" ")" @@ hvbox @@ seq pp_pair let pp_bounds = let open Format in let pp_pairs out (x,(l,u)) = fprintf out "(@[%a =< %a =< %a@])" Erat.pp l Var.pp x Erat.pp u in map Var_map.to_seq @@ within "(" ")" @@ hvbox @@ seq pp_pairs let pp_full_state out (t:t) : unit = (* print main matrix *) Format.fprintf out "(@[<hv>simplex@ :n-row %d :n-col %d@ :mat %a@ :assign %a@ :bounds %a@])" (Matrix.n_row t.tab) (Matrix.n_col t.tab) pp_mat t pp_assign t.assign pp_bounds t.bounds end module Make(Q:Rat.S)(Var:VAR) = Make_inner(Q)(Var)(CCMap.Make(Var)) module Make_full_for_expr(Q : Rat.S)(V : VAR_GEN) (L : Linear_expr.S with type Var.t = V.t and type C.t = Q.t) = struct include Make_inner(Q)(V)(L.Var_map) module L = L type op = [`Eq | `Leq | `Geq | `Lt | `Gt] type 'a constr = ([<op] as 'a) L.Constr.t module Problem = struct type 'a t = ([<op] as 'a) constr list module Infix = struct let (&&) = List.append end include Infix let eval subst = List.for_all (L.Constr.eval subst) let pp out pb = Format.(hvbox @@ list ~sep:(return "@ @<1>∧ ") L.Constr.pp) out pb end let fresh_var = V.Fresh.create () (* add a constraint *) let add_constr (t:t) (c:[<op] constr) : unit = let (x:var) = V.Fresh.fresh fresh_var in let e, op, q = L.Constr.split c in add_eq t (x, L.Comb.to_list e); begin match op with | `Leq -> add_upper_bound t ~strict:false x q | `Geq -> add_lower_bound t ~strict:false x q | `Lt -> add_upper_bound t ~strict:true x q | `Gt -> add_lower_bound t ~strict:true x q | `Eq -> add_bounds t ~strict_lower:false ~strict_upper:false (x,q,q) end let add_problem (t:t) (pb:_ Problem.t) : unit = List.iter (add_constr t) pb end module Make_full(Q : Rat.S)(V : VAR_GEN) = Make_full_for_expr(Q)(V)(Linear_expr.Make(Q)(V))
null
https://raw.githubusercontent.com/c-cube/funarith/1c86ac45e9608efaa761e3f14455402730885339/src/Simplex.ml
ocaml
new row, filled with element new column, filled with element */* */* num of columns use non-polymorphic comparison ops Simplex Implementation Exceptions reference number coefficient for epsilon, the infinitesimal * Epsilon-rationals, used for strict bounds the matrix of coefficients basic variables non basic variables assignments (lower, upper) bounds for variables basic var -> its index in [basic] non basic var -> its index in [nbasic] check invariants, for test purposes find the definition of the basic variable [x], as a linear combination of non basic variables TODO: avoid double lookup in maps find expression of [x] compute value of basic variable. It can be computed by using [x]'s definition in terms of nbasic variables, which have values extract a value for [x] nbasic variables are assigned trivial bounds find bounds of [x] is [value x] within the bounds for [x]? allocate new index for [x] add new columns to the matrix assign these variables define basic variable [x] by [eq] in [t] add [x] as a basic var add new row for defining [x] now put into the row the coefficients corresponding to [eq], expanding basic variables to their definition add bounds to [x] in [t] full assignment Find an epsilon that is small enough for finding a solution, yet it must be positive. {!Erat.t} values are used to turn strict bounds ([X > 0]) into non-strict bounds ([X >= 0 + ε]), because the simplex algorithm only deals with non-strict bounds. When a solution is found, we need to turn {!Erat.t} into {!Q.t} by finding a rational value that is small enough that it will fit into all the intervals of [t]. This rational will be the actual value of [ε]. lower bound upper bound Find nbasic variable suitable for pivoting with [x]. A nbasic variable [y] is suitable if it "goes into the right direction" (its coefficient in the definition of [x] is of the adequate sign) and if it hasn't reached its bound in this direction. precondition: [x] is a basic variable whose value in current assignment is outside its bounds We return the smallest (w.r.t Var.compare) suitable variable. This is important for termination. find best suitable variable see if other variables are better suited pivot to exchange [x] and [y] swap values ([x] becomes assigned) find minimum element of [arr] (wrt [cmp]) that satisfies predicate [f] find if any element of [l] satisfies [f] and is smaller than [x] check bounds actual solving algorithm select the smallest basic variable that is not satisfied in the current assignment. remove the basic variable exchange [x] and [y] by pivoting assign [x], now a nbasic variable, to the faulty bound [v] next iteration main method for the user to call dereference basic variables from [c·x], and add the result to [m] maybe invert bounds, if [c < 0] compute bounds for the expression [c.cert_expr], and also compute [c.cert_expr - x] to check if it's 0] check that the expanded expression is [x], and that one of the bounds on [x] is incompatible with bounds of [c.cert_expr] printer header rows print main matrix add a constraint
copyright ( c ) 2014 - 2018 , , copyright (c) 2014-2018, Guillaume Bury, Simon Cruanes *) OPTIMS : * - distinguish separate systems ( that do not interact ) , such as in { 1 < = 3x = 3y < = 2 ; z < = 3 } ? * - Implement cuts ? * - distinguish separate systems (that do not interact), such as in { 1 <= 3x = 3y <= 2; z <= 3} ? * - Implement gomorry cuts ? *) open Containers module type VAR = Linear_expr_intf.VAR module type FRESH = Linear_expr_intf.FRESH module type VAR_GEN = Linear_expr_intf.VAR_GEN module type S = Simplex_intf.S module type S_FULL = Simplex_intf.S_FULL module Vec = CCVector module Matrix : sig type 'a t val create : unit -> 'a t val get : 'a t -> int -> int -> 'a val set : 'a t -> int -> int -> 'a -> unit val get_row : 'a t -> int -> 'a Vec.vector val copy : 'a t -> 'a t val n_row : _ t -> int val n_col : _ t -> int val check_invariants : _ t -> bool end = struct type 'a t = { tab: 'a Vec.vector Vec.vector; } let[@inline] create() : _ = {tab=Vec.create(); n_col=0} let[@inline] get m i j = Vec.get (Vec.get m.tab i) j let[@inline] get_row m i = Vec.get m.tab i let[@inline] set (m:_ t) i j x = Vec.set (Vec.get m.tab i) j x let[@inline] copy m = {m with tab=Vec.map Vec.copy m.tab} let[@inline] n_row m = Vec.length m.tab let[@inline] n_col m = m.n_col let push_row m x = Vec.push m.tab (Vec.make (n_col m) x) let push_col m x = m.n_col <- m.n_col + 1; Vec.iter (fun row -> Vec.push row x) m.tab let check_invariants m = Vec.for_all (fun r -> Vec.length r = n_col m) m.tab end open Int.Infix module Make_inner(Q : Rat.S)(Var: VAR)(VMap : CCMap.S with type key=Var.t) = struct module Q = Q module Var_map = VMap module M = Var_map exception Unsat of Var.t exception AbsurdBounds of Var.t exception NoneSuitable type var = Var.t type basic_var = var type nbasic_var = var type erat = { } module Erat = struct type t = erat let zero : t = {base=Q.zero; eps_factor=Q.zero} let[@inline] make base eps_factor : t = {base; eps_factor} let[@inline] base t = t.base let[@inline] eps_factor t = t.eps_factor let[@inline] mul k e = Q.(make (k * e.base) (k * e.eps_factor)) let[@inline] sum e1 e2 = Q.(make (e1.base + e2.base) (e1.eps_factor + e2.eps_factor)) let[@inline] compare e1 e2 = match Q.compare e1.base e2.base with | 0 -> Q.compare e1.eps_factor e2.eps_factor | x -> x let lt a b = compare a b < 0 let gt a b = compare a b > 0 let[@inline] min x y = if compare x y <= 0 then x else y let[@inline] max x y = if compare x y >= 0 then x else y let[@inline] evaluate (epsilon:Q.t) (e:t) : Q.t = Q.(e.base + epsilon * e.eps_factor) let pp out e = if Q.equal Q.zero (eps_factor e) then Q.pp out (base e) else Format.fprintf out "(@[<h>%a + @<1>ε * %a@])" Q.pp (base e) Q.pp (eps_factor e) end let str_of_var = Format.to_string Var.pp let str_of_erat = Format.to_string Erat.pp let str_of_q = Format.to_string Q.pp type t = { } type cert = { cert_var: var; cert_expr: (Q.t * var) list; } type res = | Solution of Q.t Var_map.t | Unsatisfiable of cert let create () : t = { tab = Matrix.create (); basic = Vec.create (); nbasic = Vec.create (); assign = M.empty; bounds = M.empty; idx_basic = M.empty; idx_nbasic = M.empty; } let copy t = { tab = Matrix.copy t.tab; basic = Vec.copy t.basic; nbasic = Vec.copy t.nbasic; assign = t.assign; bounds = t.bounds; idx_nbasic = t.idx_nbasic; idx_basic = t.idx_basic; } let index_basic (t:t) (x:basic_var) : int = match M.find x t.idx_basic with | n -> n | exception Not_found -> -1 let index_nbasic (t:t) (x:nbasic_var) : int = match M.find x t.idx_nbasic with | n -> n | exception Not_found -> -1 let[@inline] mem_basic (t:t) (x:var) : bool = M.mem x t.idx_basic let[@inline] mem_nbasic (t:t) (x:var) : bool = M.mem x t.idx_nbasic let check_invariants (t:t) : bool = Matrix.check_invariants t.tab && Vec.for_all (fun v -> mem_basic t v) t.basic && Vec.for_all (fun v -> mem_nbasic t v) t.nbasic && Vec.for_all (fun v -> not (mem_nbasic t v)) t.basic && Vec.for_all (fun v -> not (mem_basic t v)) t.nbasic && Vec.for_all (fun v -> Var_map.mem v t.assign) t.nbasic && Vec.for_all (fun v -> not (Var_map.mem v t.assign)) t.basic && true let find_expr_basic_opt t (x:var) : Q.t Vec.vector option = begin match index_basic t x with | -1 -> None | i -> Some (Matrix.get_row t.tab i) end let find_expr_basic t (x:basic_var) : Q.t Vec.vector = match find_expr_basic_opt t x with | None -> assert false | Some e -> e build the expression [ y = \sum_i ( if x_i = y then 1 else 0)·x_i ] let find_expr_nbasic t (x:nbasic_var) : Q.t Vec.vector = Vec.map (fun y -> if Var.compare x y = 0 then Q.one else Q.zero) t.nbasic let find_expr_total (t:t) (x:var) : Q.t Vec.vector = if mem_basic t x then find_expr_basic t x else ( assert (mem_nbasic t x); find_expr_nbasic t x ) let value_basic (t:t) (x:basic_var) : Erat.t = assert (mem_basic t x); let res = ref Erat.zero in let expr = find_expr_basic t x in for i = 0 to Vec.length expr - 1 do let val_nbasic_i = try M.find (Vec.get t.nbasic i) t.assign with Not_found -> assert false in res := Erat.sum !res (Erat.mul (Vec.get expr i) val_nbasic_i) done; !res let[@inline] value (t:t) (x:var) : Erat.t = with Not_found -> value_basic t x let empty_bounds : Erat.t * Erat.t = Q.(Erat.make minus_inf zero, Erat.make inf zero) let[@inline] get_bounds (t:t) (x:var) : Erat.t * Erat.t = try M.find x t.bounds with Not_found -> empty_bounds let is_within_bounds (t:t) (x:var) : bool * Erat.t = let v = value t x in let low, upp = get_bounds t x in if Erat.compare v low < 0 then false, low else if Erat.compare v upp > 0 then false, upp else true, v add nbasic variables let add_vars (t:t) (l:var list) : unit = add new variable to idx and array for nbasic , removing duplicates and variables already present and variables already present *) let idx_nbasic, _, l = List.fold_left (fun ((idx_nbasic, offset, l) as acc) x -> if mem_basic t x then acc else if M.mem x idx_nbasic then acc else ( M.add x offset idx_nbasic, offset+1, x::l )) (t.idx_nbasic, Vec.length t.nbasic, []) l in let old_dim = Matrix.n_col t.tab in List.iter (fun _ -> Matrix.push_col t.tab Q.zero) l; assert (old_dim + List.length l = Matrix.n_col t.tab); Vec.append_list t.nbasic (List.rev l); t.assign <- List.fold_left (fun acc y -> M.add y Erat.zero acc) t.assign l; t.idx_nbasic <- idx_nbasic; () let add_eq (t:t) (x, eq : basic_var * _ list) : unit = if mem_basic t x || mem_nbasic t x then ( invalid_arg (Format.sprintf "Variable `%a` already defined." Var.pp x); ); add_vars t (List.map snd eq); t.idx_basic <- M.add x (Vec.length t.basic) t.idx_basic; Vec.push t.basic x; assert (Matrix.n_col t.tab > 0); Matrix.push_row t.tab Q.zero; let row_i = Matrix.n_row t.tab - 1 in assert (row_i >= 0); List.iter (fun (c, x) -> let expr = find_expr_total t x in assert (Vec.length expr = Matrix.n_col t.tab); Vec.iteri (fun j c' -> if not (Q.equal Q.zero c') then ( Matrix.set t.tab row_i j Q.(Matrix.get t.tab row_i j + c * c') )) expr) eq; () let add_bound_aux (t:t) (x:var) (low:Erat.t) (upp:Erat.t) : unit = add_vars t [x]; let l, u = get_bounds t x in t.bounds <- M.add x (Erat.max l low, Erat.min u upp) t.bounds let add_bounds (t:t) ?strict_lower:(slow=false) ?strict_upper:(supp=false) (x, l, u) : unit = let e1 = if slow then Q.one else Q.zero in let e2 = if supp then Q.neg Q.one else Q.zero in add_bound_aux t x (Erat.make l e1) (Erat.make u e2); if mem_nbasic t x then ( let b, v = is_within_bounds t x in if not b then ( t.assign <- M.add x v t.assign; ) ) let add_lower_bound t ?strict x l = add_bounds t ?strict_lower:strict (x,l,Q.inf) let add_upper_bound t ?strict x u = add_bounds t ?strict_upper:strict (x,Q.minus_inf,u) let full_assign (t:t) : (var * Erat.t) Iter.t = Iter.append (Vec.to_iter t.nbasic) (Vec.to_iter t.basic) |> Iter.map (fun x -> x, value t x) let[@inline] min x y = if Q.compare x y < 0 then x else y let solve_epsilon (t:t) : Q.t = let emax = M.fold (fun x ({base=low;eps_factor=e_low}, {base=upp;eps_factor=e_upp}) emax -> let {base=v; eps_factor=e_v} = value t x in let emax = if Q.compare low Q.minus_inf > 0 && Q.compare e_v e_low < 0 then min emax Q.((low - v) / (e_v - e_low)) else emax in if Q.compare upp Q.inf < 0 && Q.compare e_v e_upp > 0 then min emax Q.((upp - v) / (e_v - e_upp)) else emax) t.bounds Q.inf in if Q.compare emax Q.one >= 0 then Q.one else emax let get_full_assign_seq (t:t) : _ Iter.t = let e = solve_epsilon t in let f = Erat.evaluate e in full_assign t |> Iter.map (fun (x,v) -> x, f v) let get_full_assign t : Q.t Var_map.t = Var_map.of_iter (get_full_assign_seq t) let find_suitable_nbasic_for_pivot (t:t) (x:basic_var) : nbasic_var * Q.t = assert (mem_basic t x); let _, v = is_within_bounds t x in let b = Erat.compare (value t x) v < 0 in is nbasic var [ y ] , with [ a ] in definition of [ x ] , suitable ? let test (y:nbasic_var) (a:Q.t) : bool = assert (mem_nbasic t y); let v = value t y in let low, upp = get_bounds t y in if b then ( (Erat.lt v upp && Q.compare a Q.zero > 0) || (Erat.gt v low && Q.compare a Q.zero < 0) ) else ( (Erat.gt v low && Q.compare a Q.zero > 0) || (Erat.lt v upp && Q.compare a Q.zero < 0) ) in let nbasic_vars = t.nbasic in let expr = find_expr_basic t x in let rec aux i = if i = Vec.length nbasic_vars then ( assert (i = Vec.length expr); None ) else ( let y = Vec.get nbasic_vars i in let a = Vec.get expr i in if test y a then ( begin match aux (i+1) with | None -> Some (y,a) | Some (z, _) as res_tail -> if Var.compare y z <= 0 then Some (y,a) else res_tail end ) else ( aux (i+1) ) ) in begin match aux 0 with | Some res -> res | None -> raise NoneSuitable end let pivot (t:t) (x:basic_var) (y:nbasic_var) (a:Q.t) : unit = let val_x = value t x in t.assign <- t.assign |> M.remove y |> M.add x val_x; Matrixrix Pivot operation let kx = index_basic t x in let ky = index_nbasic t y in for j = 0 to Vec.length t.nbasic - 1 do if Var.compare y (Vec.get t.nbasic j) = 0 then ( Matrix.set t.tab kx j Q.(one / a) ) else ( Matrix.set t.tab kx j Q.(neg (Matrix.get t.tab kx j) / a) ) done; for i = 0 to Vec.length t.basic - 1 do if i <> kx then ( let c = Matrix.get t.tab i ky in Matrix.set t.tab i ky Q.zero; for j = 0 to Vec.length t.nbasic - 1 do Matrix.set t.tab i j Q.(Matrix.get t.tab i j + c * Matrix.get t.tab kx j) done ) done; Switch x and y in basic and nbasic vars Vec.set t.basic kx y; Vec.set t.nbasic ky x; t.idx_basic <- t.idx_basic |> M.remove x |> M.add y kx; t.idx_nbasic <- t.idx_nbasic |> M.remove y |> M.add x ky; () let find_min_filter ~cmp (f:'a -> bool) (arr:('a,_) Vec.t) : 'a option = find the first element that satisfies [ f ] let rec aux_find_first i = if i = Vec.length arr then None else ( let x = Vec.get arr i in if f x then aux_compare_with x (i+1) else aux_find_first (i+1) ) and aux_compare_with x i = if i = Vec.length arr then Some x else ( let y = Vec.get arr i in let best = if f y && cmp y x < 0 then y else x in aux_compare_with best (i+1) ) in aux_find_first 0 let check_bounds (t:t) : unit = M.iter (fun x (l, u) -> if Erat.gt l u then raise (AbsurdBounds x)) t.bounds let solve_aux (t:t) : unit = check_bounds t; let rec aux_select_basic_var () = match find_min_filter ~cmp:Var.compare (fun x -> not (fst (is_within_bounds t x))) t.basic with | Some x -> aux_pivot_on_basic x | None -> () and aux_pivot_on_basic x = let _b, v = is_within_bounds t x in assert (not _b); match find_suitable_nbasic_for_pivot t x with | y, a -> pivot t x y a; t.assign <- M.add x v t.assign; aux_select_basic_var () | exception NoneSuitable -> raise (Unsat x) in aux_select_basic_var (); () let solve (t:t) : res = try solve_aux t; Solution (get_full_assign t) with | Unsat x -> let cert_expr = List.combine (Vec.to_list (find_expr_basic t x)) (Vec.to_list t.nbasic) in Unsatisfiable { cert_var=x; cert_expr; } | AbsurdBounds x -> Unsatisfiable { cert_var=x; cert_expr=[]; } add [ c·x ] to [ m ] let add_expr_ (x:var) (c:Q.t) (m:Q.t M.t) = let c' = M.get_or ~default:Q.zero x m in let c' = Q.(c + c') in if Q.equal Q.zero c' then M.remove x m else M.add x c' m let rec deref_var_ t x c m = match find_expr_basic_opt t x with | None -> add_expr_ x c m | Some expr_x -> let m = ref m in Vec.iteri (fun i c_i -> let y_i = Vec.get t.nbasic i in m := deref_var_ t y_i Q.(c * c_i) !m) expr_x; !m let scale_bounds c (l,u) : erat * erat = match Q.compare c Q.zero with | 0 -> Erat.zero, Erat.zero | n when n<0 -> Erat.mul c u, Erat.mul c l | _ -> Erat.mul c l, Erat.mul c u let check_cert (t:t) (c:cert) = let x = c.cert_var in let low_x, up_x = get_bounds t x in begin match c.cert_expr with | [] -> if Erat.compare low_x up_x > 0 then `Ok else `Bad_bounds (str_of_erat low_x, str_of_erat up_x) | expr -> let e0 = deref_var_ t x (Q.neg Q.one) M.empty in let low, up, expr_minus_x = List.fold_left (fun (l,u,expr_minus_x) (c, y) -> let ly, uy = scale_bounds c (get_bounds t y) in assert (Erat.compare ly uy <= 0); let expr_minus_x = deref_var_ t y c expr_minus_x in Erat.sum l ly, Erat.sum u uy, expr_minus_x) (Erat.zero, Erat.zero, e0) expr in if M.is_empty expr_minus_x then ( if Erat.compare low_x up > 0 || Erat.compare up_x low < 0 then `Ok else `Bad_bounds (str_of_erat low, str_of_erat up) ) else `Diff_not_0 expr_minus_x end let matrix_pp_width = ref 8 let fmt_head = format_of_string "|%*s|| " let fmt_cell = format_of_string "%*s| " let pp_cert out (c:cert) = match c.cert_expr with | [] -> Format.fprintf out "(@[inconsistent-bounds %a@])" Var.pp c.cert_var | _ -> let pp_pair = Format.(hvbox ~i:2 @@ pair ~sep:(return "@ * ") Q.pp Var.pp) in Format.fprintf out "(@[<hv>cert@ :var %a@ :linexp %a@])" Var.pp c.cert_var Format.(within "[" "]" @@ hvbox @@ list ~sep:(return "@ + ") pp_pair) c.cert_expr let pp_mat out t = let open Format in fprintf out "@[<v>"; fprintf out fmt_head !matrix_pp_width ""; Vec.iter (fun x -> fprintf out fmt_cell !matrix_pp_width (str_of_var x)) t.nbasic; fprintf out "@,"; for i=0 to Matrix.n_row t.tab-1 do if i>0 then fprintf out "@,"; let v = Vec.get t.basic i in fprintf out fmt_head !matrix_pp_width (str_of_var v); let row = Matrix.get_row t.tab i in Vec.iter (fun q -> fprintf out fmt_cell !matrix_pp_width (str_of_q q)) row; done; fprintf out "@]" let pp_assign = let open Format in let pp_pair = within "(" ")" @@ hvbox @@ pair ~sep:(return "@ := ") Var.pp Erat.pp in map Var_map.to_seq @@ within "(" ")" @@ hvbox @@ seq pp_pair let pp_bounds = let open Format in let pp_pairs out (x,(l,u)) = fprintf out "(@[%a =< %a =< %a@])" Erat.pp l Var.pp x Erat.pp u in map Var_map.to_seq @@ within "(" ")" @@ hvbox @@ seq pp_pairs let pp_full_state out (t:t) : unit = Format.fprintf out "(@[<hv>simplex@ :n-row %d :n-col %d@ :mat %a@ :assign %a@ :bounds %a@])" (Matrix.n_row t.tab) (Matrix.n_col t.tab) pp_mat t pp_assign t.assign pp_bounds t.bounds end module Make(Q:Rat.S)(Var:VAR) = Make_inner(Q)(Var)(CCMap.Make(Var)) module Make_full_for_expr(Q : Rat.S)(V : VAR_GEN) (L : Linear_expr.S with type Var.t = V.t and type C.t = Q.t) = struct include Make_inner(Q)(V)(L.Var_map) module L = L type op = [`Eq | `Leq | `Geq | `Lt | `Gt] type 'a constr = ([<op] as 'a) L.Constr.t module Problem = struct type 'a t = ([<op] as 'a) constr list module Infix = struct let (&&) = List.append end include Infix let eval subst = List.for_all (L.Constr.eval subst) let pp out pb = Format.(hvbox @@ list ~sep:(return "@ @<1>∧ ") L.Constr.pp) out pb end let fresh_var = V.Fresh.create () let add_constr (t:t) (c:[<op] constr) : unit = let (x:var) = V.Fresh.fresh fresh_var in let e, op, q = L.Constr.split c in add_eq t (x, L.Comb.to_list e); begin match op with | `Leq -> add_upper_bound t ~strict:false x q | `Geq -> add_lower_bound t ~strict:false x q | `Lt -> add_upper_bound t ~strict:true x q | `Gt -> add_lower_bound t ~strict:true x q | `Eq -> add_bounds t ~strict_lower:false ~strict_upper:false (x,q,q) end let add_problem (t:t) (pb:_ Problem.t) : unit = List.iter (add_constr t) pb end module Make_full(Q : Rat.S)(V : VAR_GEN) = Make_full_for_expr(Q)(V)(Linear_expr.Make(Q)(V))
061efbfdab972afc6a7c0a7f6988a114afbdd8d62880451b58b80858f118929d
sbcl/sbcl
bit-bash.lisp
;;;; functions to implement bitblt-ish operations This software is part of the SBCL system . See the README file for ;;;; more information. ;;;; This software is derived from the CMU CL system , which was written at Carnegie Mellon University and released into the ;;;; public domain. The software is in the public domain and is ;;;; provided with absolutely no warranty. See the COPYING and CREDITS ;;;; files for more information. (in-package "SB-VM") ;;;; support routines (declaim (inline start-mask end-mask)) ;;; Produce a mask that contains 1's for the COUNT "start" bits and 0 's for the remaining " end " bits . Only the lower 5 bits of COUNT are significant ( : because of hardwired implicit dependence on 32 - bit word size -- WHN 2001 - 03 - 19 ) . (defun start-mask (count) (declare (fixnum count)) (shift-towards-start most-positive-word (- count))) ;;; Produce a mask that contains 1's for the COUNT "end" bits and 0's for the remaining " start " bits . Only the lower 5 bits of COUNT are significant ( : because of hardwired implicit dependence on 32 - bit word size -- WHN 2001 - 03 - 19 ) . (defun end-mask (count) (declare (fixnum count)) (shift-towards-end most-positive-word (- count))) ;;; the actual bashers and common uses of same (eval-when (:compile-toplevel :load-toplevel :execute) (defconstant min-bytes-c-call-threshold ;; mostly just guessing here #+(or x86 x86-64 ppc ppc64) 128 #-(or x86 x86-64 ppc ppc64) 256)) (defmacro verify-src/dst-bits-per-elt (source destination expect-bits-per-element) (declare (ignorable source destination expect-bits-per-element)) #+(and sb-devel (not sb-devel-no-errors)) `(let ((src-bits-per-element (ash 1 (aref #.%%simple-array-n-bits-shifts%% (%other-pointer-widetag ,source)))) (dst-bits-per-element (ash 1 (aref #.%%simple-array-n-bits-shifts%% (%other-pointer-widetag ,destination))))) (when (or (/= src-bits-per-element ,expect-bits-per-element) (/= dst-bits-per-element ,expect-bits-per-element)) ;; Why enforce this: because since the arrays are lisp objects ;; maybe we can be clever "somehow" (I'm not sure how) ;; and/or maybe we have to unpoison the memory for #+ubsan. Whereas BYTE - BLT takes SAPs ( and/or arrays ) and so it has to ;; be more strictly like memmove(). Because it is exactly that. (error "Misuse of bash-copy: bits-per-elt=~D but src=~d and dst=~d" ,expect-bits-per-element src-bits-per-element dst-bits-per-element)))) 1 , 2 , 4 , and 8 bytes per element can be handled with memmove ( ) or , if it 's easy enough , a loop over VECTOR - RAW - BITS . (defmacro define-byte-blt-copier (bytes-per-element &aux (bits-per-element (* bytes-per-element 8)) (vtype `(simple-array (unsigned-byte ,bits-per-element) (*))) (elements-per-word (/ n-word-bytes bytes-per-element)) (always-call-out-p ; memmove() is _always_ asymptotically faster than this ;; code, which can't make any use of vectorization that C libraries ;; typically do. It's a question of the overhead of a C call. `(>= nelements ,(/ min-bytes-c-call-threshold bytes-per-element)))) (flet ((backward-p () ;; Iterate backwards if there is overlap and byte transfer is toward higher ;; addresses. Technically (> dst-start src-start) is a necessary ;; but not sufficient condition for overlap, but it's fine. '(and (eq src dst) (> dst-start src-start))) (down () We could reduce the number of loop variables by 1 by computing ;; the distance between src-start and dst-start, and adding it in ;; to each array reference. Probably it would be worse though. '(do ((dst-index (the (or (eql -1) index) (+ dst-start nwords -1)) (1- dst-index)) (src-index (the (or (eql -1) index) (+ src-start nwords -1)) (1- src-index))) ((< dst-index dst-start)) (declare (type (or (eql -1) index) dst-index src-index)) Assigning into SRC is right , because DST and SRC are the same array . ;; We don't need "both" arrays to be in registers. (%set-vector-raw-bits src dst-index (%vector-raw-bits src (the index src-index))))) (up () '(do ((dst-index dst-start (the index (1+ dst-index))) (src-index src-start (the index (1+ src-index)))) ((>= dst-index dst-end)) (%set-vector-raw-bits dst dst-index (%vector-raw-bits src src-index)))) (use-memmove () % BYTE - BLT wants the end as an index , which it converts back to a count ;; by subtracting the start. Regardless, the args are way too confusing, so let 's go directly to memmove . from ( DEFTRANSFORM % BYTE - BLT ) `(with-pinned-objects (dst src) (memmove (sap+ (vector-sap (the ,vtype dst)) (the signed-word (* dst-start ,bytes-per-element))) (sap+ (vector-sap (the ,vtype src)) (the signed-word (* src-start ,bytes-per-element))) (the word (* nelements ,bytes-per-element)))))) ;; The arguments are array element indices. `(defun ,(intern (format nil "UB~D-BASH-COPY" bits-per-element) (find-package "SB-KERNEL")) (src src-start dst dst-start nelements) (declare (type index src-start dst-start nelements)) (verify-src/dst-bits-per-elt src dst ,bits-per-element) (locally (declare (optimize (safety 0) (sb-c::alien-funcall-saves-fp-and-pc 0))) #+cheneygc (when (> nelements 0) ;; cheneygc can't handle a WP fault in memcpy() ;; because "if(!foreign_function_call_active ..." (let ((last (truly-the index (+ dst-start (1- nelements))))) (data-vector-set (truly-the ,vtype dst) last (data-vector-ref (truly-the ,vtype dst) last)))) ,(if (= bytes-per-element sb-vm:n-word-bytes) `(if ,always-call-out-p ,(use-memmove) (let ((nwords nelements)) (if ,(backward-p) ,(down) (let ((dst-end (the index (+ dst-start nelements)))) ,(up))))) `(let ((dst-subword (mod dst-start ,elements-per-word)) (src-subword (mod src-start ,elements-per-word)) (dst (truly-the ,vtype dst)) (src (truly-the ,vtype src))) (cond ((or ,always-call-out-p (/= dst-subword src-subword)) ; too complicated ,(use-memmove)) (,(backward-p) ;; Using the primitive-type-specific data-vector-set, ;; process at most (1- ELEMENTS-PER-WORD) elements ;; until aligned to a word. (let ((dst-end (+ dst-start nelements)) (src-end (+ src-start nelements)) (original-nelements nelements)) ,@(let (initial) (loop for i downfrom (- elements-per-word 1) repeat (1- elements-per-word) do (setq initial Test NELEMENTS first because it should be in a register from the preceding DECF . `((when (and (/= nelements 0) (logtest dst-end ,(1- elements-per-word))) (data-vector-set dst (1- dst-end) (data-vector-ref src (- src-end ,i))) (decf (the index dst-end)) (decf (the index nelements)) ,@initial)))) initial) (decf src-end (the (mod 8) (- original-nelements nelements))) Now DST - END and SRC - END are element indices that start a word . ;; Scan backwards by whole words. (let ((nwords (truncate nelements ,elements-per-word))) (when (plusp nwords) ;; Convert to word indices (let* ((dst-start (- (truncate dst-end ,elements-per-word) nwords)) (src-start (- (truncate src-end ,elements-per-word) nwords))) ,(down)) (decf (the index dst-end) (* nwords ,elements-per-word)) (decf (the index src-end) (* nwords ,elements-per-word)) (decf nelements (* nwords ,elements-per-word)))) ;; If there are elements remaining after the last full word copied, ;; process element by element. ,@(let (final) (loop for i from (1- elements-per-word) downto 1 do (setq final `((unless (= nelements 0) (data-vector-set dst (- dst-end ,i) (data-vector-ref src (- src-end ,i))) ,@(unless (= i (1- elements-per-word)) '((decf (the index nelements)))) ,@final)))) final))) (t ;; Same as above (let ((original-nelements nelements)) ,@(let (initial) (loop for i downfrom (- elements-per-word 2) repeat (1- elements-per-word) do (setq initial `((when (and (/= nelements 0) (logtest dst-start ,(1- elements-per-word))) (data-vector-set dst dst-start (data-vector-ref src (+ src-start ,i))) (incf (the index dst-start)) (decf (the index nelements)) ,@initial)))) initial) (incf (the index src-start) (- original-nelements nelements))) (let ((nwords (truncate nelements ,elements-per-word))) (when (plusp nwords) (let* ((src-start (truncate src-start ,elements-per-word)) (dst-start (truncate dst-start ,elements-per-word)) (dst-end (the index (+ dst-start nwords)))) ,(up)) (incf dst-start (* nwords ,elements-per-word)) (incf src-start (* nwords ,elements-per-word)) (decf nelements (* nwords ,elements-per-word)))) ;; Same as above ,@(let (final) (loop for i from (- elements-per-word 2) downto 0 do (setq final `((unless (= nelements 0) (data-vector-set dst (+ dst-start ,i) (data-vector-ref src (+ src-start ,i))) ,@(unless (= i (- elements-per-word 2)) '((decf (the index nelements)))) ,@final)))) final))))) (values))))) (define-byte-blt-copier 1) (define-byte-blt-copier 2) (define-byte-blt-copier 4) #+64-bit (define-byte-blt-copier 8) We cheat a little bit by using TRULY - THE in the copying function to ;;; force the compiler to generate good code in the (= BITSIZE N - WORD - BITS ) case . We do n't use TRULY - THE in the other cases ;;; to give the compiler freedom to generate better code. (defmacro !define-byte-bashers (bitsize) (let* ((bytes-per-word (/ n-word-bits bitsize)) (byte-offset `(integer 0 (,bytes-per-word))) (word-offset `(integer 0 ,(ceiling array-dimension-limit bytes-per-word))) (constant-bash-name (intern (format nil "CONSTANT-UB~D-BASH" bitsize) (find-package "SB-KERNEL"))) (array-fill-name (intern (format nil "UB~D-BASH-FILL" bitsize) (find-package "SB-KERNEL"))) (unary-bash-name (intern (format nil "UNARY-UB~D-BASH" bitsize) (find-package "SB-KERNEL"))) (array-copy-name (intern (format nil "UB~D-BASH-COPY" bitsize) (find-package "SB-KERNEL")))) `(progn (declaim (inline ,constant-bash-name)) Fill DST with VALUE starting at DST - OFFSET and continuing ;; for LENGTH bytes (however bytes are defined). (defun ,constant-bash-name (dst dst-offset length value) (declare (type word value) (type index dst-offset length)) (multiple-value-bind (dst-word-offset dst-byte-offset) (floor dst-offset ,bytes-per-word) (declare (type ,word-offset dst-word-offset) (type ,byte-offset dst-byte-offset)) (multiple-value-bind (n-words final-bytes) (floor (+ dst-byte-offset length) ,bytes-per-word) (declare (type ,word-offset n-words) (type ,byte-offset final-bytes)) (if (zerop n-words) ,(unless (= bytes-per-word 1) `(unless (zerop length) (%set-vector-raw-bits dst dst-word-offset (if (>= length ,bytes-per-word) value (let ((mask (shift-towards-end (start-mask (* length ,bitsize)) (* dst-byte-offset ,bitsize)))) (word-logical-or (word-logical-and value mask) (word-logical-andc2 (%vector-raw-bits dst dst-word-offset) mask))))))) (let ((interior (floor (- length final-bytes) ,bytes-per-word))) ,@(unless (= bytes-per-word 1) `((unless (zerop dst-byte-offset) (let ((mask (end-mask (* (- dst-byte-offset) ,bitsize)))) (%set-vector-raw-bits dst dst-word-offset (word-logical-or (word-logical-and value mask) (word-logical-andc2 (%vector-raw-bits dst dst-word-offset) mask)))) (incf dst-word-offset)))) (let ((end (+ dst-word-offset interior))) (declare (type ,word-offset end)) (do () ((>= dst-word-offset end)) (%set-vector-raw-bits dst dst-word-offset value) (incf dst-word-offset))) #+nil (dotimes (i interior) (%set-vector-raw-bits dst dst-word-offset value) (incf dst-word-offset)) ,@(unless (= bytes-per-word 1) `((unless (zerop final-bytes) (let ((mask (start-mask (* final-bytes ,bitsize)))) (%set-vector-raw-bits dst dst-word-offset (word-logical-or (word-logical-and value mask) (word-logical-andc2 (%vector-raw-bits dst dst-word-offset) mask))))))))))) (values)) ;; common uses for constant-byte-bashing (defknown ,array-fill-name (word simple-unboxed-array index index) simple-unboxed-array () :result-arg 1 :derive-type (sb-c::result-type-nth-arg 1)) (defun ,array-fill-name (value dst dst-offset length) (declare (type word value) (type index dst-offset length)) (declare (optimize (speed 3) (safety 1))) (,constant-bash-name dst dst-offset length value) dst) Copying . Never use this for 8 , 16 , 32 , 64 ,@(when (member bitsize '(1 2 4)) `((declaim (inline ,unary-bash-name)) (defun ,unary-bash-name (src src-offset dst dst-offset length) (declare (type index src-offset dst-offset length)) (verify-src/dst-bits-per-elt src dst ,bitsize) (multiple-value-bind (dst-word-offset dst-byte-offset) (floor dst-offset ,bytes-per-word) (declare (type ,word-offset dst-word-offset) (type ,byte-offset dst-byte-offset)) (multiple-value-bind (src-word-offset src-byte-offset) (floor src-offset ,bytes-per-word) (declare (type ,word-offset src-word-offset) (type ,byte-offset src-byte-offset)) (cond ((<= (+ dst-byte-offset length) ,bytes-per-word) ;; We are only writing one word, so it doesn't matter what ;; order we do it in. But we might be reading from ;; multiple words, so take care. (cond ((zerop length) ;; We're not writing anything. This is really easy. ) ((>= length ,bytes-per-word) DST - BYTE - OFFSET must be equal to zero , or we would be writing multiple words . If SRC - BYTE - OFFSET is also zero , ;; the we just transfer the single word. Otherwise we have to extract bytes from two source words . (%set-vector-raw-bits dst dst-word-offset (cond ((zerop src-byte-offset) (%vector-raw-bits src src-word-offset)) ,@(unless (= bytes-per-word 1) `((t (word-logical-or (shift-towards-start (%vector-raw-bits src src-word-offset) (* src-byte-offset ,bitsize)) (shift-towards-end (%vector-raw-bits src (1+ src-word-offset)) (* (- src-byte-offset) ,bitsize))))))))) ,@(unless (= bytes-per-word 1) `((t ;; We are only writing some portion of the destination word. We still do n't know whether we need one or two source words . (let ((mask (shift-towards-end (start-mask (* length ,bitsize)) (* dst-byte-offset ,bitsize))) (orig (%vector-raw-bits dst dst-word-offset)) (value (if (> src-byte-offset dst-byte-offset) ;; The source starts further ;; into the word than does the ;; destination, so the source ;; could extend into the next ;; word. If it does, we have to merge the two words , and ;; it not, we can just shift the first word . (let ((src-byte-shift (- src-byte-offset dst-byte-offset))) (if (> (+ src-byte-offset length) ,bytes-per-word) (word-logical-or (shift-towards-start (%vector-raw-bits src src-word-offset) (* src-byte-shift ,bitsize)) (shift-towards-end (%vector-raw-bits src (1+ src-word-offset)) (* (- src-byte-shift) ,bitsize))) (shift-towards-start (%vector-raw-bits src src-word-offset) (* src-byte-shift ,bitsize)))) ;; The destination starts further ;; into the word than does the ;; source, so we know the source can not extend into a second ;; word (or else the destination ;; would too, and we wouldn't be ;; in this branch). (shift-towards-end (%vector-raw-bits src src-word-offset) (* (- dst-byte-offset src-byte-offset) ,bitsize))))) (declare (type word mask orig value)) (%set-vector-raw-bits dst dst-word-offset (word-logical-or (word-logical-and value mask) (word-logical-andc2 orig mask))))))))) ((= src-byte-offset dst-byte-offset) ;; The source and destination are aligned, so shifting ;; is unnecessary. But we have to pick the direction ;; of the copy in case the source and destination are ;; really the same object. (multiple-value-bind (words final-bytes) (floor (+ dst-byte-offset length) ,bytes-per-word) (declare (type ,word-offset words) (type ,byte-offset final-bytes)) (let ((interior (floor (- length final-bytes) ,bytes-per-word))) (declare (type ,word-offset interior)) (cond ((<= dst-offset src-offset) ;; We need to loop from left to right. ,@(unless (= bytes-per-word 1) `((unless (zerop dst-byte-offset) We are only writing part of the first word , so mask ;; off the bytes we want to preserve. (let ((mask (end-mask (* (- dst-byte-offset) ,bitsize))) (orig (%vector-raw-bits dst dst-word-offset)) (value (%vector-raw-bits src src-word-offset))) (declare (type word mask orig value)) (%set-vector-raw-bits dst dst-word-offset (word-logical-or (word-logical-and value mask) (word-logical-andc2 orig mask)))) (incf src-word-offset) (incf dst-word-offset)))) ;; Copy the interior words. (let ((end ,(if (= bytes-per-word 1) `(truly-the ,word-offset (+ dst-word-offset interior)) `(+ dst-word-offset interior)))) (declare (type ,word-offset end)) (do () ((>= dst-word-offset end)) (%set-vector-raw-bits dst dst-word-offset (%vector-raw-bits src src-word-offset)) ,(if (= bytes-per-word 1) `(setf src-word-offset (truly-the ,word-offset (+ src-word-offset 1))) `(incf src-word-offset)) (incf dst-word-offset))) ,@(unless (= bytes-per-word 1) `((unless (zerop final-bytes) ;; We are only writing part of the last word. (let ((mask (start-mask (* final-bytes ,bitsize))) (orig (%vector-raw-bits dst dst-word-offset)) (value (%vector-raw-bits src src-word-offset))) (declare (type word mask orig value)) (%set-vector-raw-bits dst dst-word-offset (word-logical-or (word-logical-and value mask) (word-logical-andc2 orig mask)))))))) (t ;; We need to loop from right to left. ,(if (= bytes-per-word 1) `(setf dst-word-offset (truly-the ,word-offset (+ dst-word-offset words))) `(incf dst-word-offset words)) ,(if (= bytes-per-word 1) `(setf src-word-offset (truly-the ,word-offset (+ src-word-offset words))) `(incf src-word-offset words)) ,@(unless (= bytes-per-word 1) `((unless (zerop final-bytes) (let ((mask (start-mask (* final-bytes ,bitsize))) (orig (%vector-raw-bits dst dst-word-offset)) (value (%vector-raw-bits src src-word-offset))) (declare (type word mask orig value)) (%set-vector-raw-bits dst dst-word-offset (word-logical-or (word-logical-and value mask) (word-logical-andc2 orig mask))))))) (let ((end (- dst-word-offset interior))) (do () ((<= dst-word-offset end)) (decf src-word-offset) (decf dst-word-offset) (%set-vector-raw-bits dst dst-word-offset (%vector-raw-bits src src-word-offset)))) ,@(unless (= bytes-per-word 1) `((unless (zerop dst-byte-offset) ;; We are only writing part of the last word. (decf src-word-offset) (decf dst-word-offset) (let ((mask (end-mask (* (- dst-byte-offset) ,bitsize))) (orig (%vector-raw-bits dst dst-word-offset)) (value (%vector-raw-bits src src-word-offset))) (declare (type word mask orig value)) (%set-vector-raw-bits dst dst-word-offset (word-logical-or (word-logical-and value mask) (word-logical-andc2 orig mask)))))))))))) (t ;; Source and destination are not aligned. (multiple-value-bind (words final-bytes) (floor (+ dst-byte-offset length) ,bytes-per-word) (declare (type ,word-offset words) (type ,byte-offset final-bytes)) (let ((src-shift (mod (- src-byte-offset dst-byte-offset) ,bytes-per-word)) (interior (floor (- length final-bytes) ,bytes-per-word))) (declare (type ,word-offset interior) (type ,byte-offset src-shift)) (cond ((<= dst-offset src-offset) ;; We need to loop from left to right. (let ((prev 0) (next (%vector-raw-bits src src-word-offset))) (declare (type word prev next)) (flet ((get-next-src () (setf prev next) (setf next (%vector-raw-bits src (incf src-word-offset))))) (declare (inline get-next-src)) ,@(unless (= bytes-per-word 1) `((unless (zerop dst-byte-offset) (when (> src-byte-offset dst-byte-offset) (get-next-src)) (let ((mask (end-mask (* (- dst-byte-offset) ,bitsize))) (orig (%vector-raw-bits dst dst-word-offset)) (value (word-logical-or (shift-towards-start prev (* src-shift ,bitsize)) (shift-towards-end next (* (- src-shift) ,bitsize))))) (declare (type word mask orig value)) (%set-vector-raw-bits dst dst-word-offset (word-logical-or (word-logical-and value mask) (word-logical-andc2 orig mask)))) (incf dst-word-offset)))) (let ((end (+ dst-word-offset interior))) (declare (type ,word-offset end)) (do () ((>= dst-word-offset end)) (get-next-src) (let ((value (word-logical-or (shift-towards-end next (* (- src-shift) ,bitsize)) (shift-towards-start prev (* src-shift ,bitsize))))) (declare (type word value)) (%set-vector-raw-bits dst dst-word-offset value) (incf dst-word-offset)))) ,@(unless (= bytes-per-word 1) `((unless (zerop final-bytes) (let ((value (if (> (+ final-bytes src-shift) ,bytes-per-word) (progn (get-next-src) (word-logical-or (shift-towards-end next (* (- src-shift) ,bitsize)) (shift-towards-start prev (* src-shift ,bitsize)))) (shift-towards-start next (* src-shift ,bitsize)))) (mask (start-mask (* final-bytes ,bitsize))) (orig (%vector-raw-bits dst dst-word-offset))) (declare (type word mask orig value)) (%set-vector-raw-bits dst dst-word-offset (word-logical-or (word-logical-and value mask) (word-logical-andc2 orig mask)))))))))) (t ;; We need to loop from right to left. (incf dst-word-offset words) (incf src-word-offset (1- (ceiling (+ src-byte-offset length) ,bytes-per-word))) (let ((next 0) (prev (%vector-raw-bits src src-word-offset))) (declare (type word prev next)) (flet ((get-next-src () (setf next prev) (setf prev (%vector-raw-bits src (decf src-word-offset))))) (declare (inline get-next-src)) ,@(unless (= bytes-per-word 1) `((unless (zerop final-bytes) (when (> final-bytes (- ,bytes-per-word src-shift)) (get-next-src)) (let ((value (word-logical-or (shift-towards-end next (* (- src-shift) ,bitsize)) (shift-towards-start prev (* src-shift ,bitsize)))) (mask (start-mask (* final-bytes ,bitsize))) (orig (%vector-raw-bits dst dst-word-offset))) (declare (type word mask orig value)) (%set-vector-raw-bits dst dst-word-offset (word-logical-or (word-logical-and value mask) (word-logical-andc2 orig mask))))))) (decf dst-word-offset) (let ((end (- dst-word-offset interior))) (do () ((<= dst-word-offset end)) (get-next-src) (let ((value (word-logical-or (shift-towards-end next (* (- src-shift) ,bitsize)) (shift-towards-start prev (* src-shift ,bitsize))))) (declare (type word value)) (%set-vector-raw-bits dst dst-word-offset value) (decf dst-word-offset)))) ,@(unless (= bytes-per-word 1) `((unless (zerop dst-byte-offset) (if (> src-byte-offset dst-byte-offset) (get-next-src) (setf next prev prev 0)) (let ((mask (end-mask (* (- dst-byte-offset) ,bitsize))) (orig (%vector-raw-bits dst dst-word-offset)) (value (word-logical-or (shift-towards-start prev (* src-shift ,bitsize)) (shift-towards-end next (* (- src-shift) ,bitsize))))) (declare (type word mask orig value)) (%set-vector-raw-bits dst dst-word-offset (word-logical-or (word-logical-and value mask) (word-logical-andc2 orig mask))))))))))))))))) (values)) ;; common uses for unary-byte-bashing (defun ,array-copy-name (src src-offset dst dst-offset length) (declare (type index src-offset dst-offset length)) (locally (declare (optimize (speed 3) (safety 1))) (,unary-bash-name src src-offset dst dst-offset length)))))))) We would normally do this with a MACROLET , but then we run into ;;; problems with the lexical environment being too hairy for the ;;; cross-compiler and it cannot inline the basic basher functions. #.(loop for i = 1 then (* i 2) collect `(!define-byte-bashers ,i) into bashers until (= i n-word-bits) finally (return `(progn ,@bashers))) (defmacro !define-constant-byte-bashers (bitsize type value-transformer &optional (name type)) (let ((constant-bash-name (intern (format nil "CONSTANT-UB~D-BASH" bitsize) (find-package "SB-KERNEL"))) (array-fill-name (intern (format nil "UB~D-BASH-FILL-WITH-~A" bitsize name) (find-package "SB-KERNEL")))) `(progn (defknown ,array-fill-name (,type simple-unboxed-array index index) simple-unboxed-array () :result-arg 1 :derive-type (sb-c::result-type-nth-arg 1)) (defun ,array-fill-name (value dst dst-offset length) (declare (type ,type value) (type index dst-offset length)) (declare (optimize (speed 3) (safety 1))) (,constant-bash-name dst dst-offset length (,value-transformer value)) dst)))) (macrolet ((def () `(progn ,@(loop for n-bits = 1 then (* n-bits 2) until (= n-bits n-word-bits) collect `(!define-constant-byte-bashers ,n-bits (unsigned-byte ,n-bits) (lambda (value) ,@(loop for i = n-bits then (* 2 i) until (= i sb-vm:n-word-bits) collect `(setf value (dpb value (byte ,i ,i) value)))) ,(format nil "UB~A" n-bits)) collect `(!define-constant-byte-bashers ,n-bits (signed-byte ,n-bits) (lambda (value) (let ((value (ldb (byte ,n-bits 0) value))) ,@(loop for i = n-bits then (* 2 i) until (= i sb-vm:n-word-bits) collect `(setf value (dpb value (byte ,i ,i) value))))) ,(format nil "SB~A" n-bits))) (!define-constant-byte-bashers ,n-word-bits (signed-byte ,n-word-bits) (lambda (value) (ldb (byte ,n-word-bits 0) value)) ,(format nil "SB~A" n-word-bits))))) (def)) (!define-constant-byte-bashers #.n-word-bits fixnum (lambda (value) (ldb (byte #.n-word-bits 0) (ash value n-fixnum-tag-bits)))) (!define-constant-byte-bashers 32 single-float (lambda (value) (let ((bits (ldb (byte 32 0) (single-float-bits value)))) #+64-bit (dpb bits (byte 32 32) bits) #-64-bit bits))) #+64-bit (!define-constant-byte-bashers 64 double-float (lambda (value) (ldb (byte 64 0) (double-float-bits value)))) #+64-bit (!define-constant-byte-bashers 64 (complex single-float) (lambda (item) #+big-endian (logior (ash (ldb (byte 32 0) (single-float-bits (realpart item))) 32) (ldb (byte 32 0) (single-float-bits (imagpart item)))) #+little-endian (logior (ash (ldb (byte 32 0) (single-float-bits (imagpart item))) 32) (ldb (byte 32 0) (single-float-bits (realpart item))))) complex-single-float) ;;;; Bashing-Style search for bits ;;;; ;;;; Similar search would work well for base-strings as well. ;;;; (Technically for all unboxed sequences of sub-word size elements, ;;;; but somehow I doubt eg. octet vectors get POSITION or FIND used ;;;; as much on them.) (defconstant +bit-position-base-mask+ (1- n-word-bits)) (defconstant +bit-position-base-shift+ (integer-length +bit-position-base-mask+)) (macrolet ((compute-start-mask (index) `(let ((first-bits (logand ,index +bit-position-base-mask+))) #+little-endian (ash -1 first-bits) #+big-endian (lognot (ash -1 (- n-word-bits first-bits))))) (compute-end-mask (index) `(let ((last-bits (logand ,index +bit-position-base-mask+))) #+little-endian (lognot (ash -1 last-bits)) #+big-endian (logand (ash -1 (- n-word-bits last-bits)) most-positive-word))) (calc-index (bit-index) `(logior (the index ,bit-index) (truly-the fixnum (ash word-index +bit-position-base-shift+)))) (def (name from-end frob) `(defun ,name (vector start end) (declare (simple-bit-vector vector) (index start end) (optimize (speed 3) (safety 0))) ;; The END parameter is an exclusive limit as is customary. ;; It's somewhat subjective whether the algorithm below would become simpler by subtracting 1 from END initially . (let* ((first-word (ash start (- +bit-position-base-shift+))) (last-word (ash end (- +bit-position-base-shift+))) ;; These mask out everything but the interesting parts. (start-mask (compute-start-mask start)) (end-mask (compute-end-mask end))) (declare (index last-word first-word)) (flet ((#+little-endian start-bit #+big-endian end-bit (x) (declare (word x)) #+(or x86-64 x86) (truly-the (mod #.n-word-bits) (%primitive unsigned-word-find-first-bit x)) #-(or x86-64 x86) (- #+big-endian n-word-bits (integer-length (logand x (- x))) #+little-endian 1)) (#+little-endian end-bit #+big-endian start-bit (x) (declare (word x)) (- #+big-endian n-word-bits (integer-length x) #+little-endian 1)) (get-word (offset) (,@frob (%vector-raw-bits vector offset)))) (declare (inline start-bit end-bit get-word)) (unless (< first-word last-word) ;; Both masks pertain to a single word. This also catches ;; START = END. In that case the masks have no bits in common. (return-from ,name (let ((mask (logand start-mask end-mask))) (unless (zerop mask) (let ((word (logand mask (get-word first-word)))) (unless (zerop word) (let ((word-index first-word)) ; for the macro to see ,(if from-end `(calc-index (end-bit word)) `(calc-index (start-bit word)))))))))) ;; Since the start and end words differ, there is no word ;; to which both masks pertain. ;; We use a fairly traditional algorithm: ( 1 ) scan some number ( 0 < = N < = n - word - bits ) of bits initially , ( 2 ) then a whole number of intervening words , ( 3 ) then some number ( 0 < N < n - word - bits ) of trailing bits Steps ( 1 ) and ( 3 ) use the START and END masks respectively . The START mask has between 1 and N - WORD - BITS ( inclusive ) consecutive 1s , starting from the appropriate end . ;; END-MASK instead of getting all 1s in the limiting case, gets all 0s , and a LAST - WORD value that is 1 too high ;; which is semantically correct - it is an "inclusive" limit ;; of a word in which no bits should be examined. ;; When that occurs, we avoid reading the final word ;; to avoid a buffer overrun bug. ,(if from-end ;; Reverse scan: `(let ((word-index last-word)) ; trailing chunk (declare (index word-index)) (unless (zerop end-mask) ;; If no bits are set, then this is off the end of the subsequence. ;; Do not read the word at all. (let ((word (logand end-mask (get-word word-index)))) (unless (zerop word) (return-from ,name (calc-index (end-bit word)))))) (decf word-index) ;; middle chunks (loop while (> word-index first-word) ; might execute 0 times do (let ((word (get-word word-index))) (unless (zerop word) (return-from ,name (calc-index (end-bit word))))) (decf word-index)) ;; leading chunk - always executed (let ((word (logand start-mask (get-word first-word)))) (unless (zerop word) (calc-index (end-bit word))))) ;; Forward scan: `(let* ((word-index first-word) (word (logand start-mask (get-word word-index)))) (declare (index word-index)) (unless (zerop word) (return-from ,name (calc-index (start-bit word)))) (incf word-index) ;; Scan full words up to but excluding LAST-WORD (loop while (< word-index last-word) ; might execute 0 times do (let ((word (get-word word-index))) (unless (zerop word) (return-from ,name (calc-index (start-bit word))))) (incf word-index)) ;; Scan last word unless no bits in mask (unless (zerop end-mask) (let ((word (logand end-mask (get-word word-index)))) (unless (zerop word) (calc-index (start-bit word)))))))))))) (defun run-bit-position-assertions () Check the claim in the comment at " ( unless ( < first - word last - word ) " (loop for i from 0 to (* 2 n-word-bits) do (let ((start-mask (compute-start-mask i)) (end-mask (compute-end-mask i))) (assert (= (logand start-mask end-mask) 0))))) (def %bit-pos-fwd/1 nil (identity)) (def %bit-pos-rev/1 t (identity)) (def %bit-pos-fwd/0 nil (logandc2 most-positive-word)) (def %bit-pos-rev/0 t (logandc2 most-positive-word))) ;; Known direction, unknown item to find (defun %bit-pos-fwd (bit vector start end) (case bit (0 (%bit-pos-fwd/0 vector start end)) (1 (%bit-pos-fwd/1 vector start end)) (otherwise nil))) (defun %bit-pos-rev (bit vector start end) (case bit (0 (%bit-pos-rev/0 vector start end)) (1 (%bit-pos-rev/1 vector start end)) (otherwise nil))) ;; Known item to find, unknown direction (declaim (maybe-inline %bit-position/0 %bit-position/1)) (defun %bit-position/0 (vector from-end start end) (if from-end (%bit-pos-rev/0 vector start end) (%bit-pos-fwd/0 vector start end))) (defun %bit-position/1 (vector from-end start end) (if from-end (%bit-pos-rev/1 vector start end) (%bit-pos-fwd/1 vector start end))) (defun %bit-position (bit vector from-end start end) (declare (inline %bit-position/0 %bit-position/1)) (case bit (0 (%bit-position/0 vector from-end start end)) (1 (%bit-position/1 vector from-end start end)) (otherwise nil))) (clear-info :function :inlinep '%bit-position/0) (clear-info :function :inlinep '%bit-position/1) (run-bit-position-assertions)
null
https://raw.githubusercontent.com/sbcl/sbcl/8911276f69a6f3e11f81e6da7c6b84c6302a4f35/src/code/bit-bash.lisp
lisp
functions to implement bitblt-ish operations more information. public domain. The software is in the public domain and is provided with absolutely no warranty. See the COPYING and CREDITS files for more information. support routines Produce a mask that contains 1's for the COUNT "start" bits and Produce a mask that contains 1's for the COUNT "end" bits and 0's the actual bashers and common uses of same mostly just guessing here Why enforce this: because since the arrays are lisp objects maybe we can be clever "somehow" (I'm not sure how) and/or maybe we have to unpoison the memory for #+ubsan. be more strictly like memmove(). Because it is exactly that. memmove() is _always_ asymptotically faster than this code, which can't make any use of vectorization that C libraries typically do. It's a question of the overhead of a C call. Iterate backwards if there is overlap and byte transfer is toward higher addresses. Technically (> dst-start src-start) is a necessary but not sufficient condition for overlap, but it's fine. the distance between src-start and dst-start, and adding it in to each array reference. Probably it would be worse though. We don't need "both" arrays to be in registers. by subtracting the start. Regardless, the args are way too confusing, The arguments are array element indices. cheneygc can't handle a WP fault in memcpy() because "if(!foreign_function_call_active ..." too complicated Using the primitive-type-specific data-vector-set, process at most (1- ELEMENTS-PER-WORD) elements until aligned to a word. Scan backwards by whole words. Convert to word indices If there are elements remaining after the last full word copied, process element by element. Same as above Same as above force the compiler to generate good code in the (= BITSIZE to give the compiler freedom to generate better code. for LENGTH bytes (however bytes are defined). common uses for constant-byte-bashing We are only writing one word, so it doesn't matter what order we do it in. But we might be reading from multiple words, so take care. We're not writing anything. This is really easy. the we just transfer the single word. Otherwise we have We are only writing some portion of the destination word. The source starts further into the word than does the destination, so the source could extend into the next word. If it does, we have it not, we can just shift The destination starts further into the word than does the source, so we know the source word (or else the destination would too, and we wouldn't be in this branch). The source and destination are aligned, so shifting is unnecessary. But we have to pick the direction of the copy in case the source and destination are really the same object. We need to loop from left to right. off the bytes we want to preserve. Copy the interior words. We are only writing part of the last word. We need to loop from right to left. We are only writing part of the last word. Source and destination are not aligned. We need to loop from left to right. We need to loop from right to left. common uses for unary-byte-bashing problems with the lexical environment being too hairy for the cross-compiler and it cannot inline the basic basher functions. Bashing-Style search for bits Similar search would work well for base-strings as well. (Technically for all unboxed sequences of sub-word size elements, but somehow I doubt eg. octet vectors get POSITION or FIND used as much on them.) The END parameter is an exclusive limit as is customary. It's somewhat subjective whether the algorithm below These mask out everything but the interesting parts. Both masks pertain to a single word. This also catches START = END. In that case the masks have no bits in common. for the macro to see Since the start and end words differ, there is no word to which both masks pertain. We use a fairly traditional algorithm: END-MASK instead of getting all 1s in the limiting case, which is semantically correct - it is an "inclusive" limit of a word in which no bits should be examined. When that occurs, we avoid reading the final word to avoid a buffer overrun bug. Reverse scan: trailing chunk If no bits are set, then this is off the end of the subsequence. Do not read the word at all. middle chunks might execute 0 times leading chunk - always executed Forward scan: Scan full words up to but excluding LAST-WORD might execute 0 times Scan last word unless no bits in mask Known direction, unknown item to find Known item to find, unknown direction
This software is part of the SBCL system . See the README file for This software is derived from the CMU CL system , which was written at Carnegie Mellon University and released into the (in-package "SB-VM") (declaim (inline start-mask end-mask)) 0 's for the remaining " end " bits . Only the lower 5 bits of COUNT are significant ( : because of hardwired implicit dependence on 32 - bit word size -- WHN 2001 - 03 - 19 ) . (defun start-mask (count) (declare (fixnum count)) (shift-towards-start most-positive-word (- count))) for the remaining " start " bits . Only the lower 5 bits of COUNT are significant ( : because of hardwired implicit dependence on 32 - bit word size -- WHN 2001 - 03 - 19 ) . (defun end-mask (count) (declare (fixnum count)) (shift-towards-end most-positive-word (- count))) (eval-when (:compile-toplevel :load-toplevel :execute) (defconstant min-bytes-c-call-threshold #+(or x86 x86-64 ppc ppc64) 128 #-(or x86 x86-64 ppc ppc64) 256)) (defmacro verify-src/dst-bits-per-elt (source destination expect-bits-per-element) (declare (ignorable source destination expect-bits-per-element)) #+(and sb-devel (not sb-devel-no-errors)) `(let ((src-bits-per-element (ash 1 (aref #.%%simple-array-n-bits-shifts%% (%other-pointer-widetag ,source)))) (dst-bits-per-element (ash 1 (aref #.%%simple-array-n-bits-shifts%% (%other-pointer-widetag ,destination))))) (when (or (/= src-bits-per-element ,expect-bits-per-element) (/= dst-bits-per-element ,expect-bits-per-element)) Whereas BYTE - BLT takes SAPs ( and/or arrays ) and so it has to (error "Misuse of bash-copy: bits-per-elt=~D but src=~d and dst=~d" ,expect-bits-per-element src-bits-per-element dst-bits-per-element)))) 1 , 2 , 4 , and 8 bytes per element can be handled with memmove ( ) or , if it 's easy enough , a loop over VECTOR - RAW - BITS . (defmacro define-byte-blt-copier (bytes-per-element &aux (bits-per-element (* bytes-per-element 8)) (vtype `(simple-array (unsigned-byte ,bits-per-element) (*))) (elements-per-word (/ n-word-bytes bytes-per-element)) `(>= nelements ,(/ min-bytes-c-call-threshold bytes-per-element)))) (flet ((backward-p () '(and (eq src dst) (> dst-start src-start))) (down () We could reduce the number of loop variables by 1 by computing '(do ((dst-index (the (or (eql -1) index) (+ dst-start nwords -1)) (1- dst-index)) (src-index (the (or (eql -1) index) (+ src-start nwords -1)) (1- src-index))) ((< dst-index dst-start)) (declare (type (or (eql -1) index) dst-index src-index)) Assigning into SRC is right , because DST and SRC are the same array . (%set-vector-raw-bits src dst-index (%vector-raw-bits src (the index src-index))))) (up () '(do ((dst-index dst-start (the index (1+ dst-index))) (src-index src-start (the index (1+ src-index)))) ((>= dst-index dst-end)) (%set-vector-raw-bits dst dst-index (%vector-raw-bits src src-index)))) (use-memmove () % BYTE - BLT wants the end as an index , which it converts back to a count so let 's go directly to memmove . from ( DEFTRANSFORM % BYTE - BLT ) `(with-pinned-objects (dst src) (memmove (sap+ (vector-sap (the ,vtype dst)) (the signed-word (* dst-start ,bytes-per-element))) (sap+ (vector-sap (the ,vtype src)) (the signed-word (* src-start ,bytes-per-element))) (the word (* nelements ,bytes-per-element)))))) `(defun ,(intern (format nil "UB~D-BASH-COPY" bits-per-element) (find-package "SB-KERNEL")) (src src-start dst dst-start nelements) (declare (type index src-start dst-start nelements)) (verify-src/dst-bits-per-elt src dst ,bits-per-element) (locally (declare (optimize (safety 0) (sb-c::alien-funcall-saves-fp-and-pc 0))) #+cheneygc (when (> nelements 0) (let ((last (truly-the index (+ dst-start (1- nelements))))) (data-vector-set (truly-the ,vtype dst) last (data-vector-ref (truly-the ,vtype dst) last)))) ,(if (= bytes-per-element sb-vm:n-word-bytes) `(if ,always-call-out-p ,(use-memmove) (let ((nwords nelements)) (if ,(backward-p) ,(down) (let ((dst-end (the index (+ dst-start nelements)))) ,(up))))) `(let ((dst-subword (mod dst-start ,elements-per-word)) (src-subword (mod src-start ,elements-per-word)) (dst (truly-the ,vtype dst)) (src (truly-the ,vtype src))) (cond ((or ,always-call-out-p ,(use-memmove)) (,(backward-p) (let ((dst-end (+ dst-start nelements)) (src-end (+ src-start nelements)) (original-nelements nelements)) ,@(let (initial) (loop for i downfrom (- elements-per-word 1) repeat (1- elements-per-word) do (setq initial Test NELEMENTS first because it should be in a register from the preceding DECF . `((when (and (/= nelements 0) (logtest dst-end ,(1- elements-per-word))) (data-vector-set dst (1- dst-end) (data-vector-ref src (- src-end ,i))) (decf (the index dst-end)) (decf (the index nelements)) ,@initial)))) initial) (decf src-end (the (mod 8) (- original-nelements nelements))) Now DST - END and SRC - END are element indices that start a word . (let ((nwords (truncate nelements ,elements-per-word))) (when (plusp nwords) (let* ((dst-start (- (truncate dst-end ,elements-per-word) nwords)) (src-start (- (truncate src-end ,elements-per-word) nwords))) ,(down)) (decf (the index dst-end) (* nwords ,elements-per-word)) (decf (the index src-end) (* nwords ,elements-per-word)) (decf nelements (* nwords ,elements-per-word)))) ,@(let (final) (loop for i from (1- elements-per-word) downto 1 do (setq final `((unless (= nelements 0) (data-vector-set dst (- dst-end ,i) (data-vector-ref src (- src-end ,i))) ,@(unless (= i (1- elements-per-word)) '((decf (the index nelements)))) ,@final)))) final))) (t (let ((original-nelements nelements)) ,@(let (initial) (loop for i downfrom (- elements-per-word 2) repeat (1- elements-per-word) do (setq initial `((when (and (/= nelements 0) (logtest dst-start ,(1- elements-per-word))) (data-vector-set dst dst-start (data-vector-ref src (+ src-start ,i))) (incf (the index dst-start)) (decf (the index nelements)) ,@initial)))) initial) (incf (the index src-start) (- original-nelements nelements))) (let ((nwords (truncate nelements ,elements-per-word))) (when (plusp nwords) (let* ((src-start (truncate src-start ,elements-per-word)) (dst-start (truncate dst-start ,elements-per-word)) (dst-end (the index (+ dst-start nwords)))) ,(up)) (incf dst-start (* nwords ,elements-per-word)) (incf src-start (* nwords ,elements-per-word)) (decf nelements (* nwords ,elements-per-word)))) ,@(let (final) (loop for i from (- elements-per-word 2) downto 0 do (setq final `((unless (= nelements 0) (data-vector-set dst (+ dst-start ,i) (data-vector-ref src (+ src-start ,i))) ,@(unless (= i (- elements-per-word 2)) '((decf (the index nelements)))) ,@final)))) final))))) (values))))) (define-byte-blt-copier 1) (define-byte-blt-copier 2) (define-byte-blt-copier 4) #+64-bit (define-byte-blt-copier 8) We cheat a little bit by using TRULY - THE in the copying function to N - WORD - BITS ) case . We do n't use TRULY - THE in the other cases (defmacro !define-byte-bashers (bitsize) (let* ((bytes-per-word (/ n-word-bits bitsize)) (byte-offset `(integer 0 (,bytes-per-word))) (word-offset `(integer 0 ,(ceiling array-dimension-limit bytes-per-word))) (constant-bash-name (intern (format nil "CONSTANT-UB~D-BASH" bitsize) (find-package "SB-KERNEL"))) (array-fill-name (intern (format nil "UB~D-BASH-FILL" bitsize) (find-package "SB-KERNEL"))) (unary-bash-name (intern (format nil "UNARY-UB~D-BASH" bitsize) (find-package "SB-KERNEL"))) (array-copy-name (intern (format nil "UB~D-BASH-COPY" bitsize) (find-package "SB-KERNEL")))) `(progn (declaim (inline ,constant-bash-name)) Fill DST with VALUE starting at DST - OFFSET and continuing (defun ,constant-bash-name (dst dst-offset length value) (declare (type word value) (type index dst-offset length)) (multiple-value-bind (dst-word-offset dst-byte-offset) (floor dst-offset ,bytes-per-word) (declare (type ,word-offset dst-word-offset) (type ,byte-offset dst-byte-offset)) (multiple-value-bind (n-words final-bytes) (floor (+ dst-byte-offset length) ,bytes-per-word) (declare (type ,word-offset n-words) (type ,byte-offset final-bytes)) (if (zerop n-words) ,(unless (= bytes-per-word 1) `(unless (zerop length) (%set-vector-raw-bits dst dst-word-offset (if (>= length ,bytes-per-word) value (let ((mask (shift-towards-end (start-mask (* length ,bitsize)) (* dst-byte-offset ,bitsize)))) (word-logical-or (word-logical-and value mask) (word-logical-andc2 (%vector-raw-bits dst dst-word-offset) mask))))))) (let ((interior (floor (- length final-bytes) ,bytes-per-word))) ,@(unless (= bytes-per-word 1) `((unless (zerop dst-byte-offset) (let ((mask (end-mask (* (- dst-byte-offset) ,bitsize)))) (%set-vector-raw-bits dst dst-word-offset (word-logical-or (word-logical-and value mask) (word-logical-andc2 (%vector-raw-bits dst dst-word-offset) mask)))) (incf dst-word-offset)))) (let ((end (+ dst-word-offset interior))) (declare (type ,word-offset end)) (do () ((>= dst-word-offset end)) (%set-vector-raw-bits dst dst-word-offset value) (incf dst-word-offset))) #+nil (dotimes (i interior) (%set-vector-raw-bits dst dst-word-offset value) (incf dst-word-offset)) ,@(unless (= bytes-per-word 1) `((unless (zerop final-bytes) (let ((mask (start-mask (* final-bytes ,bitsize)))) (%set-vector-raw-bits dst dst-word-offset (word-logical-or (word-logical-and value mask) (word-logical-andc2 (%vector-raw-bits dst dst-word-offset) mask))))))))))) (values)) (defknown ,array-fill-name (word simple-unboxed-array index index) simple-unboxed-array () :result-arg 1 :derive-type (sb-c::result-type-nth-arg 1)) (defun ,array-fill-name (value dst dst-offset length) (declare (type word value) (type index dst-offset length)) (declare (optimize (speed 3) (safety 1))) (,constant-bash-name dst dst-offset length value) dst) Copying . Never use this for 8 , 16 , 32 , 64 ,@(when (member bitsize '(1 2 4)) `((declaim (inline ,unary-bash-name)) (defun ,unary-bash-name (src src-offset dst dst-offset length) (declare (type index src-offset dst-offset length)) (verify-src/dst-bits-per-elt src dst ,bitsize) (multiple-value-bind (dst-word-offset dst-byte-offset) (floor dst-offset ,bytes-per-word) (declare (type ,word-offset dst-word-offset) (type ,byte-offset dst-byte-offset)) (multiple-value-bind (src-word-offset src-byte-offset) (floor src-offset ,bytes-per-word) (declare (type ,word-offset src-word-offset) (type ,byte-offset src-byte-offset)) (cond ((<= (+ dst-byte-offset length) ,bytes-per-word) (cond ((zerop length) ) ((>= length ,bytes-per-word) DST - BYTE - OFFSET must be equal to zero , or we would be writing multiple words . If SRC - BYTE - OFFSET is also zero , to extract bytes from two source words . (%set-vector-raw-bits dst dst-word-offset (cond ((zerop src-byte-offset) (%vector-raw-bits src src-word-offset)) ,@(unless (= bytes-per-word 1) `((t (word-logical-or (shift-towards-start (%vector-raw-bits src src-word-offset) (* src-byte-offset ,bitsize)) (shift-towards-end (%vector-raw-bits src (1+ src-word-offset)) (* (- src-byte-offset) ,bitsize))))))))) ,@(unless (= bytes-per-word 1) `((t We still do n't know whether we need one or two source words . (let ((mask (shift-towards-end (start-mask (* length ,bitsize)) (* dst-byte-offset ,bitsize))) (orig (%vector-raw-bits dst dst-word-offset)) (value (if (> src-byte-offset dst-byte-offset) to merge the two words , and the first word . (let ((src-byte-shift (- src-byte-offset dst-byte-offset))) (if (> (+ src-byte-offset length) ,bytes-per-word) (word-logical-or (shift-towards-start (%vector-raw-bits src src-word-offset) (* src-byte-shift ,bitsize)) (shift-towards-end (%vector-raw-bits src (1+ src-word-offset)) (* (- src-byte-shift) ,bitsize))) (shift-towards-start (%vector-raw-bits src src-word-offset) (* src-byte-shift ,bitsize)))) can not extend into a second (shift-towards-end (%vector-raw-bits src src-word-offset) (* (- dst-byte-offset src-byte-offset) ,bitsize))))) (declare (type word mask orig value)) (%set-vector-raw-bits dst dst-word-offset (word-logical-or (word-logical-and value mask) (word-logical-andc2 orig mask))))))))) ((= src-byte-offset dst-byte-offset) (multiple-value-bind (words final-bytes) (floor (+ dst-byte-offset length) ,bytes-per-word) (declare (type ,word-offset words) (type ,byte-offset final-bytes)) (let ((interior (floor (- length final-bytes) ,bytes-per-word))) (declare (type ,word-offset interior)) (cond ((<= dst-offset src-offset) ,@(unless (= bytes-per-word 1) `((unless (zerop dst-byte-offset) We are only writing part of the first word , so mask (let ((mask (end-mask (* (- dst-byte-offset) ,bitsize))) (orig (%vector-raw-bits dst dst-word-offset)) (value (%vector-raw-bits src src-word-offset))) (declare (type word mask orig value)) (%set-vector-raw-bits dst dst-word-offset (word-logical-or (word-logical-and value mask) (word-logical-andc2 orig mask)))) (incf src-word-offset) (incf dst-word-offset)))) (let ((end ,(if (= bytes-per-word 1) `(truly-the ,word-offset (+ dst-word-offset interior)) `(+ dst-word-offset interior)))) (declare (type ,word-offset end)) (do () ((>= dst-word-offset end)) (%set-vector-raw-bits dst dst-word-offset (%vector-raw-bits src src-word-offset)) ,(if (= bytes-per-word 1) `(setf src-word-offset (truly-the ,word-offset (+ src-word-offset 1))) `(incf src-word-offset)) (incf dst-word-offset))) ,@(unless (= bytes-per-word 1) `((unless (zerop final-bytes) (let ((mask (start-mask (* final-bytes ,bitsize))) (orig (%vector-raw-bits dst dst-word-offset)) (value (%vector-raw-bits src src-word-offset))) (declare (type word mask orig value)) (%set-vector-raw-bits dst dst-word-offset (word-logical-or (word-logical-and value mask) (word-logical-andc2 orig mask)))))))) (t ,(if (= bytes-per-word 1) `(setf dst-word-offset (truly-the ,word-offset (+ dst-word-offset words))) `(incf dst-word-offset words)) ,(if (= bytes-per-word 1) `(setf src-word-offset (truly-the ,word-offset (+ src-word-offset words))) `(incf src-word-offset words)) ,@(unless (= bytes-per-word 1) `((unless (zerop final-bytes) (let ((mask (start-mask (* final-bytes ,bitsize))) (orig (%vector-raw-bits dst dst-word-offset)) (value (%vector-raw-bits src src-word-offset))) (declare (type word mask orig value)) (%set-vector-raw-bits dst dst-word-offset (word-logical-or (word-logical-and value mask) (word-logical-andc2 orig mask))))))) (let ((end (- dst-word-offset interior))) (do () ((<= dst-word-offset end)) (decf src-word-offset) (decf dst-word-offset) (%set-vector-raw-bits dst dst-word-offset (%vector-raw-bits src src-word-offset)))) ,@(unless (= bytes-per-word 1) `((unless (zerop dst-byte-offset) (decf src-word-offset) (decf dst-word-offset) (let ((mask (end-mask (* (- dst-byte-offset) ,bitsize))) (orig (%vector-raw-bits dst dst-word-offset)) (value (%vector-raw-bits src src-word-offset))) (declare (type word mask orig value)) (%set-vector-raw-bits dst dst-word-offset (word-logical-or (word-logical-and value mask) (word-logical-andc2 orig mask)))))))))))) (t (multiple-value-bind (words final-bytes) (floor (+ dst-byte-offset length) ,bytes-per-word) (declare (type ,word-offset words) (type ,byte-offset final-bytes)) (let ((src-shift (mod (- src-byte-offset dst-byte-offset) ,bytes-per-word)) (interior (floor (- length final-bytes) ,bytes-per-word))) (declare (type ,word-offset interior) (type ,byte-offset src-shift)) (cond ((<= dst-offset src-offset) (let ((prev 0) (next (%vector-raw-bits src src-word-offset))) (declare (type word prev next)) (flet ((get-next-src () (setf prev next) (setf next (%vector-raw-bits src (incf src-word-offset))))) (declare (inline get-next-src)) ,@(unless (= bytes-per-word 1) `((unless (zerop dst-byte-offset) (when (> src-byte-offset dst-byte-offset) (get-next-src)) (let ((mask (end-mask (* (- dst-byte-offset) ,bitsize))) (orig (%vector-raw-bits dst dst-word-offset)) (value (word-logical-or (shift-towards-start prev (* src-shift ,bitsize)) (shift-towards-end next (* (- src-shift) ,bitsize))))) (declare (type word mask orig value)) (%set-vector-raw-bits dst dst-word-offset (word-logical-or (word-logical-and value mask) (word-logical-andc2 orig mask)))) (incf dst-word-offset)))) (let ((end (+ dst-word-offset interior))) (declare (type ,word-offset end)) (do () ((>= dst-word-offset end)) (get-next-src) (let ((value (word-logical-or (shift-towards-end next (* (- src-shift) ,bitsize)) (shift-towards-start prev (* src-shift ,bitsize))))) (declare (type word value)) (%set-vector-raw-bits dst dst-word-offset value) (incf dst-word-offset)))) ,@(unless (= bytes-per-word 1) `((unless (zerop final-bytes) (let ((value (if (> (+ final-bytes src-shift) ,bytes-per-word) (progn (get-next-src) (word-logical-or (shift-towards-end next (* (- src-shift) ,bitsize)) (shift-towards-start prev (* src-shift ,bitsize)))) (shift-towards-start next (* src-shift ,bitsize)))) (mask (start-mask (* final-bytes ,bitsize))) (orig (%vector-raw-bits dst dst-word-offset))) (declare (type word mask orig value)) (%set-vector-raw-bits dst dst-word-offset (word-logical-or (word-logical-and value mask) (word-logical-andc2 orig mask)))))))))) (t (incf dst-word-offset words) (incf src-word-offset (1- (ceiling (+ src-byte-offset length) ,bytes-per-word))) (let ((next 0) (prev (%vector-raw-bits src src-word-offset))) (declare (type word prev next)) (flet ((get-next-src () (setf next prev) (setf prev (%vector-raw-bits src (decf src-word-offset))))) (declare (inline get-next-src)) ,@(unless (= bytes-per-word 1) `((unless (zerop final-bytes) (when (> final-bytes (- ,bytes-per-word src-shift)) (get-next-src)) (let ((value (word-logical-or (shift-towards-end next (* (- src-shift) ,bitsize)) (shift-towards-start prev (* src-shift ,bitsize)))) (mask (start-mask (* final-bytes ,bitsize))) (orig (%vector-raw-bits dst dst-word-offset))) (declare (type word mask orig value)) (%set-vector-raw-bits dst dst-word-offset (word-logical-or (word-logical-and value mask) (word-logical-andc2 orig mask))))))) (decf dst-word-offset) (let ((end (- dst-word-offset interior))) (do () ((<= dst-word-offset end)) (get-next-src) (let ((value (word-logical-or (shift-towards-end next (* (- src-shift) ,bitsize)) (shift-towards-start prev (* src-shift ,bitsize))))) (declare (type word value)) (%set-vector-raw-bits dst dst-word-offset value) (decf dst-word-offset)))) ,@(unless (= bytes-per-word 1) `((unless (zerop dst-byte-offset) (if (> src-byte-offset dst-byte-offset) (get-next-src) (setf next prev prev 0)) (let ((mask (end-mask (* (- dst-byte-offset) ,bitsize))) (orig (%vector-raw-bits dst dst-word-offset)) (value (word-logical-or (shift-towards-start prev (* src-shift ,bitsize)) (shift-towards-end next (* (- src-shift) ,bitsize))))) (declare (type word mask orig value)) (%set-vector-raw-bits dst dst-word-offset (word-logical-or (word-logical-and value mask) (word-logical-andc2 orig mask))))))))))))))))) (values)) (defun ,array-copy-name (src src-offset dst dst-offset length) (declare (type index src-offset dst-offset length)) (locally (declare (optimize (speed 3) (safety 1))) (,unary-bash-name src src-offset dst dst-offset length)))))))) We would normally do this with a MACROLET , but then we run into #.(loop for i = 1 then (* i 2) collect `(!define-byte-bashers ,i) into bashers until (= i n-word-bits) finally (return `(progn ,@bashers))) (defmacro !define-constant-byte-bashers (bitsize type value-transformer &optional (name type)) (let ((constant-bash-name (intern (format nil "CONSTANT-UB~D-BASH" bitsize) (find-package "SB-KERNEL"))) (array-fill-name (intern (format nil "UB~D-BASH-FILL-WITH-~A" bitsize name) (find-package "SB-KERNEL")))) `(progn (defknown ,array-fill-name (,type simple-unboxed-array index index) simple-unboxed-array () :result-arg 1 :derive-type (sb-c::result-type-nth-arg 1)) (defun ,array-fill-name (value dst dst-offset length) (declare (type ,type value) (type index dst-offset length)) (declare (optimize (speed 3) (safety 1))) (,constant-bash-name dst dst-offset length (,value-transformer value)) dst)))) (macrolet ((def () `(progn ,@(loop for n-bits = 1 then (* n-bits 2) until (= n-bits n-word-bits) collect `(!define-constant-byte-bashers ,n-bits (unsigned-byte ,n-bits) (lambda (value) ,@(loop for i = n-bits then (* 2 i) until (= i sb-vm:n-word-bits) collect `(setf value (dpb value (byte ,i ,i) value)))) ,(format nil "UB~A" n-bits)) collect `(!define-constant-byte-bashers ,n-bits (signed-byte ,n-bits) (lambda (value) (let ((value (ldb (byte ,n-bits 0) value))) ,@(loop for i = n-bits then (* 2 i) until (= i sb-vm:n-word-bits) collect `(setf value (dpb value (byte ,i ,i) value))))) ,(format nil "SB~A" n-bits))) (!define-constant-byte-bashers ,n-word-bits (signed-byte ,n-word-bits) (lambda (value) (ldb (byte ,n-word-bits 0) value)) ,(format nil "SB~A" n-word-bits))))) (def)) (!define-constant-byte-bashers #.n-word-bits fixnum (lambda (value) (ldb (byte #.n-word-bits 0) (ash value n-fixnum-tag-bits)))) (!define-constant-byte-bashers 32 single-float (lambda (value) (let ((bits (ldb (byte 32 0) (single-float-bits value)))) #+64-bit (dpb bits (byte 32 32) bits) #-64-bit bits))) #+64-bit (!define-constant-byte-bashers 64 double-float (lambda (value) (ldb (byte 64 0) (double-float-bits value)))) #+64-bit (!define-constant-byte-bashers 64 (complex single-float) (lambda (item) #+big-endian (logior (ash (ldb (byte 32 0) (single-float-bits (realpart item))) 32) (ldb (byte 32 0) (single-float-bits (imagpart item)))) #+little-endian (logior (ash (ldb (byte 32 0) (single-float-bits (imagpart item))) 32) (ldb (byte 32 0) (single-float-bits (realpart item))))) complex-single-float) (defconstant +bit-position-base-mask+ (1- n-word-bits)) (defconstant +bit-position-base-shift+ (integer-length +bit-position-base-mask+)) (macrolet ((compute-start-mask (index) `(let ((first-bits (logand ,index +bit-position-base-mask+))) #+little-endian (ash -1 first-bits) #+big-endian (lognot (ash -1 (- n-word-bits first-bits))))) (compute-end-mask (index) `(let ((last-bits (logand ,index +bit-position-base-mask+))) #+little-endian (lognot (ash -1 last-bits)) #+big-endian (logand (ash -1 (- n-word-bits last-bits)) most-positive-word))) (calc-index (bit-index) `(logior (the index ,bit-index) (truly-the fixnum (ash word-index +bit-position-base-shift+)))) (def (name from-end frob) `(defun ,name (vector start end) (declare (simple-bit-vector vector) (index start end) (optimize (speed 3) (safety 0))) would become simpler by subtracting 1 from END initially . (let* ((first-word (ash start (- +bit-position-base-shift+))) (last-word (ash end (- +bit-position-base-shift+))) (start-mask (compute-start-mask start)) (end-mask (compute-end-mask end))) (declare (index last-word first-word)) (flet ((#+little-endian start-bit #+big-endian end-bit (x) (declare (word x)) #+(or x86-64 x86) (truly-the (mod #.n-word-bits) (%primitive unsigned-word-find-first-bit x)) #-(or x86-64 x86) (- #+big-endian n-word-bits (integer-length (logand x (- x))) #+little-endian 1)) (#+little-endian end-bit #+big-endian start-bit (x) (declare (word x)) (- #+big-endian n-word-bits (integer-length x) #+little-endian 1)) (get-word (offset) (,@frob (%vector-raw-bits vector offset)))) (declare (inline start-bit end-bit get-word)) (unless (< first-word last-word) (return-from ,name (let ((mask (logand start-mask end-mask))) (unless (zerop mask) (let ((word (logand mask (get-word first-word)))) (unless (zerop word) ,(if from-end `(calc-index (end-bit word)) `(calc-index (start-bit word)))))))))) ( 1 ) scan some number ( 0 < = N < = n - word - bits ) of bits initially , ( 2 ) then a whole number of intervening words , ( 3 ) then some number ( 0 < N < n - word - bits ) of trailing bits Steps ( 1 ) and ( 3 ) use the START and END masks respectively . The START mask has between 1 and N - WORD - BITS ( inclusive ) consecutive 1s , starting from the appropriate end . gets all 0s , and a LAST - WORD value that is 1 too high ,(if from-end (declare (index word-index)) (unless (zerop end-mask) (let ((word (logand end-mask (get-word word-index)))) (unless (zerop word) (return-from ,name (calc-index (end-bit word)))))) (decf word-index) do (let ((word (get-word word-index))) (unless (zerop word) (return-from ,name (calc-index (end-bit word))))) (decf word-index)) (let ((word (logand start-mask (get-word first-word)))) (unless (zerop word) (calc-index (end-bit word))))) `(let* ((word-index first-word) (word (logand start-mask (get-word word-index)))) (declare (index word-index)) (unless (zerop word) (return-from ,name (calc-index (start-bit word)))) (incf word-index) do (let ((word (get-word word-index))) (unless (zerop word) (return-from ,name (calc-index (start-bit word))))) (incf word-index)) (unless (zerop end-mask) (let ((word (logand end-mask (get-word word-index)))) (unless (zerop word) (calc-index (start-bit word)))))))))))) (defun run-bit-position-assertions () Check the claim in the comment at " ( unless ( < first - word last - word ) " (loop for i from 0 to (* 2 n-word-bits) do (let ((start-mask (compute-start-mask i)) (end-mask (compute-end-mask i))) (assert (= (logand start-mask end-mask) 0))))) (def %bit-pos-fwd/1 nil (identity)) (def %bit-pos-rev/1 t (identity)) (def %bit-pos-fwd/0 nil (logandc2 most-positive-word)) (def %bit-pos-rev/0 t (logandc2 most-positive-word))) (defun %bit-pos-fwd (bit vector start end) (case bit (0 (%bit-pos-fwd/0 vector start end)) (1 (%bit-pos-fwd/1 vector start end)) (otherwise nil))) (defun %bit-pos-rev (bit vector start end) (case bit (0 (%bit-pos-rev/0 vector start end)) (1 (%bit-pos-rev/1 vector start end)) (otherwise nil))) (declaim (maybe-inline %bit-position/0 %bit-position/1)) (defun %bit-position/0 (vector from-end start end) (if from-end (%bit-pos-rev/0 vector start end) (%bit-pos-fwd/0 vector start end))) (defun %bit-position/1 (vector from-end start end) (if from-end (%bit-pos-rev/1 vector start end) (%bit-pos-fwd/1 vector start end))) (defun %bit-position (bit vector from-end start end) (declare (inline %bit-position/0 %bit-position/1)) (case bit (0 (%bit-position/0 vector from-end start end)) (1 (%bit-position/1 vector from-end start end)) (otherwise nil))) (clear-info :function :inlinep '%bit-position/0) (clear-info :function :inlinep '%bit-position/1) (run-bit-position-assertions)
9e9c9604e5a5f27463908140390a56ef0e1962a45b17ceb6bf540c2682ceef94
Decentralized-Pictures/T4L3NT
test_store.ml
(*****************************************************************************) (* *) (* Open Source License *) Copyright ( c ) 2018 Dynamic Ledger Solutions , Inc. < > Copyright ( c ) 2020 Nomadic Labs , < > (* *) (* Permission is hereby granted, free of charge, to any person obtaining a *) (* copy of this software and associated documentation files (the "Software"),*) to deal in the Software without restriction , including without limitation (* the rights to use, copy, modify, merge, publish, distribute, sublicense, *) and/or sell copies of the Software , and to permit persons to whom the (* Software is furnished to do so, subject to the following conditions: *) (* *) (* The above copyright notice and this permission notice shall be included *) (* in all copies or substantial portions of the Software. *) (* *) THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR (* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *) (* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *) (* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*) LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING (* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *) (* DEALINGS IN THE SOFTWARE. *) (* *) (*****************************************************************************) open Test_utils let test_init _ = return_unit let test_cycles store = let chain_store = Store.main_chain_store store in List.fold_left_es (fun acc _ -> append_cycle ~should_set_head:true chain_store >>=? fun (blocks, _head) -> return (blocks @ acc)) [] (1 -- 10) >>=? fun blocks -> assert_presence_in_store chain_store blocks let test_cases = let wrap_test (s, f) = let f _ = f in wrap_test (s, f) in List.map wrap_test [("initialisation", test_init); ("store cycles", test_cycles)] open Example_tree (** Initialization *) (** Chain_traversal.path *) let rec compare_path is_eq p1 p2 = match (p1, p2) with | ([], []) -> true | (h1 :: p1, h2 :: p2) -> is_eq h1 h2 && compare_path is_eq p1 p2 | _ -> false let vblock tbl k = Nametbl.find tbl k |> WithExceptions.Option.to_exn ~none:Not_found let pp_print_list fmt l = Format.fprintf fmt "@[<h>%a@]" (Format.pp_print_list ~pp_sep:Format.pp_print_space Block_hash.pp_short) (List.map Store.Block.hash l) let test_path chain_store tbl = let check_path h1 h2 p2 = Store.Chain_traversal.path chain_store ~from_block:(vblock tbl h1) ~to_block:(vblock tbl h2) >>= function | None -> Assert.fail_msg "cannot compute path %s -> %s" h1 h2 | Some (p : Store.Block.t list) -> let p2 = List.map (fun b -> vblock tbl b) p2 in if not (compare_path Store.Block.equal p p2) then ( Format.printf "expected:\t%a@." pp_print_list p2 ; Format.printf "got:\t\t%a@." pp_print_list p ; Assert.fail_msg "bad path %s -> %s" h1 h2) ; Lwt.return_unit in check_path "Genesis" "Genesis" [] >>= fun () -> check_path "A1" "A1" [] >>= fun () -> check_path "A2" "A6" ["A3"; "A4"; "A5"; "A6"] >>= fun () -> check_path "B2" "B6" ["B3"; "B4"; "B5"; "B6"] >>= fun () -> check_path "A1" "B3" ["A2"; "A3"; "B1"; "B2"; "B3"] >>= fun () -> return_unit (****************************************************************************) (** Chain_traversal.common_ancestor *) let test_ancestor chain_store tbl = let check_ancestor h1 h2 expected = Store.Chain_traversal.common_ancestor chain_store (vblock tbl h1) (vblock tbl h2) >>= function | None -> Assert.fail_msg "not ancestor found" | Some a -> if not (Block_hash.equal (Store.Block.hash a) (Store.Block.hash expected)) then Assert.fail_msg "bad ancestor %s %s" h1 h2 ; Lwt.return_unit in check_ancestor "Genesis" "Genesis" (vblock tbl "Genesis") >>= fun () -> check_ancestor "Genesis" "A3" (vblock tbl "Genesis") >>= fun () -> check_ancestor "A3" "Genesis" (vblock tbl "Genesis") >>= fun () -> check_ancestor "A1" "A1" (vblock tbl "A1") >>= fun () -> check_ancestor "A1" "A3" (vblock tbl "A1") >>= fun () -> check_ancestor "A3" "A1" (vblock tbl "A1") >>= fun () -> check_ancestor "A6" "B6" (vblock tbl "A3") >>= fun () -> check_ancestor "B6" "A6" (vblock tbl "A3") >>= fun () -> check_ancestor "A4" "B1" (vblock tbl "A3") >>= fun () -> check_ancestor "B1" "A4" (vblock tbl "A3") >>= fun () -> check_ancestor "A3" "B1" (vblock tbl "A3") >>= fun () -> check_ancestor "B1" "A3" (vblock tbl "A3") >>= fun () -> check_ancestor "A2" "B1" (vblock tbl "A2") >>= fun () -> check_ancestor "B1" "A2" (vblock tbl "A2") >>= fun () -> return_unit (****************************************************************************) let seed = let receiver_id = P2p_peer.Id.of_string_exn (String.make P2p_peer.Id.size 'r') in let sender_id = P2p_peer.Id.of_string_exn (String.make P2p_peer.Id.size 's') in {Block_locator.receiver_id; sender_id} let iter2_exn f l1 l2 = List.iter2 ~when_different_lengths:(Failure "iter2_exn") f l1 l2 |> function | Ok () -> () | _ -> assert false (** Block_locator *) let test_locator chain_store tbl = let check_locator length h1 expected = Store.Chain.compute_locator chain_store ~max_size:length (vblock tbl h1) seed >>= fun {Block_locator.history; _} -> if Compare.List_lengths.(history <> expected) then Assert.fail_msg "Invalid locator length %s (found: %d, expected: %d)" h1 (List.length history) (List.length expected) ; iter2_exn (fun h h2 -> if not (Block_hash.equal h (Store.Block.hash @@ vblock tbl h2)) then Assert.fail_msg "Invalid locator %s (expected: %s)" h1 h2) history expected ; Lwt.return_unit in check_locator 6 "A8" ["A7"; "A6"; "A5"; "A4"; "A3"; "A2"] >>= fun () -> check_locator 8 "B8" ["B7"; "B6"; "B5"; "B4"; "B3"; "B2"; "B1"; "A3"] >>= fun () -> check_locator 4 "B8" ["B7"; "B6"; "B5"; "B4"] >>= fun () -> check_locator 0 "A5" [] >>= fun () -> check_locator 100 "A5" ["A4"; "A3"; "A2"; "A1"; "Genesis"] >>= fun () -> return_unit (****************************************************************************) (** Chain.known_heads *) let compare s name heads l = List.iter (fun b -> Format.printf "%s@." (rev_lookup b s)) heads ; if Compare.List_lengths.(heads <> l) then Assert.fail_msg "unexpected known_heads size (%s: %d %d)" name (List.length heads) (List.length l) ; List.iter (fun bname -> let hash = Store.Block.hash (vblock s bname) in if not (List.exists (fun bh -> Block_hash.equal hash bh) heads) then Assert.fail_msg "missing block in known_heads (%s: %s)" name bname) l let test_known_heads chain_store tbl = Store.Chain.known_heads chain_store >>= fun heads -> let heads = List.map fst heads in compare tbl "initial" heads ["Genesis"] ; Store.Chain.set_head chain_store (vblock tbl "A8") >>=? fun _ -> Store.Chain.set_head chain_store (vblock tbl "B8") >>=? fun _ -> Store.Chain.known_heads chain_store >>= fun heads -> let heads = List.map fst heads in compare tbl "initial" heads ["A8"; "B8"] ; return_unit (****************************************************************************) * let test_head chain_store tbl = Store.Chain.current_head chain_store >>= fun head -> Store.Chain.genesis_block chain_store >>= fun genesis_block -> if not (Store.Block.equal head genesis_block) then Assert.fail_msg "unexpected head" ; Store.Chain.set_head chain_store (vblock tbl "A6") >>=? function | None -> Assert.fail_msg "unexpected previous head" | Some prev_head -> if not (Store.Block.equal prev_head genesis_block) then Assert.fail_msg "unexpected previous head" ; Store.Chain.current_head chain_store >>= fun head -> if not (Store.Block.equal head (vblock tbl "A6")) then Assert.fail_msg "unexpected head" ; return_unit (****************************************************************************) * Chain.mem (* Genesis - A1 - A2 (cp) - A3 - A4 - A5 \ B1 - B2 - B3 - B4 - B5 *) let test_mem chain_store tbl = let mem x = let b = vblock tbl x in let b_descr = Store.Block.(hash b, level b) in Store.Chain.is_in_chain chain_store b_descr in let test_mem x = mem x >>= function | true -> Lwt.return_unit | false -> Assert.fail_msg "mem %s" x in let test_not_mem x = mem x >>= function | false -> Lwt.return_unit | true -> Assert.fail_msg "not (mem %s)" x in test_not_mem "A3" >>= fun () -> test_not_mem "A6" >>= fun () -> test_not_mem "A8" >>= fun () -> test_not_mem "B1" >>= fun () -> test_not_mem "B6" >>= fun () -> test_not_mem "B8" >>= fun () -> Store.Chain.set_head chain_store (vblock tbl "A8") >>=? fun _ -> test_mem "A3" >>= fun () -> test_mem "A6" >>= fun () -> test_mem "A8" >>= fun () -> test_not_mem "B1" >>= fun () -> test_not_mem "B6" >>= fun () -> test_not_mem "B8" >>= fun () -> (Store.Chain.set_head chain_store (vblock tbl "A6") >>=? function | Some _prev_head -> Assert.fail_msg "unexpected head switch" | None -> return_unit) >>=? fun () -> A6 is a predecessor of A8 . A8 remains the new head . test_mem "A3" >>= fun () -> test_mem "A6" >>= fun () -> test_mem "A8" >>= fun () -> test_not_mem "B1" >>= fun () -> test_not_mem "B6" >>= fun () -> test_not_mem "B8" >>= fun () -> Store.Chain.set_head chain_store (vblock tbl "B6") >>=? fun _ -> test_mem "A3" >>= fun () -> test_not_mem "A4" >>= fun () -> test_not_mem "A6" >>= fun () -> test_not_mem "A8" >>= fun () -> test_mem "B1" >>= fun () -> test_mem "B6" >>= fun () -> test_not_mem "B8" >>= fun () -> Store.Chain.set_head chain_store (vblock tbl "B8") >>=? fun _ -> test_mem "A3" >>= fun () -> test_not_mem "A4" >>= fun () -> test_not_mem "A6" >>= fun () -> test_not_mem "A8" >>= fun () -> test_mem "B1" >>= fun () -> test_mem "B6" >>= fun () -> test_mem "B8" >>= fun () -> return_unit (****************************************************************************) (** Chain_traversal.new_blocks *) let test_new_blocks chain_store tbl = let test head h expected_ancestor expected = let to_block = vblock tbl head and from_block = vblock tbl h in Store.Chain_traversal.new_blocks chain_store ~from_block ~to_block >>= fun (ancestor, blocks) -> if not (Block_hash.equal (Store.Block.hash ancestor) (Store.Block.hash @@ vblock tbl expected_ancestor)) then Assert.fail_msg "Invalid ancestor %s -> %s (expected: %s)" head h expected_ancestor ; if Compare.List_lengths.(blocks <> expected) then Assert.fail_msg "Invalid locator length %s (found: %d, expected: %d)" h (List.length blocks) (List.length expected) ; iter2_exn (fun h1 h2 -> if not (Block_hash.equal (Store.Block.hash h1) (Store.Block.hash @@ vblock tbl h2)) then Assert.fail_msg "Invalid new blocks %s -> %s (expected: %s)" head h h2) blocks expected ; Lwt.return_unit in test "A6" "A6" "A6" [] >>= fun () -> test "A8" "A6" "A6" ["A7"; "A8"] >>= fun () -> test "A8" "B7" "A3" ["A4"; "A5"; "A6"; "A7"; "A8"] >>= fun () -> return_unit (** Store.Chain.checkpoint *) (* - Valid branch are kept after setting a checkpoint. Bad branch are cut - Setting a checkpoint in the future does not remove anything - Reaching a checkpoint in the future with the right block keeps that block and remove any concurrent branch - Reaching a checkpoint in the future with a bad block remove that block and does not prevent a future good block from correctly being reached - There are no bad quadratic behaviours *) let test_basic_checkpoint chain_store table = let block = vblock table "A1" in Store.Chain.set_head chain_store block >>=? fun _prev_head -> (* Setting target for A1 *) Store.Chain.set_target chain_store (Store.Block.hash block, Store.Block.level block) >>=? fun () -> Store.Chain.checkpoint chain_store >>= fun (c_block, c_level) -> Target should not be set , only the checkpoint . (Store.Chain.target chain_store >>= function | Some _target -> Assert.fail_msg "unexpected target" | None -> return_unit) >>=? fun () -> if (not (Block_hash.equal c_block (Store.Block.hash block))) && Int32.equal c_level (Store.Block.level block) then Assert.fail_msg "unexpected checkpoint" else return_unit (* - cp: checkpoint Genesis - A1 - A2 (cp) - A3 - A4 - A5 \ B1 - B2 - B3 - B4 - B5 *) Store . Chain.acceptable_block : will the block is compatible with the current checkpoint ? will the block is compatible with the current checkpoint? *) let test_acceptable_block chain_store table = let block = vblock table "A2" in let block_hash = Store.Block.hash block in let level = Store.Block.level block in Store.Chain.set_head chain_store block >>=? fun _prev_head -> Store.Chain.set_target chain_store (block_hash, level) >>=? fun () -> (* it is accepted if the new head is greater than the checkpoint *) let block_1 = vblock table "A1" in Store.Chain.is_acceptable_block chain_store (Store.Block.hash block_1, Store.Block.level block_1) >>= fun is_accepted_block -> if not is_accepted_block then return_unit else Assert.fail_msg "unacceptable block was accepted" (* Genesis - A1 - A2 (cp) - A3 - A4 - A5 \ B1 - B2 - B3 - B4 - B5 *) let test_is_valid_target chain_store table = let block = vblock table "A2" in let block_hash = Store.Block.hash block in let level = Store.Block.level block in Store.Chain.set_head chain_store block >>=? fun _prev_head -> Store.Chain.set_target chain_store (block_hash, level) >>=? fun () -> (* "b3" is valid because: a1 - a2 (checkpoint) - b1 - b2 - b3 *) return_unit (* return a block with the best fitness amongst the known blocks which are compatible with the given checkpoint *) let test_best_know_head_for_checkpoint chain_store table = let block = vblock table "A2" in let block_hash = Store.Block.hash block in let level = Store.Block.level block in let checkpoint = (block_hash, level) in Store.Chain.set_head chain_store block >>=? fun _prev_head -> Store.Chain.set_target chain_store checkpoint >>=? fun () -> Store.Chain.set_head chain_store (vblock table "B3") >>=? fun _head -> Store.Chain.best_known_head_for_checkpoint chain_store ~checkpoint >>= fun _block -> the block returns with the best fitness is B3 at level 5 return_unit (* Setting checkpoint in the future is possible Storing a block at the same level with a different hash is not allowed. *) let test_future_target chain_store _ = Store.Chain.genesis_block chain_store >>= fun genesis_block -> let genesis_descr = Store.Block.descriptor genesis_block in make_raw_block_list genesis_descr 5 >>= fun (bad_chain, bad_head) -> make_raw_block_list genesis_descr 5 >>= fun (good_chain, good_head) -> Store.Chain.set_target chain_store (raw_descriptor good_head) >>=? fun () -> List.iter_es (fun b -> Format.printf "storing : %a@." pp_raw_block b ; store_raw_block chain_store b >>=? fun _ -> return_unit) (List.rev (List.tl (List.rev bad_chain) |> WithExceptions.Option.get ~loc:__LOC__)) >>=? fun () -> (store_raw_block chain_store bad_head >>= function | Error [Validation_errors.Checkpoint_error _] -> return_unit | Ok _ | _ -> Assert.fail_msg "incompatible head accepted") >>=? fun () -> List.iter_es (fun b -> store_raw_block chain_store b >>=? fun _ -> return_unit) (List.rev (List.tl (List.rev good_chain) |> WithExceptions.Option.get ~loc:__LOC__)) >>=? fun () -> store_raw_block chain_store good_head >>=? fun _ -> return_unit (* check if the checkpoint can be reached Genesis - A1 (cp) - A2 (head) - A3 - A4 - A5 \ B1 - B2 - B3 - B4 - B5 *) let test_reach_target chain_store table = let mem x = let b = vblock table x in Store.Chain.is_in_chain chain_store Store.Block.(hash b, level b) in let test_mem x = mem x >>= function | true -> Lwt.return_unit | false -> Assert.fail_msg "mem %s" x in let test_not_mem x = mem x >>= function | false -> Lwt.return_unit | true -> Assert.fail_msg "not (mem %s)" x in let block = vblock table "A1" in let header = Store.Block.header block in let checkpoint_hash = Store.Block.hash block in let checkpoint_level = Store.Block.level block in Store.Chain.set_head chain_store block >>=? fun _pred_head -> Store.Chain.set_target chain_store (checkpoint_hash, checkpoint_level) >>=? fun () -> Store.Chain.checkpoint chain_store >>= fun (c_hash, _c_level) -> let time_now = Time.System.to_protocol (Systime_os.now ()) in if Time.Protocol.compare (Time.Protocol.add time_now 15L) header.shell.timestamp >= 0 then if Int32.equal header.shell.level checkpoint_level && not (Block_hash.equal checkpoint_hash c_hash) then Assert.fail_msg "checkpoint error" else Store.Chain.set_head chain_store (vblock table "A2") >>=? fun _ -> Store.Chain.current_head chain_store >>= fun head -> let checkpoint_reached = (Store.Block.header head).shell.level >= checkpoint_level in if checkpoint_reached then (* if reached the checkpoint, every block before the checkpoint must be the part of the chain *) if header.shell.level <= checkpoint_level then test_mem "Genesis" >>= fun () -> test_mem "A1" >>= fun () -> test_mem "A2" >>= fun () -> test_not_mem "A3" >>= fun () -> test_not_mem "B1" >>= fun () -> return_unit else Assert.fail_msg "checkpoint error" else Assert.fail_msg "checkpoint error" else Assert.fail_msg "fail future block header" (* Check function may_update_target Genesis - A1 - A2 (cp) - A3 - A4 - A5 \ B1 - B2 - B3 - B4 - B5 chain after update: Genesis - A1 - A2 - A3(cp) - A4 - A5 \ B1 - B2 - B3 - B4 - B5 *) let test_not_may_update_target chain_store table = set target at ( 2l , A2 ) let block_a2 = vblock table "A2" in let target_hash = Store.Block.hash block_a2 in let target_level = Store.Block.level block_a2 in let target = (target_hash, target_level) in Store.Chain.set_head chain_store block_a2 >>=? fun _pred_head -> Store.Chain.set_target chain_store target >>=? fun () -> set new target at ( 1l , A1 ) in the past let block_a1 = vblock table "A1" in let target_hash = Store.Block.hash block_a1 in let target_level = Store.Block.level block_a1 in let new_target = (target_hash, target_level) in Lwt.catch (fun () -> Store.Chain.set_target chain_store new_target >>=? fun () -> Assert.fail_msg "Unexpected target update") (function _ -> return_unit) (****************************************************************************) (** Store.Chain.block_of_identifier *) let testable_hash = Alcotest.testable (fun fmt h -> Format.fprintf fmt "%s" (Block_hash.to_b58check h)) Block_hash.equal let init_block_of_identifier_test chain_store table = vblock table "A8" |> Store.Chain.set_head chain_store >|=? fun _ -> () let vblock_hash table name = vblock table name |> Store.Block.hash let assert_successful_block_of_identifier ?(init = init_block_of_identifier_test) ~input ~expected chain_store table = init chain_store table >>=? fun _ -> Store.Chain.block_of_identifier chain_store input >|=? fun found -> Alcotest.check testable_hash "same block hash" expected (Store.Block.hash found) let assert_failing_block_of_identifier ?(init = init_block_of_identifier_test) ~input chain_store table = init chain_store table >>=? fun _ -> Store.Chain.block_of_identifier chain_store input >>= function | Ok b -> Assert.fail_msg ~given:(Store.Block.hash b |> Block_hash.to_b58check) "retrieving the block did not failed as expected" | _ -> return_unit let test_block_of_identifier_success_block_from_level chain_store table = let a5 = vblock table "A5" in assert_successful_block_of_identifier ~input:(`Level (Store.Block.level a5)) ~expected:(Store.Block.hash a5) chain_store table let test_block_of_identifier_success_block_from_hash chain_store table = let a5_hash = vblock_hash table "A5" in assert_successful_block_of_identifier ~input:(`Hash (a5_hash, 0)) ~expected:a5_hash chain_store table let test_block_of_identifier_success_block_from_hash_predecessor chain_store table = assert_successful_block_of_identifier ~input:(`Hash (vblock_hash table "A5", 2)) ~expected:(vblock_hash table "A3") chain_store table let test_block_of_identifier_success_block_from_hash_successor chain_store table = assert_successful_block_of_identifier ~input:(`Hash (vblock_hash table "A5", -2)) ~expected:(vblock_hash table "A7") chain_store table let test_block_of_identifier_success_caboose chain_store table = assert_successful_block_of_identifier ~input:(`Alias (`Caboose, 0)) ~expected:(vblock_hash table "Genesis") chain_store table let test_block_of_identifier_success_caboose_successor chain_store table = assert_successful_block_of_identifier ~input:(`Alias (`Caboose, -2)) ~expected:(vblock_hash table "A2") chain_store table let test_block_of_identifier_failure_caboose_predecessor chain_store table = assert_failing_block_of_identifier ~input:(`Alias (`Caboose, 2)) chain_store table let test_block_of_identifier_success_checkpoint chain_store table = let a5 = vblock table "A5" in let a5_hash = Store.Block.hash a5 in let a5_descriptor = (a5_hash, Store.Block.level a5) in assert_successful_block_of_identifier ~init:(fun cs t -> init_block_of_identifier_test cs t >>=? fun _ -> Store.Unsafe.set_checkpoint cs a5_descriptor) ~input:(`Alias (`Checkpoint, 0)) ~expected:a5_hash chain_store table let test_block_of_identifier_success_checkpoint_predecessor chain_store table = let a5 = vblock table "A5" in let a5_hash = Store.Block.hash a5 in let a5_descriptor = (a5_hash, Store.Block.level a5) in assert_successful_block_of_identifier ~init:(fun cs t -> init_block_of_identifier_test cs t >>=? fun _ -> Store.Unsafe.set_checkpoint cs a5_descriptor) ~input:(`Alias (`Checkpoint, 2)) ~expected:(vblock_hash table "A3") chain_store table let test_block_of_identifier_success_checkpoint_successor chain_store table = let a5 = vblock table "A5" in let a5_hash = Store.Block.hash a5 in let a5_descriptor = (a5_hash, Store.Block.level a5) in assert_successful_block_of_identifier ~init:(fun cs t -> init_block_of_identifier_test cs t >>=? fun _ -> Store.Unsafe.set_checkpoint cs a5_descriptor) ~input:(`Alias (`Checkpoint, -2)) ~expected:(vblock_hash table "A7") chain_store table let test_block_of_identifier_failure_checkpoint_successor chain_store table = let a5 = vblock table "A5" in let a5_hash = Store.Block.hash a5 in let a5_descriptor = (a5_hash, Store.Block.level a5) in assert_failing_block_of_identifier ~init:(fun cs t -> init_block_of_identifier_test cs t >>=? fun _ -> Store.Unsafe.set_checkpoint cs a5_descriptor) ~input:(`Alias (`Checkpoint, -4)) chain_store table let test_block_of_identifier_success_savepoint chain_store table = assert_successful_block_of_identifier ~input:(`Alias (`Savepoint, 0)) ~expected:(vblock_hash table "Genesis") chain_store table let tests = let test_tree_cases = List.map wrap_test [ ("path between blocks", test_path); ("common ancestor", test_ancestor); ("block locators", test_locator); ("known heads", test_known_heads); ("set head", test_head); ("blocks in chain", test_mem); ("new blocks", test_new_blocks); ("basic checkpoint", test_basic_checkpoint); ("is valid target", test_is_valid_target); ("acceptable block", test_acceptable_block); ("best know head", test_best_know_head_for_checkpoint); ("future target", test_future_target); ("reach target", test_reach_target); ("update target in node", test_not_may_update_target); ( "block_of_identifier should succeed to retrieve block from level", test_block_of_identifier_success_block_from_level ); ( "block_of_identifier should succeed to retrieve block from hash", test_block_of_identifier_success_block_from_hash ); ( "block_of_identifier should succeed to retrieve block from hash \ predecessor", test_block_of_identifier_success_block_from_hash_predecessor ); ( "block_of_identifier should succeed to retrieve block from hash \ successor", test_block_of_identifier_success_block_from_hash_successor ); ( "block_of_identifier should succeed to retrieve the caboose", test_block_of_identifier_success_caboose ); ( "block_of_identifier should succeed to retrieve caboose successor", test_block_of_identifier_success_caboose_successor ); ( "block_of_identifier should fail to retrieve caboose predecessor", test_block_of_identifier_failure_caboose_predecessor ); ( "block_of_identifier should succeed to retrieve the checkpoint", test_block_of_identifier_success_checkpoint ); ( "block_of_identifier should succeed to retrieve checkpoint predecessor", test_block_of_identifier_success_checkpoint_predecessor ); ( "block_of_identifier should succeed to retrieve the checkpoint \ successor", test_block_of_identifier_success_checkpoint_successor ); ( "block_of_identifier should fail to retrieve the checkpoint \ successor after the head", test_block_of_identifier_failure_checkpoint_successor ); ( "block_of_identifier should succeed to retrieve the savepoint", test_block_of_identifier_success_savepoint ); ] in ("store", test_cases @ test_tree_cases)
null
https://raw.githubusercontent.com/Decentralized-Pictures/T4L3NT/6d4d3edb2d73575384282ad5a633518cba3d29e3/src/lib_store/test/test_store.ml
ocaml
*************************************************************************** Open Source License Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), the rights to use, copy, modify, merge, publish, distribute, sublicense, Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *************************************************************************** * Initialization * Chain_traversal.path ************************************************************************** * Chain_traversal.common_ancestor ************************************************************************** * Block_locator ************************************************************************** * Chain.known_heads ************************************************************************** ************************************************************************** Genesis - A1 - A2 (cp) - A3 - A4 - A5 \ B1 - B2 - B3 - B4 - B5 ************************************************************************** * Chain_traversal.new_blocks * Store.Chain.checkpoint - Valid branch are kept after setting a checkpoint. Bad branch are cut - Setting a checkpoint in the future does not remove anything - Reaching a checkpoint in the future with the right block keeps that block and remove any concurrent branch - Reaching a checkpoint in the future with a bad block remove that block and does not prevent a future good block from correctly being reached - There are no bad quadratic behaviours Setting target for A1 - cp: checkpoint Genesis - A1 - A2 (cp) - A3 - A4 - A5 \ B1 - B2 - B3 - B4 - B5 it is accepted if the new head is greater than the checkpoint Genesis - A1 - A2 (cp) - A3 - A4 - A5 \ B1 - B2 - B3 - B4 - B5 "b3" is valid because: a1 - a2 (checkpoint) - b1 - b2 - b3 return a block with the best fitness amongst the known blocks which are compatible with the given checkpoint Setting checkpoint in the future is possible Storing a block at the same level with a different hash is not allowed. check if the checkpoint can be reached Genesis - A1 (cp) - A2 (head) - A3 - A4 - A5 \ B1 - B2 - B3 - B4 - B5 if reached the checkpoint, every block before the checkpoint must be the part of the chain Check function may_update_target Genesis - A1 - A2 (cp) - A3 - A4 - A5 \ B1 - B2 - B3 - B4 - B5 chain after update: Genesis - A1 - A2 - A3(cp) - A4 - A5 \ B1 - B2 - B3 - B4 - B5 ************************************************************************** * Store.Chain.block_of_identifier
Copyright ( c ) 2018 Dynamic Ledger Solutions , Inc. < > Copyright ( c ) 2020 Nomadic Labs , < > to deal in the Software without restriction , including without limitation and/or sell copies of the Software , and to permit persons to whom the THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING open Test_utils let test_init _ = return_unit let test_cycles store = let chain_store = Store.main_chain_store store in List.fold_left_es (fun acc _ -> append_cycle ~should_set_head:true chain_store >>=? fun (blocks, _head) -> return (blocks @ acc)) [] (1 -- 10) >>=? fun blocks -> assert_presence_in_store chain_store blocks let test_cases = let wrap_test (s, f) = let f _ = f in wrap_test (s, f) in List.map wrap_test [("initialisation", test_init); ("store cycles", test_cycles)] open Example_tree let rec compare_path is_eq p1 p2 = match (p1, p2) with | ([], []) -> true | (h1 :: p1, h2 :: p2) -> is_eq h1 h2 && compare_path is_eq p1 p2 | _ -> false let vblock tbl k = Nametbl.find tbl k |> WithExceptions.Option.to_exn ~none:Not_found let pp_print_list fmt l = Format.fprintf fmt "@[<h>%a@]" (Format.pp_print_list ~pp_sep:Format.pp_print_space Block_hash.pp_short) (List.map Store.Block.hash l) let test_path chain_store tbl = let check_path h1 h2 p2 = Store.Chain_traversal.path chain_store ~from_block:(vblock tbl h1) ~to_block:(vblock tbl h2) >>= function | None -> Assert.fail_msg "cannot compute path %s -> %s" h1 h2 | Some (p : Store.Block.t list) -> let p2 = List.map (fun b -> vblock tbl b) p2 in if not (compare_path Store.Block.equal p p2) then ( Format.printf "expected:\t%a@." pp_print_list p2 ; Format.printf "got:\t\t%a@." pp_print_list p ; Assert.fail_msg "bad path %s -> %s" h1 h2) ; Lwt.return_unit in check_path "Genesis" "Genesis" [] >>= fun () -> check_path "A1" "A1" [] >>= fun () -> check_path "A2" "A6" ["A3"; "A4"; "A5"; "A6"] >>= fun () -> check_path "B2" "B6" ["B3"; "B4"; "B5"; "B6"] >>= fun () -> check_path "A1" "B3" ["A2"; "A3"; "B1"; "B2"; "B3"] >>= fun () -> return_unit let test_ancestor chain_store tbl = let check_ancestor h1 h2 expected = Store.Chain_traversal.common_ancestor chain_store (vblock tbl h1) (vblock tbl h2) >>= function | None -> Assert.fail_msg "not ancestor found" | Some a -> if not (Block_hash.equal (Store.Block.hash a) (Store.Block.hash expected)) then Assert.fail_msg "bad ancestor %s %s" h1 h2 ; Lwt.return_unit in check_ancestor "Genesis" "Genesis" (vblock tbl "Genesis") >>= fun () -> check_ancestor "Genesis" "A3" (vblock tbl "Genesis") >>= fun () -> check_ancestor "A3" "Genesis" (vblock tbl "Genesis") >>= fun () -> check_ancestor "A1" "A1" (vblock tbl "A1") >>= fun () -> check_ancestor "A1" "A3" (vblock tbl "A1") >>= fun () -> check_ancestor "A3" "A1" (vblock tbl "A1") >>= fun () -> check_ancestor "A6" "B6" (vblock tbl "A3") >>= fun () -> check_ancestor "B6" "A6" (vblock tbl "A3") >>= fun () -> check_ancestor "A4" "B1" (vblock tbl "A3") >>= fun () -> check_ancestor "B1" "A4" (vblock tbl "A3") >>= fun () -> check_ancestor "A3" "B1" (vblock tbl "A3") >>= fun () -> check_ancestor "B1" "A3" (vblock tbl "A3") >>= fun () -> check_ancestor "A2" "B1" (vblock tbl "A2") >>= fun () -> check_ancestor "B1" "A2" (vblock tbl "A2") >>= fun () -> return_unit let seed = let receiver_id = P2p_peer.Id.of_string_exn (String.make P2p_peer.Id.size 'r') in let sender_id = P2p_peer.Id.of_string_exn (String.make P2p_peer.Id.size 's') in {Block_locator.receiver_id; sender_id} let iter2_exn f l1 l2 = List.iter2 ~when_different_lengths:(Failure "iter2_exn") f l1 l2 |> function | Ok () -> () | _ -> assert false let test_locator chain_store tbl = let check_locator length h1 expected = Store.Chain.compute_locator chain_store ~max_size:length (vblock tbl h1) seed >>= fun {Block_locator.history; _} -> if Compare.List_lengths.(history <> expected) then Assert.fail_msg "Invalid locator length %s (found: %d, expected: %d)" h1 (List.length history) (List.length expected) ; iter2_exn (fun h h2 -> if not (Block_hash.equal h (Store.Block.hash @@ vblock tbl h2)) then Assert.fail_msg "Invalid locator %s (expected: %s)" h1 h2) history expected ; Lwt.return_unit in check_locator 6 "A8" ["A7"; "A6"; "A5"; "A4"; "A3"; "A2"] >>= fun () -> check_locator 8 "B8" ["B7"; "B6"; "B5"; "B4"; "B3"; "B2"; "B1"; "A3"] >>= fun () -> check_locator 4 "B8" ["B7"; "B6"; "B5"; "B4"] >>= fun () -> check_locator 0 "A5" [] >>= fun () -> check_locator 100 "A5" ["A4"; "A3"; "A2"; "A1"; "Genesis"] >>= fun () -> return_unit let compare s name heads l = List.iter (fun b -> Format.printf "%s@." (rev_lookup b s)) heads ; if Compare.List_lengths.(heads <> l) then Assert.fail_msg "unexpected known_heads size (%s: %d %d)" name (List.length heads) (List.length l) ; List.iter (fun bname -> let hash = Store.Block.hash (vblock s bname) in if not (List.exists (fun bh -> Block_hash.equal hash bh) heads) then Assert.fail_msg "missing block in known_heads (%s: %s)" name bname) l let test_known_heads chain_store tbl = Store.Chain.known_heads chain_store >>= fun heads -> let heads = List.map fst heads in compare tbl "initial" heads ["Genesis"] ; Store.Chain.set_head chain_store (vblock tbl "A8") >>=? fun _ -> Store.Chain.set_head chain_store (vblock tbl "B8") >>=? fun _ -> Store.Chain.known_heads chain_store >>= fun heads -> let heads = List.map fst heads in compare tbl "initial" heads ["A8"; "B8"] ; return_unit * let test_head chain_store tbl = Store.Chain.current_head chain_store >>= fun head -> Store.Chain.genesis_block chain_store >>= fun genesis_block -> if not (Store.Block.equal head genesis_block) then Assert.fail_msg "unexpected head" ; Store.Chain.set_head chain_store (vblock tbl "A6") >>=? function | None -> Assert.fail_msg "unexpected previous head" | Some prev_head -> if not (Store.Block.equal prev_head genesis_block) then Assert.fail_msg "unexpected previous head" ; Store.Chain.current_head chain_store >>= fun head -> if not (Store.Block.equal head (vblock tbl "A6")) then Assert.fail_msg "unexpected head" ; return_unit * Chain.mem let test_mem chain_store tbl = let mem x = let b = vblock tbl x in let b_descr = Store.Block.(hash b, level b) in Store.Chain.is_in_chain chain_store b_descr in let test_mem x = mem x >>= function | true -> Lwt.return_unit | false -> Assert.fail_msg "mem %s" x in let test_not_mem x = mem x >>= function | false -> Lwt.return_unit | true -> Assert.fail_msg "not (mem %s)" x in test_not_mem "A3" >>= fun () -> test_not_mem "A6" >>= fun () -> test_not_mem "A8" >>= fun () -> test_not_mem "B1" >>= fun () -> test_not_mem "B6" >>= fun () -> test_not_mem "B8" >>= fun () -> Store.Chain.set_head chain_store (vblock tbl "A8") >>=? fun _ -> test_mem "A3" >>= fun () -> test_mem "A6" >>= fun () -> test_mem "A8" >>= fun () -> test_not_mem "B1" >>= fun () -> test_not_mem "B6" >>= fun () -> test_not_mem "B8" >>= fun () -> (Store.Chain.set_head chain_store (vblock tbl "A6") >>=? function | Some _prev_head -> Assert.fail_msg "unexpected head switch" | None -> return_unit) >>=? fun () -> A6 is a predecessor of A8 . A8 remains the new head . test_mem "A3" >>= fun () -> test_mem "A6" >>= fun () -> test_mem "A8" >>= fun () -> test_not_mem "B1" >>= fun () -> test_not_mem "B6" >>= fun () -> test_not_mem "B8" >>= fun () -> Store.Chain.set_head chain_store (vblock tbl "B6") >>=? fun _ -> test_mem "A3" >>= fun () -> test_not_mem "A4" >>= fun () -> test_not_mem "A6" >>= fun () -> test_not_mem "A8" >>= fun () -> test_mem "B1" >>= fun () -> test_mem "B6" >>= fun () -> test_not_mem "B8" >>= fun () -> Store.Chain.set_head chain_store (vblock tbl "B8") >>=? fun _ -> test_mem "A3" >>= fun () -> test_not_mem "A4" >>= fun () -> test_not_mem "A6" >>= fun () -> test_not_mem "A8" >>= fun () -> test_mem "B1" >>= fun () -> test_mem "B6" >>= fun () -> test_mem "B8" >>= fun () -> return_unit let test_new_blocks chain_store tbl = let test head h expected_ancestor expected = let to_block = vblock tbl head and from_block = vblock tbl h in Store.Chain_traversal.new_blocks chain_store ~from_block ~to_block >>= fun (ancestor, blocks) -> if not (Block_hash.equal (Store.Block.hash ancestor) (Store.Block.hash @@ vblock tbl expected_ancestor)) then Assert.fail_msg "Invalid ancestor %s -> %s (expected: %s)" head h expected_ancestor ; if Compare.List_lengths.(blocks <> expected) then Assert.fail_msg "Invalid locator length %s (found: %d, expected: %d)" h (List.length blocks) (List.length expected) ; iter2_exn (fun h1 h2 -> if not (Block_hash.equal (Store.Block.hash h1) (Store.Block.hash @@ vblock tbl h2)) then Assert.fail_msg "Invalid new blocks %s -> %s (expected: %s)" head h h2) blocks expected ; Lwt.return_unit in test "A6" "A6" "A6" [] >>= fun () -> test "A8" "A6" "A6" ["A7"; "A8"] >>= fun () -> test "A8" "B7" "A3" ["A4"; "A5"; "A6"; "A7"; "A8"] >>= fun () -> return_unit let test_basic_checkpoint chain_store table = let block = vblock table "A1" in Store.Chain.set_head chain_store block >>=? fun _prev_head -> Store.Chain.set_target chain_store (Store.Block.hash block, Store.Block.level block) >>=? fun () -> Store.Chain.checkpoint chain_store >>= fun (c_block, c_level) -> Target should not be set , only the checkpoint . (Store.Chain.target chain_store >>= function | Some _target -> Assert.fail_msg "unexpected target" | None -> return_unit) >>=? fun () -> if (not (Block_hash.equal c_block (Store.Block.hash block))) && Int32.equal c_level (Store.Block.level block) then Assert.fail_msg "unexpected checkpoint" else return_unit Store . Chain.acceptable_block : will the block is compatible with the current checkpoint ? will the block is compatible with the current checkpoint? *) let test_acceptable_block chain_store table = let block = vblock table "A2" in let block_hash = Store.Block.hash block in let level = Store.Block.level block in Store.Chain.set_head chain_store block >>=? fun _prev_head -> Store.Chain.set_target chain_store (block_hash, level) >>=? fun () -> let block_1 = vblock table "A1" in Store.Chain.is_acceptable_block chain_store (Store.Block.hash block_1, Store.Block.level block_1) >>= fun is_accepted_block -> if not is_accepted_block then return_unit else Assert.fail_msg "unacceptable block was accepted" let test_is_valid_target chain_store table = let block = vblock table "A2" in let block_hash = Store.Block.hash block in let level = Store.Block.level block in Store.Chain.set_head chain_store block >>=? fun _prev_head -> Store.Chain.set_target chain_store (block_hash, level) >>=? fun () -> return_unit let test_best_know_head_for_checkpoint chain_store table = let block = vblock table "A2" in let block_hash = Store.Block.hash block in let level = Store.Block.level block in let checkpoint = (block_hash, level) in Store.Chain.set_head chain_store block >>=? fun _prev_head -> Store.Chain.set_target chain_store checkpoint >>=? fun () -> Store.Chain.set_head chain_store (vblock table "B3") >>=? fun _head -> Store.Chain.best_known_head_for_checkpoint chain_store ~checkpoint >>= fun _block -> the block returns with the best fitness is B3 at level 5 return_unit let test_future_target chain_store _ = Store.Chain.genesis_block chain_store >>= fun genesis_block -> let genesis_descr = Store.Block.descriptor genesis_block in make_raw_block_list genesis_descr 5 >>= fun (bad_chain, bad_head) -> make_raw_block_list genesis_descr 5 >>= fun (good_chain, good_head) -> Store.Chain.set_target chain_store (raw_descriptor good_head) >>=? fun () -> List.iter_es (fun b -> Format.printf "storing : %a@." pp_raw_block b ; store_raw_block chain_store b >>=? fun _ -> return_unit) (List.rev (List.tl (List.rev bad_chain) |> WithExceptions.Option.get ~loc:__LOC__)) >>=? fun () -> (store_raw_block chain_store bad_head >>= function | Error [Validation_errors.Checkpoint_error _] -> return_unit | Ok _ | _ -> Assert.fail_msg "incompatible head accepted") >>=? fun () -> List.iter_es (fun b -> store_raw_block chain_store b >>=? fun _ -> return_unit) (List.rev (List.tl (List.rev good_chain) |> WithExceptions.Option.get ~loc:__LOC__)) >>=? fun () -> store_raw_block chain_store good_head >>=? fun _ -> return_unit let test_reach_target chain_store table = let mem x = let b = vblock table x in Store.Chain.is_in_chain chain_store Store.Block.(hash b, level b) in let test_mem x = mem x >>= function | true -> Lwt.return_unit | false -> Assert.fail_msg "mem %s" x in let test_not_mem x = mem x >>= function | false -> Lwt.return_unit | true -> Assert.fail_msg "not (mem %s)" x in let block = vblock table "A1" in let header = Store.Block.header block in let checkpoint_hash = Store.Block.hash block in let checkpoint_level = Store.Block.level block in Store.Chain.set_head chain_store block >>=? fun _pred_head -> Store.Chain.set_target chain_store (checkpoint_hash, checkpoint_level) >>=? fun () -> Store.Chain.checkpoint chain_store >>= fun (c_hash, _c_level) -> let time_now = Time.System.to_protocol (Systime_os.now ()) in if Time.Protocol.compare (Time.Protocol.add time_now 15L) header.shell.timestamp >= 0 then if Int32.equal header.shell.level checkpoint_level && not (Block_hash.equal checkpoint_hash c_hash) then Assert.fail_msg "checkpoint error" else Store.Chain.set_head chain_store (vblock table "A2") >>=? fun _ -> Store.Chain.current_head chain_store >>= fun head -> let checkpoint_reached = (Store.Block.header head).shell.level >= checkpoint_level in if checkpoint_reached then if header.shell.level <= checkpoint_level then test_mem "Genesis" >>= fun () -> test_mem "A1" >>= fun () -> test_mem "A2" >>= fun () -> test_not_mem "A3" >>= fun () -> test_not_mem "B1" >>= fun () -> return_unit else Assert.fail_msg "checkpoint error" else Assert.fail_msg "checkpoint error" else Assert.fail_msg "fail future block header" let test_not_may_update_target chain_store table = set target at ( 2l , A2 ) let block_a2 = vblock table "A2" in let target_hash = Store.Block.hash block_a2 in let target_level = Store.Block.level block_a2 in let target = (target_hash, target_level) in Store.Chain.set_head chain_store block_a2 >>=? fun _pred_head -> Store.Chain.set_target chain_store target >>=? fun () -> set new target at ( 1l , A1 ) in the past let block_a1 = vblock table "A1" in let target_hash = Store.Block.hash block_a1 in let target_level = Store.Block.level block_a1 in let new_target = (target_hash, target_level) in Lwt.catch (fun () -> Store.Chain.set_target chain_store new_target >>=? fun () -> Assert.fail_msg "Unexpected target update") (function _ -> return_unit) let testable_hash = Alcotest.testable (fun fmt h -> Format.fprintf fmt "%s" (Block_hash.to_b58check h)) Block_hash.equal let init_block_of_identifier_test chain_store table = vblock table "A8" |> Store.Chain.set_head chain_store >|=? fun _ -> () let vblock_hash table name = vblock table name |> Store.Block.hash let assert_successful_block_of_identifier ?(init = init_block_of_identifier_test) ~input ~expected chain_store table = init chain_store table >>=? fun _ -> Store.Chain.block_of_identifier chain_store input >|=? fun found -> Alcotest.check testable_hash "same block hash" expected (Store.Block.hash found) let assert_failing_block_of_identifier ?(init = init_block_of_identifier_test) ~input chain_store table = init chain_store table >>=? fun _ -> Store.Chain.block_of_identifier chain_store input >>= function | Ok b -> Assert.fail_msg ~given:(Store.Block.hash b |> Block_hash.to_b58check) "retrieving the block did not failed as expected" | _ -> return_unit let test_block_of_identifier_success_block_from_level chain_store table = let a5 = vblock table "A5" in assert_successful_block_of_identifier ~input:(`Level (Store.Block.level a5)) ~expected:(Store.Block.hash a5) chain_store table let test_block_of_identifier_success_block_from_hash chain_store table = let a5_hash = vblock_hash table "A5" in assert_successful_block_of_identifier ~input:(`Hash (a5_hash, 0)) ~expected:a5_hash chain_store table let test_block_of_identifier_success_block_from_hash_predecessor chain_store table = assert_successful_block_of_identifier ~input:(`Hash (vblock_hash table "A5", 2)) ~expected:(vblock_hash table "A3") chain_store table let test_block_of_identifier_success_block_from_hash_successor chain_store table = assert_successful_block_of_identifier ~input:(`Hash (vblock_hash table "A5", -2)) ~expected:(vblock_hash table "A7") chain_store table let test_block_of_identifier_success_caboose chain_store table = assert_successful_block_of_identifier ~input:(`Alias (`Caboose, 0)) ~expected:(vblock_hash table "Genesis") chain_store table let test_block_of_identifier_success_caboose_successor chain_store table = assert_successful_block_of_identifier ~input:(`Alias (`Caboose, -2)) ~expected:(vblock_hash table "A2") chain_store table let test_block_of_identifier_failure_caboose_predecessor chain_store table = assert_failing_block_of_identifier ~input:(`Alias (`Caboose, 2)) chain_store table let test_block_of_identifier_success_checkpoint chain_store table = let a5 = vblock table "A5" in let a5_hash = Store.Block.hash a5 in let a5_descriptor = (a5_hash, Store.Block.level a5) in assert_successful_block_of_identifier ~init:(fun cs t -> init_block_of_identifier_test cs t >>=? fun _ -> Store.Unsafe.set_checkpoint cs a5_descriptor) ~input:(`Alias (`Checkpoint, 0)) ~expected:a5_hash chain_store table let test_block_of_identifier_success_checkpoint_predecessor chain_store table = let a5 = vblock table "A5" in let a5_hash = Store.Block.hash a5 in let a5_descriptor = (a5_hash, Store.Block.level a5) in assert_successful_block_of_identifier ~init:(fun cs t -> init_block_of_identifier_test cs t >>=? fun _ -> Store.Unsafe.set_checkpoint cs a5_descriptor) ~input:(`Alias (`Checkpoint, 2)) ~expected:(vblock_hash table "A3") chain_store table let test_block_of_identifier_success_checkpoint_successor chain_store table = let a5 = vblock table "A5" in let a5_hash = Store.Block.hash a5 in let a5_descriptor = (a5_hash, Store.Block.level a5) in assert_successful_block_of_identifier ~init:(fun cs t -> init_block_of_identifier_test cs t >>=? fun _ -> Store.Unsafe.set_checkpoint cs a5_descriptor) ~input:(`Alias (`Checkpoint, -2)) ~expected:(vblock_hash table "A7") chain_store table let test_block_of_identifier_failure_checkpoint_successor chain_store table = let a5 = vblock table "A5" in let a5_hash = Store.Block.hash a5 in let a5_descriptor = (a5_hash, Store.Block.level a5) in assert_failing_block_of_identifier ~init:(fun cs t -> init_block_of_identifier_test cs t >>=? fun _ -> Store.Unsafe.set_checkpoint cs a5_descriptor) ~input:(`Alias (`Checkpoint, -4)) chain_store table let test_block_of_identifier_success_savepoint chain_store table = assert_successful_block_of_identifier ~input:(`Alias (`Savepoint, 0)) ~expected:(vblock_hash table "Genesis") chain_store table let tests = let test_tree_cases = List.map wrap_test [ ("path between blocks", test_path); ("common ancestor", test_ancestor); ("block locators", test_locator); ("known heads", test_known_heads); ("set head", test_head); ("blocks in chain", test_mem); ("new blocks", test_new_blocks); ("basic checkpoint", test_basic_checkpoint); ("is valid target", test_is_valid_target); ("acceptable block", test_acceptable_block); ("best know head", test_best_know_head_for_checkpoint); ("future target", test_future_target); ("reach target", test_reach_target); ("update target in node", test_not_may_update_target); ( "block_of_identifier should succeed to retrieve block from level", test_block_of_identifier_success_block_from_level ); ( "block_of_identifier should succeed to retrieve block from hash", test_block_of_identifier_success_block_from_hash ); ( "block_of_identifier should succeed to retrieve block from hash \ predecessor", test_block_of_identifier_success_block_from_hash_predecessor ); ( "block_of_identifier should succeed to retrieve block from hash \ successor", test_block_of_identifier_success_block_from_hash_successor ); ( "block_of_identifier should succeed to retrieve the caboose", test_block_of_identifier_success_caboose ); ( "block_of_identifier should succeed to retrieve caboose successor", test_block_of_identifier_success_caboose_successor ); ( "block_of_identifier should fail to retrieve caboose predecessor", test_block_of_identifier_failure_caboose_predecessor ); ( "block_of_identifier should succeed to retrieve the checkpoint", test_block_of_identifier_success_checkpoint ); ( "block_of_identifier should succeed to retrieve checkpoint predecessor", test_block_of_identifier_success_checkpoint_predecessor ); ( "block_of_identifier should succeed to retrieve the checkpoint \ successor", test_block_of_identifier_success_checkpoint_successor ); ( "block_of_identifier should fail to retrieve the checkpoint \ successor after the head", test_block_of_identifier_failure_checkpoint_successor ); ( "block_of_identifier should succeed to retrieve the savepoint", test_block_of_identifier_success_savepoint ); ] in ("store", test_cases @ test_tree_cases)
63cd6298094f60a497d42f65906ea14eb888c15dbd68be3e3ca474b06c8bb1f2
smallmelon/sdzmmo
mod_goods.erl
%%%------------------------------------ %%% @Module : mod_goods @Author : xhg %%% @Email : @Created : 2010.05.25 @Description : %%%------------------------------------ -module(mod_goods). -behaviour(gen_server). -export([start/3]). -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -include("common.hrl"). -include("record.hrl"). start(PlayerId,CellNum, Equip) -> gen_server:start_link(?MODULE, [PlayerId,CellNum, Equip], []). init([PlayerId,CellNum, Equip]) -> ok = goods_util:init_goods_online(PlayerId), NullCells = goods_util:get_null_cells(PlayerId, CellNum), EquipSuit = goods_util:get_equip_suit(PlayerId, Equip), GoodsStatus = #goods_status{ player_id = PlayerId, null_cells = NullCells, equip_current = [0,0,0], equip_suit=EquipSuit }, NewStatus = goods_util:get_current_equip(GoodsStatus, Equip), %io:format("equip_current: ~p~n",[NewStatus#goods_status.equip_current]), {ok, NewStatus}. %%设置物品信息 handle_cast({'SET_STATUS', NewStatus}, _GoodsStatus) -> {noreply, NewStatus}; handle_cast(_R , GoodsStatus) -> {noreply, GoodsStatus}. handle_call({'STATUS'} , _From, GoodsStatus) -> {reply, GoodsStatus, GoodsStatus}; %%设置物品信息 handle_call({'SET_STATUS', NewGoodsStatus}, _From, _GoodsStatus) -> {reply, ok, NewGoodsStatus}; 获取物品详细信息 handle_call({'info', GoodsId, Location}, _From, GoodsStatus) -> case Location =:= 5 of true -> GoodsInfo = goods_util:get_goods_by_id(GoodsId); false -> GoodsInfo = goods_util:get_goods(GoodsId) end, case is_record(GoodsInfo, goods) of true when GoodsInfo#goods.player_id == GoodsStatus#goods_status.player_id -> case goods_util:has_attribute(GoodsInfo) of true -> AttributeList = goods_util:get_goods_attribute_list(GoodsStatus#goods_status.player_id, GoodsId); false -> AttributeList = [] end, SuitNum = goods_util:get_suit_num(GoodsStatus#goods_status.equip_suit, GoodsInfo#goods.suit_id), {reply, [GoodsInfo, SuitNum, AttributeList], GoodsStatus}; Error -> ?DEBUG("mod_goods info:~p", [[GoodsId,Error]]), {reply, [{}, 0, []], GoodsStatus} end; 查询别人物品详细信息 handle_call({'info_other', Owner, GoodsId}, _From, GoodsStatus) -> Info = goods_util:get_goods(GoodsId), case is_record(Info, goods) of true -> GoodsInfo = Info; false -> GoodsInfo = goods_util:get_goods_by_id(GoodsId) end, case is_record(GoodsInfo, goods) of true -> IsOnline = lib_player:is_online(Owner), case goods_util:has_attribute(GoodsInfo) of true when IsOnline =:= true -> AttributeList = goods_util:get_goods_attribute_list(Owner, GoodsId); true -> AttributeList = goods_util:get_offline_goods_attribute_list(Owner, GoodsId); false -> AttributeList = [] end, SuitNum = goods_util:get_suit_num(GoodsStatus#goods_status.equip_suit, GoodsInfo#goods.suit_id), {reply, [GoodsInfo, SuitNum, AttributeList], GoodsStatus}; Error -> ?DEBUG("mod_goods info_other:~p", [[Owner, GoodsId, Error]]), {reply, [{}, 0, []], GoodsStatus} end; %% 获取玩家物品列表信息 handle_call({'list', PlayerStatus, Location}, _From, GoodsStatus) -> case Location > 0 of %% 装备 true when Location =< 3 -> NewLocation = Location, CellNum = 12, EquipList = goods_util:get_equip_list(PlayerStatus#player_status.id, 10, NewLocation), MountList = goods_util:get_equip_list(PlayerStatus#player_status.id, 31, 1), List = EquipList ++ MountList; true -> NewLocation = Location, case Location =:= 5 of true -> CellNum = 245; %% 仓库 false -> CellNum = PlayerStatus#player_status.cell_num end, List = goods_util:get_goods_list(PlayerStatus#player_status.id, NewLocation); %% 当前装备 false -> NewLocation = PlayerStatus#player_status.equip, CellNum = 12, EquipList = goods_util:get_equip_list(PlayerStatus#player_status.id, 10, NewLocation), MountList = goods_util:get_equip_list(PlayerStatus#player_status.id, 31, 1), List = EquipList ++ MountList end, {reply, [NewLocation, CellNum, List], GoodsStatus}; %% 获取玩家物品列表信息 handle_call({'list_other', PlayerId}, _From, GoodsStatus) -> %io:format("list_other: ~p~n",[[PlayerId, lib_player:is_online(PlayerId), ets:info(?ETS_ONLINE,size)]]), case lib_player:is_online(PlayerId) of %% 玩家不在线 false -> {reply, [2, []], GoodsStatus}; true -> Player = lib_player:get_online_info(PlayerId), EquipList = goods_util:get_equip_list(PlayerId, 10, Player#ets_online.equip), MountList = goods_util:get_equip_list(PlayerId, 31, 1), List = EquipList ++ MountList, {reply, [1, List], GoodsStatus} end; %% 列出背包打造装备列表 handle_call({'make_list'}, _From, GoodsStatus) -> EquipList = goods_util:get_equip_list(GoodsStatus#goods_status.player_id, 10, 4), {reply, EquipList, GoodsStatus}; %% 取商店物品列表 handle_call({'shop', ShopType, ShopSubtype}, _From, GoodsStatus) -> ShopList = goods_util:get_shop_list(ShopType, ShopSubtype), {reply, ShopList, GoodsStatus}; %%购买物品 handle_call({'pay', PlayerStatus, GoodsTypeId, GoodsNum, ShopType}, _From, GoodsStatus) -> case check_pay(PlayerStatus, GoodsStatus, GoodsTypeId, GoodsNum, ShopType) of {fail, Res} -> {reply, [PlayerStatus, Res, []], GoodsStatus}; {ok, GoodsTypeInfo, GoodsList, Cost, PriceType} -> case (catch lib_goods:pay_goods(GoodsStatus, GoodsTypeInfo, GoodsList, GoodsNum)) of {ok, NewStatus} -> NewPlayerStatus = lib_goods:cost_money(PlayerStatus, Cost, PriceType), NewGoodsList = goods_util:get_type_goods_list(PlayerStatus#player_status.id, GoodsTypeId, GoodsTypeInfo#ets_goods_type.bind, 4), lib_task:event(buy_equip, {GoodsTypeId}, PlayerStatus#player_status.id), {reply, [NewPlayerStatus, 1, NewGoodsList], NewStatus}; Error -> ?DEBUG("mod_goods pay:~p", [Error]), {reply, [PlayerStatus, 0, []], GoodsStatus} end end; handle_call({'sell', PlayerStatus, GoodsId, GoodsNum}, _From, GoodsStatus) -> case check_sell(GoodsStatus, GoodsId, GoodsNum) of {fail, Res} -> {reply, [PlayerStatus, Res], GoodsStatus}; {ok, GoodsInfo} -> case (catch lib_goods:sell_goods(PlayerStatus, GoodsStatus, GoodsInfo, GoodsNum)) of {ok, NewPlayerStatus, NewStatus} -> {reply, [NewPlayerStatus, 1], NewStatus}; Error -> ?DEBUG("mod_goods sell:~p", [Error]), {reply, [PlayerStatus, 0], GoodsStatus} end end; 装备物品 handle_call({'equip', PlayerStatus, GoodsId, Cell}, _From, GoodsStatus) -> case check_equip(PlayerStatus, GoodsId, Cell) of {fail, Res} -> {reply, [PlayerStatus, Res, {}, {}, []], GoodsStatus}; {ok, GoodsInfo, Location, NewCell} -> case (catch lib_goods:equip_goods(PlayerStatus, GoodsStatus, GoodsInfo, Location, NewCell)) of {ok, NewPlayerStatus, NewStatus, OldGoodsInfo, Effect2} -> lib_task:event(equip, {GoodsInfo#goods.goods_id}, GoodsInfo#goods.player_id), {reply, [NewPlayerStatus, 1, GoodsInfo, OldGoodsInfo, Effect2], NewStatus}; Error -> ?DEBUG("mod_goods equip:~p", [Error]), {reply, [PlayerStatus, 0, {}, []], GoodsStatus} end end; handle_call({'unequip', PlayerStatus, GoodsId}, _From, GoodsStatus) -> case check_unequip(GoodsStatus, GoodsId, PlayerStatus#player_status.equip) of {fail, Res} -> {reply, [PlayerStatus, Res, {}], GoodsStatus}; {ok, GoodsInfo} -> case (catch lib_goods:unequip_goods(PlayerStatus, GoodsStatus, GoodsInfo)) of {ok, NewPlayerStatus, NewStatus, NewGoodsInfo} -> {reply, [NewPlayerStatus, 1, NewGoodsInfo], NewStatus}; Error -> ?DEBUG("mod_goods unequip:~p", [Error]), {reply, [PlayerStatus, 0, {}], GoodsStatus} end end; %%背包拖动物品 handle_call({'drag', PlayerStatus, GoodsId, OldCell, NewCell}, _From, GoodsStatus) -> case check_drag(GoodsStatus, GoodsId, OldCell, NewCell, PlayerStatus#player_status.cell_num) of {fail, Res} -> {reply, [Res, 0, 0, 0, 0], GoodsStatus}; {ok, GoodsInfo} -> case (catch lib_goods:drag_goods(GoodsStatus, GoodsInfo, OldCell, NewCell)) of {ok, NewStatus, [OldCellId, OldTypeId, NewCellId, NewTypeId]} -> {reply, [1, OldCellId, OldTypeId, NewCellId, NewTypeId], NewStatus}; Error -> ?DEBUG("mod_goods drag:~p", [Error]), {reply, [0, 0, 0, 0, 0], GoodsStatus} end end; handle_call({'use', PlayerStatus, GoodsId, GoodsNum}, _From, GoodsStatus) -> case check_use(GoodsStatus, GoodsId, GoodsNum, PlayerStatus#player_status.lv) of {fail, Res} -> {reply, [PlayerStatus, Res, 0, 0], GoodsStatus}; {ok, GoodsInfo} -> case (catch lib_goods:use_goods(PlayerStatus, GoodsStatus, GoodsInfo, GoodsNum)) of {ok, NewPlayerStatus, NewStatus, NewNum} -> {reply, [NewPlayerStatus, 1, GoodsInfo#goods.goods_id, NewNum], NewStatus}; Error -> ?DEBUG("mod_goods use:~p", [Error]), {reply, [PlayerStatus, 0, 0, 0], GoodsStatus} end end; %%删除多个物品 handle_call({'delete_one', GoodsId, GoodsNum}, _From, GoodsStatus) -> GoodsInfo = goods_util:get_goods(GoodsId), if is_record(GoodsInfo, goods) =:= false -> {reply, [2, 0], GoodsStatus}; %% 物品数量不正确 GoodsInfo#goods.num < GoodsNum -> {reply, [3, 0], GoodsStatus}; true -> case (catch lib_goods:delete_one(GoodsStatus, GoodsInfo, GoodsNum)) of {ok, NewStatus, NewNum} -> lib_player:refresh_client(GoodsStatus#goods_status.player_id, 2), {reply, [1, NewNum], NewStatus}; Error -> ?DEBUG("mod_goods delete_one:~p", [Error]), {reply, [0, 0], GoodsStatus} end end; 删除多个同类型物品 handle_call({'delete_more', GoodsTypeId, GoodsNum}, _From, GoodsStatus) -> GoodsList = goods_util:get_type_goods_list(GoodsStatus#goods_status.player_id, GoodsTypeId, 4), TotalNum = goods_util:get_goods_totalnum(GoodsList), if length(GoodsList) =:= 0 -> {reply, 2, GoodsStatus}; 物品数量不足 TotalNum < GoodsNum -> {reply, 3, GoodsStatus}; true -> case (catch lib_goods:delete_more(GoodsStatus, GoodsList, GoodsNum)) of {ok, NewStatus} -> lib_player:refresh_client(GoodsStatus#goods_status.player_id, 2), {reply, 1, NewStatus}; Error -> ?DEBUG("mod_goods delete_more:~p", [Error]), {reply, 0, GoodsStatus} end end; handle_call({'throw', GoodsId, GoodsNum}, _From, GoodsStatus) -> case check_throw(GoodsStatus, GoodsId, GoodsNum) of {fail, Res} -> {reply, Res, GoodsStatus}; {ok, GoodsInfo} -> case (catch lib_goods:delete_one(GoodsStatus, GoodsInfo, GoodsNum)) of {ok, NewStatus, _} -> {reply, 1, NewStatus}; Error -> ?DEBUG("mod_goods throw:~p", [Error]), {reply, 0, GoodsStatus} end end; 丢弃同类型物品 GoodsTypeList = [ GoodsTypeId1 , , ... ] handle_call({'throw_more', GoodsTypeList}, _From, GoodsStatus) -> case (catch goods_util:list_handle(fun lib_goods:delete_type_goods/2, GoodsStatus, GoodsTypeList)) of {ok, NewStatus} -> lib_player:refresh_client(NewStatus#goods_status.player_id, 2), {reply, ok, NewStatus}; {Error, Status} -> ?DEBUG("mod_goods throw_more:~p", [Error]), {reply, Error, Status} end; handle_call({'movein_bag', GoodsId, GoodsNum}, _From, GoodsStatus) -> case check_movein_bag(GoodsStatus, GoodsId, GoodsNum) of {fail, Res} -> {reply, Res, GoodsStatus}; {ok, GoodsInfo, GoodsTypeInfo} -> case (catch lib_goods:movein_bag(GoodsStatus, GoodsInfo, GoodsNum, GoodsTypeInfo)) of {ok, NewStatus} -> {reply, 1, NewStatus}; Error -> ?DEBUG("mod_goods movein_bag:~p", [Error]), {reply, 0, GoodsStatus} end end; 从仓库取出物品 handle_call({'moveout_bag', GoodsId, GoodsNum}, _From, GoodsStatus) -> case check_moveout_bag(GoodsStatus, GoodsId, GoodsNum) of {fail, Res} -> {reply, [Res, []], GoodsStatus}; {ok, GoodsInfo, GoodsTypeInfo} -> case (catch lib_goods:moveout_bag(GoodsStatus, GoodsInfo, GoodsNum, GoodsTypeInfo)) of {ok, NewStatus} -> GoodsList = goods_util:get_type_goods_list(GoodsInfo#goods.player_id, GoodsInfo#goods.goods_id, GoodsInfo#goods.bind, 4), {reply, [1, GoodsList], NewStatus}; Error -> ?DEBUG("mod_goods moveout_bag:~p", [Error]), {reply, [0, []], GoodsStatus} end end; 扩充背包 handle_call({'extend_bag', PlayerStatus}, _From, GoodsStatus) -> case check_extend_bag(PlayerStatus) of {fail, Res} -> {reply, [PlayerStatus, Res], GoodsStatus}; {ok, Cost} -> case (catch lib_goods:extend_bag(PlayerStatus, Cost)) of {ok, NewPlayerStatus} -> {reply, [NewPlayerStatus, 1], GoodsStatus}; Error -> ?DEBUG("mod_goods extend_bag:~p", [Error]), {reply, [PlayerStatus, 0], GoodsStatus} end end; handle_call({'attrit', PlayerStatus, UseNum}, _From, GoodsStatus) -> %% 查找身上耐久为1的装备 Sql = io_lib : format(<<"select id , subtype from ` goods ` where player_id = ~p and location = ~p and type = 10 and use_num < = ~p and use_num > 0 and attrition > 0 " > > , [ PlayerStatus#player_status.id , PlayerStatus#player_status.equip , UseNum ] ) , List = goods_util : get_list(goods , ) , %% 穿在身上的装备耐久减1 Sql2 = io_lib:format(<<"update `goods` set use_num = use_num - (~p) where player_id = ~p and location = ~p and type = 10 and use_num > ~p and attrition > 0 ">>, [UseNum, PlayerStatus#player_status.id, PlayerStatus#player_status.equip, UseNum]), db_sql:execute(Sql2), Sql3 = io_lib:format(<<"update `goods` set use_num = 0 where player_id = ~p and location = ~p and type = 10 and use_num <= ~p and use_num > 0 and attrition > 0 ">>, [PlayerStatus#player_status.id, PlayerStatus#player_status.equip, UseNum]), db_sql:execute(Sql3), EquipList = goods_util:get_equip_list(PlayerStatus#player_status.id, 10, PlayerStatus#player_status.equip), [_, ZeroEquipList] = lists:foldl(fun lib_goods:attrit_equip/2, [UseNum, []], EquipList), %%广播耐久更新 lib_player:refresh_client(PlayerStatus#player_status.id, 5), %% 人物属性更新 case length(ZeroEquipList) > 0 of %% 有耐久为0的装备 true -> 人物属性重新计算 EquipSuit = goods_util:get_equip_suit(PlayerStatus#player_status.id, PlayerStatus#player_status.equip), Status = GoodsStatus#goods_status{ equip_suit=EquipSuit }, {ok, NewPlayerStatus, NewStatus} = goods_util:count_role_equip_attribute(PlayerStatus, Status, {}), %% 检查武器、衣服 [NewStatus2, _] = goods_util:get_current_equip_by_list(ZeroEquipList, [NewStatus, off]), NewPlayerStatus2 = NewPlayerStatus#player_status{ equip_attrit=0, equip_current=NewStatus2#goods_status.equip_current }, 广播 {ok, BinData} = pt_12:write(12015, [NewPlayerStatus#player_status.id, NewPlayerStatus#player_status.hp, NewPlayerStatus#player_status.hp_lim, ZeroEquipList]), lib_send:send_to_area_scene(NewPlayerStatus#player_status.scene, NewPlayerStatus#player_status.x, NewPlayerStatus#player_status.y, BinData), 通知客户端 {ok, BinData1} = pt_15:write(15032, ZeroEquipList), lib_send:send_one(NewPlayerStatus#player_status.socket, BinData1), %% 返回更新人物属性 {reply, {ok, NewPlayerStatus2}, NewStatus2}; false -> {reply, {error,no,attrition,equip}, GoodsStatus} end; 获取要修理装备列表 handle_call({'mend_list', PlayerStatus}, _From, GoodsStatus) -> %% 查找有耐久度的装备 List = goods_util:get_mend_list(GoodsStatus#goods_status.player_id, PlayerStatus#player_status.equip), F = fun(GoodsInfo) -> UseNum = goods_util:get_goods_use_num(GoodsInfo#goods.attrition), case UseNum =/= GoodsInfo#goods.use_num of true -> Attrition = goods_util:get_goods_attrition(GoodsInfo#goods.attrition, GoodsInfo#goods.use_num), Cost = goods_util:get_mend_cost(GoodsInfo#goods.attrition, GoodsInfo#goods.use_num), [[GoodsInfo#goods.id, GoodsInfo#goods.goods_id, Attrition, Cost]]; false -> [] end end, MendList = lists:flatmap(F, List), {reply, MendList, GoodsStatus}; 修理装备 handle_call({'mend', PlayerStatus, GoodsId}, _From, GoodsStatus) -> case check_mend(PlayerStatus, GoodsId) of {fail, Res} -> {reply, [PlayerStatus, Res, {}], GoodsStatus}; {ok, GoodsInfo} -> case (catch lib_goods:mend_goods(PlayerStatus, GoodsStatus, GoodsInfo)) of {ok, NewPlayerStatus, NewStatus} -> {reply, [NewPlayerStatus, 1, GoodsInfo], NewStatus}; Error -> ?DEBUG("mod_goods mend:~p", [Error]), {reply, [PlayerStatus, 0, {}], GoodsStatus} end end; %% 装备品质升级 handle_call({'quality_upgrade', PlayerStatus, GoodsId, StoneId}, _From, GoodsStatus) -> case check_quality_upgrade(PlayerStatus, GoodsId, StoneId) of {fail, Res} -> {reply, [PlayerStatus, Res, 0, 0], GoodsStatus}; {ok, GoodsInfo, StoneInfo, GoodsQualityRule} -> case (catch lib_make:quality_upgrade(PlayerStatus, GoodsStatus, GoodsInfo, StoneInfo, GoodsQualityRule)) of {ok, NewPlayerStatus, NewStatus, [NewQuality, NewStoneNum]} -> {reply, [NewPlayerStatus, 1, NewQuality, NewStoneNum], NewStatus}; Error -> ?DEBUG("mod_goods quality_upgrade:~p", [Error]), {reply, [PlayerStatus, 0, 0, 0], GoodsStatus} end end; %% 装备品质石拆除 handle_call({'quality_backout', PlayerStatus, GoodsId}, _From, GoodsStatus) -> case check_quality_backout(GoodsStatus, GoodsId) of {fail, Res} -> {reply, [PlayerStatus, Res], GoodsStatus}; {ok, GoodsInfo, GoodsBackoutRuleList} -> case (catch lib_make:quality_backout(PlayerStatus, GoodsStatus, GoodsInfo, GoodsBackoutRuleList)) of {ok, NewPlayerStatus, NewStatus} -> {reply, [NewPlayerStatus, 1], NewStatus}; {fail, Res} -> {reply, [PlayerStatus, Res], GoodsStatus}; Error -> ?DEBUG("mod_goods quality_backout:~p", [Error]), {reply, [PlayerStatus, 0], GoodsStatus} end end; 装备强化 handle_call({'strengthen', PlayerStatus, GoodsId, StoneId, RuneId}, _From, GoodsStatus) -> case check_strengthen(PlayerStatus, GoodsId, StoneId, RuneId) of {fail, Res} -> {reply, [PlayerStatus, Res, 0, 0, 0], GoodsStatus}; {ok, GoodsInfo, StoneInfo, RuneInfo, GoodsStrengthenRule} -> case (catch lib_make:strengthen(PlayerStatus, GoodsStatus, GoodsInfo, StoneInfo, RuneInfo, GoodsStrengthenRule)) of {ok, NewPlayerStatus, NewStatus, [NewStrengthen, NewStoneNum, NewRuneNum]} -> {reply, [NewPlayerStatus, 1, NewStrengthen, NewStoneNum, NewRuneNum], NewStatus}; Error -> ?DEBUG("mod_goods strengthen:~p", [Error]), {reply, [PlayerStatus, 0, 0, 0, 0], GoodsStatus} end end; %% 装备打孔 handle_call({'hole', PlayerStatus, GoodsId, RuneId}, _From, GoodsStatus) -> case check_hole(PlayerStatus, GoodsId, RuneId) of {fail, Res} -> {reply, [PlayerStatus, Res, 0, 0], GoodsStatus}; {ok, GoodsInfo, RuneInfo} -> case (catch lib_make:hole(PlayerStatus, GoodsStatus, GoodsInfo, RuneInfo)) of {ok, NewPlayerStatus, NewStatus, [NewHole, NewRuneNum]} -> {reply, [NewPlayerStatus, 1, NewHole, NewRuneNum], NewStatus}; Error -> ?DEBUG("mod_goods hole:~p", [Error]), {reply, [PlayerStatus, 0, 0, 0], GoodsStatus} end end; %% 宝石合成 handle_call({'compose', PlayerStatus, RuneId, StoneTypeId, StoneList}, _From, GoodsStatus) -> case check_compose(PlayerStatus, GoodsStatus, RuneId, StoneTypeId, StoneList) of {fail, Res} -> {reply, [PlayerStatus, Res, 0], GoodsStatus}; {ok, NewStoneList, RuneInfo, GoodsComposeRule} -> case (catch lib_make:compose(PlayerStatus, GoodsStatus, NewStoneList, RuneInfo, GoodsComposeRule)) of {ok, NewPlayerStatus, NewStatus, NewGoodsTypeId} -> {reply, [NewPlayerStatus, 1, NewGoodsTypeId], NewStatus}; Error -> ?DEBUG("mod_goods compose:~p", [Error]), {reply, [PlayerStatus, 0, 0], GoodsStatus} end end; %% 宝石镶嵌 handle_call({'inlay', PlayerStatus, GoodsId, StoneId, RuneList}, _From, GoodsStatus) -> case check_inlay(PlayerStatus, GoodsId, StoneId, RuneList) of {fail, Res} -> {reply, [PlayerStatus, Res], GoodsStatus}; {ok, GoodsInfo, StoneInfo, TotalRuneNum, NewRuneList, GoodsInlayRule} -> case (catch lib_make:inlay(PlayerStatus, GoodsStatus, GoodsInfo, StoneInfo, TotalRuneNum, NewRuneList, GoodsInlayRule)) of {ok, Res, NewPlayerStatus, NewStatus} -> {reply, [NewPlayerStatus, Res], NewStatus}; Error -> ?DEBUG("mod_goods inlay:~p", [Error]), {reply, [PlayerStatus, 10], GoodsStatus} end end; %% 宝石拆除 handle_call({'backout', PlayerStatus, GoodsId, RuneId}, _From, GoodsStatus) -> case check_backout(PlayerStatus, GoodsStatus, GoodsId, RuneId) of {fail, Res} -> {reply, [PlayerStatus, Res], GoodsStatus}; {ok, GoodsInfo, RuneInfo} -> case (catch lib_make:backout(PlayerStatus, GoodsStatus, GoodsInfo, RuneInfo)) of {ok, NewPlayerStatus, NewStatus} -> {reply, [NewPlayerStatus, 1], NewStatus}; Error -> ?DEBUG("mod_goods backout:~p", [Error]), {reply, [PlayerStatus, 0], GoodsStatus} end end; %% 洗附加属性 handle_call({'wash', PlayerStatus, GoodsId, RuneId}, _From, GoodsStatus) -> case check_wash(PlayerStatus, GoodsId, RuneId) of {fail, Res} -> {reply, [PlayerStatus, Res, 0], GoodsStatus}; {ok, GoodsInfo, RuneInfo, AddAttributeRuleList} -> case (catch lib_make:wash(PlayerStatus, GoodsStatus, GoodsInfo, RuneInfo, AddAttributeRuleList)) of {ok, NewPlayerStatus, NewStatus, NewRuneNum} -> {reply, [NewPlayerStatus, 1, NewRuneNum], NewStatus}; Error -> ?DEBUG("mod_goods wash:~p", [Error]), {reply, [PlayerStatus, 0, 0], GoodsStatus} end end; %% 切换装备 handle_call({'change_equip', PlayerStatus, Equip}, _From, GoodsStatus) -> case check_change_equip(PlayerStatus, Equip) of {fail, Res} -> {reply, [PlayerStatus, Res, []], GoodsStatus}; ok -> case (catch lib_goods:change_equip(PlayerStatus, GoodsStatus, Equip)) of {ok, NewPlayerStatus, NewStatus, EquipList} -> {reply, [NewPlayerStatus, 1, EquipList], NewStatus}; Error -> ?DEBUG("mod_goods change_equip:~p", [Error]), {reply, [PlayerStatus, 0, []], GoodsStatus} end end; %% 整理背包 handle_call({'clean', PlayerStatus}, _From, GoodsStatus) -> %% 查询背包物品列表 GoodsList = goods_util:get_goods_list(GoodsStatus#goods_status.player_id, 4), %% 按物品类型ID排序 GoodsList1 = goods_util:sort(GoodsList, goods_id), %% 整理 [Num, _] = lists:foldl(fun lib_goods:clean_bag/2, [1, {}], GoodsList1), %% 重新计算 NewGoodsList = goods_util:get_goods_list(GoodsStatus#goods_status.player_id, 4), NullCells = lists:seq(Num, PlayerStatus#player_status.cell_num), NewGoodsStatus = GoodsStatus#goods_status{ null_cells = NullCells }, {reply, NewGoodsList, NewGoodsStatus}; %% 查看地上的掉落包 handle_call({'drop_list', PlayerStatus, DropId}, _From, GoodsStatus) -> case check_drop_list(PlayerStatus, DropId) of {fail, Res} -> {reply, [Res, []], GoodsStatus}; {ok, DropInfo} -> {reply, [1, DropInfo#ets_goods_drop.drop_goods], GoodsStatus} end; %% 拣取地上掉落包的物品 handle_call({'drop_choose', PlayerStatus, DropId, GoodsTypeId}, _From, GoodsStatus) -> case check_drop_choose(PlayerStatus, GoodsStatus, DropId, GoodsTypeId) of {fail, Res} -> {reply, Res, GoodsStatus}; {ok, DropInfo, GoodsInfo} -> case (catch lib_goods:drop_choose(PlayerStatus, GoodsStatus, DropInfo, GoodsInfo)) of {ok, NewStatus} -> {reply, 1, NewStatus}; Error -> ?DEBUG("mod_goods drop_choose:~p", [Error]), {reply, 0, GoodsStatus} end end; %% 赠送物品 handle_call({'give_goods', _PlayerStatus, GoodsTypeId, GoodsNum}, _From, GoodsStatus) -> case (catch lib_goods:give_goods({GoodsTypeId, GoodsNum}, GoodsStatus)) of {ok, NewStatus} -> lib_player:refresh_client(NewStatus#goods_status.player_id, 2), {reply, ok, NewStatus}; {fail, Error, Status} -> ?DEBUG("mod_goods give_goods:~p", [Error]), {reply, Error, Status} end; %% 赠送物品 = [ , } , ... ] handle_call({'give_more', _PlayerStatus, GoodsList}, _From, GoodsStatus) -> case (catch goods_util:list_handle(fun lib_goods:give_goods/2, GoodsStatus, GoodsList)) of {ok, NewStatus} -> lib_player:refresh_client(NewStatus#goods_status.player_id, 2), {reply, ok, NewStatus}; {fail, Error, Status} -> ?DEBUG("mod_goods give_more:~p", [Error]), {reply, Error, Status} end; %% 怪物掉落 { ' mon_drop ' , PlayerStatus , MonStatus } - > { ok , } | { fail , no_drop } handle_call({'mon_drop', PlayerStatus, MonStatus}, _From, GoodsStatus) -> PlayerId = PlayerStatus#player_status.id, TeamId = PlayerStatus#player_status.pid_team, MonId = MonStatus#ets_mon.mid, RealMonId = MonStatus#ets_mon.id, NumRule = lib_goods:get_drop_num_rule(MonId), case is_record(NumRule, ets_goods_drop_num) of true when NumRule#ets_goods_drop_num.drop_num > 0 -> [TotalRatio, RuleList] = lib_goods:get_drop_rule_list(PlayerId, MonId), case length(RuleList) > 0 of true -> DropNum = NumRule#ets_goods_drop_num.drop_num, [NewGoodsStatus, _, _, RuleResult, TaskResult] = lists:foldl(fun lib_goods:mon_drop/2, [GoodsStatus, RuleList, TotalRatio, [], []], lists:seq(1, DropNum)), %io:format("mon_drop RuleResult: ~p~n",[RuleResult]), case length(TaskResult) > 0 of true -> io : format("mon_drop : ~p ~ n",[TaskResult ] ) , lib_task:event(item, TaskResult, PlayerId), lib_player:refresh_client(PlayerId, 2); false -> skip end, case length(RuleResult) > 0 of %% 如果有掉落,则插入ETS true -> ExpireTime = util:unixtime() + 60, DropInfo = #ets_goods_drop{ id=RealMonId, player_id=PlayerId, team_id=TeamId, drop_goods=RuleResult, expire_time=ExpireTime }, ets:insert(?ETS_GOODS_DROP, DropInfo), 广播 {ok, BinData} = pt_12:write(12017, [RealMonId, 60, MonStatus#ets_mon.x, MonStatus#ets_mon.y]), lib_send:send_to_team(PlayerStatus#player_status.sid, PlayerStatus#player_status.pid_team, BinData), {reply, ok, NewGoodsStatus}; %% 无掉落 false -> {reply, {fail, no_drop}, NewGoodsStatus} end; %% 无掉落 false -> {reply, {fail, no_drop}, GoodsStatus} end; %% 无掉落 _ -> {reply, {fail, no_drop}, GoodsStatus} end; %% 获取空格子数 handle_call({'cell_num'} , _From, GoodsStatus) -> {reply, length(GoodsStatus#goods_status.null_cells), GoodsStatus}; handle_call(_R , _From, GoodsStatus) -> {reply, ok, GoodsStatus}. handle_info(_Reason, GoodsStatus) -> {noreply, GoodsStatus}. terminate(_Reason, _GoodsStatus) -> ok. code_change(_OldVsn, GoodsStatus, _Extra)-> {ok, GoodsStatus}. %% Local Function check_pay(PlayerStatus, GoodsStatus, GoodsTypeId, GoodsNum, ShopType) -> ShopInfo = goods_util:get_shop_info(ShopType, GoodsTypeId), GoodsTypeInfo = goods_util:get_goods_type(GoodsTypeId), case is_record(GoodsTypeInfo, ets_goods_type) andalso is_record(ShopInfo, ets_shop) of false -> {fail, 2}; true -> GoodsList = goods_util:get_type_goods_list(GoodsStatus#goods_status.player_id, GoodsTypeId, GoodsTypeInfo#ets_goods_type.bind, 4), CellNum = goods_util:get_null_cell_num(GoodsList, GoodsTypeInfo#ets_goods_type.max_overlap, GoodsNum), case length(GoodsStatus#goods_status.null_cells) < CellNum of 背包格子不足 true -> {fail, 4}; false -> Cost = GoodsTypeInfo#ets_goods_type.price * GoodsNum, PriceType = goods_util:get_price_type(GoodsTypeInfo#ets_goods_type.price_type), case goods_util:is_enough_money(PlayerStatus, Cost, PriceType) of %% 金额不足 false -> {fail, 3}; true -> {ok, GoodsTypeInfo, GoodsList, Cost, PriceType} end end end. check_sell(GoodsStatus, GoodsId, GoodsNum) -> GoodsInfo = goods_util:get_goods(GoodsId), if is_record(GoodsInfo, goods) =:= false -> {fail, 2}; %% 物品不属于你所有 GoodsInfo#goods.player_id =/= GoodsStatus#goods_status.player_id -> {fail, 3}; %% 物品不在背包 GoodsInfo#goods.location =/= 4 -> {fail, 4}; %% 物品不可出售 GoodsInfo#goods.sell =:= 1 -> {fail, 5}; 物品数量不足 GoodsInfo#goods.num < GoodsNum -> {fail, 6}; true -> {ok, GoodsInfo} end. check_equip(PlayerStatus, GoodsId, Cell) -> Location = PlayerStatus#player_status.equip, GoodsInfo = goods_util:get_goods(GoodsId), if is_record(GoodsInfo, goods) =:= false -> {fail, 2}; %% 物品不属于你所有 GoodsInfo#goods.player_id =/= PlayerStatus#player_status.id -> {fail, 3}; GoodsInfo#goods.location =/= 4 -> {fail, 4}; Location =/= 1 andalso Location =/= 2 andalso Location =/= 3 -> {fail, 4}; %% 物品类型不可装备 GoodsInfo#goods.type =/= 10 -> {fail, 5}; true -> case goods_util:can_equip(PlayerStatus, GoodsInfo#goods.goods_id, Cell) of %% 玩家条件不符 false -> {fail, 6}; NewCell -> {ok, GoodsInfo, Location, NewCell} end end. check_unequip(GoodsStatus, GoodsId, Equip) -> GoodsInfo = goods_util:get_goods(GoodsId), if is_record(GoodsInfo, goods) =:= false -> {fail, 2}; %% 物品不属于你所有 GoodsInfo#goods.player_id =/= GoodsStatus#goods_status.player_id -> {fail, 3}; 物品不在身上 GoodsInfo#goods.location > 3 orelse GoodsInfo#goods.location < 1 -> {fail, 4}; 物品不在身上 GoodsInfo#goods.location =/= Equip -> {fail, 4}; %% 物品类型不可装备 GoodsInfo#goods.type =/= 10 -> {fail, 5}; %% 背包已满 length(GoodsStatus#goods_status.null_cells) =:= 0 -> {fail, 6}; true -> {ok, GoodsInfo} end. check_drag(GoodsStatus, GoodsId, OldCell, NewCell, MaxCellNum) -> GoodsInfo = goods_util:get_goods(GoodsId), if is_record(GoodsInfo, goods) =:= false -> {fail, 2}; %% 物品不属于你所有 GoodsInfo#goods.player_id =/= GoodsStatus#goods_status.player_id -> {fail, 3}; %% 物品不在背包 GoodsInfo#goods.location =/= 4 -> {fail, 4}; %% 物品格子位置不正确 GoodsInfo#goods.cell =/= OldCell -> {fail, 5}; %% 物品格子位置不正确 NewCell < 1 orelse NewCell > MaxCellNum -> {fail, 5}; true -> {ok, GoodsInfo} end. check_use(GoodsStatus, GoodsId, GoodsNum, Level) -> NowTime = util:unixtime(), GoodsInfo = goods_util:get_goods(GoodsId), if is_record(GoodsInfo, goods) =:= false -> {fail, 2}; %% 物品不属于你所有 GoodsInfo#goods.player_id =/= GoodsStatus#goods_status.player_id -> {fail, 3}; %% 物品不在背包 GoodsInfo#goods.location =/= 4 -> {fail, 4}; 物品类型不符 GoodsInfo#goods.type =/= 20 andalso GoodsInfo#goods.type =/= 22 -> {fail, 5}; %% 物品数量不正确 GoodsInfo#goods.num < GoodsNum -> {fail, 6}; %% 冷却时间 GoodsInfo#goods.type =:= 20 andalso GoodsStatus#goods_status.ct_time > NowTime -> {fail, 7}; %% 人物等级不足 GoodsInfo#goods.level > Level -> {fail, 8}; true -> {ok, GoodsInfo} end. check_throw(GoodsStatus, GoodsId, GoodsNum) -> GoodsInfo = goods_util:get_goods(GoodsId), if is_record(GoodsInfo, goods) =:= false -> {fail, 2}; %% 物品不属于你所有 GoodsInfo#goods.player_id =/= GoodsStatus#goods_status.player_id -> {fail, 3}; %% 物品不在背包 GoodsInfo#goods.location =/= 4 -> {fail, 4}; %% 物品不可丢弃 GoodsInfo#goods.isdrop =:= 1 -> {fail, 5}; %% 物品数量不正确 GoodsInfo#goods.num < GoodsNum -> {fail, 6}; true -> {ok, GoodsInfo} end. check_movein_bag(GoodsStatus, GoodsId, GoodsNum) -> GoodsInfo = goods_util:get_goods(GoodsId), if is_record(GoodsInfo, goods) =:= false -> {fail, 2}; %% 物品不属于你所有 GoodsInfo#goods.player_id =/= GoodsStatus#goods_status.player_id -> {fail, 3}; %% 物品不在背包 GoodsInfo#goods.location =/= 4 -> {fail, 4}; %% 物品数量不正确 GoodsInfo#goods.num < GoodsNum -> {fail, 5}; true -> GoodsTypeInfo = goods_util:get_goods_type(GoodsInfo#goods.goods_id), if %% 物品类型不存在 is_record(GoodsTypeInfo, ets_goods_type) =:= false -> {fail, 2}; true -> {ok, GoodsInfo, GoodsTypeInfo} end end. check_moveout_bag(GoodsStatus, GoodsId, GoodsNum) -> GoodsInfo = goods_util:get_goods_by_id(GoodsId), if is_record(GoodsInfo, goods) =:= false -> {fail, 2}; %% 物品不属于你所有 GoodsInfo#goods.player_id =/= GoodsStatus#goods_status.player_id -> {fail, 3}; %% 物品不在仓库 GoodsInfo#goods.location =/= 5 -> {fail, 4}; %% 物品数量不正确 GoodsInfo#goods.num < GoodsNum -> {fail, 5}; true -> GoodsTypeInfo = goods_util:get_goods_type(GoodsInfo#goods.goods_id), if %% 物品类型不存在 is_record(GoodsTypeInfo, ets_goods_type) =:= false -> {fail, 2}; %% 背包已满 length(GoodsStatus#goods_status.null_cells) =< 0 -> {fail, 6}; true -> {ok, GoodsInfo, GoodsTypeInfo} end end. check_extend_bag(PlayerStatus) -> Cost = 1000, MaxCell = 147, if 背包已达上限 PlayerStatus#player_status.cell_num >= MaxCell -> {fail, 3}; true -> case goods_util:is_enough_money(PlayerStatus, Cost, coin) of %% 玩家金额不足 false -> {fail, 2}; true ->{ok, Cost} end end. check_mend(PlayerStatus, GoodsId) -> GoodsInfo = goods_util:get_goods(GoodsId), is_record(GoodsInfo, goods) =:= false -> {fail, 2}; %% 物品不属于你所有 GoodsInfo#goods.player_id =/= PlayerStatus#player_status.id -> {fail, 3}; %% 物品类型不正确 GoodsInfo#goods.type =/= 10 orelse GoodsInfo#goods.attrition =:= 0 -> {fail, 4}; true -> UseNum = goods_util:get_goods_use_num(GoodsInfo#goods.attrition), if %% 无磨损 UseNum > 0 andalso UseNum =:= GoodsInfo#goods.use_num -> {fail, 5}; true -> Cost = goods_util:get_mend_cost(GoodsInfo#goods.attrition, GoodsInfo#goods.use_num), case goods_util:is_enough_money(PlayerStatus, Cost, coin) of %% 余额不足 false -> {fail, 6}; true -> {ok, GoodsInfo} end end end. check_quality_upgrade(PlayerStatus, GoodsId, StoneId) -> GoodsInfo = goods_util:get_goods(GoodsId), StoneInfo = goods_util:get_goods(StoneId), if is_record(GoodsInfo, goods) =:= false orelse is_record(StoneInfo, goods) =:= false -> {fail, 2}; GoodsInfo#goods.num < 1 orelse StoneInfo#goods.num < 1 -> {fail, 2}; %% 物品不属于你所有 GoodsInfo#goods.player_id =/= PlayerStatus#player_status.id orelse StoneInfo#goods.player_id =/= PlayerStatus#player_status.id -> {fail, 3}; GoodsInfo#goods.location =/= 4 -> {fail, 4}; %% 物品类型不正确 GoodsInfo#goods.type =/= 10 -> {fail, 5}; %% 物品类型不正确 StoneInfo#goods.type =/= 11 orelse StoneInfo#goods.subtype =/= 11 -> {fail, 5}; true -> Pattern = #ets_goods_quality_upgrade{ goods_id=StoneInfo#goods.goods_id, quality=GoodsInfo#goods.quality, _='_' }, GoodsQualityRule = goods_util:get_ets_info(?ETS_GOODS_QUALITY_UPGRADE, Pattern), if %% 品质升级规则不存在 is_record(GoodsQualityRule, ets_goods_quality_upgrade) =:= false -> {fail, 6}; %% 玩家铜钱不足 (PlayerStatus#player_status.coin + PlayerStatus#player_status.bcoin) < GoodsQualityRule#ets_goods_quality_upgrade.coin -> {fail, 7}; true -> {ok, GoodsInfo, StoneInfo, GoodsQualityRule} end end. check_quality_backout(GoodsStatus, GoodsId) -> GoodsInfo = goods_util:get_goods(GoodsId), if is_record(GoodsInfo, goods) =:= false orelse GoodsInfo#goods.num < 1 -> {fail, 2}; %% 物品不属于你所有 GoodsInfo#goods.player_id =/= GoodsStatus#goods_status.player_id -> {fail, 3}; %% 物品类型不正确 GoodsInfo#goods.type =/= 10 -> {fail, 5}; %% 物品品质不正确 GoodsInfo#goods.quality < 1 -> {fail, 6}; %% 背包满 length(GoodsStatus#goods_status.null_cells) =:= 0 -> {fail, 8}; true -> Pattern = #ets_goods_quality_backout{ quality=GoodsInfo#goods.quality, _='_' }, GoodsBackoutRuleList = goods_util:get_ets_list(?ETS_GOODS_QUALITY_BACKOUT, Pattern), if %% 装备品质石拆除规则不存在 length(GoodsBackoutRuleList) =:= 0 -> {fail, 7}; true -> {ok, GoodsInfo, GoodsBackoutRuleList} end end. check_strengthen(PlayerStatus, GoodsId, StoneId, RuneId) -> GoodsInfo = goods_util:get_goods(GoodsId), StoneInfo = goods_util:get_goods(StoneId), case RuneId > 0 of true -> RuneInfo = goods_util:get_goods(RuneId); false -> RuneInfo = #goods{ num = 1, player_id = PlayerStatus#player_status.id, location = 4, type = 11, subtype = 10 } end, if is_record(GoodsInfo, goods) =:= false orelse is_record(StoneInfo, goods) =:= false -> {fail, 2}; RuneId > 0 andalso is_record(RuneInfo, goods) =:= false -> {fail, 2}; GoodsInfo#goods.num < 1 orelse StoneInfo#goods.num < 1 -> {fail, 2}; %% 物品不属于你所有 GoodsInfo#goods.player_id =/= PlayerStatus#player_status.id orelse StoneInfo#goods.player_id =/= PlayerStatus#player_status.id -> {fail, 3}; %% 物品不属于你所有 RuneId > 0 andalso RuneInfo#goods.player_id =/= PlayerStatus#player_status.id -> {fail, 3}; GoodsInfo#goods.location =/= 4 -> {fail, 4}; %% 物品类型不正确 GoodsInfo#goods.type =/= 10 -> {fail, 5}; %% 物品类型不正确 StoneInfo#goods.type =/= 11 orelse StoneInfo#goods.subtype =/= 10 -> {fail, 5}; %% 物品类型不正确 RuneId > 0 andalso RuneInfo#goods.type =/= 12 -> {fail, 5}; %% 物品类型不正确 RuneId > 0 andalso RuneInfo#goods.subtype =/= 10 andalso RuneInfo#goods.subtype =/= 18 -> {fail, 5}; %% 强化已达上限 GoodsInfo#goods.stren >= 10 -> {fail, 8}; true -> Pattern = #ets_goods_strengthen{ goods_id=StoneInfo#goods.goods_id, strengthen=GoodsInfo#goods.stren, _='_' }, GoodsStrengthenRule = goods_util:get_ets_info(?ETS_GOODS_STRENGTHEN, Pattern), if %% 强化规则不存在 is_record(GoodsStrengthenRule, ets_goods_strengthen) =:= false -> {fail, 6}; %% 玩家铜钱不足 (PlayerStatus#player_status.coin + PlayerStatus#player_status.bcoin) < GoodsStrengthenRule#ets_goods_strengthen.coin -> {fail, 7}; true -> {ok, GoodsInfo, StoneInfo, RuneInfo, GoodsStrengthenRule} end end. check_hole(PlayerStatus, GoodsId, RuneId) -> Cost = 100, GoodsInfo = goods_util:get_goods(GoodsId), RuneInfo = goods_util:get_goods(RuneId), if is_record(GoodsInfo, goods) =:= false orelse is_record(RuneInfo, goods) =:= false -> {fail, 2}; GoodsInfo#goods.num < 1 orelse RuneInfo#goods.num < 1 -> {fail, 2}; %% 物品不属于你所有 GoodsInfo#goods.player_id =/= PlayerStatus#player_status.id orelse RuneInfo#goods.player_id =/= PlayerStatus#player_status.id -> {fail, 3}; GoodsInfo#goods.location =/= 4 -> {fail, 4}; %% 物品类型不正确 GoodsInfo#goods.type =/= 10 -> {fail, 5}; %% 物品类型不正确 RuneInfo#goods.type =/= 12 orelse RuneInfo#goods.subtype =/= 12 -> {fail, 5}; 孔数已达上限 GoodsInfo#goods.hole >= 3 -> {fail, 6}; %% 玩家铜钱不足 (PlayerStatus#player_status.coin + PlayerStatus#player_status.bcoin) < Cost -> {fail, 7}; true -> {ok, GoodsInfo, RuneInfo} end. check_compose(PlayerStatus, GoodsStatus, RuneId, StoneTypeId, StoneList) -> case RuneId > 0 of true -> RuneInfo = goods_util:get_goods(RuneId); false -> RuneInfo = #goods{ num = 1, player_id = PlayerStatus#player_status.id, location = 4, type = 12, subtype = 13, color=3 } end, if is_record(RuneInfo, goods) =:= false -> {fail, 2}; %% 物品不属于你所有 RuneInfo#goods.player_id =/= PlayerStatus#player_status.id -> {fail, 3}; RuneInfo#goods.location =/= 4 -> {fail, 4}; %% 物品类型不正确 RuneInfo#goods.type =/= 12 orelse RuneInfo#goods.subtype =/= 13 -> {fail, 5}; %% 物品数量不正确 RuneInfo#goods.num < 1 -> {fail, 6}; %% 物品数量不正确 length(StoneList) =:= 0 -> {fail, 6}; true -> case goods_util:list_handle(fun check_compose_stone/2, [RuneInfo, StoneTypeId, 0, []], StoneList) of {fail, Res} -> {fail, Res}; {ok, [_, _, TotalStoneNum, NewStoneList]} -> Pattern = #ets_goods_compose{ goods_id=StoneTypeId, goods_num=TotalStoneNum, _='_' }, GoodsComposeRule = goods_util:get_ets_info(?ETS_GOODS_COMPOSE, Pattern), if %% 合成规则不存在 is_record(GoodsComposeRule, ets_goods_compose) =:= false -> {fail, 7}; %% 玩家铜钱不足 (PlayerStatus#player_status.coin + PlayerStatus#player_status.bcoin) < GoodsComposeRule#ets_goods_compose.coin -> {fail, 8}; %% 背包满 length(GoodsStatus#goods_status.null_cells) =:= 0 -> {fail, 9}; true -> {ok, NewStoneList, RuneInfo, GoodsComposeRule} end end end. %% 处理合成宝石 check_compose_stone([StoneId, StoneNum], [RuneInfo, StoneTypeId, Num, L]) -> StoneInfo = goods_util:get_goods(StoneId), if is_record(StoneInfo, goods) =:= false -> {fail, 2}; %% 物品不属于你所有 StoneInfo#goods.player_id =/= RuneInfo#goods.player_id -> {fail, 3}; %% 物品类型不正确 StoneInfo#goods.goods_id =/= StoneTypeId -> {fail, 5}; %% 物品类型不正确 RuneInfo#goods.color < StoneInfo#goods.color -> {fail, 5}; %% 物品数量不正确 StoneInfo#goods.num < StoneNum -> {fail, 6}; true -> {ok, [RuneInfo, StoneTypeId, Num+StoneNum, [[StoneInfo, StoneNum]|L]]} end. check_inlay(PlayerStatus, GoodsId, StoneId, RuneList) -> GoodsInfo = goods_util:get_goods(GoodsId), StoneInfo = goods_util:get_goods(StoneId), if is_record(GoodsInfo, goods) =:= false orelse is_record(StoneInfo, goods) =:= false -> {fail, 2}; GoodsInfo#goods.num < 1 orelse StoneInfo#goods.num < 1 -> {fail, 2}; %% 物品不属于你所有 GoodsInfo#goods.player_id =/= PlayerStatus#player_status.id orelse StoneInfo#goods.player_id =/= PlayerStatus#player_status.id -> {fail, 3}; GoodsInfo#goods.location =/= 4 -> {fail, 4}; %% 物品类型不正确 GoodsInfo#goods.type =/= 10 -> {fail, 5}; %% 物品类型不正确 StoneInfo#goods.type =/= 11 orelse StoneInfo#goods.subtype =/= 14 -> {fail, 5}; %% 物品类型不正确 StoneInfo#goods.goods_id =:= GoodsInfo#goods.hole1_goods orelse StoneInfo#goods.goods_id =:= GoodsInfo#goods.hole2_goods orelse StoneInfo#goods.goods_id =:= GoodsInfo#goods.hole3_goods -> {fail, 5}; %% 没有孔位 GoodsInfo#goods.hole =:= 0 -> {fail, 6}; %% 没有孔位 GoodsInfo#goods.hole =:= 1 andalso GoodsInfo#goods.hole1_goods > 0 -> {fail, 6}; %% 没有孔位 GoodsInfo#goods.hole =:= 2 andalso GoodsInfo#goods.hole2_goods > 0 -> {fail, 6}; %% 没有孔位 GoodsInfo#goods.hole =:= 3 andalso GoodsInfo#goods.hole3_goods > 0 -> {fail, 6}; true -> case goods_util:list_handle(fun check_inlay_rune/2, [PlayerStatus#player_status.id, 0, []], RuneList) of {fail, Res} -> {fail, Res}; {ok, [_, TotalRuneNum, NewRuneList]} -> Pattern = #ets_goods_inlay{ goods_id=StoneInfo#goods.goods_id, _='_' }, GoodsInlayRule = goods_util:get_ets_info(?ETS_GOODS_INLAY, Pattern), if 镶嵌规则不存在 is_record(GoodsInlayRule, ets_goods_inlay) =:= false -> {fail, 7}; %% 玩家铜钱不足 (PlayerStatus#player_status.coin + PlayerStatus#player_status.bcoin) < GoodsInlayRule#ets_goods_inlay.coin -> {fail, 8}; true -> case length(GoodsInlayRule#ets_goods_inlay.equip_types) > 0 andalso lists:member(GoodsInfo#goods.subtype, GoodsInlayRule#ets_goods_inlay.equip_types) =:= false of %% 不可镶嵌的类型 true -> {fail, 9}; false -> {ok, GoodsInfo, StoneInfo, TotalRuneNum, NewRuneList, GoodsInlayRule} end end end end. 处理镶嵌符 check_inlay_rune([RuneId, RuneNum], [PlayerId, Num, L]) -> RuneInfo = goods_util:get_goods(RuneId), if is_record(RuneInfo, goods) =:= false -> {fail, 2}; %% 物品不属于你所有 RuneInfo#goods.player_id =/= PlayerId -> {fail, 3}; %% 物品类型不正确 RuneInfo#goods.type =/= 12 orelse RuneInfo#goods.subtype =/= 14 -> {fail, 5}; %% 物品数量不正确 RuneInfo#goods.num < RuneNum -> {fail, 6}; true -> {ok, [PlayerId, Num+RuneNum, [[RuneInfo, RuneNum]|L]]} end. check_backout(PlayerStatus, GoodsStatus, GoodsId, RuneId) -> Cost = 100, GoodsInfo = goods_util:get_goods(GoodsId), RuneInfo = goods_util:get_goods(RuneId), if is_record(GoodsInfo, goods) =:= false orelse GoodsInfo#goods.num < 1 -> {fail, 2}; is_record(RuneInfo, goods) =:= false orelse RuneInfo#goods.num < 1 -> {fail, 2}; %% 物品不属于你所有 GoodsInfo#goods.player_id =/= PlayerStatus#player_status.id orelse RuneInfo#goods.player_id =/= PlayerStatus#player_status.id -> {fail, 3}; GoodsInfo#goods.location =/= 4 orelse RuneInfo#goods.location =/= 4 -> {fail, 4}; %% 物品类型不正确 GoodsInfo#goods.type =/= 10 -> {fail, 5}; %% 物品类型不正确 RuneInfo#goods.type =/= 12 andalso RuneInfo#goods.subtype =/= 17 -> {fail, 5}; %% 没有宝石可拆 GoodsInfo#goods.hole1_goods =:= 0 -> {fail, 8}; %% 玩家铜钱不足 (PlayerStatus#player_status.coin + PlayerStatus#player_status.bcoin) < Cost -> {fail, 6}; true -> InlayNum = goods_util:get_inlay_num(GoodsInfo), if 背包格子不足 length(GoodsStatus#goods_status.null_cells) < InlayNum -> {fail, 7}; true -> {ok, GoodsInfo, RuneInfo} end end. check_wash(PlayerStatus, GoodsId, RuneId) -> Cost = 100, GoodsInfo = goods_util:get_goods(GoodsId), RuneInfo = goods_util:get_goods(RuneId), if is_record(GoodsInfo, goods) =:= false orelse is_record(RuneInfo, goods) =:= false -> {fail, 2}; GoodsInfo#goods.num < 1 orelse RuneInfo#goods.num < 1 -> {fail, 2}; %% 物品不属于你所有 GoodsInfo#goods.player_id =/= PlayerStatus#player_status.id orelse RuneInfo#goods.player_id =/= PlayerStatus#player_status.id -> {fail, 3}; GoodsInfo#goods.location =/= 4 orelse RuneInfo#goods.location =/= 4 -> {fail, 4}; %% 物品类型不正确 GoodsInfo#goods.type =/= 10 -> {fail, 5}; %% 物品类型不正确 RuneInfo#goods.type =/= 12 orelse RuneInfo#goods.subtype =/= 15 -> {fail, 5}; %% 物品类型不正确 GoodsInfo#goods.color =:= 0 -> {fail, 5}; %% 玩家铜钱不足 (PlayerStatus#player_status.coin + PlayerStatus#player_status.bcoin) < Cost -> {fail, 6}; true -> Pattern = #ets_goods_attribute_rule{ goods_id=GoodsInfo#goods.goods_id, _='_'}, AddAttributeRuleList = goods_util:get_ets_list(?ETS_GOODS_ATTRIBUTE_RULE, Pattern), if %% 装备附加属性规则不存在 length(AddAttributeRuleList) =:= 0 -> {fail, 7}; true -> {ok, GoodsInfo, RuneInfo, AddAttributeRuleList} end end. check_change_equip(PlayerStatus, Equip) -> if %% 装备类型错误 Equip > 3 orelse Equip < 1 -> {fail, 2}; %% 装备类型错误 Equip =:= PlayerStatus#player_status.equip -> {fail, 2}; true -> ok end. check_drop_list(PlayerStatus, DropId) -> DropInfo = goods_util:get_ets_info(?ETS_GOODS_DROP, DropId), NowTime = util:unixtime(), if %% 掉落包已经消失 is_record(DropInfo, ets_goods_drop) =:= false -> {fail, 2}; %% 掉落包已经消失 DropInfo#ets_goods_drop.expire_time =< NowTime -> {fail, 2}; %% 无权拣取 DropInfo#ets_goods_drop.team_id =:= 0 andalso DropInfo#ets_goods_drop.player_id =/= PlayerStatus#player_status.id -> {fail, 3}; %% 无权拣取 DropInfo#ets_goods_drop.team_id > 0 andalso DropInfo#ets_goods_drop.team_id =/= PlayerStatus#player_status.pid_team andalso DropInfo#ets_goods_drop.player_id =/= PlayerStatus#player_status.id -> {fail, 3}; true -> {ok, DropInfo} end. check_drop_choose(PlayerStatus, GoodsStatus, DropId, GoodsTypeId) -> case check_drop_list(PlayerStatus, DropId) of {fail, Res} -> {fail, Res}; {ok, DropInfo} -> case lists:keyfind(GoodsTypeId, 1, DropInfo#ets_goods_drop.drop_goods) of 物品已经不存在 false -> {fail, 4}; GoodsInfo -> {GoodsTypeId, _Type, GoodsNum, _GoodsQuality} = GoodsInfo, GoodsTypeInfo = goods_util:get_goods_type(GoodsTypeId), if is_record(GoodsTypeInfo, ets_goods_type) =:= false -> {fail, 4}; true -> GoodsList = goods_util:get_type_goods_list(GoodsStatus#goods_status.player_id, GoodsTypeId, GoodsTypeInfo#ets_goods_type.bind, 4), CellNum = goods_util:get_null_cell_num(GoodsList, GoodsTypeInfo#ets_goods_type.max_overlap, GoodsNum), if 背包格子不足 length(GoodsStatus#goods_status.null_cells) < CellNum -> {fail, 5}; true -> {ok, DropInfo, GoodsInfo} end end end end.
null
https://raw.githubusercontent.com/smallmelon/sdzmmo/254ff430481de474527c0e96202c63fb0d2c29d2/src/mod/mod_goods.erl
erlang
------------------------------------ @Module : mod_goods @Email : ------------------------------------ io:format("equip_current: ~p~n",[NewStatus#goods_status.equip_current]), 设置物品信息 设置物品信息 获取玩家物品列表信息 装备 仓库 当前装备 获取玩家物品列表信息 io:format("list_other: ~p~n",[[PlayerId, lib_player:is_online(PlayerId), ets:info(?ETS_ONLINE,size)]]), 玩家不在线 列出背包打造装备列表 取商店物品列表 购买物品 背包拖动物品 删除多个物品 物品数量不正确 查找身上耐久为1的装备 穿在身上的装备耐久减1 广播耐久更新 人物属性更新 有耐久为0的装备 检查武器、衣服 返回更新人物属性 查找有耐久度的装备 装备品质升级 装备品质石拆除 装备打孔 宝石合成 宝石镶嵌 宝石拆除 洗附加属性 切换装备 整理背包 查询背包物品列表 按物品类型ID排序 整理 重新计算 查看地上的掉落包 拣取地上掉落包的物品 赠送物品 赠送物品 怪物掉落 io:format("mon_drop RuleResult: ~p~n",[RuleResult]), 如果有掉落,则插入ETS 无掉落 无掉落 无掉落 获取空格子数 Local Function 金额不足 物品不属于你所有 物品不在背包 物品不可出售 物品不属于你所有 物品类型不可装备 玩家条件不符 物品不属于你所有 物品类型不可装备 背包已满 物品不属于你所有 物品不在背包 物品格子位置不正确 物品格子位置不正确 物品不属于你所有 物品不在背包 物品数量不正确 冷却时间 人物等级不足 物品不属于你所有 物品不在背包 物品不可丢弃 物品数量不正确 物品不属于你所有 物品不在背包 物品数量不正确 物品类型不存在 物品不属于你所有 物品不在仓库 物品数量不正确 物品类型不存在 背包已满 玩家金额不足 物品不属于你所有 物品类型不正确 无磨损 余额不足 物品不属于你所有 物品类型不正确 物品类型不正确 品质升级规则不存在 玩家铜钱不足 物品不属于你所有 物品类型不正确 物品品质不正确 背包满 装备品质石拆除规则不存在 物品不属于你所有 物品不属于你所有 物品类型不正确 物品类型不正确 物品类型不正确 物品类型不正确 强化已达上限 强化规则不存在 玩家铜钱不足 物品不属于你所有 物品类型不正确 物品类型不正确 玩家铜钱不足 物品不属于你所有 物品类型不正确 物品数量不正确 物品数量不正确 合成规则不存在 玩家铜钱不足 背包满 处理合成宝石 物品不属于你所有 物品类型不正确 物品类型不正确 物品数量不正确 物品不属于你所有 物品类型不正确 物品类型不正确 物品类型不正确 没有孔位 没有孔位 没有孔位 没有孔位 玩家铜钱不足 不可镶嵌的类型 物品不属于你所有 物品类型不正确 物品数量不正确 物品不属于你所有 物品类型不正确 物品类型不正确 没有宝石可拆 玩家铜钱不足 物品不属于你所有 物品类型不正确 物品类型不正确 物品类型不正确 玩家铜钱不足 装备附加属性规则不存在 装备类型错误 装备类型错误 掉落包已经消失 掉落包已经消失 无权拣取 无权拣取
@Author : xhg @Created : 2010.05.25 @Description : -module(mod_goods). -behaviour(gen_server). -export([start/3]). -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -include("common.hrl"). -include("record.hrl"). start(PlayerId,CellNum, Equip) -> gen_server:start_link(?MODULE, [PlayerId,CellNum, Equip], []). init([PlayerId,CellNum, Equip]) -> ok = goods_util:init_goods_online(PlayerId), NullCells = goods_util:get_null_cells(PlayerId, CellNum), EquipSuit = goods_util:get_equip_suit(PlayerId, Equip), GoodsStatus = #goods_status{ player_id = PlayerId, null_cells = NullCells, equip_current = [0,0,0], equip_suit=EquipSuit }, NewStatus = goods_util:get_current_equip(GoodsStatus, Equip), {ok, NewStatus}. handle_cast({'SET_STATUS', NewStatus}, _GoodsStatus) -> {noreply, NewStatus}; handle_cast(_R , GoodsStatus) -> {noreply, GoodsStatus}. handle_call({'STATUS'} , _From, GoodsStatus) -> {reply, GoodsStatus, GoodsStatus}; handle_call({'SET_STATUS', NewGoodsStatus}, _From, _GoodsStatus) -> {reply, ok, NewGoodsStatus}; 获取物品详细信息 handle_call({'info', GoodsId, Location}, _From, GoodsStatus) -> case Location =:= 5 of true -> GoodsInfo = goods_util:get_goods_by_id(GoodsId); false -> GoodsInfo = goods_util:get_goods(GoodsId) end, case is_record(GoodsInfo, goods) of true when GoodsInfo#goods.player_id == GoodsStatus#goods_status.player_id -> case goods_util:has_attribute(GoodsInfo) of true -> AttributeList = goods_util:get_goods_attribute_list(GoodsStatus#goods_status.player_id, GoodsId); false -> AttributeList = [] end, SuitNum = goods_util:get_suit_num(GoodsStatus#goods_status.equip_suit, GoodsInfo#goods.suit_id), {reply, [GoodsInfo, SuitNum, AttributeList], GoodsStatus}; Error -> ?DEBUG("mod_goods info:~p", [[GoodsId,Error]]), {reply, [{}, 0, []], GoodsStatus} end; 查询别人物品详细信息 handle_call({'info_other', Owner, GoodsId}, _From, GoodsStatus) -> Info = goods_util:get_goods(GoodsId), case is_record(Info, goods) of true -> GoodsInfo = Info; false -> GoodsInfo = goods_util:get_goods_by_id(GoodsId) end, case is_record(GoodsInfo, goods) of true -> IsOnline = lib_player:is_online(Owner), case goods_util:has_attribute(GoodsInfo) of true when IsOnline =:= true -> AttributeList = goods_util:get_goods_attribute_list(Owner, GoodsId); true -> AttributeList = goods_util:get_offline_goods_attribute_list(Owner, GoodsId); false -> AttributeList = [] end, SuitNum = goods_util:get_suit_num(GoodsStatus#goods_status.equip_suit, GoodsInfo#goods.suit_id), {reply, [GoodsInfo, SuitNum, AttributeList], GoodsStatus}; Error -> ?DEBUG("mod_goods info_other:~p", [[Owner, GoodsId, Error]]), {reply, [{}, 0, []], GoodsStatus} end; handle_call({'list', PlayerStatus, Location}, _From, GoodsStatus) -> case Location > 0 of true when Location =< 3 -> NewLocation = Location, CellNum = 12, EquipList = goods_util:get_equip_list(PlayerStatus#player_status.id, 10, NewLocation), MountList = goods_util:get_equip_list(PlayerStatus#player_status.id, 31, 1), List = EquipList ++ MountList; true -> NewLocation = Location, case Location =:= 5 of false -> CellNum = PlayerStatus#player_status.cell_num end, List = goods_util:get_goods_list(PlayerStatus#player_status.id, NewLocation); false -> NewLocation = PlayerStatus#player_status.equip, CellNum = 12, EquipList = goods_util:get_equip_list(PlayerStatus#player_status.id, 10, NewLocation), MountList = goods_util:get_equip_list(PlayerStatus#player_status.id, 31, 1), List = EquipList ++ MountList end, {reply, [NewLocation, CellNum, List], GoodsStatus}; handle_call({'list_other', PlayerId}, _From, GoodsStatus) -> case lib_player:is_online(PlayerId) of false -> {reply, [2, []], GoodsStatus}; true -> Player = lib_player:get_online_info(PlayerId), EquipList = goods_util:get_equip_list(PlayerId, 10, Player#ets_online.equip), MountList = goods_util:get_equip_list(PlayerId, 31, 1), List = EquipList ++ MountList, {reply, [1, List], GoodsStatus} end; handle_call({'make_list'}, _From, GoodsStatus) -> EquipList = goods_util:get_equip_list(GoodsStatus#goods_status.player_id, 10, 4), {reply, EquipList, GoodsStatus}; handle_call({'shop', ShopType, ShopSubtype}, _From, GoodsStatus) -> ShopList = goods_util:get_shop_list(ShopType, ShopSubtype), {reply, ShopList, GoodsStatus}; handle_call({'pay', PlayerStatus, GoodsTypeId, GoodsNum, ShopType}, _From, GoodsStatus) -> case check_pay(PlayerStatus, GoodsStatus, GoodsTypeId, GoodsNum, ShopType) of {fail, Res} -> {reply, [PlayerStatus, Res, []], GoodsStatus}; {ok, GoodsTypeInfo, GoodsList, Cost, PriceType} -> case (catch lib_goods:pay_goods(GoodsStatus, GoodsTypeInfo, GoodsList, GoodsNum)) of {ok, NewStatus} -> NewPlayerStatus = lib_goods:cost_money(PlayerStatus, Cost, PriceType), NewGoodsList = goods_util:get_type_goods_list(PlayerStatus#player_status.id, GoodsTypeId, GoodsTypeInfo#ets_goods_type.bind, 4), lib_task:event(buy_equip, {GoodsTypeId}, PlayerStatus#player_status.id), {reply, [NewPlayerStatus, 1, NewGoodsList], NewStatus}; Error -> ?DEBUG("mod_goods pay:~p", [Error]), {reply, [PlayerStatus, 0, []], GoodsStatus} end end; handle_call({'sell', PlayerStatus, GoodsId, GoodsNum}, _From, GoodsStatus) -> case check_sell(GoodsStatus, GoodsId, GoodsNum) of {fail, Res} -> {reply, [PlayerStatus, Res], GoodsStatus}; {ok, GoodsInfo} -> case (catch lib_goods:sell_goods(PlayerStatus, GoodsStatus, GoodsInfo, GoodsNum)) of {ok, NewPlayerStatus, NewStatus} -> {reply, [NewPlayerStatus, 1], NewStatus}; Error -> ?DEBUG("mod_goods sell:~p", [Error]), {reply, [PlayerStatus, 0], GoodsStatus} end end; 装备物品 handle_call({'equip', PlayerStatus, GoodsId, Cell}, _From, GoodsStatus) -> case check_equip(PlayerStatus, GoodsId, Cell) of {fail, Res} -> {reply, [PlayerStatus, Res, {}, {}, []], GoodsStatus}; {ok, GoodsInfo, Location, NewCell} -> case (catch lib_goods:equip_goods(PlayerStatus, GoodsStatus, GoodsInfo, Location, NewCell)) of {ok, NewPlayerStatus, NewStatus, OldGoodsInfo, Effect2} -> lib_task:event(equip, {GoodsInfo#goods.goods_id}, GoodsInfo#goods.player_id), {reply, [NewPlayerStatus, 1, GoodsInfo, OldGoodsInfo, Effect2], NewStatus}; Error -> ?DEBUG("mod_goods equip:~p", [Error]), {reply, [PlayerStatus, 0, {}, []], GoodsStatus} end end; handle_call({'unequip', PlayerStatus, GoodsId}, _From, GoodsStatus) -> case check_unequip(GoodsStatus, GoodsId, PlayerStatus#player_status.equip) of {fail, Res} -> {reply, [PlayerStatus, Res, {}], GoodsStatus}; {ok, GoodsInfo} -> case (catch lib_goods:unequip_goods(PlayerStatus, GoodsStatus, GoodsInfo)) of {ok, NewPlayerStatus, NewStatus, NewGoodsInfo} -> {reply, [NewPlayerStatus, 1, NewGoodsInfo], NewStatus}; Error -> ?DEBUG("mod_goods unequip:~p", [Error]), {reply, [PlayerStatus, 0, {}], GoodsStatus} end end; handle_call({'drag', PlayerStatus, GoodsId, OldCell, NewCell}, _From, GoodsStatus) -> case check_drag(GoodsStatus, GoodsId, OldCell, NewCell, PlayerStatus#player_status.cell_num) of {fail, Res} -> {reply, [Res, 0, 0, 0, 0], GoodsStatus}; {ok, GoodsInfo} -> case (catch lib_goods:drag_goods(GoodsStatus, GoodsInfo, OldCell, NewCell)) of {ok, NewStatus, [OldCellId, OldTypeId, NewCellId, NewTypeId]} -> {reply, [1, OldCellId, OldTypeId, NewCellId, NewTypeId], NewStatus}; Error -> ?DEBUG("mod_goods drag:~p", [Error]), {reply, [0, 0, 0, 0, 0], GoodsStatus} end end; handle_call({'use', PlayerStatus, GoodsId, GoodsNum}, _From, GoodsStatus) -> case check_use(GoodsStatus, GoodsId, GoodsNum, PlayerStatus#player_status.lv) of {fail, Res} -> {reply, [PlayerStatus, Res, 0, 0], GoodsStatus}; {ok, GoodsInfo} -> case (catch lib_goods:use_goods(PlayerStatus, GoodsStatus, GoodsInfo, GoodsNum)) of {ok, NewPlayerStatus, NewStatus, NewNum} -> {reply, [NewPlayerStatus, 1, GoodsInfo#goods.goods_id, NewNum], NewStatus}; Error -> ?DEBUG("mod_goods use:~p", [Error]), {reply, [PlayerStatus, 0, 0, 0], GoodsStatus} end end; handle_call({'delete_one', GoodsId, GoodsNum}, _From, GoodsStatus) -> GoodsInfo = goods_util:get_goods(GoodsId), if is_record(GoodsInfo, goods) =:= false -> {reply, [2, 0], GoodsStatus}; GoodsInfo#goods.num < GoodsNum -> {reply, [3, 0], GoodsStatus}; true -> case (catch lib_goods:delete_one(GoodsStatus, GoodsInfo, GoodsNum)) of {ok, NewStatus, NewNum} -> lib_player:refresh_client(GoodsStatus#goods_status.player_id, 2), {reply, [1, NewNum], NewStatus}; Error -> ?DEBUG("mod_goods delete_one:~p", [Error]), {reply, [0, 0], GoodsStatus} end end; 删除多个同类型物品 handle_call({'delete_more', GoodsTypeId, GoodsNum}, _From, GoodsStatus) -> GoodsList = goods_util:get_type_goods_list(GoodsStatus#goods_status.player_id, GoodsTypeId, 4), TotalNum = goods_util:get_goods_totalnum(GoodsList), if length(GoodsList) =:= 0 -> {reply, 2, GoodsStatus}; 物品数量不足 TotalNum < GoodsNum -> {reply, 3, GoodsStatus}; true -> case (catch lib_goods:delete_more(GoodsStatus, GoodsList, GoodsNum)) of {ok, NewStatus} -> lib_player:refresh_client(GoodsStatus#goods_status.player_id, 2), {reply, 1, NewStatus}; Error -> ?DEBUG("mod_goods delete_more:~p", [Error]), {reply, 0, GoodsStatus} end end; handle_call({'throw', GoodsId, GoodsNum}, _From, GoodsStatus) -> case check_throw(GoodsStatus, GoodsId, GoodsNum) of {fail, Res} -> {reply, Res, GoodsStatus}; {ok, GoodsInfo} -> case (catch lib_goods:delete_one(GoodsStatus, GoodsInfo, GoodsNum)) of {ok, NewStatus, _} -> {reply, 1, NewStatus}; Error -> ?DEBUG("mod_goods throw:~p", [Error]), {reply, 0, GoodsStatus} end end; 丢弃同类型物品 GoodsTypeList = [ GoodsTypeId1 , , ... ] handle_call({'throw_more', GoodsTypeList}, _From, GoodsStatus) -> case (catch goods_util:list_handle(fun lib_goods:delete_type_goods/2, GoodsStatus, GoodsTypeList)) of {ok, NewStatus} -> lib_player:refresh_client(NewStatus#goods_status.player_id, 2), {reply, ok, NewStatus}; {Error, Status} -> ?DEBUG("mod_goods throw_more:~p", [Error]), {reply, Error, Status} end; handle_call({'movein_bag', GoodsId, GoodsNum}, _From, GoodsStatus) -> case check_movein_bag(GoodsStatus, GoodsId, GoodsNum) of {fail, Res} -> {reply, Res, GoodsStatus}; {ok, GoodsInfo, GoodsTypeInfo} -> case (catch lib_goods:movein_bag(GoodsStatus, GoodsInfo, GoodsNum, GoodsTypeInfo)) of {ok, NewStatus} -> {reply, 1, NewStatus}; Error -> ?DEBUG("mod_goods movein_bag:~p", [Error]), {reply, 0, GoodsStatus} end end; 从仓库取出物品 handle_call({'moveout_bag', GoodsId, GoodsNum}, _From, GoodsStatus) -> case check_moveout_bag(GoodsStatus, GoodsId, GoodsNum) of {fail, Res} -> {reply, [Res, []], GoodsStatus}; {ok, GoodsInfo, GoodsTypeInfo} -> case (catch lib_goods:moveout_bag(GoodsStatus, GoodsInfo, GoodsNum, GoodsTypeInfo)) of {ok, NewStatus} -> GoodsList = goods_util:get_type_goods_list(GoodsInfo#goods.player_id, GoodsInfo#goods.goods_id, GoodsInfo#goods.bind, 4), {reply, [1, GoodsList], NewStatus}; Error -> ?DEBUG("mod_goods moveout_bag:~p", [Error]), {reply, [0, []], GoodsStatus} end end; 扩充背包 handle_call({'extend_bag', PlayerStatus}, _From, GoodsStatus) -> case check_extend_bag(PlayerStatus) of {fail, Res} -> {reply, [PlayerStatus, Res], GoodsStatus}; {ok, Cost} -> case (catch lib_goods:extend_bag(PlayerStatus, Cost)) of {ok, NewPlayerStatus} -> {reply, [NewPlayerStatus, 1], GoodsStatus}; Error -> ?DEBUG("mod_goods extend_bag:~p", [Error]), {reply, [PlayerStatus, 0], GoodsStatus} end end; handle_call({'attrit', PlayerStatus, UseNum}, _From, GoodsStatus) -> Sql = io_lib : format(<<"select id , subtype from ` goods ` where player_id = ~p and location = ~p and type = 10 and use_num < = ~p and use_num > 0 and attrition > 0 " > > , [ PlayerStatus#player_status.id , PlayerStatus#player_status.equip , UseNum ] ) , List = goods_util : get_list(goods , ) , Sql2 = io_lib:format(<<"update `goods` set use_num = use_num - (~p) where player_id = ~p and location = ~p and type = 10 and use_num > ~p and attrition > 0 ">>, [UseNum, PlayerStatus#player_status.id, PlayerStatus#player_status.equip, UseNum]), db_sql:execute(Sql2), Sql3 = io_lib:format(<<"update `goods` set use_num = 0 where player_id = ~p and location = ~p and type = 10 and use_num <= ~p and use_num > 0 and attrition > 0 ">>, [PlayerStatus#player_status.id, PlayerStatus#player_status.equip, UseNum]), db_sql:execute(Sql3), EquipList = goods_util:get_equip_list(PlayerStatus#player_status.id, 10, PlayerStatus#player_status.equip), [_, ZeroEquipList] = lists:foldl(fun lib_goods:attrit_equip/2, [UseNum, []], EquipList), lib_player:refresh_client(PlayerStatus#player_status.id, 5), case length(ZeroEquipList) > 0 of true -> 人物属性重新计算 EquipSuit = goods_util:get_equip_suit(PlayerStatus#player_status.id, PlayerStatus#player_status.equip), Status = GoodsStatus#goods_status{ equip_suit=EquipSuit }, {ok, NewPlayerStatus, NewStatus} = goods_util:count_role_equip_attribute(PlayerStatus, Status, {}), [NewStatus2, _] = goods_util:get_current_equip_by_list(ZeroEquipList, [NewStatus, off]), NewPlayerStatus2 = NewPlayerStatus#player_status{ equip_attrit=0, equip_current=NewStatus2#goods_status.equip_current }, 广播 {ok, BinData} = pt_12:write(12015, [NewPlayerStatus#player_status.id, NewPlayerStatus#player_status.hp, NewPlayerStatus#player_status.hp_lim, ZeroEquipList]), lib_send:send_to_area_scene(NewPlayerStatus#player_status.scene, NewPlayerStatus#player_status.x, NewPlayerStatus#player_status.y, BinData), 通知客户端 {ok, BinData1} = pt_15:write(15032, ZeroEquipList), lib_send:send_one(NewPlayerStatus#player_status.socket, BinData1), {reply, {ok, NewPlayerStatus2}, NewStatus2}; false -> {reply, {error,no,attrition,equip}, GoodsStatus} end; 获取要修理装备列表 handle_call({'mend_list', PlayerStatus}, _From, GoodsStatus) -> List = goods_util:get_mend_list(GoodsStatus#goods_status.player_id, PlayerStatus#player_status.equip), F = fun(GoodsInfo) -> UseNum = goods_util:get_goods_use_num(GoodsInfo#goods.attrition), case UseNum =/= GoodsInfo#goods.use_num of true -> Attrition = goods_util:get_goods_attrition(GoodsInfo#goods.attrition, GoodsInfo#goods.use_num), Cost = goods_util:get_mend_cost(GoodsInfo#goods.attrition, GoodsInfo#goods.use_num), [[GoodsInfo#goods.id, GoodsInfo#goods.goods_id, Attrition, Cost]]; false -> [] end end, MendList = lists:flatmap(F, List), {reply, MendList, GoodsStatus}; 修理装备 handle_call({'mend', PlayerStatus, GoodsId}, _From, GoodsStatus) -> case check_mend(PlayerStatus, GoodsId) of {fail, Res} -> {reply, [PlayerStatus, Res, {}], GoodsStatus}; {ok, GoodsInfo} -> case (catch lib_goods:mend_goods(PlayerStatus, GoodsStatus, GoodsInfo)) of {ok, NewPlayerStatus, NewStatus} -> {reply, [NewPlayerStatus, 1, GoodsInfo], NewStatus}; Error -> ?DEBUG("mod_goods mend:~p", [Error]), {reply, [PlayerStatus, 0, {}], GoodsStatus} end end; handle_call({'quality_upgrade', PlayerStatus, GoodsId, StoneId}, _From, GoodsStatus) -> case check_quality_upgrade(PlayerStatus, GoodsId, StoneId) of {fail, Res} -> {reply, [PlayerStatus, Res, 0, 0], GoodsStatus}; {ok, GoodsInfo, StoneInfo, GoodsQualityRule} -> case (catch lib_make:quality_upgrade(PlayerStatus, GoodsStatus, GoodsInfo, StoneInfo, GoodsQualityRule)) of {ok, NewPlayerStatus, NewStatus, [NewQuality, NewStoneNum]} -> {reply, [NewPlayerStatus, 1, NewQuality, NewStoneNum], NewStatus}; Error -> ?DEBUG("mod_goods quality_upgrade:~p", [Error]), {reply, [PlayerStatus, 0, 0, 0], GoodsStatus} end end; handle_call({'quality_backout', PlayerStatus, GoodsId}, _From, GoodsStatus) -> case check_quality_backout(GoodsStatus, GoodsId) of {fail, Res} -> {reply, [PlayerStatus, Res], GoodsStatus}; {ok, GoodsInfo, GoodsBackoutRuleList} -> case (catch lib_make:quality_backout(PlayerStatus, GoodsStatus, GoodsInfo, GoodsBackoutRuleList)) of {ok, NewPlayerStatus, NewStatus} -> {reply, [NewPlayerStatus, 1], NewStatus}; {fail, Res} -> {reply, [PlayerStatus, Res], GoodsStatus}; Error -> ?DEBUG("mod_goods quality_backout:~p", [Error]), {reply, [PlayerStatus, 0], GoodsStatus} end end; 装备强化 handle_call({'strengthen', PlayerStatus, GoodsId, StoneId, RuneId}, _From, GoodsStatus) -> case check_strengthen(PlayerStatus, GoodsId, StoneId, RuneId) of {fail, Res} -> {reply, [PlayerStatus, Res, 0, 0, 0], GoodsStatus}; {ok, GoodsInfo, StoneInfo, RuneInfo, GoodsStrengthenRule} -> case (catch lib_make:strengthen(PlayerStatus, GoodsStatus, GoodsInfo, StoneInfo, RuneInfo, GoodsStrengthenRule)) of {ok, NewPlayerStatus, NewStatus, [NewStrengthen, NewStoneNum, NewRuneNum]} -> {reply, [NewPlayerStatus, 1, NewStrengthen, NewStoneNum, NewRuneNum], NewStatus}; Error -> ?DEBUG("mod_goods strengthen:~p", [Error]), {reply, [PlayerStatus, 0, 0, 0, 0], GoodsStatus} end end; handle_call({'hole', PlayerStatus, GoodsId, RuneId}, _From, GoodsStatus) -> case check_hole(PlayerStatus, GoodsId, RuneId) of {fail, Res} -> {reply, [PlayerStatus, Res, 0, 0], GoodsStatus}; {ok, GoodsInfo, RuneInfo} -> case (catch lib_make:hole(PlayerStatus, GoodsStatus, GoodsInfo, RuneInfo)) of {ok, NewPlayerStatus, NewStatus, [NewHole, NewRuneNum]} -> {reply, [NewPlayerStatus, 1, NewHole, NewRuneNum], NewStatus}; Error -> ?DEBUG("mod_goods hole:~p", [Error]), {reply, [PlayerStatus, 0, 0, 0], GoodsStatus} end end; handle_call({'compose', PlayerStatus, RuneId, StoneTypeId, StoneList}, _From, GoodsStatus) -> case check_compose(PlayerStatus, GoodsStatus, RuneId, StoneTypeId, StoneList) of {fail, Res} -> {reply, [PlayerStatus, Res, 0], GoodsStatus}; {ok, NewStoneList, RuneInfo, GoodsComposeRule} -> case (catch lib_make:compose(PlayerStatus, GoodsStatus, NewStoneList, RuneInfo, GoodsComposeRule)) of {ok, NewPlayerStatus, NewStatus, NewGoodsTypeId} -> {reply, [NewPlayerStatus, 1, NewGoodsTypeId], NewStatus}; Error -> ?DEBUG("mod_goods compose:~p", [Error]), {reply, [PlayerStatus, 0, 0], GoodsStatus} end end; handle_call({'inlay', PlayerStatus, GoodsId, StoneId, RuneList}, _From, GoodsStatus) -> case check_inlay(PlayerStatus, GoodsId, StoneId, RuneList) of {fail, Res} -> {reply, [PlayerStatus, Res], GoodsStatus}; {ok, GoodsInfo, StoneInfo, TotalRuneNum, NewRuneList, GoodsInlayRule} -> case (catch lib_make:inlay(PlayerStatus, GoodsStatus, GoodsInfo, StoneInfo, TotalRuneNum, NewRuneList, GoodsInlayRule)) of {ok, Res, NewPlayerStatus, NewStatus} -> {reply, [NewPlayerStatus, Res], NewStatus}; Error -> ?DEBUG("mod_goods inlay:~p", [Error]), {reply, [PlayerStatus, 10], GoodsStatus} end end; handle_call({'backout', PlayerStatus, GoodsId, RuneId}, _From, GoodsStatus) -> case check_backout(PlayerStatus, GoodsStatus, GoodsId, RuneId) of {fail, Res} -> {reply, [PlayerStatus, Res], GoodsStatus}; {ok, GoodsInfo, RuneInfo} -> case (catch lib_make:backout(PlayerStatus, GoodsStatus, GoodsInfo, RuneInfo)) of {ok, NewPlayerStatus, NewStatus} -> {reply, [NewPlayerStatus, 1], NewStatus}; Error -> ?DEBUG("mod_goods backout:~p", [Error]), {reply, [PlayerStatus, 0], GoodsStatus} end end; handle_call({'wash', PlayerStatus, GoodsId, RuneId}, _From, GoodsStatus) -> case check_wash(PlayerStatus, GoodsId, RuneId) of {fail, Res} -> {reply, [PlayerStatus, Res, 0], GoodsStatus}; {ok, GoodsInfo, RuneInfo, AddAttributeRuleList} -> case (catch lib_make:wash(PlayerStatus, GoodsStatus, GoodsInfo, RuneInfo, AddAttributeRuleList)) of {ok, NewPlayerStatus, NewStatus, NewRuneNum} -> {reply, [NewPlayerStatus, 1, NewRuneNum], NewStatus}; Error -> ?DEBUG("mod_goods wash:~p", [Error]), {reply, [PlayerStatus, 0, 0], GoodsStatus} end end; handle_call({'change_equip', PlayerStatus, Equip}, _From, GoodsStatus) -> case check_change_equip(PlayerStatus, Equip) of {fail, Res} -> {reply, [PlayerStatus, Res, []], GoodsStatus}; ok -> case (catch lib_goods:change_equip(PlayerStatus, GoodsStatus, Equip)) of {ok, NewPlayerStatus, NewStatus, EquipList} -> {reply, [NewPlayerStatus, 1, EquipList], NewStatus}; Error -> ?DEBUG("mod_goods change_equip:~p", [Error]), {reply, [PlayerStatus, 0, []], GoodsStatus} end end; handle_call({'clean', PlayerStatus}, _From, GoodsStatus) -> GoodsList = goods_util:get_goods_list(GoodsStatus#goods_status.player_id, 4), GoodsList1 = goods_util:sort(GoodsList, goods_id), [Num, _] = lists:foldl(fun lib_goods:clean_bag/2, [1, {}], GoodsList1), NewGoodsList = goods_util:get_goods_list(GoodsStatus#goods_status.player_id, 4), NullCells = lists:seq(Num, PlayerStatus#player_status.cell_num), NewGoodsStatus = GoodsStatus#goods_status{ null_cells = NullCells }, {reply, NewGoodsList, NewGoodsStatus}; handle_call({'drop_list', PlayerStatus, DropId}, _From, GoodsStatus) -> case check_drop_list(PlayerStatus, DropId) of {fail, Res} -> {reply, [Res, []], GoodsStatus}; {ok, DropInfo} -> {reply, [1, DropInfo#ets_goods_drop.drop_goods], GoodsStatus} end; handle_call({'drop_choose', PlayerStatus, DropId, GoodsTypeId}, _From, GoodsStatus) -> case check_drop_choose(PlayerStatus, GoodsStatus, DropId, GoodsTypeId) of {fail, Res} -> {reply, Res, GoodsStatus}; {ok, DropInfo, GoodsInfo} -> case (catch lib_goods:drop_choose(PlayerStatus, GoodsStatus, DropInfo, GoodsInfo)) of {ok, NewStatus} -> {reply, 1, NewStatus}; Error -> ?DEBUG("mod_goods drop_choose:~p", [Error]), {reply, 0, GoodsStatus} end end; handle_call({'give_goods', _PlayerStatus, GoodsTypeId, GoodsNum}, _From, GoodsStatus) -> case (catch lib_goods:give_goods({GoodsTypeId, GoodsNum}, GoodsStatus)) of {ok, NewStatus} -> lib_player:refresh_client(NewStatus#goods_status.player_id, 2), {reply, ok, NewStatus}; {fail, Error, Status} -> ?DEBUG("mod_goods give_goods:~p", [Error]), {reply, Error, Status} end; = [ , } , ... ] handle_call({'give_more', _PlayerStatus, GoodsList}, _From, GoodsStatus) -> case (catch goods_util:list_handle(fun lib_goods:give_goods/2, GoodsStatus, GoodsList)) of {ok, NewStatus} -> lib_player:refresh_client(NewStatus#goods_status.player_id, 2), {reply, ok, NewStatus}; {fail, Error, Status} -> ?DEBUG("mod_goods give_more:~p", [Error]), {reply, Error, Status} end; { ' mon_drop ' , PlayerStatus , MonStatus } - > { ok , } | { fail , no_drop } handle_call({'mon_drop', PlayerStatus, MonStatus}, _From, GoodsStatus) -> PlayerId = PlayerStatus#player_status.id, TeamId = PlayerStatus#player_status.pid_team, MonId = MonStatus#ets_mon.mid, RealMonId = MonStatus#ets_mon.id, NumRule = lib_goods:get_drop_num_rule(MonId), case is_record(NumRule, ets_goods_drop_num) of true when NumRule#ets_goods_drop_num.drop_num > 0 -> [TotalRatio, RuleList] = lib_goods:get_drop_rule_list(PlayerId, MonId), case length(RuleList) > 0 of true -> DropNum = NumRule#ets_goods_drop_num.drop_num, [NewGoodsStatus, _, _, RuleResult, TaskResult] = lists:foldl(fun lib_goods:mon_drop/2, [GoodsStatus, RuleList, TotalRatio, [], []], lists:seq(1, DropNum)), case length(TaskResult) > 0 of true -> io : format("mon_drop : ~p ~ n",[TaskResult ] ) , lib_task:event(item, TaskResult, PlayerId), lib_player:refresh_client(PlayerId, 2); false -> skip end, case length(RuleResult) > 0 of true -> ExpireTime = util:unixtime() + 60, DropInfo = #ets_goods_drop{ id=RealMonId, player_id=PlayerId, team_id=TeamId, drop_goods=RuleResult, expire_time=ExpireTime }, ets:insert(?ETS_GOODS_DROP, DropInfo), 广播 {ok, BinData} = pt_12:write(12017, [RealMonId, 60, MonStatus#ets_mon.x, MonStatus#ets_mon.y]), lib_send:send_to_team(PlayerStatus#player_status.sid, PlayerStatus#player_status.pid_team, BinData), {reply, ok, NewGoodsStatus}; false -> {reply, {fail, no_drop}, NewGoodsStatus} end; false -> {reply, {fail, no_drop}, GoodsStatus} end; _ -> {reply, {fail, no_drop}, GoodsStatus} end; handle_call({'cell_num'} , _From, GoodsStatus) -> {reply, length(GoodsStatus#goods_status.null_cells), GoodsStatus}; handle_call(_R , _From, GoodsStatus) -> {reply, ok, GoodsStatus}. handle_info(_Reason, GoodsStatus) -> {noreply, GoodsStatus}. terminate(_Reason, _GoodsStatus) -> ok. code_change(_OldVsn, GoodsStatus, _Extra)-> {ok, GoodsStatus}. check_pay(PlayerStatus, GoodsStatus, GoodsTypeId, GoodsNum, ShopType) -> ShopInfo = goods_util:get_shop_info(ShopType, GoodsTypeId), GoodsTypeInfo = goods_util:get_goods_type(GoodsTypeId), case is_record(GoodsTypeInfo, ets_goods_type) andalso is_record(ShopInfo, ets_shop) of false -> {fail, 2}; true -> GoodsList = goods_util:get_type_goods_list(GoodsStatus#goods_status.player_id, GoodsTypeId, GoodsTypeInfo#ets_goods_type.bind, 4), CellNum = goods_util:get_null_cell_num(GoodsList, GoodsTypeInfo#ets_goods_type.max_overlap, GoodsNum), case length(GoodsStatus#goods_status.null_cells) < CellNum of 背包格子不足 true -> {fail, 4}; false -> Cost = GoodsTypeInfo#ets_goods_type.price * GoodsNum, PriceType = goods_util:get_price_type(GoodsTypeInfo#ets_goods_type.price_type), case goods_util:is_enough_money(PlayerStatus, Cost, PriceType) of false -> {fail, 3}; true -> {ok, GoodsTypeInfo, GoodsList, Cost, PriceType} end end end. check_sell(GoodsStatus, GoodsId, GoodsNum) -> GoodsInfo = goods_util:get_goods(GoodsId), if is_record(GoodsInfo, goods) =:= false -> {fail, 2}; GoodsInfo#goods.player_id =/= GoodsStatus#goods_status.player_id -> {fail, 3}; GoodsInfo#goods.location =/= 4 -> {fail, 4}; GoodsInfo#goods.sell =:= 1 -> {fail, 5}; 物品数量不足 GoodsInfo#goods.num < GoodsNum -> {fail, 6}; true -> {ok, GoodsInfo} end. check_equip(PlayerStatus, GoodsId, Cell) -> Location = PlayerStatus#player_status.equip, GoodsInfo = goods_util:get_goods(GoodsId), if is_record(GoodsInfo, goods) =:= false -> {fail, 2}; GoodsInfo#goods.player_id =/= PlayerStatus#player_status.id -> {fail, 3}; GoodsInfo#goods.location =/= 4 -> {fail, 4}; Location =/= 1 andalso Location =/= 2 andalso Location =/= 3 -> {fail, 4}; GoodsInfo#goods.type =/= 10 -> {fail, 5}; true -> case goods_util:can_equip(PlayerStatus, GoodsInfo#goods.goods_id, Cell) of false -> {fail, 6}; NewCell -> {ok, GoodsInfo, Location, NewCell} end end. check_unequip(GoodsStatus, GoodsId, Equip) -> GoodsInfo = goods_util:get_goods(GoodsId), if is_record(GoodsInfo, goods) =:= false -> {fail, 2}; GoodsInfo#goods.player_id =/= GoodsStatus#goods_status.player_id -> {fail, 3}; 物品不在身上 GoodsInfo#goods.location > 3 orelse GoodsInfo#goods.location < 1 -> {fail, 4}; 物品不在身上 GoodsInfo#goods.location =/= Equip -> {fail, 4}; GoodsInfo#goods.type =/= 10 -> {fail, 5}; length(GoodsStatus#goods_status.null_cells) =:= 0 -> {fail, 6}; true -> {ok, GoodsInfo} end. check_drag(GoodsStatus, GoodsId, OldCell, NewCell, MaxCellNum) -> GoodsInfo = goods_util:get_goods(GoodsId), if is_record(GoodsInfo, goods) =:= false -> {fail, 2}; GoodsInfo#goods.player_id =/= GoodsStatus#goods_status.player_id -> {fail, 3}; GoodsInfo#goods.location =/= 4 -> {fail, 4}; GoodsInfo#goods.cell =/= OldCell -> {fail, 5}; NewCell < 1 orelse NewCell > MaxCellNum -> {fail, 5}; true -> {ok, GoodsInfo} end. check_use(GoodsStatus, GoodsId, GoodsNum, Level) -> NowTime = util:unixtime(), GoodsInfo = goods_util:get_goods(GoodsId), if is_record(GoodsInfo, goods) =:= false -> {fail, 2}; GoodsInfo#goods.player_id =/= GoodsStatus#goods_status.player_id -> {fail, 3}; GoodsInfo#goods.location =/= 4 -> {fail, 4}; 物品类型不符 GoodsInfo#goods.type =/= 20 andalso GoodsInfo#goods.type =/= 22 -> {fail, 5}; GoodsInfo#goods.num < GoodsNum -> {fail, 6}; GoodsInfo#goods.type =:= 20 andalso GoodsStatus#goods_status.ct_time > NowTime -> {fail, 7}; GoodsInfo#goods.level > Level -> {fail, 8}; true -> {ok, GoodsInfo} end. check_throw(GoodsStatus, GoodsId, GoodsNum) -> GoodsInfo = goods_util:get_goods(GoodsId), if is_record(GoodsInfo, goods) =:= false -> {fail, 2}; GoodsInfo#goods.player_id =/= GoodsStatus#goods_status.player_id -> {fail, 3}; GoodsInfo#goods.location =/= 4 -> {fail, 4}; GoodsInfo#goods.isdrop =:= 1 -> {fail, 5}; GoodsInfo#goods.num < GoodsNum -> {fail, 6}; true -> {ok, GoodsInfo} end. check_movein_bag(GoodsStatus, GoodsId, GoodsNum) -> GoodsInfo = goods_util:get_goods(GoodsId), if is_record(GoodsInfo, goods) =:= false -> {fail, 2}; GoodsInfo#goods.player_id =/= GoodsStatus#goods_status.player_id -> {fail, 3}; GoodsInfo#goods.location =/= 4 -> {fail, 4}; GoodsInfo#goods.num < GoodsNum -> {fail, 5}; true -> GoodsTypeInfo = goods_util:get_goods_type(GoodsInfo#goods.goods_id), if is_record(GoodsTypeInfo, ets_goods_type) =:= false -> {fail, 2}; true -> {ok, GoodsInfo, GoodsTypeInfo} end end. check_moveout_bag(GoodsStatus, GoodsId, GoodsNum) -> GoodsInfo = goods_util:get_goods_by_id(GoodsId), if is_record(GoodsInfo, goods) =:= false -> {fail, 2}; GoodsInfo#goods.player_id =/= GoodsStatus#goods_status.player_id -> {fail, 3}; GoodsInfo#goods.location =/= 5 -> {fail, 4}; GoodsInfo#goods.num < GoodsNum -> {fail, 5}; true -> GoodsTypeInfo = goods_util:get_goods_type(GoodsInfo#goods.goods_id), if is_record(GoodsTypeInfo, ets_goods_type) =:= false -> {fail, 2}; length(GoodsStatus#goods_status.null_cells) =< 0 -> {fail, 6}; true -> {ok, GoodsInfo, GoodsTypeInfo} end end. check_extend_bag(PlayerStatus) -> Cost = 1000, MaxCell = 147, if 背包已达上限 PlayerStatus#player_status.cell_num >= MaxCell -> {fail, 3}; true -> case goods_util:is_enough_money(PlayerStatus, Cost, coin) of false -> {fail, 2}; true ->{ok, Cost} end end. check_mend(PlayerStatus, GoodsId) -> GoodsInfo = goods_util:get_goods(GoodsId), is_record(GoodsInfo, goods) =:= false -> {fail, 2}; GoodsInfo#goods.player_id =/= PlayerStatus#player_status.id -> {fail, 3}; GoodsInfo#goods.type =/= 10 orelse GoodsInfo#goods.attrition =:= 0 -> {fail, 4}; true -> UseNum = goods_util:get_goods_use_num(GoodsInfo#goods.attrition), UseNum > 0 andalso UseNum =:= GoodsInfo#goods.use_num -> {fail, 5}; true -> Cost = goods_util:get_mend_cost(GoodsInfo#goods.attrition, GoodsInfo#goods.use_num), case goods_util:is_enough_money(PlayerStatus, Cost, coin) of false -> {fail, 6}; true -> {ok, GoodsInfo} end end end. check_quality_upgrade(PlayerStatus, GoodsId, StoneId) -> GoodsInfo = goods_util:get_goods(GoodsId), StoneInfo = goods_util:get_goods(StoneId), if is_record(GoodsInfo, goods) =:= false orelse is_record(StoneInfo, goods) =:= false -> {fail, 2}; GoodsInfo#goods.num < 1 orelse StoneInfo#goods.num < 1 -> {fail, 2}; GoodsInfo#goods.player_id =/= PlayerStatus#player_status.id orelse StoneInfo#goods.player_id =/= PlayerStatus#player_status.id -> {fail, 3}; GoodsInfo#goods.location =/= 4 -> {fail, 4}; GoodsInfo#goods.type =/= 10 -> {fail, 5}; StoneInfo#goods.type =/= 11 orelse StoneInfo#goods.subtype =/= 11 -> {fail, 5}; true -> Pattern = #ets_goods_quality_upgrade{ goods_id=StoneInfo#goods.goods_id, quality=GoodsInfo#goods.quality, _='_' }, GoodsQualityRule = goods_util:get_ets_info(?ETS_GOODS_QUALITY_UPGRADE, Pattern), if is_record(GoodsQualityRule, ets_goods_quality_upgrade) =:= false -> {fail, 6}; (PlayerStatus#player_status.coin + PlayerStatus#player_status.bcoin) < GoodsQualityRule#ets_goods_quality_upgrade.coin -> {fail, 7}; true -> {ok, GoodsInfo, StoneInfo, GoodsQualityRule} end end. check_quality_backout(GoodsStatus, GoodsId) -> GoodsInfo = goods_util:get_goods(GoodsId), if is_record(GoodsInfo, goods) =:= false orelse GoodsInfo#goods.num < 1 -> {fail, 2}; GoodsInfo#goods.player_id =/= GoodsStatus#goods_status.player_id -> {fail, 3}; GoodsInfo#goods.type =/= 10 -> {fail, 5}; GoodsInfo#goods.quality < 1 -> {fail, 6}; length(GoodsStatus#goods_status.null_cells) =:= 0 -> {fail, 8}; true -> Pattern = #ets_goods_quality_backout{ quality=GoodsInfo#goods.quality, _='_' }, GoodsBackoutRuleList = goods_util:get_ets_list(?ETS_GOODS_QUALITY_BACKOUT, Pattern), if length(GoodsBackoutRuleList) =:= 0 -> {fail, 7}; true -> {ok, GoodsInfo, GoodsBackoutRuleList} end end. check_strengthen(PlayerStatus, GoodsId, StoneId, RuneId) -> GoodsInfo = goods_util:get_goods(GoodsId), StoneInfo = goods_util:get_goods(StoneId), case RuneId > 0 of true -> RuneInfo = goods_util:get_goods(RuneId); false -> RuneInfo = #goods{ num = 1, player_id = PlayerStatus#player_status.id, location = 4, type = 11, subtype = 10 } end, if is_record(GoodsInfo, goods) =:= false orelse is_record(StoneInfo, goods) =:= false -> {fail, 2}; RuneId > 0 andalso is_record(RuneInfo, goods) =:= false -> {fail, 2}; GoodsInfo#goods.num < 1 orelse StoneInfo#goods.num < 1 -> {fail, 2}; GoodsInfo#goods.player_id =/= PlayerStatus#player_status.id orelse StoneInfo#goods.player_id =/= PlayerStatus#player_status.id -> {fail, 3}; RuneId > 0 andalso RuneInfo#goods.player_id =/= PlayerStatus#player_status.id -> {fail, 3}; GoodsInfo#goods.location =/= 4 -> {fail, 4}; GoodsInfo#goods.type =/= 10 -> {fail, 5}; StoneInfo#goods.type =/= 11 orelse StoneInfo#goods.subtype =/= 10 -> {fail, 5}; RuneId > 0 andalso RuneInfo#goods.type =/= 12 -> {fail, 5}; RuneId > 0 andalso RuneInfo#goods.subtype =/= 10 andalso RuneInfo#goods.subtype =/= 18 -> {fail, 5}; GoodsInfo#goods.stren >= 10 -> {fail, 8}; true -> Pattern = #ets_goods_strengthen{ goods_id=StoneInfo#goods.goods_id, strengthen=GoodsInfo#goods.stren, _='_' }, GoodsStrengthenRule = goods_util:get_ets_info(?ETS_GOODS_STRENGTHEN, Pattern), if is_record(GoodsStrengthenRule, ets_goods_strengthen) =:= false -> {fail, 6}; (PlayerStatus#player_status.coin + PlayerStatus#player_status.bcoin) < GoodsStrengthenRule#ets_goods_strengthen.coin -> {fail, 7}; true -> {ok, GoodsInfo, StoneInfo, RuneInfo, GoodsStrengthenRule} end end. check_hole(PlayerStatus, GoodsId, RuneId) -> Cost = 100, GoodsInfo = goods_util:get_goods(GoodsId), RuneInfo = goods_util:get_goods(RuneId), if is_record(GoodsInfo, goods) =:= false orelse is_record(RuneInfo, goods) =:= false -> {fail, 2}; GoodsInfo#goods.num < 1 orelse RuneInfo#goods.num < 1 -> {fail, 2}; GoodsInfo#goods.player_id =/= PlayerStatus#player_status.id orelse RuneInfo#goods.player_id =/= PlayerStatus#player_status.id -> {fail, 3}; GoodsInfo#goods.location =/= 4 -> {fail, 4}; GoodsInfo#goods.type =/= 10 -> {fail, 5}; RuneInfo#goods.type =/= 12 orelse RuneInfo#goods.subtype =/= 12 -> {fail, 5}; 孔数已达上限 GoodsInfo#goods.hole >= 3 -> {fail, 6}; (PlayerStatus#player_status.coin + PlayerStatus#player_status.bcoin) < Cost -> {fail, 7}; true -> {ok, GoodsInfo, RuneInfo} end. check_compose(PlayerStatus, GoodsStatus, RuneId, StoneTypeId, StoneList) -> case RuneId > 0 of true -> RuneInfo = goods_util:get_goods(RuneId); false -> RuneInfo = #goods{ num = 1, player_id = PlayerStatus#player_status.id, location = 4, type = 12, subtype = 13, color=3 } end, if is_record(RuneInfo, goods) =:= false -> {fail, 2}; RuneInfo#goods.player_id =/= PlayerStatus#player_status.id -> {fail, 3}; RuneInfo#goods.location =/= 4 -> {fail, 4}; RuneInfo#goods.type =/= 12 orelse RuneInfo#goods.subtype =/= 13 -> {fail, 5}; RuneInfo#goods.num < 1 -> {fail, 6}; length(StoneList) =:= 0 -> {fail, 6}; true -> case goods_util:list_handle(fun check_compose_stone/2, [RuneInfo, StoneTypeId, 0, []], StoneList) of {fail, Res} -> {fail, Res}; {ok, [_, _, TotalStoneNum, NewStoneList]} -> Pattern = #ets_goods_compose{ goods_id=StoneTypeId, goods_num=TotalStoneNum, _='_' }, GoodsComposeRule = goods_util:get_ets_info(?ETS_GOODS_COMPOSE, Pattern), if is_record(GoodsComposeRule, ets_goods_compose) =:= false -> {fail, 7}; (PlayerStatus#player_status.coin + PlayerStatus#player_status.bcoin) < GoodsComposeRule#ets_goods_compose.coin -> {fail, 8}; length(GoodsStatus#goods_status.null_cells) =:= 0 -> {fail, 9}; true -> {ok, NewStoneList, RuneInfo, GoodsComposeRule} end end end. check_compose_stone([StoneId, StoneNum], [RuneInfo, StoneTypeId, Num, L]) -> StoneInfo = goods_util:get_goods(StoneId), if is_record(StoneInfo, goods) =:= false -> {fail, 2}; StoneInfo#goods.player_id =/= RuneInfo#goods.player_id -> {fail, 3}; StoneInfo#goods.goods_id =/= StoneTypeId -> {fail, 5}; RuneInfo#goods.color < StoneInfo#goods.color -> {fail, 5}; StoneInfo#goods.num < StoneNum -> {fail, 6}; true -> {ok, [RuneInfo, StoneTypeId, Num+StoneNum, [[StoneInfo, StoneNum]|L]]} end. check_inlay(PlayerStatus, GoodsId, StoneId, RuneList) -> GoodsInfo = goods_util:get_goods(GoodsId), StoneInfo = goods_util:get_goods(StoneId), if is_record(GoodsInfo, goods) =:= false orelse is_record(StoneInfo, goods) =:= false -> {fail, 2}; GoodsInfo#goods.num < 1 orelse StoneInfo#goods.num < 1 -> {fail, 2}; GoodsInfo#goods.player_id =/= PlayerStatus#player_status.id orelse StoneInfo#goods.player_id =/= PlayerStatus#player_status.id -> {fail, 3}; GoodsInfo#goods.location =/= 4 -> {fail, 4}; GoodsInfo#goods.type =/= 10 -> {fail, 5}; StoneInfo#goods.type =/= 11 orelse StoneInfo#goods.subtype =/= 14 -> {fail, 5}; StoneInfo#goods.goods_id =:= GoodsInfo#goods.hole1_goods orelse StoneInfo#goods.goods_id =:= GoodsInfo#goods.hole2_goods orelse StoneInfo#goods.goods_id =:= GoodsInfo#goods.hole3_goods -> {fail, 5}; GoodsInfo#goods.hole =:= 0 -> {fail, 6}; GoodsInfo#goods.hole =:= 1 andalso GoodsInfo#goods.hole1_goods > 0 -> {fail, 6}; GoodsInfo#goods.hole =:= 2 andalso GoodsInfo#goods.hole2_goods > 0 -> {fail, 6}; GoodsInfo#goods.hole =:= 3 andalso GoodsInfo#goods.hole3_goods > 0 -> {fail, 6}; true -> case goods_util:list_handle(fun check_inlay_rune/2, [PlayerStatus#player_status.id, 0, []], RuneList) of {fail, Res} -> {fail, Res}; {ok, [_, TotalRuneNum, NewRuneList]} -> Pattern = #ets_goods_inlay{ goods_id=StoneInfo#goods.goods_id, _='_' }, GoodsInlayRule = goods_util:get_ets_info(?ETS_GOODS_INLAY, Pattern), if 镶嵌规则不存在 is_record(GoodsInlayRule, ets_goods_inlay) =:= false -> {fail, 7}; (PlayerStatus#player_status.coin + PlayerStatus#player_status.bcoin) < GoodsInlayRule#ets_goods_inlay.coin -> {fail, 8}; true -> case length(GoodsInlayRule#ets_goods_inlay.equip_types) > 0 andalso lists:member(GoodsInfo#goods.subtype, GoodsInlayRule#ets_goods_inlay.equip_types) =:= false of true -> {fail, 9}; false -> {ok, GoodsInfo, StoneInfo, TotalRuneNum, NewRuneList, GoodsInlayRule} end end end end. 处理镶嵌符 check_inlay_rune([RuneId, RuneNum], [PlayerId, Num, L]) -> RuneInfo = goods_util:get_goods(RuneId), if is_record(RuneInfo, goods) =:= false -> {fail, 2}; RuneInfo#goods.player_id =/= PlayerId -> {fail, 3}; RuneInfo#goods.type =/= 12 orelse RuneInfo#goods.subtype =/= 14 -> {fail, 5}; RuneInfo#goods.num < RuneNum -> {fail, 6}; true -> {ok, [PlayerId, Num+RuneNum, [[RuneInfo, RuneNum]|L]]} end. check_backout(PlayerStatus, GoodsStatus, GoodsId, RuneId) -> Cost = 100, GoodsInfo = goods_util:get_goods(GoodsId), RuneInfo = goods_util:get_goods(RuneId), if is_record(GoodsInfo, goods) =:= false orelse GoodsInfo#goods.num < 1 -> {fail, 2}; is_record(RuneInfo, goods) =:= false orelse RuneInfo#goods.num < 1 -> {fail, 2}; GoodsInfo#goods.player_id =/= PlayerStatus#player_status.id orelse RuneInfo#goods.player_id =/= PlayerStatus#player_status.id -> {fail, 3}; GoodsInfo#goods.location =/= 4 orelse RuneInfo#goods.location =/= 4 -> {fail, 4}; GoodsInfo#goods.type =/= 10 -> {fail, 5}; RuneInfo#goods.type =/= 12 andalso RuneInfo#goods.subtype =/= 17 -> {fail, 5}; GoodsInfo#goods.hole1_goods =:= 0 -> {fail, 8}; (PlayerStatus#player_status.coin + PlayerStatus#player_status.bcoin) < Cost -> {fail, 6}; true -> InlayNum = goods_util:get_inlay_num(GoodsInfo), if 背包格子不足 length(GoodsStatus#goods_status.null_cells) < InlayNum -> {fail, 7}; true -> {ok, GoodsInfo, RuneInfo} end end. check_wash(PlayerStatus, GoodsId, RuneId) -> Cost = 100, GoodsInfo = goods_util:get_goods(GoodsId), RuneInfo = goods_util:get_goods(RuneId), if is_record(GoodsInfo, goods) =:= false orelse is_record(RuneInfo, goods) =:= false -> {fail, 2}; GoodsInfo#goods.num < 1 orelse RuneInfo#goods.num < 1 -> {fail, 2}; GoodsInfo#goods.player_id =/= PlayerStatus#player_status.id orelse RuneInfo#goods.player_id =/= PlayerStatus#player_status.id -> {fail, 3}; GoodsInfo#goods.location =/= 4 orelse RuneInfo#goods.location =/= 4 -> {fail, 4}; GoodsInfo#goods.type =/= 10 -> {fail, 5}; RuneInfo#goods.type =/= 12 orelse RuneInfo#goods.subtype =/= 15 -> {fail, 5}; GoodsInfo#goods.color =:= 0 -> {fail, 5}; (PlayerStatus#player_status.coin + PlayerStatus#player_status.bcoin) < Cost -> {fail, 6}; true -> Pattern = #ets_goods_attribute_rule{ goods_id=GoodsInfo#goods.goods_id, _='_'}, AddAttributeRuleList = goods_util:get_ets_list(?ETS_GOODS_ATTRIBUTE_RULE, Pattern), if length(AddAttributeRuleList) =:= 0 -> {fail, 7}; true -> {ok, GoodsInfo, RuneInfo, AddAttributeRuleList} end end. check_change_equip(PlayerStatus, Equip) -> if Equip > 3 orelse Equip < 1 -> {fail, 2}; Equip =:= PlayerStatus#player_status.equip -> {fail, 2}; true -> ok end. check_drop_list(PlayerStatus, DropId) -> DropInfo = goods_util:get_ets_info(?ETS_GOODS_DROP, DropId), NowTime = util:unixtime(), if is_record(DropInfo, ets_goods_drop) =:= false -> {fail, 2}; DropInfo#ets_goods_drop.expire_time =< NowTime -> {fail, 2}; DropInfo#ets_goods_drop.team_id =:= 0 andalso DropInfo#ets_goods_drop.player_id =/= PlayerStatus#player_status.id -> {fail, 3}; DropInfo#ets_goods_drop.team_id > 0 andalso DropInfo#ets_goods_drop.team_id =/= PlayerStatus#player_status.pid_team andalso DropInfo#ets_goods_drop.player_id =/= PlayerStatus#player_status.id -> {fail, 3}; true -> {ok, DropInfo} end. check_drop_choose(PlayerStatus, GoodsStatus, DropId, GoodsTypeId) -> case check_drop_list(PlayerStatus, DropId) of {fail, Res} -> {fail, Res}; {ok, DropInfo} -> case lists:keyfind(GoodsTypeId, 1, DropInfo#ets_goods_drop.drop_goods) of 物品已经不存在 false -> {fail, 4}; GoodsInfo -> {GoodsTypeId, _Type, GoodsNum, _GoodsQuality} = GoodsInfo, GoodsTypeInfo = goods_util:get_goods_type(GoodsTypeId), if is_record(GoodsTypeInfo, ets_goods_type) =:= false -> {fail, 4}; true -> GoodsList = goods_util:get_type_goods_list(GoodsStatus#goods_status.player_id, GoodsTypeId, GoodsTypeInfo#ets_goods_type.bind, 4), CellNum = goods_util:get_null_cell_num(GoodsList, GoodsTypeInfo#ets_goods_type.max_overlap, GoodsNum), if 背包格子不足 length(GoodsStatus#goods_status.null_cells) < CellNum -> {fail, 5}; true -> {ok, DropInfo, GoodsInfo} end end end end.
8a77886f9aa4cc92ebd8e0ed99bcf2a185be47e937aae9f007f9ff880abf06c4
HunterYIboHu/htdp2-solution
ex312-eye-colors.rkt
The first three lines of this file were inserted by . They record metadata ;; about the language level of this file in a form that our tools can easily process. #reader(lib "htdp-intermediate-lambda-reader.ss" "lang")((modname ex312-eye-colors) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f))) (require 2htdp/abstraction) ;; data difinitions (define-struct no-parent []) (define NP (make-no-parent)) (define-struct child [father mother name date eyes]) A FT ( short for family tree ) is one of : – NP – ( make - child FT FT String N String ) ;; constants ; Oldest Generation: (define Carl (make-child NP NP "Carl" 1926 "green")) (define Bettina (make-child NP NP "Bettina" 1926 "green")) ; Middle Generation: (define Adam (make-child Carl Bettina "Adam" 1950 "hazel")) (define Dave (make-child Carl Bettina "Dave" 1955 "black")) (define Eva (make-child Carl Bettina "Eva" 1965 "blue")) (define Fred (make-child NP NP "Fred" 1966 "pink")) ; Youngest Generation: (define Gustav (make-child Fred Eva "Gustav" 1988 "brown")) ;; functions ; FT -> [List-of String] ; produces a list of all eye colors in the tree, an eye color may occur more than ; once. (check-expect (eye-colors Carl) '("green")) (check-expect (eye-colors Adam) '("green" "green" "hazel")) (check-expect (eye-colors Gustav) '("pink" "green" "green" "blue" "brown")) (define (eye-colors a-ftree) (match a-ftree [(? no-parent?) '()] [(child fa mo n d e) `(,@(eye-colors fa) ,@(eye-colors mo) ,e)]))
null
https://raw.githubusercontent.com/HunterYIboHu/htdp2-solution/6182b4c2ef650ac7059f3c143f639d09cd708516/Chapter4/Section19-the-poetry-of-s-expressions/ex312-eye-colors.rkt
racket
about the language level of this file in a form that our tools can easily process. data difinitions constants Oldest Generation: Middle Generation: Youngest Generation: functions FT -> [List-of String] produces a list of all eye colors in the tree, an eye color may occur more than once.
The first three lines of this file were inserted by . They record metadata #reader(lib "htdp-intermediate-lambda-reader.ss" "lang")((modname ex312-eye-colors) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f))) (require 2htdp/abstraction) (define-struct no-parent []) (define NP (make-no-parent)) (define-struct child [father mother name date eyes]) A FT ( short for family tree ) is one of : – NP – ( make - child FT FT String N String ) (define Carl (make-child NP NP "Carl" 1926 "green")) (define Bettina (make-child NP NP "Bettina" 1926 "green")) (define Adam (make-child Carl Bettina "Adam" 1950 "hazel")) (define Dave (make-child Carl Bettina "Dave" 1955 "black")) (define Eva (make-child Carl Bettina "Eva" 1965 "blue")) (define Fred (make-child NP NP "Fred" 1966 "pink")) (define Gustav (make-child Fred Eva "Gustav" 1988 "brown")) (check-expect (eye-colors Carl) '("green")) (check-expect (eye-colors Adam) '("green" "green" "hazel")) (check-expect (eye-colors Gustav) '("pink" "green" "green" "blue" "brown")) (define (eye-colors a-ftree) (match a-ftree [(? no-parent?) '()] [(child fa mo n d e) `(,@(eye-colors fa) ,@(eye-colors mo) ,e)]))
3a52f8dfe7d9c17bacd562bb857f19e2341b1095cdb7c3b869a7d00f1603a65b
samrushing/irken-compiler
t_anno1.scm
;; (define (thing:(int -> int) x) ;; 3) (define (printn x) (%%cexp ('a -> undefined) "dump_object (%0, 0); fprintf (stdout, \"\\n\")" x)) (define (thing x) : (int -> int) (printn x) (printn x) (printn x) (printn x) (printn x) (printn x) (printn x) 3) (printn (thing 3)) (printn (thing 4)) (printn (thing 5))
null
https://raw.githubusercontent.com/samrushing/irken-compiler/690da48852d55497f873738df54f14e8e135d006/tests/t_anno1.scm
scheme
(define (thing:(int -> int) x) 3)
(define (printn x) (%%cexp ('a -> undefined) "dump_object (%0, 0); fprintf (stdout, \"\\n\")" x)) (define (thing x) : (int -> int) (printn x) (printn x) (printn x) (printn x) (printn x) (printn x) (printn x) 3) (printn (thing 3)) (printn (thing 4)) (printn (thing 5))
8e19ace1f7784cdfe04f7230fe548fc3247f519a3f93fd701935298ab13341cb
s-expressionists/Concrete-Syntax-Tree
packages.lisp
(cl:defpackage #:concrete-syntax-tree-test (:use #:common-lisp) (:export #:run-tests)) (cl:in-package #:concrete-syntax-tree-test) (defun run-tests () (test-cst-from-expression) (test-reconstruct) (test-reconstruct-1) (test-quasiquotation))
null
https://raw.githubusercontent.com/s-expressionists/Concrete-Syntax-Tree/a34e9f01f3e8121a32aad03d35cf113916694492/Test/packages.lisp
lisp
(cl:defpackage #:concrete-syntax-tree-test (:use #:common-lisp) (:export #:run-tests)) (cl:in-package #:concrete-syntax-tree-test) (defun run-tests () (test-cst-from-expression) (test-reconstruct) (test-reconstruct-1) (test-quasiquotation))
c685c5b273c4093ad305d5f4e8faf580d8a9f97fb0bccb5309e4f260eeaa4a9a
rixed/ramen
output_specs.ml
(* Manually written impostor to output_specs_wire, converting from/to hashes *) open Batteries open Stdint open DessserOCamlBackEndHelpers module Wire = Output_specs_wire.DessserGen module DessserGen = struct type file_spec = { file_type : Wire.file_type ; fieldmask : DessserMasks.t ; filters : (Uint16.t * Raql_value.t array) array ; mutable channels : (Uint16.t, Wire.channel_specs) Hashtbl.t } type t = (Wire.recipient, file_spec) Hashtbl.t let to_wire (t : t) = Hashtbl.enum t /@ (fun (r, s) -> r, Wire.{ file_type = s.file_type ; fieldmask = s.fieldmask ; filters = s.filters ; channels = Hashtbl.enum s.channels |> Array.of_enum }) |> Array.of_enum let of_wire w = Array.enum w /@ (fun (r, s) -> r, { file_type = s.Wire.file_type ; fieldmask = s.Wire.fieldmask ; filters = s.Wire.filters ; channels = Array.enum s.Wire.channels |> Hashtbl.of_enum }) |> Hashtbl.of_enum let to_row_binary_with_mask m t p = Wire.to_row_binary_with_mask m (to_wire t) p let to_row_binary t p = Wire.to_row_binary (to_wire t) p let sersize_of_row_binary_with_mask m t = Wire.sersize_of_row_binary_with_mask m (to_wire t) let sersize_of_row_binary t = Wire.sersize_of_row_binary (to_wire t) let of_row_binary p = let t, p = Wire.of_row_binary p in of_wire t, p end
null
https://raw.githubusercontent.com/rixed/ramen/e395febf4b101461adb2af484e78e1e21a4f4905/src/output_specs.ml
ocaml
Manually written impostor to output_specs_wire, converting from/to hashes
open Batteries open Stdint open DessserOCamlBackEndHelpers module Wire = Output_specs_wire.DessserGen module DessserGen = struct type file_spec = { file_type : Wire.file_type ; fieldmask : DessserMasks.t ; filters : (Uint16.t * Raql_value.t array) array ; mutable channels : (Uint16.t, Wire.channel_specs) Hashtbl.t } type t = (Wire.recipient, file_spec) Hashtbl.t let to_wire (t : t) = Hashtbl.enum t /@ (fun (r, s) -> r, Wire.{ file_type = s.file_type ; fieldmask = s.fieldmask ; filters = s.filters ; channels = Hashtbl.enum s.channels |> Array.of_enum }) |> Array.of_enum let of_wire w = Array.enum w /@ (fun (r, s) -> r, { file_type = s.Wire.file_type ; fieldmask = s.Wire.fieldmask ; filters = s.Wire.filters ; channels = Array.enum s.Wire.channels |> Hashtbl.of_enum }) |> Hashtbl.of_enum let to_row_binary_with_mask m t p = Wire.to_row_binary_with_mask m (to_wire t) p let to_row_binary t p = Wire.to_row_binary (to_wire t) p let sersize_of_row_binary_with_mask m t = Wire.sersize_of_row_binary_with_mask m (to_wire t) let sersize_of_row_binary t = Wire.sersize_of_row_binary (to_wire t) let of_row_binary p = let t, p = Wire.of_row_binary p in of_wire t, p end
85cb57fe0a1fa259e96eb1b1d330e3f600460f806e6838a4e29c8abdc7e552a9
nvim-treesitter/nvim-treesitter
highlights.scm
[ "require" "replace" "go" "exclude" "retract" "module" ] @keyword "=>" @operator (comment) @comment (module_path) @text.uri [ (version) (go_version) ] @string
null
https://raw.githubusercontent.com/nvim-treesitter/nvim-treesitter/0493aa026bd726b762004a7e78ccb19471e47daa/queries/gomod/highlights.scm
scheme
[ "require" "replace" "go" "exclude" "retract" "module" ] @keyword "=>" @operator (comment) @comment (module_path) @text.uri [ (version) (go_version) ] @string
5b0719dc3ebfb3572a0cb90c38a498073eefe60ea5b5585758af331268c9c05e
msakai/toysolver
ProbSAT.hs
# LANGUAGE FlexibleContexts # # LANGUAGE ScopedTypeVariables # # LANGUAGE TemplateHaskell # module Test.ProbSAT (probSATTestGroup) where import Control.Applicative import Control.Monad import Data.Array.IArray import Data.Default.Class import Data.Maybe import Test.Tasty import Test.Tasty.QuickCheck import Test.Tasty.HUnit import Test.Tasty.TH import qualified Test.QuickCheck.Monadic as QM import Test.QuickCheck.Modifiers import qualified ToySolver.FileFormat.CNF as CNF import qualified ToySolver.SAT.Types as SAT import qualified ToySolver.SAT.Solver.SLS.ProbSAT as ProbSAT import Test.SAT.Utils prop_probSAT :: Property prop_probSAT = QM.monadicIO $ do cnf <- QM.pick arbitraryCNF opt <- QM.pick $ do target <- choose (0, 10) maxTries <- choose (0, 10) maxFlips <- choose (0, 1000) return $ def { ProbSAT.optTarget = target , ProbSAT.optMaxTries = maxTries , ProbSAT.optMaxFlips = maxFlips } (obj,sol) <- QM.run $ do solver <- ProbSAT.newSolver cnf let cb = 3.6 cm = 0.5 f make break = cm**make / cb**break ProbSAT.probsat solver opt def f ProbSAT.getBestSolution solver QM.monitor (counterexample (show (obj,sol))) QM.assert (bounds sol == (1, CNF.cnfNumVars cnf)) QM.assert (obj == fromIntegral (evalCNFCost sol cnf)) prop_probSAT_weighted :: Property prop_probSAT_weighted = QM.monadicIO $ do wcnf <- QM.pick arbitraryWCNF opt <- QM.pick $ do target <- choose (0, 10) maxTries <- choose (0, 10) maxFlips <- choose (0, 1000) return $ def { ProbSAT.optTarget = target , ProbSAT.optMaxTries = maxTries , ProbSAT.optMaxFlips = maxFlips } (obj,sol) <- QM.run $ do solver <- ProbSAT.newSolverWeighted wcnf let cb = 3.6 cm = 0.5 f make break = cm**make / cb**break ProbSAT.probsat solver opt def f ProbSAT.getBestSolution solver QM.monitor (counterexample (show (obj,sol))) QM.assert (bounds sol == (1, CNF.wcnfNumVars wcnf)) QM.assert (obj == evalWCNFCost sol wcnf) case_probSAT_case1 :: Assertion case_probSAT_case1 = do let cnf = CNF.CNF { CNF.cnfNumVars = 1 , CNF.cnfNumClauses = 2 , CNF.cnfClauses = map SAT.packClause [ [1,-1] , [] ] } solver <- ProbSAT.newSolver cnf let opt = def { ProbSAT.optTarget = 0 , ProbSAT.optMaxTries = 1 , ProbSAT.optMaxFlips = 10 } cb = 3.6 cm = 0.5 f make break = cm**make / cb**break ProbSAT.probsat solver opt def f ------------------------------------------------------------------------ -- Test harness probSATTestGroup :: TestTree probSATTestGroup = $(testGroupGenerator)
null
https://raw.githubusercontent.com/msakai/toysolver/5dc84559c2ec782b2247febe529e4abd0971d1d3/test/Test/ProbSAT.hs
haskell
---------------------------------------------------------------------- Test harness
# LANGUAGE FlexibleContexts # # LANGUAGE ScopedTypeVariables # # LANGUAGE TemplateHaskell # module Test.ProbSAT (probSATTestGroup) where import Control.Applicative import Control.Monad import Data.Array.IArray import Data.Default.Class import Data.Maybe import Test.Tasty import Test.Tasty.QuickCheck import Test.Tasty.HUnit import Test.Tasty.TH import qualified Test.QuickCheck.Monadic as QM import Test.QuickCheck.Modifiers import qualified ToySolver.FileFormat.CNF as CNF import qualified ToySolver.SAT.Types as SAT import qualified ToySolver.SAT.Solver.SLS.ProbSAT as ProbSAT import Test.SAT.Utils prop_probSAT :: Property prop_probSAT = QM.monadicIO $ do cnf <- QM.pick arbitraryCNF opt <- QM.pick $ do target <- choose (0, 10) maxTries <- choose (0, 10) maxFlips <- choose (0, 1000) return $ def { ProbSAT.optTarget = target , ProbSAT.optMaxTries = maxTries , ProbSAT.optMaxFlips = maxFlips } (obj,sol) <- QM.run $ do solver <- ProbSAT.newSolver cnf let cb = 3.6 cm = 0.5 f make break = cm**make / cb**break ProbSAT.probsat solver opt def f ProbSAT.getBestSolution solver QM.monitor (counterexample (show (obj,sol))) QM.assert (bounds sol == (1, CNF.cnfNumVars cnf)) QM.assert (obj == fromIntegral (evalCNFCost sol cnf)) prop_probSAT_weighted :: Property prop_probSAT_weighted = QM.monadicIO $ do wcnf <- QM.pick arbitraryWCNF opt <- QM.pick $ do target <- choose (0, 10) maxTries <- choose (0, 10) maxFlips <- choose (0, 1000) return $ def { ProbSAT.optTarget = target , ProbSAT.optMaxTries = maxTries , ProbSAT.optMaxFlips = maxFlips } (obj,sol) <- QM.run $ do solver <- ProbSAT.newSolverWeighted wcnf let cb = 3.6 cm = 0.5 f make break = cm**make / cb**break ProbSAT.probsat solver opt def f ProbSAT.getBestSolution solver QM.monitor (counterexample (show (obj,sol))) QM.assert (bounds sol == (1, CNF.wcnfNumVars wcnf)) QM.assert (obj == evalWCNFCost sol wcnf) case_probSAT_case1 :: Assertion case_probSAT_case1 = do let cnf = CNF.CNF { CNF.cnfNumVars = 1 , CNF.cnfNumClauses = 2 , CNF.cnfClauses = map SAT.packClause [ [1,-1] , [] ] } solver <- ProbSAT.newSolver cnf let opt = def { ProbSAT.optTarget = 0 , ProbSAT.optMaxTries = 1 , ProbSAT.optMaxFlips = 10 } cb = 3.6 cm = 0.5 f make break = cm**make / cb**break ProbSAT.probsat solver opt def f probSATTestGroup :: TestTree probSATTestGroup = $(testGroupGenerator)
0a2972766506b11673f361bc3b01b4d499902e824e8c6a95338c1dd4bacdae97
iambrj/imin
functions_test_3.rkt
(define (car [x : (Vector Integer)]) : Integer (vector-ref x 0)) (car (vector 1))
null
https://raw.githubusercontent.com/iambrj/imin/f350276a35bff309e17fb03e41996dd2e550b789/tests/functions_test_3.rkt
racket
(define (car [x : (Vector Integer)]) : Integer (vector-ref x 0)) (car (vector 1))
ed1049c834e608004fba958c037ff20f415633bde573b158fd1db0c36403d0dc
stuartsierra/altlaw-backend
crawl.clj
(ns org.altlaw.jobs.web.crawl (:require [org.altlaw.extract.scrape.handler :as handler] [org.altlaw.util.log :as log] [org.altlaw.util.hadoop :as h] [org.altlaw.util.date :as date] [org.altlaw.util.crawler :as crawler] [org.altlaw.util.context :as context] [org.altlaw.db.download-log :as dl] [clojure.contrib.duck-streams :as duck]) (:import (java.net URI))) (h/setup-mapreduce) (defn my-map [line-number request] [[(.getHost (URI. (:request_uri request))), request]]) (defn handle-request [request] (let [response (crawler/handle-download-request request) code (:response_status_code response)] (h/counter "Response codes" code) (if (= 200 code) [response nil] (do (log/warn "HTTP response code " code " for " (:request_uri request)) nil)))) (defn my-reduce [host requests] (filter identity (map handle-request requests))) (def mapper-map (partial h/standard-map my-map)) (defn reducer-configure [this job] (context/use-hadoop-jobconf job)) (def reducer-reduce (partial h/standard-reduce my-reduce)) (defn reducer-close [this] (dl/save-download-log)) (defn tool-run [this args] (let [job (h/default-jobconf this) inpath (Path. (h/job-path :web :request)) outpath (Path. (h/job-path :web :crawl) (str "c-" (date/filename-timestamp))) hdfs (FileSystem/get job)] (.delete hdfs outpath true) (FileInputFormat/setInputPaths job (str inpath)) (FileOutputFormat/setOutputPath job outpath) (FileOutputFormat/setOutputCompressorClass job GzipCodec) (.setInputFormat job TextInputFormat) (.setOutputFormat job TextOutputFormat) (.setMapperClass job org.altlaw.jobs.web.crawl_mapper) (.setReducerClass job org.altlaw.jobs.web.crawl_reducer) (.setNumReduceTasks job 1) (.setJobName job "web.crawl") (JobClient/runJob job)) 0)
null
https://raw.githubusercontent.com/stuartsierra/altlaw-backend/c2ceeb0be2d622ca921339be06de5485733451bc/src/org/altlaw/jobs/web/crawl.clj
clojure
(ns org.altlaw.jobs.web.crawl (:require [org.altlaw.extract.scrape.handler :as handler] [org.altlaw.util.log :as log] [org.altlaw.util.hadoop :as h] [org.altlaw.util.date :as date] [org.altlaw.util.crawler :as crawler] [org.altlaw.util.context :as context] [org.altlaw.db.download-log :as dl] [clojure.contrib.duck-streams :as duck]) (:import (java.net URI))) (h/setup-mapreduce) (defn my-map [line-number request] [[(.getHost (URI. (:request_uri request))), request]]) (defn handle-request [request] (let [response (crawler/handle-download-request request) code (:response_status_code response)] (h/counter "Response codes" code) (if (= 200 code) [response nil] (do (log/warn "HTTP response code " code " for " (:request_uri request)) nil)))) (defn my-reduce [host requests] (filter identity (map handle-request requests))) (def mapper-map (partial h/standard-map my-map)) (defn reducer-configure [this job] (context/use-hadoop-jobconf job)) (def reducer-reduce (partial h/standard-reduce my-reduce)) (defn reducer-close [this] (dl/save-download-log)) (defn tool-run [this args] (let [job (h/default-jobconf this) inpath (Path. (h/job-path :web :request)) outpath (Path. (h/job-path :web :crawl) (str "c-" (date/filename-timestamp))) hdfs (FileSystem/get job)] (.delete hdfs outpath true) (FileInputFormat/setInputPaths job (str inpath)) (FileOutputFormat/setOutputPath job outpath) (FileOutputFormat/setOutputCompressorClass job GzipCodec) (.setInputFormat job TextInputFormat) (.setOutputFormat job TextOutputFormat) (.setMapperClass job org.altlaw.jobs.web.crawl_mapper) (.setReducerClass job org.altlaw.jobs.web.crawl_reducer) (.setNumReduceTasks job 1) (.setJobName job "web.crawl") (JobClient/runJob job)) 0)
2ef2965259ae497948875470751192435c0ec0c831f8981caca331a07b7532bd
alexlenail/Erlang-Shen
shen_print.erl
%% =================================================================== shen_print.erl %% %% Helper module for printing progress information for the user. %% %% =================================================================== -module(shen_print). %% API -export([title/2, event/2]). %% =================================================================== %% API Functions %% =================================================================== title(Text, Format) -> io:format("========================================~n"), io:format(Text, Format), io:format("========================================~n"), ok. event(Text, Format) -> io:format(Text, Format), ok.
null
https://raw.githubusercontent.com/alexlenail/Erlang-Shen/ddfcbab261865af0925b7aeb6866febeb7142d00/src/shen_print.erl
erlang
=================================================================== Helper module for printing progress information for the user. =================================================================== API =================================================================== API Functions ===================================================================
shen_print.erl -module(shen_print). -export([title/2, event/2]). title(Text, Format) -> io:format("========================================~n"), io:format(Text, Format), io:format("========================================~n"), ok. event(Text, Format) -> io:format(Text, Format), ok.