_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
7382dae5101c4d69144327fc51e76a3fb3fe84a0bdcf9bd9888c7daa72dafe83
LLNL/rhizome
algorithm.clj
(ns rhizome.turbotopics.algorithm "The actual Turbo Topics (style) algorithm" (:use [rhizome.turbotopics.util :only (not-nil?)]) (:use [rhizome.turbotopics.permtest :only (null-score)]) (:use [clojure.set :only (union)]) (:use [clojure.contrib.seq-utils :only (indexed)]) (:use [clojure.contrib.generic.math-functions :only (log exp)])) ;; Occurrence counts (defrecord OccurCounts [nuv nv nu sumv]) ;; A significant bigram (defrecord SigBigram [ngram count score]) (defn- corpus-unigram "Count topic unigrams" [topic positions] (frequencies (map :w (filter #(== topic (:z %1)) positions)))) ;; Turbo topics - log - likelihood ratio score of adding new word ;; (defn- safelog "Avoid NaN contamination of our calculations" [val] (if (zero? val) (double -100000000) (log val))) (defn- lr-score "Given counts and u, calculate score of v" [counts u v] (if (zero? (-> counts :nuv (get u) (get v 0))) (double -100000000) (let [;; Pre-fetch the necessary counts nuv (-> counts :nuv (get u) (get v)) nu (-> counts :nu (get u)) nv (-> counts :nv (get v)) sumv (:sumv counts) ;; P(v|u) under new lpi-vu-new (safelog (/ nuv nu)) ;; P(v ~| u) under new lpi-v-new (- (safelog (- nv nuv)) (safelog (- sumv nu))) ;; P(v) old lpi-v-old (safelog (/ nv sumv)) ;; P(v') - SHOULD THIS BE UPDATED - I THINK SO...? ln2 (safelog (- 1 (exp lpi-v-new))) ld2 (safelog (- 1 (exp lpi-v-old))) lgamma2 (- ln2 ld2) ;; gamma_u new scaling factor ;; ;; If we believe P(v') should be updated for v' != v, ;; then should mult old-style gamma_u by new gamma_{not u} ;; ( 1 - pi - v - new ) terms cancel , leaving 1 - pi - v - old in denom ;; lnumer (safelog (- 1 (exp lpi-vu-new))) ( ( - 1 ( exp lpi - v - new ) ) ) ldenom (safelog (- 1 (exp lpi-v-old))) lgamma (- lnumer ldenom)] ;; Calculate and return actual log-odds ratio (+ (* nuv lpi-vu-new) ;; bigram occur (* (- nv nuv) lpi-v-new) ;; unigram occur (* (- nu nuv) lgamma) ;; re-normalized uv' for v' != v (* (- (- sumv nv) nu) lgamma2) ;; re-normalized v' for v' != v and not u (* -1 nv lpi-v-old))))) ;; previous unigram occur (defn root-candidates "Any root term occuring > minu times is a bigram root candidate" [counts minu] (filter #(> (-> counts :nu (get %1 0)) minu) (keys (:nu counts)))) (defn second-candidates "Second terms must occur > minv times to be bigram second candidates" [counts u minv] (filter #(> (-> counts :nuv (get u) (get %1 0)) minv) (keys (-> counts :nuv (get u))))) (defn- get-sig-bigrams "For a given u, get significant v according to like ratio (eq4)" [params counts u] (let [candterms (second-candidates counts u (:minv params)) scorer (partial lr-score counts u) sighits (filter #(> (scorer %1) (:thresh params)) candterms)] sighits)) (defn- process-root-word "Generate significant uv bigrams from root word u" [params counts u] (set (map #(vector u %1) (get-sig-bigrams params counts u)))) (defn process-topic "EXT CALLED: for a topic, find significant bigrams and scores (uses pmap)" [params counts vocab] (let [rootcand (root-candidates counts (:minu params)) ;; candidate root word sigbigrams (apply union (pmap #(process-root-word params counts %1) rootcand))] (for [[u v] sigbigrams] (SigBigram. (str (vocab u) " " (vocab v)) (-> counts :nuv (get u) (get v)) (lr-score counts u v)))))
null
https://raw.githubusercontent.com/LLNL/rhizome/af8e00ac89a98e2d07fe7a6272857951c2781182/src/rhizome/turbotopics/algorithm.clj
clojure
Occurrence counts A significant bigram Pre-fetch the necessary counts P(v|u) under new P(v ~| u) under new P(v) old P(v') - SHOULD THIS BE UPDATED - I THINK SO...? gamma_u new scaling factor If we believe P(v') should be updated for v' != v, then should mult old-style gamma_u by new gamma_{not u} Calculate and return actual log-odds ratio bigram occur unigram occur re-normalized uv' for v' != v re-normalized v' for v' != v and not u previous unigram occur candidate root word
(ns rhizome.turbotopics.algorithm "The actual Turbo Topics (style) algorithm" (:use [rhizome.turbotopics.util :only (not-nil?)]) (:use [rhizome.turbotopics.permtest :only (null-score)]) (:use [clojure.set :only (union)]) (:use [clojure.contrib.seq-utils :only (indexed)]) (:use [clojure.contrib.generic.math-functions :only (log exp)])) (defrecord OccurCounts [nuv nv nu sumv]) (defrecord SigBigram [ngram count score]) (defn- corpus-unigram "Count topic unigrams" [topic positions] (frequencies (map :w (filter #(== topic (:z %1)) positions)))) Turbo topics - log - likelihood ratio score of adding new word (defn- safelog "Avoid NaN contamination of our calculations" [val] (if (zero? val) (double -100000000) (log val))) (defn- lr-score "Given counts and u, calculate score of v" [counts u v] (if (zero? (-> counts :nuv (get u) (get v 0))) (double -100000000) nuv (-> counts :nuv (get u) (get v)) nu (-> counts :nu (get u)) nv (-> counts :nv (get v)) sumv (:sumv counts) lpi-vu-new (safelog (/ nuv nu)) lpi-v-new (- (safelog (- nv nuv)) (safelog (- sumv nu))) lpi-v-old (safelog (/ nv sumv)) ln2 (safelog (- 1 (exp lpi-v-new))) ld2 (safelog (- 1 (exp lpi-v-old))) lgamma2 (- ln2 ld2) ( 1 - pi - v - new ) terms cancel , leaving 1 - pi - v - old in denom lnumer (safelog (- 1 (exp lpi-vu-new))) ( ( - 1 ( exp lpi - v - new ) ) ) ldenom (safelog (- 1 (exp lpi-v-old))) lgamma (- lnumer ldenom)] (* (- nu nuv) lgamma) (* (- (- sumv nv) nu) (defn root-candidates "Any root term occuring > minu times is a bigram root candidate" [counts minu] (filter #(> (-> counts :nu (get %1 0)) minu) (keys (:nu counts)))) (defn second-candidates "Second terms must occur > minv times to be bigram second candidates" [counts u minv] (filter #(> (-> counts :nuv (get u) (get %1 0)) minv) (keys (-> counts :nuv (get u))))) (defn- get-sig-bigrams "For a given u, get significant v according to like ratio (eq4)" [params counts u] (let [candterms (second-candidates counts u (:minv params)) scorer (partial lr-score counts u) sighits (filter #(> (scorer %1) (:thresh params)) candterms)] sighits)) (defn- process-root-word "Generate significant uv bigrams from root word u" [params counts u] (set (map #(vector u %1) (get-sig-bigrams params counts u)))) (defn process-topic "EXT CALLED: for a topic, find significant bigrams and scores (uses pmap)" [params counts vocab] sigbigrams (apply union (pmap #(process-root-word params counts %1) rootcand))] (for [[u v] sigbigrams] (SigBigram. (str (vocab u) " " (vocab v)) (-> counts :nuv (get u) (get v)) (lr-score counts u v)))))
76a9cdb14d065e9ddff5ac34417efed59b7f0a414d171e35f4161159c8563d07
runeksvendsen/bitcoin-payment-channel
PubKey.hs
{-# LANGUAGE DeriveGeneric #-} # LANGUAGE GeneralizedNewtypeDeriving # module PaymentChannel.Internal.Crypto.PubKey ( IsPubKey(..) , SendPubKey(..) , RecvPubKey(..) , HasSendPubKey(..) , HasRecvPubKey(..) ) where import Data.Word (Word32) import qualified Network.Haskoin.Crypto as HC import PaymentChannel.Internal.Util -- |Types which contain a pubkey class Serialize a => IsPubKey a where getPubKey :: a -> HC.PubKeyC instance IsPubKey HC.PubKeyC where getPubKey = id -- |Wrapper for value sender's public key newtype SendPubKey = MkSendPubKey { getSenderPK :: HC.PubKeyC } deriving (Eq, Show, Serialize, Generic, FromJSON, ToJSON, NFData) instance IsPubKey SendPubKey where getPubKey = getSenderPK -- |Wrapper for value receiver's public key newtype RecvPubKey = MkRecvPubKey { getReceiverPK :: HC.PubKeyC } deriving (Eq, Show, Serialize, Generic, FromJSON, ToJSON, NFData) instance IsPubKey RecvPubKey where getPubKey = getReceiverPK instance IsPubKey HC.XPubKey where getPubKey = HC.xPubKey -- |Types which contain a 'SendPubKey' class HasSendPubKey a where getSendPubKey :: a -> SendPubKey class HasRecvPubKey a where getRecvPubKey :: a -> RecvPubKey
null
https://raw.githubusercontent.com/runeksvendsen/bitcoin-payment-channel/3d2ee56c027571d1a86092c317640e5eae7adde3/src/PaymentChannel/Internal/Crypto/PubKey.hs
haskell
# LANGUAGE DeriveGeneric # |Types which contain a pubkey |Wrapper for value sender's public key |Wrapper for value receiver's public key |Types which contain a 'SendPubKey'
# LANGUAGE GeneralizedNewtypeDeriving # module PaymentChannel.Internal.Crypto.PubKey ( IsPubKey(..) , SendPubKey(..) , RecvPubKey(..) , HasSendPubKey(..) , HasRecvPubKey(..) ) where import Data.Word (Word32) import qualified Network.Haskoin.Crypto as HC import PaymentChannel.Internal.Util class Serialize a => IsPubKey a where getPubKey :: a -> HC.PubKeyC instance IsPubKey HC.PubKeyC where getPubKey = id newtype SendPubKey = MkSendPubKey { getSenderPK :: HC.PubKeyC } deriving (Eq, Show, Serialize, Generic, FromJSON, ToJSON, NFData) instance IsPubKey SendPubKey where getPubKey = getSenderPK newtype RecvPubKey = MkRecvPubKey { getReceiverPK :: HC.PubKeyC } deriving (Eq, Show, Serialize, Generic, FromJSON, ToJSON, NFData) instance IsPubKey RecvPubKey where getPubKey = getReceiverPK instance IsPubKey HC.XPubKey where getPubKey = HC.xPubKey class HasSendPubKey a where getSendPubKey :: a -> SendPubKey class HasRecvPubKey a where getRecvPubKey :: a -> RecvPubKey
fe083891bf47471c29b89ca0d57e36e53bfcde88e9617ac1806501649613fdc5
elisehuard/game-in-haskell
Backend.hs
{-# LANGUAGE PackageImports #-} module Hunted.Backend ( withWindow , readInput , exitKeyPressed , swapBuffers ) where import "GLFW-b" Graphics.UI.GLFW as GLFW import Control.Monad (when) import Control.Applicative ((<$>), (<*>)) --withWindow :: Int -> Int -> String -> (GLFW.Window -> IO ()) -> IO () withWindow :: Int -> Int -> ((Int, Int) -> IO ()) -> String -> (Window -> IO a) -> IO () withWindow width height windowSizeSink title f = do GLFW.setErrorCallback $ Just simpleErrorCallback r <- GLFW.init when r $ do m <- GLFW.createWindow width height title Nothing Nothing case m of (Just win) -> do GLFW.makeContextCurrent m setWindowSizeCallback win $ Just $ resize windowSizeSink _ <- f win GLFW.setErrorCallback $ Just simpleErrorCallback GLFW.destroyWindow win Nothing -> return () GLFW.terminate where simpleErrorCallback e s = putStrLn $ unwords [show e, show s] resize :: ((Int, Int) -> IO()) -> Window -> Int -> Int -> IO() resize windowSizeSink _ w h = windowSizeSink (w, h) keyIsPressed :: Window -> Key -> IO Bool keyIsPressed win key = isPress `fmap` GLFW.getKey win key isPress :: KeyState -> Bool isPress KeyState'Pressed = True isPress KeyState'Repeating = True isPress _ = False readInput :: Window -> ((Bool, Bool, Bool, Bool) -> IO ()) -> ((Bool, Bool, Bool, Bool) -> IO ()) -> IO () readInput window directionKeySink shootKeySink = do pollEvents l <- keyIsPressed window Key'Left r <- keyIsPressed window Key'Right u <- keyIsPressed window Key'Up d <- keyIsPressed window Key'Down directionKeySink (l, r, u, d) shootKeySink =<< (,,,) <$> keyIsPressed window Key'A <*> keyIsPressed window Key'D <*> keyIsPressed window Key'W <*> keyIsPressed window Key'S exitKeyPressed :: Window -> IO Bool exitKeyPressed window = keyIsPressed window Key'Escape
null
https://raw.githubusercontent.com/elisehuard/game-in-haskell/b755c42d63ff5dc9246b46590fb23ebcc1d455b1/src/Hunted/Backend.hs
haskell
# LANGUAGE PackageImports # withWindow :: Int -> Int -> String -> (GLFW.Window -> IO ()) -> IO ()
module Hunted.Backend ( withWindow , readInput , exitKeyPressed , swapBuffers ) where import "GLFW-b" Graphics.UI.GLFW as GLFW import Control.Monad (when) import Control.Applicative ((<$>), (<*>)) withWindow :: Int -> Int -> ((Int, Int) -> IO ()) -> String -> (Window -> IO a) -> IO () withWindow width height windowSizeSink title f = do GLFW.setErrorCallback $ Just simpleErrorCallback r <- GLFW.init when r $ do m <- GLFW.createWindow width height title Nothing Nothing case m of (Just win) -> do GLFW.makeContextCurrent m setWindowSizeCallback win $ Just $ resize windowSizeSink _ <- f win GLFW.setErrorCallback $ Just simpleErrorCallback GLFW.destroyWindow win Nothing -> return () GLFW.terminate where simpleErrorCallback e s = putStrLn $ unwords [show e, show s] resize :: ((Int, Int) -> IO()) -> Window -> Int -> Int -> IO() resize windowSizeSink _ w h = windowSizeSink (w, h) keyIsPressed :: Window -> Key -> IO Bool keyIsPressed win key = isPress `fmap` GLFW.getKey win key isPress :: KeyState -> Bool isPress KeyState'Pressed = True isPress KeyState'Repeating = True isPress _ = False readInput :: Window -> ((Bool, Bool, Bool, Bool) -> IO ()) -> ((Bool, Bool, Bool, Bool) -> IO ()) -> IO () readInput window directionKeySink shootKeySink = do pollEvents l <- keyIsPressed window Key'Left r <- keyIsPressed window Key'Right u <- keyIsPressed window Key'Up d <- keyIsPressed window Key'Down directionKeySink (l, r, u, d) shootKeySink =<< (,,,) <$> keyIsPressed window Key'A <*> keyIsPressed window Key'D <*> keyIsPressed window Key'W <*> keyIsPressed window Key'S exitKeyPressed :: Window -> IO Bool exitKeyPressed window = keyIsPressed window Key'Escape
b80e37190645c818c36ab633b366b21aef04a2c01136a6010312881289027d16
minoki/yurumath
Execution.hs
{-# LANGUAGE RankNTypes #-} # LANGUAGE FlexibleContexts # # LANGUAGE FlexibleInstances # # LANGUAGE MultiParamTypeClasses # # LANGUAGE UndecidableInstances # # LANGUAGE DataKinds # {-# LANGUAGE GADTs #-} # LANGUAGE ScopedTypeVariables # module Text.YuruMath.TeX.Execution (readRegIndex ,Assignment ,runLocal ,runGlobal ,texAssign ,arithmeticInteger ,arithmeticQuantity ,CommonExecutable(..) ,executableDefinitions ) where import Text.YuruMath.TeX.Types import Text.YuruMath.TeX.Meaning import Text.YuruMath.TeX.Quantity import Text.YuruMath.TeX.State import Text.YuruMath.TeX.Expansion import Data.Text (Text) import qualified Data.Map.Strict as Map import Control.Monad.Error.Class import Control.Lens.Lens (Lens') import Control.Lens.At (at) import Control.Lens.Getter (use,uses) import Control.Lens.Setter (assign,mapped,ASetter) import Data.OpenUnion import TypeFun.Data.List (SubList) -- Used by \count, \countdef, etc 8 - bit ( 0 - 255 ) on the original TeX , 15 - bit ( 0 - 32767 ) on e - TeX , and 16 - bit ( 0 - 65535 ) on LuaTeX readRegIndex :: (MonadTeXState s m, MonadError String m) => m Int readRegIndex = do x <- readIntBetween minBound maxBound if x < 0 || 65536 <= x then throwError $ "Bad register code (" ++ show x ++ ")" else return x data Assignment s where WillAssign :: ASetter (LocalState s) (LocalState s) b b -> !b -> Assignment s runLocal, runGlobal :: (MonadTeXState s m) => m (Assignment s) -> m () runLocal m = do WillAssign setter value <- m assign (localState . setter) value runGlobal m = do WillAssign setter value <- m assign (localStates . mapped . setter) value texAssign :: (MonadTeXState s m) => ASetter (LocalState s) (LocalState s) b b -> b -> m (Assignment s) texAssign setter !value = return (WillAssign setter value) globalCommand :: (MonadTeXState s m, MonadError String m, Meaning (NValue s)) => m () globalCommand = do (_,v) <- required nextExpandedToken case toCommonValue v of Just Relax -> globalCommand -- ignore \relax Just (Character _ CCSpace) -> globalCommand -- ignore spaces _ -> case doGlobal v of Just m -> m Nothing -> invalidPrefix "global" v letCommand :: (MonadTeXState s m, MonadError String m) => m (Assignment s) letCommand = do name <- readCommandName readUnexpandedEquals readUnexpandedOneOptionalSpace v <- required nextUnexpandedToken >>= meaningWithoutExpansion texAssign (definitionAt name) v futureletCommand :: (MonadTeXState s m, MonadError String m) => m (Assignment s) futureletCommand = do name <- readCommandName t1 <- required nextUnexpandedToken t2 <- required nextUnexpandedToken unreadTokens' [t1,t2] v <- meaningWithoutExpansion t2 texAssign (definitionAt name) v mapChar :: (Char -> Char) -> ExpansionToken -> ExpansionToken mapChar f t@(ETCharacter { etChar = c }) | let d = f c, d /= '\0' = t { etChar = d } mapChar f t@(ETCommandName { etName = NActiveChar c }) | let d = f c, d /= '\0' = t { etFlavor = ECNFPlain, etName = NActiveChar d } -- strip 'isrelax' flag or 'noexpand' flag mapChar _ t@(ETCommandName { etFlavor = ECNFIsRelax }) = t { etFlavor = ECNFPlain } -- strip 'isrelax' flag mapChar _ t@(ETCommandName { etFlavor = ECNFNoexpand }) = t { etFlavor = ECNFPlain } -- strip 'noexpand' flag mapChar _ t = t uppercaseCommand :: (MonadTeXState s m, MonadError String m) => m () uppercaseCommand = do text <- readUnexpandedGeneralTextE toUpper <- ucCodeFn unreadTokens' (map (mapChar toUpper) text) lowercaseCommand :: (MonadTeXState s m, MonadError String m) => m () lowercaseCommand = do text <- readUnexpandedGeneralTextE toLower <- lcCodeFn unreadTokens' (map (mapChar toLower) text) ignorespacesCommand :: (MonadTeXState s m, MonadError String m) => m () ignorespacesCommand = do readOptionalSpaces \chardef < control sequence><equals><number > chardefCommand :: (MonadTeXState s m, MonadError String m) => m (Assignment s) chardefCommand = do name <- readCommandName readEquals c <- readUnicodeScalarValue let w = DefinedCharacter c texAssign (definitionAt name) (nonexpandableToValue w) -- \mathchardef<control sequence><equals><15-bit number> mathchardefCommand :: (MonadTeXState s m, MonadError String m) => m (Assignment s) mathchardefCommand = do name <- readCommandName readEquals v <- readIntBetween 0 0x8000 -- "Bad math code (" ++ show v ++ ")" let w = DefinedMathCharacter (MathCode (fromIntegral v)) texAssign (definitionAt name) (nonexpandableToValue w) -- \Umathchardef<control sequence><equals><3-bit number><8-bit number><21-bit number> umathchardefCommand :: (MonadTeXState s m, MonadError String m) => m (Assignment s) umathchardefCommand = do name <- readCommandName readEquals w <- readUMathCodeTriplet texAssign (definitionAt name) (nonexpandableToValue $ DefinedMathCharacter w) -- \Umathcharnumdef<control sequence><equals><32-bit number> umathcharnumdefCommand :: (MonadTeXState s m, MonadError String m) => m (Assignment s) umathcharnumdefCommand = do name <- readCommandName readEquals w <- readUMathCode32 texAssign (definitionAt name) (nonexpandableToValue $ DefinedMathCharacter w) intdefCommand :: (MonadTeXState s m, MonadError String m) => m (Assignment s) intdefCommand = do name <- readCommandName readEquals value <- readInt32 texAssign (definitionAt name) (nonexpandableToValue $ IntegerConstant value) catcodeGet :: (MonadTeXState s m, MonadError String m) => m Integer catcodeGet = do slot <- readUnicodeScalarValue (fromIntegral . fromEnum) <$> categoryCodeOf slot -- \catcode<21-bit number><equals><4-bit number> catcodeSet :: (MonadTeXState s m, MonadError String m) => m (Assignment s) catcodeSet = do slot <- readUnicodeScalarValue readEquals " Invalid code ( " + + show v + + " ) , should be in the range 0 .. 15 . " let w = toEnum v texAssign (catcodeMap . at slot) (Just w) lccodeGet :: (MonadTeXState s m, MonadError String m) => m Integer lccodeGet = do slot <- readUnicodeScalarValue (fromIntegral . fromEnum) <$> lcCodeOf slot -- \lccode<21-bit number><equals><21-bit number> lccodeSet :: (MonadTeXState s m, MonadError String m) => m (Assignment s) lccodeSet = do slot <- readUnicodeScalarValue readEquals v <- readUnicodeScalarValue texAssign (lccodeMap . at slot) (Just v) uccodeGet :: (MonadTeXState s m, MonadError String m) => m Integer uccodeGet = do slot <- readUnicodeScalarValue (fromIntegral . fromEnum) <$> ucCodeOf slot -- \uccode<21-bit number><equals><21-bit number> uccodeSet :: (MonadTeXState s m, MonadError String m) => m (Assignment s) uccodeSet = do slot <- readUnicodeScalarValue readEquals v <- readUnicodeScalarValue texAssign (uccodeMap . at slot) (Just v) mathcodeGet :: (MonadTeXState s m, MonadError String m) => m Integer mathcodeGet = do slot <- readUnicodeScalarValue mathcodeToInt <$> mathCodeOf slot where mathcodeToInt (MathCode x) = fromIntegral x mathcodeToInt (UMathCode x) = fromIntegral x -- \mathcode<21-bit number><equals><15-bit number> mathcodeSet :: (MonadTeXState s m, MonadError String m) => m (Assignment s) mathcodeSet = do slot <- readUnicodeScalarValue readEquals v <- readIntBetween 0 0x8000 -- "Bad math code (" ++ show v ++ ")" let w = MathCode (fromIntegral v) texAssign (mathcodeMap . at slot) (Just w) -- \Umathcode<21-bit number><equals><3-bit number><8-bit number><21-bit number> umathcodeSet :: (MonadTeXState s m, MonadError String m) => m (Assignment s) umathcodeSet = do slot <- readUnicodeScalarValue readEquals w <- readUMathCodeTriplet texAssign (mathcodeMap . at slot) (Just w) -- \Umathcodenum<21-bit number><equals><32-bit number> umathcodenumSet :: (MonadTeXState s m, MonadError String m) => m (Assignment s) umathcodenumSet = do slot <- readUnicodeScalarValue readEquals w <- readUMathCode32 texAssign (mathcodeMap . at slot) (Just w) delcodeGet :: (MonadTeXState s m, MonadError String m) => m Integer delcodeGet = do slot <- readUnicodeScalarValue delcodeToInt <$> delimiterCodeOf slot where delcodeToInt (DelimiterCode x) = fromIntegral x delcodeToInt (UDelimiterCode x) = fromIntegral x -- \delcode<21-bit number><equals><24-bit number> delcodeSet :: (MonadTeXState s m, MonadError String m) => m (Assignment s) delcodeSet = do slot <- readUnicodeScalarValue readEquals " Invalid delimiter code . " let w = DelimiterCode (fromIntegral v) texAssign (delcodeMap . at slot) (Just w) -- \Udelcode<21-bit number><equals><8-bit number><21-bit number> udelcodeSet :: (MonadTeXState s m, MonadError String m) => m (Assignment s) udelcodeSet = do slot <- readUnicodeScalarValue readEquals w <- readUDelimiterCodePair texAssign (delcodeMap . at slot) (Just w) -- \Udelcodenum<21-bit number><equals><32-bit number> udelcodenumSet :: (MonadTeXState s m, MonadError String m) => m (Assignment s) udelcodenumSet = do slot <- readUnicodeScalarValue readEquals w <- readUDelimiterCode32 texAssign (delcodeMap . at slot) (Just w) endlinecharGet :: (MonadTeXState s m, MonadError String m) => m Integer endlinecharGet = do uses (localState . endlinechar) fromIntegral endlinecharSet :: (MonadTeXState s m, MonadError String m) => m (Assignment s) endlinecharSet = do readEquals value <- readIntBetween minBound maxBound texAssign endlinechar value escapecharGet :: (MonadTeXState s m, MonadError String m) => m Integer escapecharGet = do uses (localState . escapechar) fromIntegral escapecharSet :: (MonadTeXState s m, MonadError String m) => m (Assignment s) escapecharSet = do readEquals value <- readIntBetween minBound maxBound texAssign escapechar value begingroupCommand :: (MonadTeXState s m, MonadError String m) => m () begingroupCommand = do enterGroup ScopeByBeginGroup endgroupCommand :: (MonadTeXState s m, MonadError String m) => m () endgroupCommand = do leaveGroup ScopeByBeginGroup advanceCommand :: (MonadTeXState s m, MonadError String m) => Bool -> m () advanceCommand !global = do (et,v) <- required nextExpandedToken case doArithmetic v of Just m -> do n <- if global then arithmeticGlobalAdvance <$> m else arithmeticLocalAdvance <$> m readOptionalKeyword "by" n Nothing -> throwError $ "You can't use " ++ show et ++ " after \\advance" multiplyCommand :: (MonadTeXState s m, MonadError String m) => Bool -> m () multiplyCommand !global = do (et,v) <- required nextExpandedToken case doArithmetic v of Just m -> do n <- if global then arithmeticGlobalMultiply <$> m else arithmeticLocalMultiply <$> m readOptionalKeyword "by" n Nothing -> throwError $ "You can't use " ++ show et ++ " after \\multiply" divideCommand :: (MonadTeXState s m, MonadError String m) => Bool -> m () divideCommand !global = do (et,v) <- required nextExpandedToken case doArithmetic v of Just m -> do n <- if global then arithmeticGlobalDivide <$> m else arithmeticLocalDivide <$> m readOptionalKeyword "by" n Nothing -> throwError $ "You can't use " ++ show et ++ " after \\divide" advanceInteger :: (MonadTeXState s m, MonadError String m, IntegralB i) => Lens' (LocalState s) i -> m (Assignment s) advanceInteger l = do value <- use (localState . l) arg <- readNumber case maybeFromInteger (fromIntegral value + arg) of Just value' -> texAssign l (fromInteger value') Nothing -> throwError "Arithmetic overflow" advanceQuantity :: (MonadTeXState s m, MonadError String m, QuantityRead q) => Lens' (LocalState s) q -> m (Assignment s) advanceQuantity l = do value <- use (localState . l) arg <- readQuantity texAssign l (value <+> arg) multiplyInteger :: (MonadTeXState s m, MonadError String m, IntegralB i) => Lens' (LocalState s) i -> m (Assignment s) multiplyInteger l = do value <- use (localState . l) arg <- readNumber case maybeFromInteger (fromIntegral value * arg) of Just value' -> texAssign l (fromInteger value') Nothing -> throwError "Arithmetic overflow" multiplyQuantity :: (MonadTeXState s m, MonadError String m, Quantity q) => Lens' (LocalState s) q -> m (Assignment s) multiplyQuantity l = do value <- use (localState . l) arg <- readNumber texAssign l (scaleAsInteger (* arg) value) divideInteger :: (MonadTeXState s m, MonadError String m, IntegralB i) => Lens' (LocalState s) i -> m (Assignment s) divideInteger l = do value <- use (localState . l) arg <- readNumber if arg == 0 says " Arithmetic overflow . " else case maybeFromInteger (fromIntegral value `quot` arg) of Just value' -> texAssign l (fromInteger value') Nothing -> throwError "Arithmetic overflow" divideQuantity :: (MonadTeXState s m, MonadError String m, Quantity q) => Lens' (LocalState s) q -> m (Assignment s) divideQuantity l = do value <- use (localState . l) arg <- readNumber if arg == 0 then throwError "Divide by zero" else texAssign l (scaleAsInteger (`quot` arg) value) arithmeticInteger :: (MonadTeXState s m, MonadError String m, IntegralB i) => Lens' (LocalState s) i -> m (Arithmetic m) arithmeticInteger l = pure $ Arithmetic { arithmeticLocalAdvance = runLocal $ advanceInteger l , arithmeticGlobalAdvance = runGlobal $ advanceInteger l , arithmeticLocalMultiply = runLocal $ multiplyInteger l , arithmeticGlobalMultiply = runGlobal $ multiplyInteger l , arithmeticLocalDivide = runLocal $ divideInteger l , arithmeticGlobalDivide = runGlobal $ divideInteger l } arithmeticQuantity :: (MonadTeXState s m, MonadError String m, QuantityRead q) => Lens' (LocalState s) q -> m (Arithmetic m) arithmeticQuantity l = pure $ Arithmetic { arithmeticLocalAdvance = runLocal $ advanceQuantity l , arithmeticGlobalAdvance = runGlobal $ advanceQuantity l , arithmeticLocalMultiply = runLocal $ multiplyQuantity l , arithmeticGlobalMultiply = runGlobal $ multiplyQuantity l , arithmeticLocalDivide = runLocal $ divideQuantity l , arithmeticGlobalDivide = runGlobal $ divideQuantity l } data CommonExecutable = Eglobal | Elet | Efuturelet | Euppercase | Elowercase | Eignorespaces | Echardef | Emathchardef | EUmathchardef | EUmathcharnumdef | EYuruMathIntDef | Ecatcode | Elccode | Euccode | Emathcode | Edelcode | EUmathcode | EUmathcodenum | EUdelcode | EUdelcodenum | Ebegingroup | Eendgroup | Eendlinechar | Eescapechar | Eadvance | Emultiply | Edivide deriving (Eq,Show,Enum,Bounded) instance IsPrimitive CommonExecutable where primitiveName Eglobal = "global" primitiveName Elet = "let" primitiveName Efuturelet = "futurelet" primitiveName Euppercase = "uppercase" primitiveName Elowercase = "lowercase" primitiveName Eignorespaces = "ignorespaces" primitiveName Echardef = "chardef" primitiveName Emathchardef = "mathchardef" primitiveName EUmathchardef = "Umathchardef" primitiveName EUmathcharnumdef = "Umathcharnumdef" primitiveName EYuruMathIntDef = "YuruMathIntDef" primitiveName Ecatcode = "catcode" primitiveName Elccode = "lccode" primitiveName Euccode = "uccode" primitiveName Emathcode = "mathcode" primitiveName Edelcode = "delcode" primitiveName EUmathcode = "Umathcode" primitiveName EUmathcodenum = "Umathcodenum" primitiveName EUdelcode = "Udelcode" primitiveName EUdelcodenum = "Udelcodenum" primitiveName Ebegingroup = "begingroup" primitiveName Eendgroup = "endgroup" primitiveName Eendlinechar = "endlinechar" primitiveName Eescapechar = "escapechar" primitiveName Eadvance = "advance" primitiveName Emultiply = "multiply" primitiveName Edivide = "divide" instance Meaning CommonExecutable instance (Monad m, MonadTeXState s m, MonadError String m, Meaning (NValue s)) => DoExecute CommonExecutable m where doExecute Eglobal = globalCommand doExecute Elet = runLocal letCommand doExecute Efuturelet = runLocal futureletCommand doExecute Echardef = runLocal chardefCommand doExecute Emathchardef = runLocal mathchardefCommand doExecute EUmathchardef = runLocal umathchardefCommand doExecute EUmathcharnumdef = runLocal umathcharnumdefCommand doExecute EYuruMathIntDef = runLocal intdefCommand doExecute Ecatcode = runLocal catcodeSet doExecute Elccode = runLocal lccodeSet doExecute Euccode = runLocal uccodeSet doExecute Emathcode = runLocal mathcodeSet doExecute Edelcode = runLocal delcodeSet doExecute EUmathcode = runLocal umathcodeSet doExecute EUmathcodenum = runLocal umathcodenumSet doExecute EUdelcode = runLocal udelcodeSet doExecute EUdelcodenum = runLocal udelcodenumSet doExecute Eendlinechar = runLocal endlinecharSet doExecute Eescapechar = runLocal escapecharSet doExecute Euppercase = uppercaseCommand doExecute Elowercase = lowercaseCommand doExecute Ebegingroup = begingroupCommand doExecute Eendgroup = endgroupCommand doExecute Eignorespaces = ignorespacesCommand doExecute Eadvance = advanceCommand False doExecute Emultiply = multiplyCommand False doExecute Edivide = divideCommand False doGlobal Eglobal = Just globalCommand doGlobal Elet = Just $ runGlobal letCommand doGlobal Efuturelet = Just $ runGlobal futureletCommand doGlobal Echardef = Just $ runGlobal chardefCommand doGlobal Emathchardef = Just $ runGlobal mathchardefCommand doGlobal EUmathchardef = Just $ runGlobal umathchardefCommand doGlobal EUmathcharnumdef = Just $ runGlobal umathcharnumdefCommand doGlobal EYuruMathIntDef = Just $ runGlobal intdefCommand doGlobal Ecatcode = Just $ runGlobal catcodeSet doGlobal Elccode = Just $ runGlobal lccodeSet doGlobal Euccode = Just $ runGlobal uccodeSet doGlobal Emathcode = Just $ runGlobal mathcodeSet doGlobal Edelcode = Just $ runGlobal delcodeSet doGlobal EUmathcode = Just $ runGlobal umathcodeSet doGlobal EUmathcodenum = Just $ runGlobal umathcodenumSet doGlobal EUdelcode = Just $ runGlobal udelcodeSet doGlobal EUdelcodenum = Just $ runGlobal udelcodenumSet doGlobal Eendlinechar = Just $ runGlobal endlinecharSet doGlobal Eescapechar = Just $ runGlobal escapecharSet doGlobal Eadvance = Just $ advanceCommand True doGlobal Emultiply = Just $ multiplyCommand True doGlobal Edivide = Just $ divideCommand True doGlobal _ = Nothing doArithmetic Eendlinechar = Just $ arithmeticInteger endlinechar doArithmetic Eescapechar = Just $ arithmeticInteger escapechar doArithmetic _ = Nothing getQuantity Ecatcode = QInteger catcodeGet getQuantity Elccode = QInteger lccodeGet getQuantity Euccode = QInteger uccodeGet getQuantity Emathcode = QInteger mathcodeGet getQuantity Edelcode = QInteger delcodeGet getQuantity EUmathcode = QInteger mathcodeGet -- Same as \mathcode getQuantity EUmathcodenum = QInteger mathcodeGet -- Same as \mathcode getQuantity EUdelcode = QInteger delcodeGet -- Same as \delcode getQuantity EUdelcodenum = QInteger delcodeGet -- Same as \delcode getQuantity Eendlinechar = QInteger endlinecharGet getQuantity Eescapechar = QInteger escapecharGet getQuantity _ = NotQuantity executableDefinitions :: (SubList '[CommonValue,CommonExecutable] set) => Map.Map Text (Union set) executableDefinitions = Map.fromList [("relax", liftUnion Relax) ,("endcsname", liftUnion Endcsname) ,("global", liftUnion Eglobal) ,("let", liftUnion Elet) ,("futurelet", liftUnion Efuturelet) ,("uppercase", liftUnion Euppercase) ,("lowercase", liftUnion Elowercase) ,("ignorespaces", liftUnion Eignorespaces) ,("chardef", liftUnion Echardef) ,("mathchardef", liftUnion Emathchardef) ,("Umathchardef", liftUnion EUmathchardef) ,("Umathcharnumdef",liftUnion EUmathcharnumdef) ,("YuruMathIntDef", liftUnion EYuruMathIntDef) ,("catcode", liftUnion Ecatcode) ,("lccode", liftUnion Elccode) ,("uccode", liftUnion Euccode) ,("mathcode", liftUnion Emathcode) ,("delcode", liftUnion Edelcode) ,("Umathcode", liftUnion EUmathcode) ,("Umathcodenum", liftUnion EUmathcodenum) ,("Udelcode", liftUnion EUdelcode) ,("Udelcodenum", liftUnion EUdelcodenum) ,("begingroup", liftUnion Ebegingroup) ,("endgroup", liftUnion Eendgroup) ,("endlinechar", liftUnion Eendlinechar) ,("escapechar", liftUnion Eescapechar) ,("advance", liftUnion Eadvance) ,("multiply", liftUnion Emultiply) ,("divide", liftUnion Edivide) ]
null
https://raw.githubusercontent.com/minoki/yurumath/8529390f351654b3ea3157e2852497d0d09e7601/src/Text/YuruMath/TeX/Execution.hs
haskell
# LANGUAGE RankNTypes # # LANGUAGE GADTs # Used by \count, \countdef, etc ignore \relax ignore spaces strip 'isrelax' flag or 'noexpand' flag strip 'isrelax' flag strip 'noexpand' flag \mathchardef<control sequence><equals><15-bit number> "Bad math code (" ++ show v ++ ")" \Umathchardef<control sequence><equals><3-bit number><8-bit number><21-bit number> \Umathcharnumdef<control sequence><equals><32-bit number> \catcode<21-bit number><equals><4-bit number> \lccode<21-bit number><equals><21-bit number> \uccode<21-bit number><equals><21-bit number> \mathcode<21-bit number><equals><15-bit number> "Bad math code (" ++ show v ++ ")" \Umathcode<21-bit number><equals><3-bit number><8-bit number><21-bit number> \Umathcodenum<21-bit number><equals><32-bit number> \delcode<21-bit number><equals><24-bit number> \Udelcode<21-bit number><equals><8-bit number><21-bit number> \Udelcodenum<21-bit number><equals><32-bit number> Same as \mathcode Same as \mathcode Same as \delcode Same as \delcode
# LANGUAGE FlexibleContexts # # LANGUAGE FlexibleInstances # # LANGUAGE MultiParamTypeClasses # # LANGUAGE UndecidableInstances # # LANGUAGE DataKinds # # LANGUAGE ScopedTypeVariables # module Text.YuruMath.TeX.Execution (readRegIndex ,Assignment ,runLocal ,runGlobal ,texAssign ,arithmeticInteger ,arithmeticQuantity ,CommonExecutable(..) ,executableDefinitions ) where import Text.YuruMath.TeX.Types import Text.YuruMath.TeX.Meaning import Text.YuruMath.TeX.Quantity import Text.YuruMath.TeX.State import Text.YuruMath.TeX.Expansion import Data.Text (Text) import qualified Data.Map.Strict as Map import Control.Monad.Error.Class import Control.Lens.Lens (Lens') import Control.Lens.At (at) import Control.Lens.Getter (use,uses) import Control.Lens.Setter (assign,mapped,ASetter) import Data.OpenUnion import TypeFun.Data.List (SubList) 8 - bit ( 0 - 255 ) on the original TeX , 15 - bit ( 0 - 32767 ) on e - TeX , and 16 - bit ( 0 - 65535 ) on LuaTeX readRegIndex :: (MonadTeXState s m, MonadError String m) => m Int readRegIndex = do x <- readIntBetween minBound maxBound if x < 0 || 65536 <= x then throwError $ "Bad register code (" ++ show x ++ ")" else return x data Assignment s where WillAssign :: ASetter (LocalState s) (LocalState s) b b -> !b -> Assignment s runLocal, runGlobal :: (MonadTeXState s m) => m (Assignment s) -> m () runLocal m = do WillAssign setter value <- m assign (localState . setter) value runGlobal m = do WillAssign setter value <- m assign (localStates . mapped . setter) value texAssign :: (MonadTeXState s m) => ASetter (LocalState s) (LocalState s) b b -> b -> m (Assignment s) texAssign setter !value = return (WillAssign setter value) globalCommand :: (MonadTeXState s m, MonadError String m, Meaning (NValue s)) => m () globalCommand = do (_,v) <- required nextExpandedToken case toCommonValue v of _ -> case doGlobal v of Just m -> m Nothing -> invalidPrefix "global" v letCommand :: (MonadTeXState s m, MonadError String m) => m (Assignment s) letCommand = do name <- readCommandName readUnexpandedEquals readUnexpandedOneOptionalSpace v <- required nextUnexpandedToken >>= meaningWithoutExpansion texAssign (definitionAt name) v futureletCommand :: (MonadTeXState s m, MonadError String m) => m (Assignment s) futureletCommand = do name <- readCommandName t1 <- required nextUnexpandedToken t2 <- required nextUnexpandedToken unreadTokens' [t1,t2] v <- meaningWithoutExpansion t2 texAssign (definitionAt name) v mapChar :: (Char -> Char) -> ExpansionToken -> ExpansionToken mapChar f t@(ETCharacter { etChar = c }) | let d = f c, d /= '\0' = t { etChar = d } mapChar f t@(ETCommandName { etName = NActiveChar c }) mapChar _ t@(ETCommandName { etFlavor = ECNFIsRelax }) mapChar _ t@(ETCommandName { etFlavor = ECNFNoexpand }) mapChar _ t = t uppercaseCommand :: (MonadTeXState s m, MonadError String m) => m () uppercaseCommand = do text <- readUnexpandedGeneralTextE toUpper <- ucCodeFn unreadTokens' (map (mapChar toUpper) text) lowercaseCommand :: (MonadTeXState s m, MonadError String m) => m () lowercaseCommand = do text <- readUnexpandedGeneralTextE toLower <- lcCodeFn unreadTokens' (map (mapChar toLower) text) ignorespacesCommand :: (MonadTeXState s m, MonadError String m) => m () ignorespacesCommand = do readOptionalSpaces \chardef < control sequence><equals><number > chardefCommand :: (MonadTeXState s m, MonadError String m) => m (Assignment s) chardefCommand = do name <- readCommandName readEquals c <- readUnicodeScalarValue let w = DefinedCharacter c texAssign (definitionAt name) (nonexpandableToValue w) mathchardefCommand :: (MonadTeXState s m, MonadError String m) => m (Assignment s) mathchardefCommand = do name <- readCommandName readEquals let w = DefinedMathCharacter (MathCode (fromIntegral v)) texAssign (definitionAt name) (nonexpandableToValue w) umathchardefCommand :: (MonadTeXState s m, MonadError String m) => m (Assignment s) umathchardefCommand = do name <- readCommandName readEquals w <- readUMathCodeTriplet texAssign (definitionAt name) (nonexpandableToValue $ DefinedMathCharacter w) umathcharnumdefCommand :: (MonadTeXState s m, MonadError String m) => m (Assignment s) umathcharnumdefCommand = do name <- readCommandName readEquals w <- readUMathCode32 texAssign (definitionAt name) (nonexpandableToValue $ DefinedMathCharacter w) intdefCommand :: (MonadTeXState s m, MonadError String m) => m (Assignment s) intdefCommand = do name <- readCommandName readEquals value <- readInt32 texAssign (definitionAt name) (nonexpandableToValue $ IntegerConstant value) catcodeGet :: (MonadTeXState s m, MonadError String m) => m Integer catcodeGet = do slot <- readUnicodeScalarValue (fromIntegral . fromEnum) <$> categoryCodeOf slot catcodeSet :: (MonadTeXState s m, MonadError String m) => m (Assignment s) catcodeSet = do slot <- readUnicodeScalarValue readEquals " Invalid code ( " + + show v + + " ) , should be in the range 0 .. 15 . " let w = toEnum v texAssign (catcodeMap . at slot) (Just w) lccodeGet :: (MonadTeXState s m, MonadError String m) => m Integer lccodeGet = do slot <- readUnicodeScalarValue (fromIntegral . fromEnum) <$> lcCodeOf slot lccodeSet :: (MonadTeXState s m, MonadError String m) => m (Assignment s) lccodeSet = do slot <- readUnicodeScalarValue readEquals v <- readUnicodeScalarValue texAssign (lccodeMap . at slot) (Just v) uccodeGet :: (MonadTeXState s m, MonadError String m) => m Integer uccodeGet = do slot <- readUnicodeScalarValue (fromIntegral . fromEnum) <$> ucCodeOf slot uccodeSet :: (MonadTeXState s m, MonadError String m) => m (Assignment s) uccodeSet = do slot <- readUnicodeScalarValue readEquals v <- readUnicodeScalarValue texAssign (uccodeMap . at slot) (Just v) mathcodeGet :: (MonadTeXState s m, MonadError String m) => m Integer mathcodeGet = do slot <- readUnicodeScalarValue mathcodeToInt <$> mathCodeOf slot where mathcodeToInt (MathCode x) = fromIntegral x mathcodeToInt (UMathCode x) = fromIntegral x mathcodeSet :: (MonadTeXState s m, MonadError String m) => m (Assignment s) mathcodeSet = do slot <- readUnicodeScalarValue readEquals let w = MathCode (fromIntegral v) texAssign (mathcodeMap . at slot) (Just w) umathcodeSet :: (MonadTeXState s m, MonadError String m) => m (Assignment s) umathcodeSet = do slot <- readUnicodeScalarValue readEquals w <- readUMathCodeTriplet texAssign (mathcodeMap . at slot) (Just w) umathcodenumSet :: (MonadTeXState s m, MonadError String m) => m (Assignment s) umathcodenumSet = do slot <- readUnicodeScalarValue readEquals w <- readUMathCode32 texAssign (mathcodeMap . at slot) (Just w) delcodeGet :: (MonadTeXState s m, MonadError String m) => m Integer delcodeGet = do slot <- readUnicodeScalarValue delcodeToInt <$> delimiterCodeOf slot where delcodeToInt (DelimiterCode x) = fromIntegral x delcodeToInt (UDelimiterCode x) = fromIntegral x delcodeSet :: (MonadTeXState s m, MonadError String m) => m (Assignment s) delcodeSet = do slot <- readUnicodeScalarValue readEquals " Invalid delimiter code . " let w = DelimiterCode (fromIntegral v) texAssign (delcodeMap . at slot) (Just w) udelcodeSet :: (MonadTeXState s m, MonadError String m) => m (Assignment s) udelcodeSet = do slot <- readUnicodeScalarValue readEquals w <- readUDelimiterCodePair texAssign (delcodeMap . at slot) (Just w) udelcodenumSet :: (MonadTeXState s m, MonadError String m) => m (Assignment s) udelcodenumSet = do slot <- readUnicodeScalarValue readEquals w <- readUDelimiterCode32 texAssign (delcodeMap . at slot) (Just w) endlinecharGet :: (MonadTeXState s m, MonadError String m) => m Integer endlinecharGet = do uses (localState . endlinechar) fromIntegral endlinecharSet :: (MonadTeXState s m, MonadError String m) => m (Assignment s) endlinecharSet = do readEquals value <- readIntBetween minBound maxBound texAssign endlinechar value escapecharGet :: (MonadTeXState s m, MonadError String m) => m Integer escapecharGet = do uses (localState . escapechar) fromIntegral escapecharSet :: (MonadTeXState s m, MonadError String m) => m (Assignment s) escapecharSet = do readEquals value <- readIntBetween minBound maxBound texAssign escapechar value begingroupCommand :: (MonadTeXState s m, MonadError String m) => m () begingroupCommand = do enterGroup ScopeByBeginGroup endgroupCommand :: (MonadTeXState s m, MonadError String m) => m () endgroupCommand = do leaveGroup ScopeByBeginGroup advanceCommand :: (MonadTeXState s m, MonadError String m) => Bool -> m () advanceCommand !global = do (et,v) <- required nextExpandedToken case doArithmetic v of Just m -> do n <- if global then arithmeticGlobalAdvance <$> m else arithmeticLocalAdvance <$> m readOptionalKeyword "by" n Nothing -> throwError $ "You can't use " ++ show et ++ " after \\advance" multiplyCommand :: (MonadTeXState s m, MonadError String m) => Bool -> m () multiplyCommand !global = do (et,v) <- required nextExpandedToken case doArithmetic v of Just m -> do n <- if global then arithmeticGlobalMultiply <$> m else arithmeticLocalMultiply <$> m readOptionalKeyword "by" n Nothing -> throwError $ "You can't use " ++ show et ++ " after \\multiply" divideCommand :: (MonadTeXState s m, MonadError String m) => Bool -> m () divideCommand !global = do (et,v) <- required nextExpandedToken case doArithmetic v of Just m -> do n <- if global then arithmeticGlobalDivide <$> m else arithmeticLocalDivide <$> m readOptionalKeyword "by" n Nothing -> throwError $ "You can't use " ++ show et ++ " after \\divide" advanceInteger :: (MonadTeXState s m, MonadError String m, IntegralB i) => Lens' (LocalState s) i -> m (Assignment s) advanceInteger l = do value <- use (localState . l) arg <- readNumber case maybeFromInteger (fromIntegral value + arg) of Just value' -> texAssign l (fromInteger value') Nothing -> throwError "Arithmetic overflow" advanceQuantity :: (MonadTeXState s m, MonadError String m, QuantityRead q) => Lens' (LocalState s) q -> m (Assignment s) advanceQuantity l = do value <- use (localState . l) arg <- readQuantity texAssign l (value <+> arg) multiplyInteger :: (MonadTeXState s m, MonadError String m, IntegralB i) => Lens' (LocalState s) i -> m (Assignment s) multiplyInteger l = do value <- use (localState . l) arg <- readNumber case maybeFromInteger (fromIntegral value * arg) of Just value' -> texAssign l (fromInteger value') Nothing -> throwError "Arithmetic overflow" multiplyQuantity :: (MonadTeXState s m, MonadError String m, Quantity q) => Lens' (LocalState s) q -> m (Assignment s) multiplyQuantity l = do value <- use (localState . l) arg <- readNumber texAssign l (scaleAsInteger (* arg) value) divideInteger :: (MonadTeXState s m, MonadError String m, IntegralB i) => Lens' (LocalState s) i -> m (Assignment s) divideInteger l = do value <- use (localState . l) arg <- readNumber if arg == 0 says " Arithmetic overflow . " else case maybeFromInteger (fromIntegral value `quot` arg) of Just value' -> texAssign l (fromInteger value') Nothing -> throwError "Arithmetic overflow" divideQuantity :: (MonadTeXState s m, MonadError String m, Quantity q) => Lens' (LocalState s) q -> m (Assignment s) divideQuantity l = do value <- use (localState . l) arg <- readNumber if arg == 0 then throwError "Divide by zero" else texAssign l (scaleAsInteger (`quot` arg) value) arithmeticInteger :: (MonadTeXState s m, MonadError String m, IntegralB i) => Lens' (LocalState s) i -> m (Arithmetic m) arithmeticInteger l = pure $ Arithmetic { arithmeticLocalAdvance = runLocal $ advanceInteger l , arithmeticGlobalAdvance = runGlobal $ advanceInteger l , arithmeticLocalMultiply = runLocal $ multiplyInteger l , arithmeticGlobalMultiply = runGlobal $ multiplyInteger l , arithmeticLocalDivide = runLocal $ divideInteger l , arithmeticGlobalDivide = runGlobal $ divideInteger l } arithmeticQuantity :: (MonadTeXState s m, MonadError String m, QuantityRead q) => Lens' (LocalState s) q -> m (Arithmetic m) arithmeticQuantity l = pure $ Arithmetic { arithmeticLocalAdvance = runLocal $ advanceQuantity l , arithmeticGlobalAdvance = runGlobal $ advanceQuantity l , arithmeticLocalMultiply = runLocal $ multiplyQuantity l , arithmeticGlobalMultiply = runGlobal $ multiplyQuantity l , arithmeticLocalDivide = runLocal $ divideQuantity l , arithmeticGlobalDivide = runGlobal $ divideQuantity l } data CommonExecutable = Eglobal | Elet | Efuturelet | Euppercase | Elowercase | Eignorespaces | Echardef | Emathchardef | EUmathchardef | EUmathcharnumdef | EYuruMathIntDef | Ecatcode | Elccode | Euccode | Emathcode | Edelcode | EUmathcode | EUmathcodenum | EUdelcode | EUdelcodenum | Ebegingroup | Eendgroup | Eendlinechar | Eescapechar | Eadvance | Emultiply | Edivide deriving (Eq,Show,Enum,Bounded) instance IsPrimitive CommonExecutable where primitiveName Eglobal = "global" primitiveName Elet = "let" primitiveName Efuturelet = "futurelet" primitiveName Euppercase = "uppercase" primitiveName Elowercase = "lowercase" primitiveName Eignorespaces = "ignorespaces" primitiveName Echardef = "chardef" primitiveName Emathchardef = "mathchardef" primitiveName EUmathchardef = "Umathchardef" primitiveName EUmathcharnumdef = "Umathcharnumdef" primitiveName EYuruMathIntDef = "YuruMathIntDef" primitiveName Ecatcode = "catcode" primitiveName Elccode = "lccode" primitiveName Euccode = "uccode" primitiveName Emathcode = "mathcode" primitiveName Edelcode = "delcode" primitiveName EUmathcode = "Umathcode" primitiveName EUmathcodenum = "Umathcodenum" primitiveName EUdelcode = "Udelcode" primitiveName EUdelcodenum = "Udelcodenum" primitiveName Ebegingroup = "begingroup" primitiveName Eendgroup = "endgroup" primitiveName Eendlinechar = "endlinechar" primitiveName Eescapechar = "escapechar" primitiveName Eadvance = "advance" primitiveName Emultiply = "multiply" primitiveName Edivide = "divide" instance Meaning CommonExecutable instance (Monad m, MonadTeXState s m, MonadError String m, Meaning (NValue s)) => DoExecute CommonExecutable m where doExecute Eglobal = globalCommand doExecute Elet = runLocal letCommand doExecute Efuturelet = runLocal futureletCommand doExecute Echardef = runLocal chardefCommand doExecute Emathchardef = runLocal mathchardefCommand doExecute EUmathchardef = runLocal umathchardefCommand doExecute EUmathcharnumdef = runLocal umathcharnumdefCommand doExecute EYuruMathIntDef = runLocal intdefCommand doExecute Ecatcode = runLocal catcodeSet doExecute Elccode = runLocal lccodeSet doExecute Euccode = runLocal uccodeSet doExecute Emathcode = runLocal mathcodeSet doExecute Edelcode = runLocal delcodeSet doExecute EUmathcode = runLocal umathcodeSet doExecute EUmathcodenum = runLocal umathcodenumSet doExecute EUdelcode = runLocal udelcodeSet doExecute EUdelcodenum = runLocal udelcodenumSet doExecute Eendlinechar = runLocal endlinecharSet doExecute Eescapechar = runLocal escapecharSet doExecute Euppercase = uppercaseCommand doExecute Elowercase = lowercaseCommand doExecute Ebegingroup = begingroupCommand doExecute Eendgroup = endgroupCommand doExecute Eignorespaces = ignorespacesCommand doExecute Eadvance = advanceCommand False doExecute Emultiply = multiplyCommand False doExecute Edivide = divideCommand False doGlobal Eglobal = Just globalCommand doGlobal Elet = Just $ runGlobal letCommand doGlobal Efuturelet = Just $ runGlobal futureletCommand doGlobal Echardef = Just $ runGlobal chardefCommand doGlobal Emathchardef = Just $ runGlobal mathchardefCommand doGlobal EUmathchardef = Just $ runGlobal umathchardefCommand doGlobal EUmathcharnumdef = Just $ runGlobal umathcharnumdefCommand doGlobal EYuruMathIntDef = Just $ runGlobal intdefCommand doGlobal Ecatcode = Just $ runGlobal catcodeSet doGlobal Elccode = Just $ runGlobal lccodeSet doGlobal Euccode = Just $ runGlobal uccodeSet doGlobal Emathcode = Just $ runGlobal mathcodeSet doGlobal Edelcode = Just $ runGlobal delcodeSet doGlobal EUmathcode = Just $ runGlobal umathcodeSet doGlobal EUmathcodenum = Just $ runGlobal umathcodenumSet doGlobal EUdelcode = Just $ runGlobal udelcodeSet doGlobal EUdelcodenum = Just $ runGlobal udelcodenumSet doGlobal Eendlinechar = Just $ runGlobal endlinecharSet doGlobal Eescapechar = Just $ runGlobal escapecharSet doGlobal Eadvance = Just $ advanceCommand True doGlobal Emultiply = Just $ multiplyCommand True doGlobal Edivide = Just $ divideCommand True doGlobal _ = Nothing doArithmetic Eendlinechar = Just $ arithmeticInteger endlinechar doArithmetic Eescapechar = Just $ arithmeticInteger escapechar doArithmetic _ = Nothing getQuantity Ecatcode = QInteger catcodeGet getQuantity Elccode = QInteger lccodeGet getQuantity Euccode = QInteger uccodeGet getQuantity Emathcode = QInteger mathcodeGet getQuantity Edelcode = QInteger delcodeGet getQuantity Eendlinechar = QInteger endlinecharGet getQuantity Eescapechar = QInteger escapecharGet getQuantity _ = NotQuantity executableDefinitions :: (SubList '[CommonValue,CommonExecutable] set) => Map.Map Text (Union set) executableDefinitions = Map.fromList [("relax", liftUnion Relax) ,("endcsname", liftUnion Endcsname) ,("global", liftUnion Eglobal) ,("let", liftUnion Elet) ,("futurelet", liftUnion Efuturelet) ,("uppercase", liftUnion Euppercase) ,("lowercase", liftUnion Elowercase) ,("ignorespaces", liftUnion Eignorespaces) ,("chardef", liftUnion Echardef) ,("mathchardef", liftUnion Emathchardef) ,("Umathchardef", liftUnion EUmathchardef) ,("Umathcharnumdef",liftUnion EUmathcharnumdef) ,("YuruMathIntDef", liftUnion EYuruMathIntDef) ,("catcode", liftUnion Ecatcode) ,("lccode", liftUnion Elccode) ,("uccode", liftUnion Euccode) ,("mathcode", liftUnion Emathcode) ,("delcode", liftUnion Edelcode) ,("Umathcode", liftUnion EUmathcode) ,("Umathcodenum", liftUnion EUmathcodenum) ,("Udelcode", liftUnion EUdelcode) ,("Udelcodenum", liftUnion EUdelcodenum) ,("begingroup", liftUnion Ebegingroup) ,("endgroup", liftUnion Eendgroup) ,("endlinechar", liftUnion Eendlinechar) ,("escapechar", liftUnion Eescapechar) ,("advance", liftUnion Eadvance) ,("multiply", liftUnion Emultiply) ,("divide", liftUnion Edivide) ]
b2cc3f1f7c8b3090febca4251bf92d13205857790128b60ce07d8b8199040d1f
arrdem/katamari
generate_manifest.clj
Copyright ( c ) . All rights reserved . ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (-1.0.php) ; which can be found in the file epl-v10.html at the root of this distribution. ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. ; You must not remove this notice, or any other, from this software. (ns clojure.tools.deps.alpha.script.generate-manifest (:require [clojure.java.io :as jio] [clojure.string :as str] [clojure.tools.cli :as cli] [clojure.tools.deps.alpha :as deps] [clojure.tools.deps.alpha.gen.pom :as pom] [clojure.tools.deps.alpha.reader :as reader] [clojure.tools.deps.alpha.script.parse :as parse] [clojure.tools.deps.alpha.script.make-classpath :as makecp] [clojure.tools.deps.alpha.util.io :refer [printerrln]]) (:import [clojure.lang ExceptionInfo])) (def ^:private opts [[nil "--config-files PATHS" "Comma delimited list of deps.edn files to merge" :parse-fn parse/parse-files] [nil "--config-data EDN" "Final deps.edn data to treat as the last deps.edn file" :parse-fn parse/parse-config] [nil "--gen TYPE" "manifest type to generate" :parse-fn keyword] ["-R" "--resolve-aliases ALIASES" "Concatenated resolve-deps alias names" :parse-fn parse/parse-kws] ["-C" "--makecp-aliases ALIASES" "Concatenated make-classpath alias names" :parse-fn parse/parse-kws] ["-A" "--aliases ALIASES" "Concatenated generic alias names" :parse-fn parse/parse-kws]]) (defn -main "Main entry point for generating a manifest file. Required: --config-files DEP_FILES - comma-delimited list of deps.edn files to merge --config-data={...} - deps.edn as data --gen TYPE - manifest type to generate (currently only pom) Options: -Raliases - concated resolve-deps alias names, applied to the :deps -Aaliases - concatenated generic alias names" [& args] (let [{:keys [options errors]} (cli/parse-opts args opts)] (when (seq errors) (run! println errors) (System/exit 1)) (let [{:keys [gen resolve-aliases makecp-aliases aliases]} options] (try (let [deps-map (makecp/combine-deps-files options) resolve-args (deps/combine-aliases deps-map (concat resolve-aliases aliases)) {:keys [extra-deps override-deps]} resolve-args cp-args (deps/combine-aliases deps-map (concat makecp-aliases aliases)) {:keys [extra-paths]} cp-args mod-map (merge-with concat (merge-with merge deps-map {:deps override-deps} {:deps extra-deps}) {:paths extra-paths})] (pom/sync-pom mod-map (jio/file "."))) (catch Throwable t (printerrln "Error generating" (name gen) "manifest:" (.getMessage t)) (when-not (instance? ExceptionInfo t) (.printStackTrace t)) (System/exit 1)))))) (comment (-main "--config-files" "deps.edn" "--gen" "pom") )
null
https://raw.githubusercontent.com/arrdem/katamari/55e2da2c37c02774a1332e410ceebee0a0742d27/src/clojure-tools/src/main/clj/clojure/tools/deps/alpha/script/generate_manifest.clj
clojure
The use and distribution terms for this software are covered by the Eclipse Public License 1.0 (-1.0.php) which can be found in the file epl-v10.html at the root of this distribution. By using this software in any fashion, you are agreeing to be bound by the terms of this license. You must not remove this notice, or any other, from this software.
Copyright ( c ) . All rights reserved . (ns clojure.tools.deps.alpha.script.generate-manifest (:require [clojure.java.io :as jio] [clojure.string :as str] [clojure.tools.cli :as cli] [clojure.tools.deps.alpha :as deps] [clojure.tools.deps.alpha.gen.pom :as pom] [clojure.tools.deps.alpha.reader :as reader] [clojure.tools.deps.alpha.script.parse :as parse] [clojure.tools.deps.alpha.script.make-classpath :as makecp] [clojure.tools.deps.alpha.util.io :refer [printerrln]]) (:import [clojure.lang ExceptionInfo])) (def ^:private opts [[nil "--config-files PATHS" "Comma delimited list of deps.edn files to merge" :parse-fn parse/parse-files] [nil "--config-data EDN" "Final deps.edn data to treat as the last deps.edn file" :parse-fn parse/parse-config] [nil "--gen TYPE" "manifest type to generate" :parse-fn keyword] ["-R" "--resolve-aliases ALIASES" "Concatenated resolve-deps alias names" :parse-fn parse/parse-kws] ["-C" "--makecp-aliases ALIASES" "Concatenated make-classpath alias names" :parse-fn parse/parse-kws] ["-A" "--aliases ALIASES" "Concatenated generic alias names" :parse-fn parse/parse-kws]]) (defn -main "Main entry point for generating a manifest file. Required: --config-files DEP_FILES - comma-delimited list of deps.edn files to merge --config-data={...} - deps.edn as data --gen TYPE - manifest type to generate (currently only pom) Options: -Raliases - concated resolve-deps alias names, applied to the :deps -Aaliases - concatenated generic alias names" [& args] (let [{:keys [options errors]} (cli/parse-opts args opts)] (when (seq errors) (run! println errors) (System/exit 1)) (let [{:keys [gen resolve-aliases makecp-aliases aliases]} options] (try (let [deps-map (makecp/combine-deps-files options) resolve-args (deps/combine-aliases deps-map (concat resolve-aliases aliases)) {:keys [extra-deps override-deps]} resolve-args cp-args (deps/combine-aliases deps-map (concat makecp-aliases aliases)) {:keys [extra-paths]} cp-args mod-map (merge-with concat (merge-with merge deps-map {:deps override-deps} {:deps extra-deps}) {:paths extra-paths})] (pom/sync-pom mod-map (jio/file "."))) (catch Throwable t (printerrln "Error generating" (name gen) "manifest:" (.getMessage t)) (when-not (instance? ExceptionInfo t) (.printStackTrace t)) (System/exit 1)))))) (comment (-main "--config-files" "deps.edn" "--gen" "pom") )
c4d5ecac9c0817fcd47fae3b3c0ec9154bc89692230adc5649714fb4bf25a70e
commercialhaskell/stack
Spec.hs
main :: IO () main = asdf
null
https://raw.githubusercontent.com/commercialhaskell/stack/255cd830627870cdef34b5e54d670ef07882523e/test/integration/tests/1659-skip-component/files/test/Spec.hs
haskell
main :: IO () main = asdf
e81af2bbd7d31b7a0d4649855237a2aabe665985ce56c387e86a146b6841ffd1
jordanthayer/ocaml-search
sliding_window.ml
* A sliding window is an array with indexes that do n't start at zero . It is dynamically sizing but can have its size fixed if desired . Since we may want to marshal this structure to a channel , we make sure that it does n't hold onto any functions ( hence requiring the init_fun parameter all over the place ) . @author eaburns @since 2009 - 12 - 17 zero. It is dynamically sizing but can have its size fixed if desired. Since we may want to marshal this structure to a channel, we make sure that it doesn't hold onto any functions (hence requiring the init_fun parameter all over the place). @author eaburns @since 2009-12-17 *) module type InitializerType = sig type t val init : int -> t end module Make(Init : InitializerType) = struct type 'a t = { mutable min_num : int; mutable max_size : int; mutable data : 'a Garray.t; } let init_fun = Init.init let ind_of_num t n = n - t.min_num (** [ind_of_num t n] gets the index for a sequence number. *) let num_of_ind t ind = ind + t.min_num (** [num_of_ind t ind] gets the seq number from an index. *) let ind_of_num_bound from t n = (** [ind_of_num_bound from t n] errors if [n] is out of the window otherwise the index is given. *) let ind = ind_of_num t n in if t.max_size >= 0 && ind >= t.max_size then invalid_arg (Wrutils.str "Sliding_window.%s: %d is above the window (max=%d)" from n (num_of_ind t (t.max_size - 1))) else if ind < 0 then invalid_arg (Wrutils.str "Sliding_window.%s: %d is below the window (min=%d)" from n t.min_num) else ind let init min_num max_size = * [ init ? init_size min_num max_size ] initializes a new sliding window where each element is initialized by calling the initialization function . If [ max_size ] is less than one then the absolute value of it is used as the inital size . window where each element is initialized by calling the initialization function. If [max_size] is less than one then the absolute value of it is used as the inital size. *) let init_size = if max_size >= 0 then max_size else ~-max_size in let t = { min_num = min_num; max_size = max_size; data = Garray.init ~init_size:init_size (fun i -> init_fun (min_num + i)); } in t let reset sw min_num = (** [reset sw min_num] resets the sliding window [min_num] is the new minimum number to use. *) sw.min_num <- min_num; Garray.clear ~init_fun sw.data let get t n = (** [get t i] gets the data at sequence number [n]. *) let ind = ind_of_num_bound "get" t n in Garray.get t.data ~init_fun ind let set t n v = (** [set t i] sets the data at sequence number [n] to [v]. *) let ind = ind_of_num_bound "set" t n in Garray.set t.data ~init_fun ind v let slide t delta = (** [slide t delta] slides the window so that the new minimum sequence number is the old plus [delta]. Elements that were slid out side of the window are lost forever. *) if delta <> 0 then begin if (t.max_size > 0 && (abs delta) > t.max_size) then (* The window was slid clear. *) Garray.clear t.data ~init_fun else begin let min_num' = t.min_num + delta in let min_ind' = ind_of_num t min_num' in let fill = Garray.get_fill t.data in if delta < 0 then begin (* slide window left. *) for i = fill - 1 downto Math.imax min_ind' 0 do if t.max_size < 0 || i - delta < t.max_size then (Garray.set t.data ~init_fun (i - delta) (Garray.nth t.data ~init_fun i)) done; try Garray.clear_range t.data ~init_fun 0 (abs delta); with _ -> assert false; end else begin (* slide window right. *) if fill > delta then begin for i = delta to fill - 1 do Garray.set t.data ~init_fun (i - delta) (Garray.nth t.data ~init_fun i) done; Garray.clear_range t.data ~init_fun (fill - delta) delta end else Garray.clear t.data ~init_fun end; t.min_num <- min_num'; end end let get_max_used t = num_of_ind t ((Garray.get_fill t.data) - 1) (** [get_max_used t] gets the maximum sequence number that is in use. *) end
null
https://raw.githubusercontent.com/jordanthayer/ocaml-search/57cfc85417aa97ee5d8fbcdb84c333aae148175f/structs/sliding_window.ml
ocaml
* [ind_of_num t n] gets the index for a sequence number. * [num_of_ind t ind] gets the seq number from an index. * [ind_of_num_bound from t n] errors if [n] is out of the window otherwise the index is given. * [reset sw min_num] resets the sliding window [min_num] is the new minimum number to use. * [get t i] gets the data at sequence number [n]. * [set t i] sets the data at sequence number [n] to [v]. * [slide t delta] slides the window so that the new minimum sequence number is the old plus [delta]. Elements that were slid out side of the window are lost forever. The window was slid clear. slide window left. slide window right. * [get_max_used t] gets the maximum sequence number that is in use.
* A sliding window is an array with indexes that do n't start at zero . It is dynamically sizing but can have its size fixed if desired . Since we may want to marshal this structure to a channel , we make sure that it does n't hold onto any functions ( hence requiring the init_fun parameter all over the place ) . @author eaburns @since 2009 - 12 - 17 zero. It is dynamically sizing but can have its size fixed if desired. Since we may want to marshal this structure to a channel, we make sure that it doesn't hold onto any functions (hence requiring the init_fun parameter all over the place). @author eaburns @since 2009-12-17 *) module type InitializerType = sig type t val init : int -> t end module Make(Init : InitializerType) = struct type 'a t = { mutable min_num : int; mutable max_size : int; mutable data : 'a Garray.t; } let init_fun = Init.init let ind_of_num t n = n - t.min_num let num_of_ind t ind = ind + t.min_num let ind_of_num_bound from t n = let ind = ind_of_num t n in if t.max_size >= 0 && ind >= t.max_size then invalid_arg (Wrutils.str "Sliding_window.%s: %d is above the window (max=%d)" from n (num_of_ind t (t.max_size - 1))) else if ind < 0 then invalid_arg (Wrutils.str "Sliding_window.%s: %d is below the window (min=%d)" from n t.min_num) else ind let init min_num max_size = * [ init ? init_size min_num max_size ] initializes a new sliding window where each element is initialized by calling the initialization function . If [ max_size ] is less than one then the absolute value of it is used as the inital size . window where each element is initialized by calling the initialization function. If [max_size] is less than one then the absolute value of it is used as the inital size. *) let init_size = if max_size >= 0 then max_size else ~-max_size in let t = { min_num = min_num; max_size = max_size; data = Garray.init ~init_size:init_size (fun i -> init_fun (min_num + i)); } in t let reset sw min_num = sw.min_num <- min_num; Garray.clear ~init_fun sw.data let get t n = let ind = ind_of_num_bound "get" t n in Garray.get t.data ~init_fun ind let set t n v = let ind = ind_of_num_bound "set" t n in Garray.set t.data ~init_fun ind v let slide t delta = if delta <> 0 then begin if (t.max_size > 0 && (abs delta) > t.max_size) then Garray.clear t.data ~init_fun else begin let min_num' = t.min_num + delta in let min_ind' = ind_of_num t min_num' in let fill = Garray.get_fill t.data in if delta < 0 then begin for i = fill - 1 downto Math.imax min_ind' 0 do if t.max_size < 0 || i - delta < t.max_size then (Garray.set t.data ~init_fun (i - delta) (Garray.nth t.data ~init_fun i)) done; try Garray.clear_range t.data ~init_fun 0 (abs delta); with _ -> assert false; end else begin if fill > delta then begin for i = delta to fill - 1 do Garray.set t.data ~init_fun (i - delta) (Garray.nth t.data ~init_fun i) done; Garray.clear_range t.data ~init_fun (fill - delta) delta end else Garray.clear t.data ~init_fun end; t.min_num <- min_num'; end end let get_max_used t = num_of_ind t ((Garray.get_fill t.data) - 1) end
d8c20f5ebe82787b2dd2d270acdb651fb06fbfde5361f7c431c60a6aae2fd6cd
97jaz/hamt
perf.rkt
#lang racket/base (require data/hamt (prefix-in f: data/hamt/fast) racket/syntax (for-syntax racket/base)) (define (random-key) (list->string (map integer->char (for/list ([i (in-range 1 (add1 (random 20)))]) (random 256))))) (define N 500000) (define (gc) (collect-garbage) (collect-garbage) (collect-garbage)) (define-syntax-rule (run keys kons set ref remove) (begin (printf "\n") (printf " - ~a\n" 'kons) (printf " -- insertion\n") (gc) (let ([h (time (for/fold ([h (kons)]) ([k (in-list keys)]) (set h k #t)))]) (printf " -- lookup\n") (gc) (time (for ([k (in-list keys)]) (ref h k))) (printf " -- removal\n") (gc) (void (time (for/fold ([h h]) ([k (in-list keys)]) (remove h k))))))) (printf "1. random string keys [equal?]\n") (let ([keys (for/list ([i N]) (random-key))]) (run keys hash hash-set hash-ref hash-remove) (run keys hamt hamt-set hamt-ref hamt-remove) (run keys f:hamt f:hamt-set f:hamt-ref f:hamt-remove)) (printf "\n2. sequential integer keys [eqv?]\n") (let ([keys (for/list ([i (in-range N)]) i)]) (run keys hasheqv hash-set hash-ref hash-remove) (run keys hamteqv hamt-set hamt-ref hamt-remove) (run keys f:hamteqv f:hamt-set f:hamt-ref f:hamt-remove)) (printf "\n3. random integer keys [eqv?]\n") (let ([keys (for/list ([i (in-range N)]) (random 1000000000))]) (run keys hasheqv hash-set hash-ref hash-remove) (run keys hamteqv hamt-set hamt-ref hamt-remove) (run keys f:hamteqv f:hamt-set f:hamt-ref f:hamt-remove)) (printf "\n4. random symbol keys [eq?]\n") (let ([keys (for/list ([i (in-range N)]) (string->symbol (random-key)))]) (run keys hasheq hash-set hash-ref hash-remove) (run keys hamteq hamt-set hamt-ref hamt-remove) (run keys f:hamteq f:hamt-set f:hamt-ref f:hamt-remove))
null
https://raw.githubusercontent.com/97jaz/hamt/561cb6a447e9766dcb8abf2c01b30b87d91135f5/tests/data/hamt/perf.rkt
racket
#lang racket/base (require data/hamt (prefix-in f: data/hamt/fast) racket/syntax (for-syntax racket/base)) (define (random-key) (list->string (map integer->char (for/list ([i (in-range 1 (add1 (random 20)))]) (random 256))))) (define N 500000) (define (gc) (collect-garbage) (collect-garbage) (collect-garbage)) (define-syntax-rule (run keys kons set ref remove) (begin (printf "\n") (printf " - ~a\n" 'kons) (printf " -- insertion\n") (gc) (let ([h (time (for/fold ([h (kons)]) ([k (in-list keys)]) (set h k #t)))]) (printf " -- lookup\n") (gc) (time (for ([k (in-list keys)]) (ref h k))) (printf " -- removal\n") (gc) (void (time (for/fold ([h h]) ([k (in-list keys)]) (remove h k))))))) (printf "1. random string keys [equal?]\n") (let ([keys (for/list ([i N]) (random-key))]) (run keys hash hash-set hash-ref hash-remove) (run keys hamt hamt-set hamt-ref hamt-remove) (run keys f:hamt f:hamt-set f:hamt-ref f:hamt-remove)) (printf "\n2. sequential integer keys [eqv?]\n") (let ([keys (for/list ([i (in-range N)]) i)]) (run keys hasheqv hash-set hash-ref hash-remove) (run keys hamteqv hamt-set hamt-ref hamt-remove) (run keys f:hamteqv f:hamt-set f:hamt-ref f:hamt-remove)) (printf "\n3. random integer keys [eqv?]\n") (let ([keys (for/list ([i (in-range N)]) (random 1000000000))]) (run keys hasheqv hash-set hash-ref hash-remove) (run keys hamteqv hamt-set hamt-ref hamt-remove) (run keys f:hamteqv f:hamt-set f:hamt-ref f:hamt-remove)) (printf "\n4. random symbol keys [eq?]\n") (let ([keys (for/list ([i (in-range N)]) (string->symbol (random-key)))]) (run keys hasheq hash-set hash-ref hash-remove) (run keys hamteq hamt-set hamt-ref hamt-remove) (run keys f:hamteq f:hamt-set f:hamt-ref f:hamt-remove))
6d1f5e6642f4783971ef38d7402d3dc2c875b5104c10ca81aa83509ba9f07186
QuantumNovice/AutoLisp-AutoCAD
tyyblock.lisp
(defun pointdivide (point n) (print point) (print n) (setq x(/ (cadr point) 2)) (setq y(/ (cadr point) 2)) (setq point (list x y)) (print point) ) (setq p1 (list 2 2)) (setq p2 (list 8 9.0)) (command "rectangle" p1 p2 "") (setq (pointdivide p1 2)) (setq (pointdivide p2 2)) (command "rectangle" p1 p2 "")
null
https://raw.githubusercontent.com/QuantumNovice/AutoLisp-AutoCAD/388cb1cfc75ee6723caa5fc0e6566bab64250d0d/RAW/AutoLisp/tyyblock.lisp
lisp
(defun pointdivide (point n) (print point) (print n) (setq x(/ (cadr point) 2)) (setq y(/ (cadr point) 2)) (setq point (list x y)) (print point) ) (setq p1 (list 2 2)) (setq p2 (list 8 9.0)) (command "rectangle" p1 p2 "") (setq (pointdivide p1 2)) (setq (pointdivide p2 2)) (command "rectangle" p1 p2 "")
a0f56e97ac65be7341167354d0363b992cb8bfdb13a4bb1203cad12eefea83ea
diagrams/geometry
Shapes.hs
# LANGUAGE FlexibleContexts # # LANGUAGE TemplateHaskell # # LANGUAGE TypeFamilies # ----------------------------------------------------------------------------- -- | -- Module : Geometry.TwoD.Shapes Copyright : ( c ) 2011 - 2017 diagrams team ( see LICENSE ) -- License : BSD-style (see LICENSE) -- Maintainer : -- Various two - dimensional shapes . -- ----------------------------------------------------------------------------- module Geometry.TwoD.Shapes ( -- * Miscellaneous hrule, vrule -- * Regular polygons , regPoly , triangle , eqTriangle , square , pentagon , hexagon , heptagon , septagon , octagon , nonagon , decagon , hendecagon , dodecagon -- * Other special polygons , unitSquare , rect -- * Other shapes , roundedRect , RoundedRectOpts(..), radiusTL, radiusTR, radiusBL, radiusBR , roundedRect' ) where import Control.Lens (makeLenses, (&), (.~), (<>~), (^.)) import Data.Default.Class import qualified Data.Semigroup as Sem import Geometry.Space import Geometry.Angle import Geometry.Located (at) import Geometry.Segment import Geometry.Trail import Geometry.TwoD.Arc import Geometry.TwoD.Polygons import Geometry.TwoD.Transform import Geometry.TwoD.Types import Geometry.TwoD.Vector -- | Create a centered horizontal (L-R) line of the given length. -- -- <<diagrams/src_Geometry_TwoD_Shapes_hruleEx.svg#diagram=hruleEx&width=300>> -- > hruleEx = 0.2 ( map hrule [ 1 .. 5 ] ) > # centerXY # pad 1.1 hrule :: (InSpace V2 n t, FromTrail t, Fractional n) => n -> t hrule d = fromLocTrail $ fromSegments [straight $ r2 (d, 0)] `at` p2 (-d/2,0) -- | Create a centered vertical (T-B) line of the given length. -- -- <<diagrams/src_Geometry_TwoD_Shapes_vruleEx.svg#diagram=vruleEx&height=100>> -- > vruleEx = hsep 0.2 ( map vrule [ 1 , 1.2 .. 2 ] ) > # centerXY # pad 1.1 vrule :: (InSpace V2 n t, FromTrail t, Fractional n) => n -> t vrule d = fromLocTrail $ fromSegments [straight $ r2 (0, -d)] `at` p2 (0,d/2) | A square with its center at the origin and sides of length 1 , -- oriented parallel to the axes. -- -- <<diagrams/src_Geometry_TwoD_Shapes_unitSquareEx.svg#diagram=unitSquareEx&width=100>> unitSquare :: (InSpace V2 n t, FromTrail t, OrderedField n) => t unitSquare = polygon (def & polyType .~ PolyRegular 4 (sqrt 2 / 2) & polyOrient .~ OrientH) > unitSquareEx = unitSquare # pad 1.1 # showOrigin -- | A square with its center at the origin and sides of the given -- length, oriented parallel to the axes. -- -- <<diagrams/src_Geometry_TwoD_Shapes_squareEx.svg#diagram=squareEx&width=200>> square :: (InSpace V2 n t, FromTrail t, OrderedField n) => n -> t square d = rect d d > squareEx = hsep 0.5 [ square 1 , square 2 , square 3 ] > # centerXY # pad 1.1 -- | @rect w h@ is an axis-aligned rectangle of width @w@ and height @h@ , centered at the origin . -- -- <<diagrams/src_Geometry_TwoD_Shapes_rectEx.svg#diagram=rectEx&width=150>> rect :: (InSpace V2 n t, FromTrail t, OrderedField n) => n -> n -> t rect w h = fromLocTrail . scaleX w . scaleY h $ unitSquare > rectEx = rect 1 0.7 # pad 1.1 -- The above may seem a bit roundabout. In fact, we used to have -- -- rect w h = unitSquare # scaleX w # scaleY h -- since unitSquare can produce any FromTrail . The current code -- instead uses (unitSquare # scaleX w # scaleY h) to specifically -- produce a Path, which is then deconstructed and passed back into ' fromLocTrail ' to create any FromTrail . -- The difference is that while scaling by zero works fine for -- Path it does not work very well for, say, Diagrams (leading to NaNs or worse ) . This way , we force the scaling to happen on a -- Path, where we know it will behave properly, and then use the resulting geometry to construct an arbitrary FromTrail . -- -- See -lib/issues/43 . ------------------------------------------------------------ -- Regular polygons ------------------------------------------------------------ | Create a regular polygon . The first argument is the number of sides , and the second is the /length/ of the sides . ( Compare to the ' polygon ' function with a ' PolyRegular ' option , which produces -- polygons of a given /radius/). -- The polygon will be oriented with one edge parallel to the x - axis . regPoly :: (InSpace V2 n t, FromTrail t, OrderedField n) => Int -> n -> t regPoly n l = polygon (def & polyType .~ PolySides (repeat (1/fromIntegral n @@ turn)) (replicate (n-1) l) & polyOrient .~ OrientH ) > shapeEx sh = sh 1 # pad 1.1 -- > triangleEx = shapeEx triangle -- > pentagonEx = shapeEx pentagon -- > hexagonEx = shapeEx hexagon > heptagonEx = shapeEx -- > octagonEx = shapeEx octagon -- > nonagonEx = shapeEx nonagon -- > decagonEx = shapeEx decagon > hendecagonEx = shapeEx hendecagon -- > dodecagonEx = shapeEx dodecagon -- | A synonym for 'triangle', provided for backwards compatibility. eqTriangle :: (InSpace V2 n t, FromTrail t, OrderedField n) => n -> t eqTriangle = triangle -- | An equilateral triangle, with sides of the given length and base -- parallel to the x-axis. -- -- <<diagrams/src_Geometry_TwoD_Shapes_triangleEx.svg#diagram=triangleEx&width=100>> triangle :: (InSpace V2 n t, FromTrail t, OrderedField n) => n -> t triangle = regPoly 3 | A regular pentagon , with sides of the given length and base -- parallel to the x-axis. -- -- <<diagrams/src_Geometry_TwoD_Shapes_pentagonEx.svg#diagram=pentagonEx&width=100>> pentagon :: (InSpace V2 n t, FromTrail t, OrderedField n) => n -> t pentagon = regPoly 5 -- | A regular hexagon, with sides of the given length and base -- parallel to the x-axis. -- -- <<diagrams/src_Geometry_TwoD_Shapes_hexagonEx.svg#diagram=hexagonEx&width=100>> hexagon :: (InSpace V2 n t, FromTrail t, OrderedField n) => n -> t hexagon = regPoly 6 | A regular heptagon , with sides of the given length and base -- parallel to the x-axis. -- -- <<diagrams/src_Geometry_TwoD_Shapes_heptagonEx.svg#diagram=heptagonEx&width=100>> heptagon :: (InSpace V2 n t, FromTrail t, OrderedField n) => n -> t heptagon = regPoly 7 | A synonym for ' ' . It is , however , completely inferior , being a base admixture of the Latin /septum/ ( seven ) and the Greek γωνία ( angle ) . septagon :: (InSpace V2 n t, FromTrail t, OrderedField n) => n -> t septagon = heptagon -- | A regular octagon, with sides of the given length and base -- parallel to the x-axis. -- -- <<diagrams/src_Geometry_TwoD_Shapes_octagonEx.svg#diagram=octagonEx&width=100>> octagon :: (InSpace V2 n t, FromTrail t, OrderedField n) => n -> t octagon = regPoly 8 -- | A regular nonagon, with sides of the given length and base -- parallel to the x-axis. -- -- <<diagrams/src_Geometry_TwoD_Shapes_nonagonEx.svg#diagram=nonagonEx&width=100>> nonagon :: (InSpace V2 n t, FromTrail t, OrderedField n) => n -> t nonagon = regPoly 9 -- | A regular decagon, with sides of the given length and base -- parallel to the x-axis. -- -- <<diagrams/src_Geometry_TwoD_Shapes_decagonEx.svg#diagram=decagonEx&width=100>> decagon :: (InSpace V2 n t, FromTrail t, OrderedField n) => n -> t decagon = regPoly 10 -- | A regular hendecagon, with sides of the given length and base -- parallel to the x-axis. -- -- <<diagrams/src_Geometry_TwoD_Shapes_hendecagonEx.svg#diagram=hendecagonEx&width=100>> hendecagon :: (InSpace V2 n t, FromTrail t, OrderedField n) => n -> t hendecagon = regPoly 11 -- | A regular dodecagon, with sides of the given length and base -- parallel to the x-axis. -- -- <<diagrams/src_Geometry_TwoD_Shapes_dodecagonEx.svg#diagram=dodecagonEx&width=100>> dodecagon :: (InSpace V2 n t, FromTrail t, OrderedField n) => n -> t dodecagon = regPoly 12 ------------------------------------------------------------ -- Other shapes ------------------------------------------ ------------------------------------------------------------ data RoundedRectOpts d = RoundedRectOpts { _radiusTL :: d , _radiusTR :: d , _radiusBL :: d , _radiusBR :: d } makeLenses ''RoundedRectOpts instance (Num d) => Default (RoundedRectOpts d) where def = RoundedRectOpts 0 0 0 0 -- | @roundedRect w h r@ generates a closed trail, or closed path -- centered at the origin, of an axis-aligned rectangle with width @w@ , height @h@ , and circular rounded corners of radius @r@. If -- @r@ is negative the corner will be cut out in a reverse arc. If the size of @r@ is larger than half the smaller dimension of @w@ and @h@ , then it will be reduced to fit in that range , to prevent -- the corners from overlapping. The trail or path begins with the -- right edge and proceeds counterclockwise. If you need to specify -- a different radius for each corner individually, use -- 'roundedRect'' instead. -- -- <<diagrams/src_Geometry_TwoD_Shapes_roundedRectEx.svg#diagram=roundedRectEx&width=400>> -- > roundedRectEx = pad 1.1 . centerXY $ hsep 0.2 > [ roundedRect 0.5 0.4 0.1 > , roundedRect 0.5 0.4 ( -0.1 ) > , roundedRect ' 0.7 0.4 ( with & radiusTL .~ 0.2 > & radiusTR .~ -0.2 -- > & radiusBR .~ 0.1) -- > ] roundedRect :: (InSpace V2 n t, FromTrail t, RealFloat n) => n -> n -> n -> t roundedRect w h r = roundedRect' w h (def & radiusTL .~ r & radiusBR .~ r & radiusTR .~ r & radiusBL .~ r) -- | @roundedRect'@ works like @roundedRect@ but allows you to set the radius of -- each corner indivually, using @RoundedRectOpts@. The default corner radius is 0. -- Each radius can also be negative, which results in the curves being reversed -- to be inward instead of outward. roundedRect' :: (InSpace V2 n t, FromTrail t, RealFloat n) => n -> n -> RoundedRectOpts n -> t roundedRect' w h opts = fromLocTrail . (`at` p2 (w/2, abs rBR - h/2)) . wrapLoop . glueLine $ seg (0, h - abs rTR - abs rBR) Sem.<> mkCorner 0 rTR Sem.<> seg (abs rTR + abs rTL - w, 0) Sem.<> mkCorner 1 rTL Sem.<> seg (0, abs rTL + abs rBL - h) Sem.<> mkCorner 2 rBL Sem.<> seg (w - abs rBL - abs rBR, 0) Sem.<> mkCorner 3 rBR where seg = fromOffsets . (:[]) . r2 diag = sqrt (w * w + h * h) -- to clamp corner radius, need to compare with other corners that share an edge . If the corners overlap then reduce the largest corner first , as far as 50 % of the edge in question . rTL = clampCnr radiusTR radiusBL radiusBR radiusTL rBL = clampCnr radiusBR radiusTL radiusTR radiusBL rTR = clampCnr radiusTL radiusBR radiusBL radiusTR rBR = clampCnr radiusBL radiusTR radiusTL radiusBR clampCnr rx ry ro r = let (rx',ry',ro',r') = (opts^.rx, opts^.ry, opts^.ro, opts^.r) in clampDiag ro' . clampAdj h ry' . clampAdj w rx' $ r' -- prevent curves of adjacent corners from overlapping clampAdj len adj r = if abs r > len/2 then sign r * max (len/2) (min (len - abs adj) (abs r)) else r -- prevent inward curves of diagonally opposite corners from intersecting clampDiag opp r = if r < 0 && opp < 0 && abs r > diag / 2 then sign r * max (diag / 2) (min (abs r) (diag + opp)) else r sign n = if n < 0 then -1 else 1 mkCorner k r | r == 0 = mempty | r < 0 = doArc 3 (-1) | otherwise = doArc 0 1 where doArc d s = arc' r (xDir & _theta <>~ ((k+d)/4 @@ turn)) (s/4 @@ turn)
null
https://raw.githubusercontent.com/diagrams/geometry/945c8c36b22e71d0c0e4427f23de6614f4e7594a/src/Geometry/TwoD/Shapes.hs
haskell
--------------------------------------------------------------------------- | Module : Geometry.TwoD.Shapes License : BSD-style (see LICENSE) Maintainer : --------------------------------------------------------------------------- * Miscellaneous * Regular polygons * Other special polygons * Other shapes | Create a centered horizontal (L-R) line of the given length. <<diagrams/src_Geometry_TwoD_Shapes_hruleEx.svg#diagram=hruleEx&width=300>> | Create a centered vertical (T-B) line of the given length. <<diagrams/src_Geometry_TwoD_Shapes_vruleEx.svg#diagram=vruleEx&height=100>> oriented parallel to the axes. <<diagrams/src_Geometry_TwoD_Shapes_unitSquareEx.svg#diagram=unitSquareEx&width=100>> | A square with its center at the origin and sides of the given length, oriented parallel to the axes. <<diagrams/src_Geometry_TwoD_Shapes_squareEx.svg#diagram=squareEx&width=200>> | @rect w h@ is an axis-aligned rectangle of width @w@ and height <<diagrams/src_Geometry_TwoD_Shapes_rectEx.svg#diagram=rectEx&width=150>> The above may seem a bit roundabout. In fact, we used to have rect w h = unitSquare # scaleX w # scaleY h instead uses (unitSquare # scaleX w # scaleY h) to specifically produce a Path, which is then deconstructed and passed back into Path it does not work very well for, say, Diagrams (leading to Path, where we know it will behave properly, and then use the See -lib/issues/43 . ---------------------------------------------------------- Regular polygons ---------------------------------------------------------- polygons of a given /radius/). > triangleEx = shapeEx triangle > pentagonEx = shapeEx pentagon > hexagonEx = shapeEx hexagon > octagonEx = shapeEx octagon > nonagonEx = shapeEx nonagon > decagonEx = shapeEx decagon > dodecagonEx = shapeEx dodecagon | A synonym for 'triangle', provided for backwards compatibility. | An equilateral triangle, with sides of the given length and base parallel to the x-axis. <<diagrams/src_Geometry_TwoD_Shapes_triangleEx.svg#diagram=triangleEx&width=100>> parallel to the x-axis. <<diagrams/src_Geometry_TwoD_Shapes_pentagonEx.svg#diagram=pentagonEx&width=100>> | A regular hexagon, with sides of the given length and base parallel to the x-axis. <<diagrams/src_Geometry_TwoD_Shapes_hexagonEx.svg#diagram=hexagonEx&width=100>> parallel to the x-axis. <<diagrams/src_Geometry_TwoD_Shapes_heptagonEx.svg#diagram=heptagonEx&width=100>> | A regular octagon, with sides of the given length and base parallel to the x-axis. <<diagrams/src_Geometry_TwoD_Shapes_octagonEx.svg#diagram=octagonEx&width=100>> | A regular nonagon, with sides of the given length and base parallel to the x-axis. <<diagrams/src_Geometry_TwoD_Shapes_nonagonEx.svg#diagram=nonagonEx&width=100>> | A regular decagon, with sides of the given length and base parallel to the x-axis. <<diagrams/src_Geometry_TwoD_Shapes_decagonEx.svg#diagram=decagonEx&width=100>> | A regular hendecagon, with sides of the given length and base parallel to the x-axis. <<diagrams/src_Geometry_TwoD_Shapes_hendecagonEx.svg#diagram=hendecagonEx&width=100>> | A regular dodecagon, with sides of the given length and base parallel to the x-axis. <<diagrams/src_Geometry_TwoD_Shapes_dodecagonEx.svg#diagram=dodecagonEx&width=100>> ---------------------------------------------------------- Other shapes ------------------------------------------ ---------------------------------------------------------- | @roundedRect w h r@ generates a closed trail, or closed path centered at the origin, of an axis-aligned rectangle with width @r@ is negative the corner will be cut out in a reverse arc. If the corners from overlapping. The trail or path begins with the right edge and proceeds counterclockwise. If you need to specify a different radius for each corner individually, use 'roundedRect'' instead. <<diagrams/src_Geometry_TwoD_Shapes_roundedRectEx.svg#diagram=roundedRectEx&width=400>> > & radiusBR .~ 0.1) > ] | @roundedRect'@ works like @roundedRect@ but allows you to set the radius of each corner indivually, using @RoundedRectOpts@. The default corner radius is 0. Each radius can also be negative, which results in the curves being reversed to be inward instead of outward. to clamp corner radius, need to compare with other corners that share an prevent curves of adjacent corners from overlapping prevent inward curves of diagonally opposite corners from intersecting
# LANGUAGE FlexibleContexts # # LANGUAGE TemplateHaskell # # LANGUAGE TypeFamilies # Copyright : ( c ) 2011 - 2017 diagrams team ( see LICENSE ) Various two - dimensional shapes . module Geometry.TwoD.Shapes ( hrule, vrule , regPoly , triangle , eqTriangle , square , pentagon , hexagon , heptagon , septagon , octagon , nonagon , decagon , hendecagon , dodecagon , unitSquare , rect , roundedRect , RoundedRectOpts(..), radiusTL, radiusTR, radiusBL, radiusBR , roundedRect' ) where import Control.Lens (makeLenses, (&), (.~), (<>~), (^.)) import Data.Default.Class import qualified Data.Semigroup as Sem import Geometry.Space import Geometry.Angle import Geometry.Located (at) import Geometry.Segment import Geometry.Trail import Geometry.TwoD.Arc import Geometry.TwoD.Polygons import Geometry.TwoD.Transform import Geometry.TwoD.Types import Geometry.TwoD.Vector > hruleEx = 0.2 ( map hrule [ 1 .. 5 ] ) > # centerXY # pad 1.1 hrule :: (InSpace V2 n t, FromTrail t, Fractional n) => n -> t hrule d = fromLocTrail $ fromSegments [straight $ r2 (d, 0)] `at` p2 (-d/2,0) > vruleEx = hsep 0.2 ( map vrule [ 1 , 1.2 .. 2 ] ) > # centerXY # pad 1.1 vrule :: (InSpace V2 n t, FromTrail t, Fractional n) => n -> t vrule d = fromLocTrail $ fromSegments [straight $ r2 (0, -d)] `at` p2 (0,d/2) | A square with its center at the origin and sides of length 1 , unitSquare :: (InSpace V2 n t, FromTrail t, OrderedField n) => t unitSquare = polygon (def & polyType .~ PolyRegular 4 (sqrt 2 / 2) & polyOrient .~ OrientH) > unitSquareEx = unitSquare # pad 1.1 # showOrigin square :: (InSpace V2 n t, FromTrail t, OrderedField n) => n -> t square d = rect d d > squareEx = hsep 0.5 [ square 1 , square 2 , square 3 ] > # centerXY # pad 1.1 @h@ , centered at the origin . rect :: (InSpace V2 n t, FromTrail t, OrderedField n) => n -> n -> t rect w h = fromLocTrail . scaleX w . scaleY h $ unitSquare > rectEx = rect 1 0.7 # pad 1.1 since unitSquare can produce any FromTrail . The current code ' fromLocTrail ' to create any FromTrail . The difference is that while scaling by zero works fine for NaNs or worse ) . This way , we force the scaling to happen on a resulting geometry to construct an arbitrary FromTrail . | Create a regular polygon . The first argument is the number of sides , and the second is the /length/ of the sides . ( Compare to the ' polygon ' function with a ' PolyRegular ' option , which produces The polygon will be oriented with one edge parallel to the x - axis . regPoly :: (InSpace V2 n t, FromTrail t, OrderedField n) => Int -> n -> t regPoly n l = polygon (def & polyType .~ PolySides (repeat (1/fromIntegral n @@ turn)) (replicate (n-1) l) & polyOrient .~ OrientH ) > shapeEx sh = sh 1 # pad 1.1 > heptagonEx = shapeEx > hendecagonEx = shapeEx hendecagon eqTriangle :: (InSpace V2 n t, FromTrail t, OrderedField n) => n -> t eqTriangle = triangle triangle :: (InSpace V2 n t, FromTrail t, OrderedField n) => n -> t triangle = regPoly 3 | A regular pentagon , with sides of the given length and base pentagon :: (InSpace V2 n t, FromTrail t, OrderedField n) => n -> t pentagon = regPoly 5 hexagon :: (InSpace V2 n t, FromTrail t, OrderedField n) => n -> t hexagon = regPoly 6 | A regular heptagon , with sides of the given length and base heptagon :: (InSpace V2 n t, FromTrail t, OrderedField n) => n -> t heptagon = regPoly 7 | A synonym for ' ' . It is , however , completely inferior , being a base admixture of the Latin /septum/ ( seven ) and the Greek γωνία ( angle ) . septagon :: (InSpace V2 n t, FromTrail t, OrderedField n) => n -> t septagon = heptagon octagon :: (InSpace V2 n t, FromTrail t, OrderedField n) => n -> t octagon = regPoly 8 nonagon :: (InSpace V2 n t, FromTrail t, OrderedField n) => n -> t nonagon = regPoly 9 decagon :: (InSpace V2 n t, FromTrail t, OrderedField n) => n -> t decagon = regPoly 10 hendecagon :: (InSpace V2 n t, FromTrail t, OrderedField n) => n -> t hendecagon = regPoly 11 dodecagon :: (InSpace V2 n t, FromTrail t, OrderedField n) => n -> t dodecagon = regPoly 12 data RoundedRectOpts d = RoundedRectOpts { _radiusTL :: d , _radiusTR :: d , _radiusBL :: d , _radiusBR :: d } makeLenses ''RoundedRectOpts instance (Num d) => Default (RoundedRectOpts d) where def = RoundedRectOpts 0 0 0 0 @w@ , height @h@ , and circular rounded corners of radius @r@. If the size of @r@ is larger than half the smaller dimension of @w@ and @h@ , then it will be reduced to fit in that range , to prevent > roundedRectEx = pad 1.1 . centerXY $ hsep 0.2 > [ roundedRect 0.5 0.4 0.1 > , roundedRect 0.5 0.4 ( -0.1 ) > , roundedRect ' 0.7 0.4 ( with & radiusTL .~ 0.2 > & radiusTR .~ -0.2 roundedRect :: (InSpace V2 n t, FromTrail t, RealFloat n) => n -> n -> n -> t roundedRect w h r = roundedRect' w h (def & radiusTL .~ r & radiusBR .~ r & radiusTR .~ r & radiusBL .~ r) roundedRect' :: (InSpace V2 n t, FromTrail t, RealFloat n) => n -> n -> RoundedRectOpts n -> t roundedRect' w h opts = fromLocTrail . (`at` p2 (w/2, abs rBR - h/2)) . wrapLoop . glueLine $ seg (0, h - abs rTR - abs rBR) Sem.<> mkCorner 0 rTR Sem.<> seg (abs rTR + abs rTL - w, 0) Sem.<> mkCorner 1 rTL Sem.<> seg (0, abs rTL + abs rBL - h) Sem.<> mkCorner 2 rBL Sem.<> seg (w - abs rBL - abs rBR, 0) Sem.<> mkCorner 3 rBR where seg = fromOffsets . (:[]) . r2 diag = sqrt (w * w + h * h) edge . If the corners overlap then reduce the largest corner first , as far as 50 % of the edge in question . rTL = clampCnr radiusTR radiusBL radiusBR radiusTL rBL = clampCnr radiusBR radiusTL radiusTR radiusBL rTR = clampCnr radiusTL radiusBR radiusBL radiusTR rBR = clampCnr radiusBL radiusTR radiusTL radiusBR clampCnr rx ry ro r = let (rx',ry',ro',r') = (opts^.rx, opts^.ry, opts^.ro, opts^.r) in clampDiag ro' . clampAdj h ry' . clampAdj w rx' $ r' clampAdj len adj r = if abs r > len/2 then sign r * max (len/2) (min (len - abs adj) (abs r)) else r clampDiag opp r = if r < 0 && opp < 0 && abs r > diag / 2 then sign r * max (diag / 2) (min (abs r) (diag + opp)) else r sign n = if n < 0 then -1 else 1 mkCorner k r | r == 0 = mempty | r < 0 = doArc 3 (-1) | otherwise = doArc 0 1 where doArc d s = arc' r (xDir & _theta <>~ ((k+d)/4 @@ turn)) (s/4 @@ turn)
d1f87bf96f091b571d392a78fba3072630d06305460f4cbe25fe68890f6b7653
VisionsGlobalEmpowerment/webchange
views.cljs
(ns webchange.lesson-builder.tools.script.dialog-item.character-movement.views (:require [re-frame.core :as re-frame] [webchange.lesson-builder.tools.script.dialog-item.character-movement.state :as state] [webchange.lesson-builder.tools.script.dialog-item.wrapper.views :refer [item-wrapper]] [webchange.ui.index :as ui])) (defn character-movement [{:keys [action-path]}] (let [name @(re-frame/subscribe [::state/name action-path]) handle-remove-click #(re-frame/dispatch [::state/remove action-path])] [item-wrapper {:class-name "dialog-item--character-movement" :actions [{:icon "trash" :title "Delete phrase" :on-click handle-remove-click}] :action-path action-path} [ui/icon {:icon "movement" :class-name "effect-general--icon"}] name]))
null
https://raw.githubusercontent.com/VisionsGlobalEmpowerment/webchange/1bcebce2d5a99b26cd559295d301d5255cca6a1a/src/cljs/webchange/lesson_builder/tools/script/dialog_item/character_movement/views.cljs
clojure
(ns webchange.lesson-builder.tools.script.dialog-item.character-movement.views (:require [re-frame.core :as re-frame] [webchange.lesson-builder.tools.script.dialog-item.character-movement.state :as state] [webchange.lesson-builder.tools.script.dialog-item.wrapper.views :refer [item-wrapper]] [webchange.ui.index :as ui])) (defn character-movement [{:keys [action-path]}] (let [name @(re-frame/subscribe [::state/name action-path]) handle-remove-click #(re-frame/dispatch [::state/remove action-path])] [item-wrapper {:class-name "dialog-item--character-movement" :actions [{:icon "trash" :title "Delete phrase" :on-click handle-remove-click}] :action-path action-path} [ui/icon {:icon "movement" :class-name "effect-general--icon"}] name]))
22e69d0c0f71253430c4ff39433b8ba09bcb7ddd3d26ad01e1cdf346df3020c8
triffon/fp-2019-20
01-rewrite-expressions.rkt
#lang racket (require rackunit) (require rackunit/text-ui) 1.1 - Преведете следващите изрази в префиксна форма ; Попълвате на мястото на (void) a - ( ( 2 + 3/16 ) / ( 9 * 2.78 ) ) + ( ( 5 / 2 ) - 6 ) (define a (+ (/ (+ 2 (/ 3 16)) (* 9 2.78)) (- (/ 5 2) 6))) b - ( 15 + 21 + ( 3 / 15 ) + ( 7 - ( 2 * 2 ) ) ) / 16 (define b (/ (+ 15 21 (/ 3 15) (- 7 (* 2 2))) 16)) c - ( 5 + 1/4 + ( 2 - ( 3 - ( 6 + 1/5 ) ) ) ) / 3(6 - 2)(2 - 7 ) (define c (/ (+ 5 (/ 1 4) (- 2 (- 3 (+ 6 (/ 1 5))))) (* 3 (- 6 2) (- 2 7)))) (define (square x) (* x x)) d - ( 3 ^ 2 + 5 ) / ( 3 ^ 3 - 2 ) (define d (/ (+ (square 3) 5) (- (* 3 (square 3)) 2))) e - ( 16 ^ 4 + 95/2 ) (define e (+ (square (square 16)) (/ 95 2))) (define first-tests (test-suite "Translated expressions tests" (test-case "1.1-a" (check-equal? a -3.412569944044764)) (test-case "1.1-b" (check-equal? b 49/20)) (test-case "1.1-c" (check-equal? c -209/1200)) (test-case "1.1-d" (check-equal? d 14/25)) (test-case "1.1-e" (check-equal? e 131167/2)))) (run-tests first-tests 'verbose)
null
https://raw.githubusercontent.com/triffon/fp-2019-20/7efb13ff4de3ea13baa2c5c59eb57341fac15641/exercises/computer-science-3/exercises/01.introduction/solutions/01-rewrite-expressions.rkt
racket
Попълвате на мястото на (void)
#lang racket (require rackunit) (require rackunit/text-ui) 1.1 - Преведете следващите изрази в префиксна форма a - ( ( 2 + 3/16 ) / ( 9 * 2.78 ) ) + ( ( 5 / 2 ) - 6 ) (define a (+ (/ (+ 2 (/ 3 16)) (* 9 2.78)) (- (/ 5 2) 6))) b - ( 15 + 21 + ( 3 / 15 ) + ( 7 - ( 2 * 2 ) ) ) / 16 (define b (/ (+ 15 21 (/ 3 15) (- 7 (* 2 2))) 16)) c - ( 5 + 1/4 + ( 2 - ( 3 - ( 6 + 1/5 ) ) ) ) / 3(6 - 2)(2 - 7 ) (define c (/ (+ 5 (/ 1 4) (- 2 (- 3 (+ 6 (/ 1 5))))) (* 3 (- 6 2) (- 2 7)))) (define (square x) (* x x)) d - ( 3 ^ 2 + 5 ) / ( 3 ^ 3 - 2 ) (define d (/ (+ (square 3) 5) (- (* 3 (square 3)) 2))) e - ( 16 ^ 4 + 95/2 ) (define e (+ (square (square 16)) (/ 95 2))) (define first-tests (test-suite "Translated expressions tests" (test-case "1.1-a" (check-equal? a -3.412569944044764)) (test-case "1.1-b" (check-equal? b 49/20)) (test-case "1.1-c" (check-equal? c -209/1200)) (test-case "1.1-d" (check-equal? d 14/25)) (test-case "1.1-e" (check-equal? e 131167/2)))) (run-tests first-tests 'verbose)
533915baac9f289cae6694a3f98cccaa314a85e4b5424772b2a9d0c178c03277
racket/gui
alignment-test.rkt
(require mzlib/class mzlib/etc mred "../verthoriz-alignment.rkt" "../lines.rkt" "../aligned-pasteboard.rkt" "../snip-wrapper.rkt") (require "../snip-lib.rkt") (define f (new frame% (label "f") (height 500) (width 500))) (send f show true) (define p (new aligned-pasteboard%)) (define c (new editor-canvas% (editor p) (parent f))) (define a1 (new vertical-alignment% (parent p))) (define a2 (new horizontal-alignment% (parent a1))) (define a3 (new horizontal-alignment% (parent a1))) (new snip-wrapper% (snip (make-object string-snip% "One")) (parent a2)) (new snip-wrapper% (snip (make-object string-snip% "Two")) (parent a2)) (new snip-wrapper% (snip (make-object string-snip% "Three")) (parent a3)) (new snip-wrapper% (snip (make-object string-snip% "Three")) (parent a3))
null
https://raw.githubusercontent.com/racket/gui/d1fef7a43a482c0fdd5672be9a6e713f16d8be5c/gui-lib/embedded-gui/private/tests/alignment-test.rkt
racket
(require mzlib/class mzlib/etc mred "../verthoriz-alignment.rkt" "../lines.rkt" "../aligned-pasteboard.rkt" "../snip-wrapper.rkt") (require "../snip-lib.rkt") (define f (new frame% (label "f") (height 500) (width 500))) (send f show true) (define p (new aligned-pasteboard%)) (define c (new editor-canvas% (editor p) (parent f))) (define a1 (new vertical-alignment% (parent p))) (define a2 (new horizontal-alignment% (parent a1))) (define a3 (new horizontal-alignment% (parent a1))) (new snip-wrapper% (snip (make-object string-snip% "One")) (parent a2)) (new snip-wrapper% (snip (make-object string-snip% "Two")) (parent a2)) (new snip-wrapper% (snip (make-object string-snip% "Three")) (parent a3)) (new snip-wrapper% (snip (make-object string-snip% "Three")) (parent a3))
a63d3d49dfdc04722af2c0c606871561a19bea4d448e58336ac6ed0e9e464864
tweag/ormolu
Comments.hs
# LANGUAGE LambdaCase # {-# LANGUAGE OverloadedStrings #-} -- | Helpers for formatting of comments. This is low-level code, use -- "Ormolu.Printer.Combinators" unless you know what you are doing. module Ormolu.Printer.Comments ( spitPrecedingComments, spitFollowingComments, spitRemainingComments, spitCommentNow, spitCommentPending, ) where import Control.Monad import qualified Data.List.NonEmpty as NE import Data.Maybe (listToMaybe) import GHC.Types.SrcLoc import Ormolu.Parser.CommentStream import Ormolu.Printer.Internal ---------------------------------------------------------------------------- -- Top-level -- | Output all preceding comments for an element at given location. spitPrecedingComments :: -- | Span of the element to attach comments to RealSrcSpan -> R () spitPrecedingComments ref = do gotSome <- handleCommentSeries (spitPrecedingComment ref) when gotSome $ do lastMark <- getSpanMark -- Insert a blank line between the preceding comments and the thing -- after them if there was a blank line in the input. when (needsNewlineBefore ref lastMark) newline -- | Output all comments following an element at given location. spitFollowingComments :: -- | Span of the element to attach comments to RealSrcSpan -> R () spitFollowingComments ref = do trimSpanStream ref void $ handleCommentSeries (spitFollowingComment ref) -- | Output all remaining comments in the comment stream. spitRemainingComments :: R () spitRemainingComments = do -- Make sure we have a blank a line between the last definition and the -- trailing comments. newline void $ handleCommentSeries spitRemainingComment ---------------------------------------------------------------------------- -- Single-comment functions -- | Output a single preceding comment for an element at given location. spitPrecedingComment :: -- | Span of the element to attach comments to RealSrcSpan -> -- | Are we done? R Bool spitPrecedingComment ref = do mlastMark <- getSpanMark let p (L l _) = realSrcSpanEnd l <= realSrcSpanStart ref withPoppedComment p $ \l comment -> do lineSpans <- thisLineSpans let thisCommentLine = srcLocLine (realSrcSpanStart l) needsNewline = case listToMaybe lineSpans of Nothing -> False Just spn -> srcLocLine (realSrcSpanEnd spn) /= thisCommentLine when (needsNewline || needsNewlineBefore l mlastMark) newline spitCommentNow l comment if theSameLinePre l ref then space else newline -- | Output a comment that follows element at given location immediately on -- the same line, if there is any. spitFollowingComment :: -- | AST element to attach comments to RealSrcSpan -> -- | Are we done? R Bool spitFollowingComment ref = do mlastMark <- getSpanMark mnSpn <- nextEltSpan Get first enclosing span that is not equal to reference span , i.e. it 's -- truly something enclosing the AST element. meSpn <- getEnclosingSpan (/= ref) withPoppedComment (commentFollowsElt ref mnSpn meSpn mlastMark) $ \l comment -> if theSameLinePost l ref then if isMultilineComment comment then space >> spitCommentNow l comment else spitCommentPending OnTheSameLine l comment else do when (needsNewlineBefore l mlastMark) $ registerPendingCommentLine OnNextLine "" spitCommentPending OnNextLine l comment -- | Output a single remaining comment from the comment stream. spitRemainingComment :: -- | Are we done? R Bool spitRemainingComment = do mlastMark <- getSpanMark withPoppedComment (const True) $ \l comment -> do when (needsNewlineBefore l mlastMark) newline spitCommentNow l comment newline ---------------------------------------------------------------------------- -- Helpers -- | Output series of comments. handleCommentSeries :: -- | Given location of previous comment, output the next comment -- returning 'True' if we're done R Bool -> -- | Whether we printed any comments R Bool handleCommentSeries f = go False where go gotSome = do done <- f if done then return gotSome else go True -- | Try to pop a comment using given predicate and if there is a comment -- matching the predicate, print it out. withPoppedComment :: -- | Comment predicate (RealLocated Comment -> Bool) -> -- | Printing function (RealSrcSpan -> Comment -> R ()) -> -- | Are we done? R Bool withPoppedComment p f = do r <- popComment p case r of Nothing -> return True Just (L l comment) -> False <$ f l comment -- | Determine if we need to insert a newline between current comment and -- last printed comment. needsNewlineBefore :: -- | Current comment span RealSrcSpan -> -- | Last printed comment span Maybe SpanMark -> Bool needsNewlineBefore _ (Just (HaddockSpan _ _)) = True needsNewlineBefore l mlastMark = case spanMarkSpan <$> mlastMark of Nothing -> False Just lastMark -> srcSpanStartLine l > srcSpanEndLine lastMark + 1 | Is the preceding comment and AST element are on the same line ? theSameLinePre :: -- | Current comment span RealSrcSpan -> -- | AST element location RealSrcSpan -> Bool theSameLinePre l ref = srcSpanEndLine l == srcSpanStartLine ref | Is the following comment and AST element are on the same line ? theSameLinePost :: -- | Current comment span RealSrcSpan -> -- | AST element location RealSrcSpan -> Bool theSameLinePost l ref = srcSpanStartLine l == srcSpanEndLine ref | Determine if given comment follows AST element . commentFollowsElt :: -- | Location of AST element RealSrcSpan -> -- | Location of next AST element Maybe RealSrcSpan -> | Location of enclosing AST element Maybe RealSrcSpan -> -- | Location of last comment in the series Maybe SpanMark -> -- | Comment to test RealLocated Comment -> Bool commentFollowsElt ref mnSpn meSpn mlastMark (L l comment) = A comment follows a AST element if all 4 conditions are satisfied : goesAfter && logicallyFollows && noEltBetween && (continuation || lastInEnclosing || supersedesParentElt) where 1 ) The comment starts after end of the AST element : goesAfter = realSrcSpanStart l >= realSrcSpanEnd ref 2 ) The comment logically belongs to the element , four cases : logicallyFollows = theSameLinePost l ref -- a) it's on the same line || continuation -- b) it's a continuation of a comment block || lastInEnclosing -- c) it's the last element in the enclosing construct 3 ) There is no other AST element between this element and the comment : noEltBetween = case mnSpn of Nothing -> True Just nspn -> realSrcSpanStart nspn >= realSrcSpanEnd l 4 ) Less obvious : if column of comment is closer to the start of -- enclosing element, it probably related to that parent element, not to -- the current child element. This rule is important because otherwise -- all comments would end up assigned to closest inner elements, and -- parent elements won't have a chance to get any comments assigned to -- them. This is not OK because comments will get indented according to -- the AST elements they are attached to. -- -- Skip this rule if the comment is a continuation of a comment block. supersedesParentElt = case meSpn of Nothing -> True Just espn -> let startColumn = srcLocCol . realSrcSpanStart in startColumn espn > startColumn ref || ( abs (startColumn espn - startColumn l) >= abs (startColumn ref - startColumn l) ) continuation = -- A comment is a continuation when it doesn't have non-whitespace -- lexemes in front of it and goes right after the previous comment. not (hasAtomsBefore comment) && ( case mlastMark of Just (HaddockSpan _ _) -> False Just (CommentSpan spn) -> srcSpanEndLine spn + 1 == srcSpanStartLine l _ -> False ) lastInEnclosing = case meSpn of -- When there is no enclosing element, return false Nothing -> False -- When there is an enclosing element, Just espn -> let -- Make sure that the comment is inside the enclosing element insideParent = realSrcSpanEnd l <= realSrcSpanEnd espn -- And check if the next element is outside of the parent nextOutsideParent = case mnSpn of Nothing -> True Just nspn -> realSrcSpanEnd espn < realSrcSpanStart nspn in insideParent && nextOutsideParent -- | Output a 'Comment' immediately. This is a low-level printing function. spitCommentNow :: RealSrcSpan -> Comment -> R () spitCommentNow spn comment = do sitcc . sequence_ . NE.intersperse newline . fmap txt . unComment $ comment setSpanMark (CommentSpan spn) -- | Output a 'Comment' at the end of correct line or after it depending on ' CommentPosition ' . Used for comments that may potentially follow on the -- same line as something we just rendered, but not immediately after it. spitCommentPending :: CommentPosition -> RealSrcSpan -> Comment -> R () spitCommentPending position spn comment = do let wrapper = case position of OnTheSameLine -> sitcc OnNextLine -> id wrapper . sequence_ . NE.toList . fmap (registerPendingCommentLine position) . unComment $ comment setSpanMark (CommentSpan spn)
null
https://raw.githubusercontent.com/tweag/ormolu/f0b8690ae138b96a284f7d72204ca72382724e97/src/Ormolu/Printer/Comments.hs
haskell
# LANGUAGE OverloadedStrings # | Helpers for formatting of comments. This is low-level code, use "Ormolu.Printer.Combinators" unless you know what you are doing. -------------------------------------------------------------------------- Top-level | Output all preceding comments for an element at given location. | Span of the element to attach comments to Insert a blank line between the preceding comments and the thing after them if there was a blank line in the input. | Output all comments following an element at given location. | Span of the element to attach comments to | Output all remaining comments in the comment stream. Make sure we have a blank a line between the last definition and the trailing comments. -------------------------------------------------------------------------- Single-comment functions | Output a single preceding comment for an element at given location. | Span of the element to attach comments to | Are we done? | Output a comment that follows element at given location immediately on the same line, if there is any. | AST element to attach comments to | Are we done? truly something enclosing the AST element. | Output a single remaining comment from the comment stream. | Are we done? -------------------------------------------------------------------------- Helpers | Output series of comments. | Given location of previous comment, output the next comment returning 'True' if we're done | Whether we printed any comments | Try to pop a comment using given predicate and if there is a comment matching the predicate, print it out. | Comment predicate | Printing function | Are we done? | Determine if we need to insert a newline between current comment and last printed comment. | Current comment span | Last printed comment span | Current comment span | AST element location | Current comment span | AST element location | Location of AST element | Location of next AST element | Location of last comment in the series | Comment to test a) it's on the same line b) it's a continuation of a comment block c) it's the last element in the enclosing construct enclosing element, it probably related to that parent element, not to the current child element. This rule is important because otherwise all comments would end up assigned to closest inner elements, and parent elements won't have a chance to get any comments assigned to them. This is not OK because comments will get indented according to the AST elements they are attached to. Skip this rule if the comment is a continuation of a comment block. A comment is a continuation when it doesn't have non-whitespace lexemes in front of it and goes right after the previous comment. When there is no enclosing element, return false When there is an enclosing element, Make sure that the comment is inside the enclosing element And check if the next element is outside of the parent | Output a 'Comment' immediately. This is a low-level printing function. | Output a 'Comment' at the end of correct line or after it depending on same line as something we just rendered, but not immediately after it.
# LANGUAGE LambdaCase # module Ormolu.Printer.Comments ( spitPrecedingComments, spitFollowingComments, spitRemainingComments, spitCommentNow, spitCommentPending, ) where import Control.Monad import qualified Data.List.NonEmpty as NE import Data.Maybe (listToMaybe) import GHC.Types.SrcLoc import Ormolu.Parser.CommentStream import Ormolu.Printer.Internal spitPrecedingComments :: RealSrcSpan -> R () spitPrecedingComments ref = do gotSome <- handleCommentSeries (spitPrecedingComment ref) when gotSome $ do lastMark <- getSpanMark when (needsNewlineBefore ref lastMark) newline spitFollowingComments :: RealSrcSpan -> R () spitFollowingComments ref = do trimSpanStream ref void $ handleCommentSeries (spitFollowingComment ref) spitRemainingComments :: R () spitRemainingComments = do newline void $ handleCommentSeries spitRemainingComment spitPrecedingComment :: RealSrcSpan -> R Bool spitPrecedingComment ref = do mlastMark <- getSpanMark let p (L l _) = realSrcSpanEnd l <= realSrcSpanStart ref withPoppedComment p $ \l comment -> do lineSpans <- thisLineSpans let thisCommentLine = srcLocLine (realSrcSpanStart l) needsNewline = case listToMaybe lineSpans of Nothing -> False Just spn -> srcLocLine (realSrcSpanEnd spn) /= thisCommentLine when (needsNewline || needsNewlineBefore l mlastMark) newline spitCommentNow l comment if theSameLinePre l ref then space else newline spitFollowingComment :: RealSrcSpan -> R Bool spitFollowingComment ref = do mlastMark <- getSpanMark mnSpn <- nextEltSpan Get first enclosing span that is not equal to reference span , i.e. it 's meSpn <- getEnclosingSpan (/= ref) withPoppedComment (commentFollowsElt ref mnSpn meSpn mlastMark) $ \l comment -> if theSameLinePost l ref then if isMultilineComment comment then space >> spitCommentNow l comment else spitCommentPending OnTheSameLine l comment else do when (needsNewlineBefore l mlastMark) $ registerPendingCommentLine OnNextLine "" spitCommentPending OnNextLine l comment spitRemainingComment :: R Bool spitRemainingComment = do mlastMark <- getSpanMark withPoppedComment (const True) $ \l comment -> do when (needsNewlineBefore l mlastMark) newline spitCommentNow l comment newline handleCommentSeries :: R Bool -> R Bool handleCommentSeries f = go False where go gotSome = do done <- f if done then return gotSome else go True withPoppedComment :: (RealLocated Comment -> Bool) -> (RealSrcSpan -> Comment -> R ()) -> R Bool withPoppedComment p f = do r <- popComment p case r of Nothing -> return True Just (L l comment) -> False <$ f l comment needsNewlineBefore :: RealSrcSpan -> Maybe SpanMark -> Bool needsNewlineBefore _ (Just (HaddockSpan _ _)) = True needsNewlineBefore l mlastMark = case spanMarkSpan <$> mlastMark of Nothing -> False Just lastMark -> srcSpanStartLine l > srcSpanEndLine lastMark + 1 | Is the preceding comment and AST element are on the same line ? theSameLinePre :: RealSrcSpan -> RealSrcSpan -> Bool theSameLinePre l ref = srcSpanEndLine l == srcSpanStartLine ref | Is the following comment and AST element are on the same line ? theSameLinePost :: RealSrcSpan -> RealSrcSpan -> Bool theSameLinePost l ref = srcSpanStartLine l == srcSpanEndLine ref | Determine if given comment follows AST element . commentFollowsElt :: RealSrcSpan -> Maybe RealSrcSpan -> | Location of enclosing AST element Maybe RealSrcSpan -> Maybe SpanMark -> RealLocated Comment -> Bool commentFollowsElt ref mnSpn meSpn mlastMark (L l comment) = A comment follows a AST element if all 4 conditions are satisfied : goesAfter && logicallyFollows && noEltBetween && (continuation || lastInEnclosing || supersedesParentElt) where 1 ) The comment starts after end of the AST element : goesAfter = realSrcSpanStart l >= realSrcSpanEnd ref 2 ) The comment logically belongs to the element , four cases : logicallyFollows = 3 ) There is no other AST element between this element and the comment : noEltBetween = case mnSpn of Nothing -> True Just nspn -> realSrcSpanStart nspn >= realSrcSpanEnd l 4 ) Less obvious : if column of comment is closer to the start of supersedesParentElt = case meSpn of Nothing -> True Just espn -> let startColumn = srcLocCol . realSrcSpanStart in startColumn espn > startColumn ref || ( abs (startColumn espn - startColumn l) >= abs (startColumn ref - startColumn l) ) continuation = not (hasAtomsBefore comment) && ( case mlastMark of Just (HaddockSpan _ _) -> False Just (CommentSpan spn) -> srcSpanEndLine spn + 1 == srcSpanStartLine l _ -> False ) lastInEnclosing = case meSpn of Nothing -> False Just espn -> insideParent = realSrcSpanEnd l <= realSrcSpanEnd espn nextOutsideParent = case mnSpn of Nothing -> True Just nspn -> realSrcSpanEnd espn < realSrcSpanStart nspn in insideParent && nextOutsideParent spitCommentNow :: RealSrcSpan -> Comment -> R () spitCommentNow spn comment = do sitcc . sequence_ . NE.intersperse newline . fmap txt . unComment $ comment setSpanMark (CommentSpan spn) ' CommentPosition ' . Used for comments that may potentially follow on the spitCommentPending :: CommentPosition -> RealSrcSpan -> Comment -> R () spitCommentPending position spn comment = do let wrapper = case position of OnTheSameLine -> sitcc OnNextLine -> id wrapper . sequence_ . NE.toList . fmap (registerPendingCommentLine position) . unComment $ comment setSpanMark (CommentSpan spn)
2dbdd4f746e15f8e8e4564326ea426404348ba58e4728ec05dc6d877a9d1a799
RefactoringTools/HaRe
ExactPrint.hs
# LANGUAGE FlexibleContexts # # LANGUAGE FlexibleInstances # # LANGUAGE ScopedTypeVariables # # LANGUAGE NamedFieldPuns # {-# LANGUAGE RankNTypes #-} module Language.Haskell.Refact.Utils.ExactPrint ( replace , replaceAnnKey , copyAnn , setAnnKeywordDP , clearPriorComments , balanceAllComments , locate , addEmptyAnn , addAnnVal , addAnn , zeroDP , setDP , handleParseResult , removeAnns , synthesizeAnns , addNewKeyword , addNewKeywords ) where import qualified GHC as GHC import qualified Data.Generics as SYB import Control.Monad import Language.Haskell.GHC.ExactPrint.Transform import Language.Haskell.GHC.ExactPrint.Types import Language.Haskell.GHC.ExactPrint.Utils import Language.Haskell.Refact.Utils.GhcUtils import Language.Haskell.Refact.Utils.Monad import Language.Haskell.Refact.Utils.MonadFunctions import qualified Data.Map as Map -- --------------------------------------------------------------------- + + AZ++:TODO : Move this to ghc - exactprint -- |The annotations are keyed to the constructor, so if we replace a qualified with an unqualified RdrName or vice versa we have to rebuild the key for the -- appropriate annotation. replaceAnnKey :: (SYB.Data old,SYB.Data new) => GHC.Located old -> GHC.Located new -> Anns -> Anns replaceAnnKey old new ans = case Map.lookup (mkAnnKey old) ans of Nothing -> ans Just v -> anns' where anns1 = Map.delete (mkAnnKey old) ans anns' = Map.insert (mkAnnKey new) v anns1 -- --------------------------------------------------------------------- + + AZ++ TODO : migrate this to ghc - exactprint copyAnn :: (SYB.Data old,SYB.Data new) => GHC.Located old -> GHC.Located new -> Anns -> Anns copyAnn old new ans = case Map.lookup (mkAnnKey old) ans of Nothing -> ans Just v -> Map.insert (mkAnnKey new) v ans -- --------------------------------------------------------------------- -- | Replaces an old expression with a new expression replace :: AnnKey -> AnnKey -> Anns -> Maybe Anns replace old new ans = do let as = ans oldan <- Map.lookup old as newan <- Map.lookup new as let newan' = Ann { annEntryDelta = annEntryDelta oldan , annDelta = annDelta oldan , annTrueEntryDelta = , annPriorComments = annPriorComments oldan , annFollowingComments = annFollowingComments oldan , annsDP = moveAnns (annsDP oldan) (annsDP newan) , annSortKey = annSortKey oldan , annCapturedSpan = annCapturedSpan oldan } return ((\anns -> Map.delete old . Map.insert new newan' $ anns) ans) -- --------------------------------------------------------------------- | Shift the first output annotation into the correct place moveAnns :: [(KeywordId, DeltaPos)] -> [(KeywordId, DeltaPos)] -> [(KeywordId, DeltaPos)] moveAnns [] xs = xs moveAnns ((_, dp): _) ((kw, _):xs) = (kw,dp) : xs moveAnns _ [] = [] -- --------------------------------------------------------------------- -- |Change the @DeltaPos@ for a given @KeywordId@ if it appears in the -- annotation for the given item. setAnnKeywordDP :: (SYB.Data a) => GHC.Located a -> KeywordId -> DeltaPos -> Transform () setAnnKeywordDP la kw dp = modifyAnnsT changer where changer ans = case Map.lookup (mkAnnKey la) ans of Nothing -> ans Just an -> Map.insert (mkAnnKey la) (an {annsDP = map update (annsDP an)}) ans update (kw',dp') | kw == kw' = (kw',dp) | otherwise = (kw',dp') -- --------------------------------------------------------------------- -- |Remove any preceding comments from the given item clearPriorComments :: (SYB.Data a) => GHC.Located a -> Transform () clearPriorComments la = do edp <- getEntryDPT la modifyAnnsT $ \ans -> case Map.lookup (mkAnnKey la) ans of Nothing -> ans Just an -> Map.insert (mkAnnKey la) (an {annPriorComments = [] }) ans setEntryDPT la edp -- --------------------------------------------------------------------- balanceAllComments :: SYB.Data a => GHC.Located a -> Transform (GHC.Located a) balanceAllComments la -- Must be top-down = everywhereM' (SYB.mkM inMod `SYB.extM` inExpr `SYB.extM` inMatch `SYB.extM` inStmt ) la where inMod :: GHC.ParsedSource -> Transform (GHC.ParsedSource) inMod m = doBalance m inExpr :: GHC.LHsExpr GHC.RdrName -> Transform (GHC.LHsExpr GHC.RdrName) inExpr e = doBalance e inMatch :: (GHC.LMatch GHC.RdrName (GHC.LHsExpr GHC.RdrName)) -> Transform (GHC.LMatch GHC.RdrName (GHC.LHsExpr GHC.RdrName)) inMatch m = doBalance m inStmt :: GHC.LStmt GHC.RdrName (GHC.LHsExpr GHC.RdrName) -> Transform (GHC.LStmt GHC.RdrName (GHC.LHsExpr GHC.RdrName)) inStmt s = doBalance s -- |Balance all comments between adjacent decls, as well as pushing all -- trailing comments to the right place. {- e.g., for foo = do return x where x = ['a'] -- do bar = undefined the "-- do" comment must end up in the trailing comments for "x = ['a']" -} doBalance t = do decls <- hsDecls t let go [] = return [] go [x] = return [x] go (x1:x2:xs) = do balanceComments x1 x2 go (x2:xs) _ <- go decls -- replaceDecls t decls' unless (null decls) $ moveTrailingComments t (last decls) return t --This generates a unique location and wraps the given ast chunk with that location --Also adds an empty annotation at that location locate :: (SYB.Data a) => a -> RefactGhc (GHC.Located a) locate ast = do loc <- liftT uniqueSrcSpanT let res = (GHC.L loc ast) addEmptyAnn res return res --Adds an empty annotation at the provided location addEmptyAnn :: (SYB.Data a) => GHC.Located a -> RefactGhc () addEmptyAnn a = addAnn a annNone Adds an " AnnVal " annotation at the provided location addAnnVal :: (SYB.Data a) => GHC.Located a -> RefactGhc () addAnnVal a = addAnn a valAnn where valAnn = annNone {annEntryDelta = DP (0,1), annsDP = [(G GHC.AnnVal, DP (0,0))]} --Adds the given annotation at the provided location addAnn :: (SYB.Data a) => GHC.Located a -> Annotation -> RefactGhc () addAnn a ann = do currAnns <- fetchAnnsFinal let k = mkAnnKey a setRefactAnns $ Map.insert k ann currAnns --Sets the entry delta position of an ast chunk setDP :: (SYB.Data a) => DeltaPos -> GHC.Located a -> RefactGhc () setDP dp ast = do currAnns <- fetchAnnsFinal let k = mkAnnKey ast mv = Map.lookup k currAnns case mv of Nothing -> return () Just v -> addAnn ast (v {annEntryDelta = dp}) Resets the given AST chunk 's delta position to zero . zeroDP :: (SYB.Data a) => GHC.Located a -> RefactGhc () zeroDP = setDP (DP (0,0)) --This just pulls out the successful result from an exact print parser or throws an error if the parse was unsuccessful. handleParseResult :: String -> Either (GHC.SrcSpan, String) (Anns, a) -> RefactGhc (Anns, a) handleParseResult msg e = case e of (Left (_, errStr)) -> error $ "The parse from: " ++ msg ++ " with error: " ++ errStr (Right res) -> return res -- This creates an empty annotation for every located item where an annotation does not already exist in the given AST chunk synthesizeAnns :: (SYB.Data a) => a -> RefactGhc a synthesizeAnns = generic `SYB.ext2M` located where generic :: SYB.Data a => a -> RefactGhc a generic a = do _ <- SYB.gmapM synthesizeAnns a return a located :: (SYB.Data b, SYB.Data loc) => GHC.GenLocated loc b -> RefactGhc (GHC.GenLocated loc b) located b@(GHC.L ss a) = case SYB.cast ss of Just (s :: GHC.SrcSpan) -> do --logm $ "Located found: " ++ (show $ toConstr a) anns <- fetchAnnsFinal let castRes = (GHC.L s a) ann = getAnnotationEP castRes anns logm $ " Found : " + + show case ann of Nothing -> do logm " No found for located item " let newKey = mkAnnKey castRes newAnns = Map.insert newKey annNone anns setRefactAnns newAnns return () _ -> return () _ <- SYB.gmapM synthesizeAnns b return b Nothing -> return b -- This removes all the annotations associated with the given AST chunk. removeAnns :: (SYB.Data a) => a -> RefactGhc a removeAnns = generic `SYB.ext2M` located where generic :: SYB.Data a => a -> RefactGhc a generic a = do _ <- SYB.gmapM synthesizeAnns a return a located :: (SYB.Data b, SYB.Data loc) => GHC.GenLocated loc b -> RefactGhc (GHC.GenLocated loc b) located b@(GHC.L ss a) = case SYB.cast ss of Just (s :: GHC.SrcSpan) -> do anns <- fetchAnnsFinal let k = mkAnnKey (GHC.L s a) logm $ "Deleting ann at: " ++ (show s) setRefactAnns $ Map.delete k anns _ <- SYB.gmapM removeAnns b return b Nothing -> return b This takes in a located ast chunk and adds the provided keyword and delta position into the annsDP list --If there is not annotation associated with the chunk nothing happens addNewKeyword :: (SYB.Data a) => (KeywordId, DeltaPos) -> GHC.Located a -> RefactGhc () addNewKeyword entry a = do anns <- liftT getAnnsT let key = mkAnnKey a mAnn = Map.lookup key anns case mAnn of Nothing -> return () (Just ann) -> do let newAnn = ann{annsDP = (entry:(annsDP ann))} setRefactAnns $ Map.insert key newAnn anns addNewKeywords :: (SYB.Data a) => [(KeywordId, DeltaPos)] -> GHC.Located a -> RefactGhc () addNewKeywords entries a = mapM_ ((flip addNewKeyword) a) entries
null
https://raw.githubusercontent.com/RefactoringTools/HaRe/ef5dee64c38fb104e6e5676095946279fbce381c/src/Language/Haskell/Refact/Utils/ExactPrint.hs
haskell
# LANGUAGE RankNTypes # --------------------------------------------------------------------- |The annotations are keyed to the constructor, so if we replace a qualified appropriate annotation. --------------------------------------------------------------------- --------------------------------------------------------------------- | Replaces an old expression with a new expression --------------------------------------------------------------------- --------------------------------------------------------------------- |Change the @DeltaPos@ for a given @KeywordId@ if it appears in the annotation for the given item. --------------------------------------------------------------------- |Remove any preceding comments from the given item --------------------------------------------------------------------- Must be top-down |Balance all comments between adjacent decls, as well as pushing all trailing comments to the right place. e.g., for foo = do return x where x = ['a'] -- do bar = undefined the "-- do" comment must end up in the trailing comments for "x = ['a']" replaceDecls t decls' This generates a unique location and wraps the given ast chunk with that location Also adds an empty annotation at that location Adds an empty annotation at the provided location Adds the given annotation at the provided location Sets the entry delta position of an ast chunk This just pulls out the successful result from an exact print parser or throws an error if the parse was unsuccessful. This creates an empty annotation for every located item where an annotation does not already exist in the given AST chunk logm $ "Located found: " ++ (show $ toConstr a) This removes all the annotations associated with the given AST chunk. If there is not annotation associated with the chunk nothing happens
# LANGUAGE FlexibleContexts # # LANGUAGE FlexibleInstances # # LANGUAGE ScopedTypeVariables # # LANGUAGE NamedFieldPuns # module Language.Haskell.Refact.Utils.ExactPrint ( replace , replaceAnnKey , copyAnn , setAnnKeywordDP , clearPriorComments , balanceAllComments , locate , addEmptyAnn , addAnnVal , addAnn , zeroDP , setDP , handleParseResult , removeAnns , synthesizeAnns , addNewKeyword , addNewKeywords ) where import qualified GHC as GHC import qualified Data.Generics as SYB import Control.Monad import Language.Haskell.GHC.ExactPrint.Transform import Language.Haskell.GHC.ExactPrint.Types import Language.Haskell.GHC.ExactPrint.Utils import Language.Haskell.Refact.Utils.GhcUtils import Language.Haskell.Refact.Utils.Monad import Language.Haskell.Refact.Utils.MonadFunctions import qualified Data.Map as Map + + AZ++:TODO : Move this to ghc - exactprint with an unqualified RdrName or vice versa we have to rebuild the key for the replaceAnnKey :: (SYB.Data old,SYB.Data new) => GHC.Located old -> GHC.Located new -> Anns -> Anns replaceAnnKey old new ans = case Map.lookup (mkAnnKey old) ans of Nothing -> ans Just v -> anns' where anns1 = Map.delete (mkAnnKey old) ans anns' = Map.insert (mkAnnKey new) v anns1 + + AZ++ TODO : migrate this to ghc - exactprint copyAnn :: (SYB.Data old,SYB.Data new) => GHC.Located old -> GHC.Located new -> Anns -> Anns copyAnn old new ans = case Map.lookup (mkAnnKey old) ans of Nothing -> ans Just v -> Map.insert (mkAnnKey new) v ans replace :: AnnKey -> AnnKey -> Anns -> Maybe Anns replace old new ans = do let as = ans oldan <- Map.lookup old as newan <- Map.lookup new as let newan' = Ann { annEntryDelta = annEntryDelta oldan , annDelta = annDelta oldan , annTrueEntryDelta = , annPriorComments = annPriorComments oldan , annFollowingComments = annFollowingComments oldan , annsDP = moveAnns (annsDP oldan) (annsDP newan) , annSortKey = annSortKey oldan , annCapturedSpan = annCapturedSpan oldan } return ((\anns -> Map.delete old . Map.insert new newan' $ anns) ans) | Shift the first output annotation into the correct place moveAnns :: [(KeywordId, DeltaPos)] -> [(KeywordId, DeltaPos)] -> [(KeywordId, DeltaPos)] moveAnns [] xs = xs moveAnns ((_, dp): _) ((kw, _):xs) = (kw,dp) : xs moveAnns _ [] = [] setAnnKeywordDP :: (SYB.Data a) => GHC.Located a -> KeywordId -> DeltaPos -> Transform () setAnnKeywordDP la kw dp = modifyAnnsT changer where changer ans = case Map.lookup (mkAnnKey la) ans of Nothing -> ans Just an -> Map.insert (mkAnnKey la) (an {annsDP = map update (annsDP an)}) ans update (kw',dp') | kw == kw' = (kw',dp) | otherwise = (kw',dp') clearPriorComments :: (SYB.Data a) => GHC.Located a -> Transform () clearPriorComments la = do edp <- getEntryDPT la modifyAnnsT $ \ans -> case Map.lookup (mkAnnKey la) ans of Nothing -> ans Just an -> Map.insert (mkAnnKey la) (an {annPriorComments = [] }) ans setEntryDPT la edp balanceAllComments :: SYB.Data a => GHC.Located a -> Transform (GHC.Located a) balanceAllComments la = everywhereM' (SYB.mkM inMod `SYB.extM` inExpr `SYB.extM` inMatch `SYB.extM` inStmt ) la where inMod :: GHC.ParsedSource -> Transform (GHC.ParsedSource) inMod m = doBalance m inExpr :: GHC.LHsExpr GHC.RdrName -> Transform (GHC.LHsExpr GHC.RdrName) inExpr e = doBalance e inMatch :: (GHC.LMatch GHC.RdrName (GHC.LHsExpr GHC.RdrName)) -> Transform (GHC.LMatch GHC.RdrName (GHC.LHsExpr GHC.RdrName)) inMatch m = doBalance m inStmt :: GHC.LStmt GHC.RdrName (GHC.LHsExpr GHC.RdrName) -> Transform (GHC.LStmt GHC.RdrName (GHC.LHsExpr GHC.RdrName)) inStmt s = doBalance s doBalance t = do decls <- hsDecls t let go [] = return [] go [x] = return [x] go (x1:x2:xs) = do balanceComments x1 x2 go (x2:xs) _ <- go decls unless (null decls) $ moveTrailingComments t (last decls) return t locate :: (SYB.Data a) => a -> RefactGhc (GHC.Located a) locate ast = do loc <- liftT uniqueSrcSpanT let res = (GHC.L loc ast) addEmptyAnn res return res addEmptyAnn :: (SYB.Data a) => GHC.Located a -> RefactGhc () addEmptyAnn a = addAnn a annNone Adds an " AnnVal " annotation at the provided location addAnnVal :: (SYB.Data a) => GHC.Located a -> RefactGhc () addAnnVal a = addAnn a valAnn where valAnn = annNone {annEntryDelta = DP (0,1), annsDP = [(G GHC.AnnVal, DP (0,0))]} addAnn :: (SYB.Data a) => GHC.Located a -> Annotation -> RefactGhc () addAnn a ann = do currAnns <- fetchAnnsFinal let k = mkAnnKey a setRefactAnns $ Map.insert k ann currAnns setDP :: (SYB.Data a) => DeltaPos -> GHC.Located a -> RefactGhc () setDP dp ast = do currAnns <- fetchAnnsFinal let k = mkAnnKey ast mv = Map.lookup k currAnns case mv of Nothing -> return () Just v -> addAnn ast (v {annEntryDelta = dp}) Resets the given AST chunk 's delta position to zero . zeroDP :: (SYB.Data a) => GHC.Located a -> RefactGhc () zeroDP = setDP (DP (0,0)) handleParseResult :: String -> Either (GHC.SrcSpan, String) (Anns, a) -> RefactGhc (Anns, a) handleParseResult msg e = case e of (Left (_, errStr)) -> error $ "The parse from: " ++ msg ++ " with error: " ++ errStr (Right res) -> return res synthesizeAnns :: (SYB.Data a) => a -> RefactGhc a synthesizeAnns = generic `SYB.ext2M` located where generic :: SYB.Data a => a -> RefactGhc a generic a = do _ <- SYB.gmapM synthesizeAnns a return a located :: (SYB.Data b, SYB.Data loc) => GHC.GenLocated loc b -> RefactGhc (GHC.GenLocated loc b) located b@(GHC.L ss a) = case SYB.cast ss of Just (s :: GHC.SrcSpan) -> do anns <- fetchAnnsFinal let castRes = (GHC.L s a) ann = getAnnotationEP castRes anns logm $ " Found : " + + show case ann of Nothing -> do logm " No found for located item " let newKey = mkAnnKey castRes newAnns = Map.insert newKey annNone anns setRefactAnns newAnns return () _ -> return () _ <- SYB.gmapM synthesizeAnns b return b Nothing -> return b removeAnns :: (SYB.Data a) => a -> RefactGhc a removeAnns = generic `SYB.ext2M` located where generic :: SYB.Data a => a -> RefactGhc a generic a = do _ <- SYB.gmapM synthesizeAnns a return a located :: (SYB.Data b, SYB.Data loc) => GHC.GenLocated loc b -> RefactGhc (GHC.GenLocated loc b) located b@(GHC.L ss a) = case SYB.cast ss of Just (s :: GHC.SrcSpan) -> do anns <- fetchAnnsFinal let k = mkAnnKey (GHC.L s a) logm $ "Deleting ann at: " ++ (show s) setRefactAnns $ Map.delete k anns _ <- SYB.gmapM removeAnns b return b Nothing -> return b This takes in a located ast chunk and adds the provided keyword and delta position into the annsDP list addNewKeyword :: (SYB.Data a) => (KeywordId, DeltaPos) -> GHC.Located a -> RefactGhc () addNewKeyword entry a = do anns <- liftT getAnnsT let key = mkAnnKey a mAnn = Map.lookup key anns case mAnn of Nothing -> return () (Just ann) -> do let newAnn = ann{annsDP = (entry:(annsDP ann))} setRefactAnns $ Map.insert key newAnn anns addNewKeywords :: (SYB.Data a) => [(KeywordId, DeltaPos)] -> GHC.Located a -> RefactGhc () addNewKeywords entries a = mapM_ ((flip addNewKeyword) a) entries
c1691cc0acfdc66a027bdad5448343b55e148f704b4e4c481bd15f4ec3426918
ocaml-omake/omake
lm_position.mli
val debug_pos : bool ref val trace_pos : bool ref * Lm_position information . * Lm_position information. *) type 'a pos (* * Module for creating positions. * You have to specify the name of the module * where the exception are being created: use * MakePos in each file where Name.name is set * to the name of the module. *) module MakePos (Name : sig type t (* This is the name of the module where the position info is created *) val name : string Utilities for managing values val loc_of_t : t -> Lm_location.t val pp_print_t : t Lm_printf.t end ) : sig type t = Name.t (* Creating positions *) val loc_exp_pos : Lm_location.t -> t pos val loc_pos : Lm_location.t -> t pos -> t pos val base_pos : t -> t pos val cons_pos : t -> t pos -> t pos val pos_pos : t pos -> t pos -> t pos val int_pos : int -> t pos -> t pos val string_pos : string -> t pos -> t pos val symbol_pos : Lm_symbol.t -> t pos -> t pos val del_pos : (Format.formatter -> unit) -> Lm_location.t -> t pos val del_exp_pos : (Format.formatter -> unit) -> t pos -> t pos Utilities val loc_of_pos : t pos -> Lm_location.t val pp_print_pos : t pos Lm_printf.t end
null
https://raw.githubusercontent.com/ocaml-omake/omake/08b2a83fb558f6eb6847566cbe1a562230da2b14/src/libmojave/lm_position.mli
ocaml
* Module for creating positions. * You have to specify the name of the module * where the exception are being created: use * MakePos in each file where Name.name is set * to the name of the module. This is the name of the module where the position info is created Creating positions
val debug_pos : bool ref val trace_pos : bool ref * Lm_position information . * Lm_position information. *) type 'a pos module MakePos (Name : sig type t val name : string Utilities for managing values val loc_of_t : t -> Lm_location.t val pp_print_t : t Lm_printf.t end ) : sig type t = Name.t val loc_exp_pos : Lm_location.t -> t pos val loc_pos : Lm_location.t -> t pos -> t pos val base_pos : t -> t pos val cons_pos : t -> t pos -> t pos val pos_pos : t pos -> t pos -> t pos val int_pos : int -> t pos -> t pos val string_pos : string -> t pos -> t pos val symbol_pos : Lm_symbol.t -> t pos -> t pos val del_pos : (Format.formatter -> unit) -> Lm_location.t -> t pos val del_exp_pos : (Format.formatter -> unit) -> t pos -> t pos Utilities val loc_of_pos : t pos -> Lm_location.t val pp_print_pos : t pos Lm_printf.t end
6bc27fd0ad8aba608ce13096231d4a07351bfac930b9c4d34e0f440a6220cf0e
finnishtransportagency/harja
urakoiden_luonti.cljs
(ns harja.tiedot.vesivaylat.hallinta.urakoiden-luonti (:require [reagent.core :refer [atom]] [harja.asiakas.kommunikaatio :as k] [harja.loki :refer [log tarkkaile!]] [cljs.core.async :as async] [harja.ui.kartta.esitettavat-asiat :refer [kartalla-esitettavaan-muotoon]] [tuck.core :as tuck] [cljs.pprint :refer [pprint]] [harja.tyokalut.functor :refer [fmap]] [harja.domain.urakka :as u] [harja.domain.organisaatio :as o] [harja.domain.sopimus :as s] [harja.domain.hanke :as h] [harja.ui.viesti :as viesti] [namespacefy.core :refer [namespacefy]] [harja.tyokalut.local-storage :refer [local-storage-atom]] [harja.pvm :as pvm] [harja.id :refer [id-olemassa?]]) (:require-macros [cljs.core.async.macros :refer [go]])) (def tyhja-sopimus {::s/nimi nil ::s/alku nil ::s/loppu nil ::s/paasopimus-id nil ::s/id nil}) (def uusi-urakka {::u/sopimukset [tyhja-sopimus]}) (defonce tila (atom {:nakymassa? false :valittu-urakka nil :tallennus-kaynnissa? false :urakoiden-haku-kaynnissa? false :haetut-urakat nil :haetut-hallintayksikot nil :haetut-urakoitsijat nil :haetut-hankkeet nil :haetut-sopimukset nil :kaynnissa-olevat-sahkelahetykset #{}})) (defn sopimukset-paasopimuksella [sopimukset paasopimus] (->> sopimukset Asetetaan sopimuksille , mikä sopimus on niiden pääsopimus itse pääsopimukselle asetetaan paasopimus - id : (map #(assoc % ::s/paasopimus-id (when (not= (::s/id %) (::s/id paasopimus)) (::s/id paasopimus)))))) (defn vapaa-sopimus? [s] (nil? (get-in s [::s/urakka ::u/id]))) (defn sopiva-sopimus-urakalle? [u s] (or (vapaa-sopimus? s) (= (::u/id u) (get-in s [::s/urakka ::u/id])))) (defn vapaat-sopimukset [urakka sopimukset urakan-sopimukset] (->> sopimukset (filter (partial sopiva-sopimus-urakalle? urakka)) (remove (comp (into #{} (keep ::s/id urakan-sopimukset)) ::s/id)))) (defn uusin-tieto [hanke sopimukset urakoitsija urakka] (sort-by #(or (:muokattu %) (:luotu %)) pvm/jalkeen? (conj sopimukset hanke urakoitsija urakka))) (defn- lahetykset-uusimmasta-vanhimpaan [lahetykset] (sort-by :lahetetty pvm/jalkeen? lahetykset)) (defn uusin-lahetys [lahetykset] (first (lahetykset-uusimmasta-vanhimpaan lahetykset))) (defn uusin-onnistunut-lahetys [lahetykset] (first (filter :onnistui (lahetykset-uusimmasta-vanhimpaan lahetykset)))) (defrecord ValitseUrakka [urakka]) (defrecord Nakymassa? [nakymassa?]) (defrecord UusiUrakka []) (defrecord TallennaUrakka [urakka]) (defrecord UrakkaTallennettu [urakka]) (defrecord UrakkaEiTallennettu [virhe]) (defrecord UrakkaaMuokattu [urakka]) (defrecord HaeUrakat []) (defrecord UrakatHaettu [urakat]) (defrecord UrakatEiHaettu [virhe]) (defrecord PaivitaSopimuksetGrid [sopimukset]) (defrecord HaeLomakevaihtoehdot []) (defrecord LomakevaihtoehdotHaettu [tulos]) (defrecord LomakevaihtoehdotEiHaettu [virhe]) (extend-protocol tuck/Event ValitseUrakka (process-event [{urakka :urakka} app] (assoc app :valittu-urakka urakka)) Nakymassa? (process-event [{nakymassa? :nakymassa?} app] (assoc app :nakymassa? nakymassa?)) UusiUrakka (process-event [_ app] (assoc app :valittu-urakka uusi-urakka)) TallennaUrakka (process-event [{urakka :urakka} app] (assert (some? (:haetut-urakat app)) "Urakkaa ei voi yrittää tallentaa, ennen kuin urakoiden haku on valmis.") (let [tulos! (tuck/send-async! ->UrakkaTallennettu) fail! (tuck/send-async! ->UrakkaEiTallennettu)] (go (try (let [vastaus (async/<! (k/post! :tallenna-vesivaylaurakka (update urakka ::u/sopimukset #(->> % grid antaa id : n , " oikea i d " , kun valitaan . on neg . i d vain , . (filter (comp id-olemassa? ::s/id))))))] (if (k/virhe? vastaus) (fail! vastaus) (tulos! vastaus))) (catch :default e (fail! nil) (throw e))))) (assoc app :tallennus-kaynnissa? true)) UrakkaTallennettu (process-event [{urakka :urakka} app] (viesti/nayta! "Urakka tallennettu!") (let [vanhat (group-by ::u/id (:haetut-urakat app)) uusi {(::u/id urakka) [urakka]}] Yhdistetään tallennettu . tultaessa Grid kaikki hankkeet , mutta yritetään tässä aikaan (assoc app :haetut-urakat (sort-by ::u/alkupvm pvm/jalkeen? (vec (apply concat (vals (merge vanhat uusi))))) :tallennus-kaynnissa? false :valittu-urakka nil))) UrakkaEiTallennettu (process-event [{virhe :virhe} app] (viesti/nayta! [:span "Virhe tallennuksessa! Urakkaa ei tallennettu."] :danger) (assoc app :tallennus-kaynnissa? false :valittu-urakka nil)) UrakkaaMuokattu (process-event [{urakka :urakka} app] (assoc app :valittu-urakka urakka)) HaeUrakat (process-event [_ app] (let [tulos! (tuck/send-async! ->UrakatHaettu) fail! (tuck/send-async! ->UrakatEiHaettu)] (go (try (let [vastaus (async/<! (k/post! :hae-harjassa-luodut-urakat {}))] (if (k/virhe? vastaus) (fail! vastaus) (tulos! vastaus))) (catch :default e (fail! nil) (throw e))))) (assoc app :urakoiden-haku-kaynnissa? true)) UrakatHaettu (process-event [{urakat :urakat} app] (assoc app :haetut-urakat urakat :urakoiden-haku-kaynnissa? false)) UrakatEiHaettu (process-event [_ app] (viesti/nayta! [:span "Virhe urakoiden haussa!"] :danger) (assoc app :urakoiden-haku-kaynnissa? false)) PaivitaSopimuksetGrid (process-event [{sopimukset :sopimukset} {urakka :valittu-urakka :as app}] (let [urakan-sopimukset-ilman-poistettuja (remove (comp (into #{} (map ::s/id (filter :poistettu sopimukset))) ::s/id) (::u/sopimukset urakka)) paasopimus (s/ainoa-paasopimus urakan-sopimukset-ilman-poistettuja) gridissä , poista pääsopimusmerkintä - yhtäkään sopimusta ei . paasopimus-id (when ((into #{} (map ::s/id sopimukset)) (::s/id paasopimus)) (::s/id paasopimus))] (->> sopimukset Asetetaan sopimukset viittaamaan pääsopimukseen (map #(assoc % ::s/paasopimus-id paasopimus-id)) Jos sopimus on pääsopimus , : paasopimus - id asetetaan nilliksi (map #(update % ::s/paasopimus-id (fn [ps] (when-not (= ps (::s/id %)) ps)))) (assoc-in app [:valittu-urakka ::u/sopimukset])))) HaeLomakevaihtoehdot (process-event [_ app] (let [tulos! (tuck/send-async! ->LomakevaihtoehdotHaettu) fail! (tuck/send-async! ->LomakevaihtoehdotEiHaettu)] (go (try (let [hallintayksikot (k/post! :hallintayksikot {:liikennemuoto :vesi}) hankkeet (k/post! :hae-harjassa-luodut-hankkeet {}) urakoitsijat (k/post! :hae-urakoitsijat-urakkatietoineen {}) sopimukset (k/post! :hae-harjassa-luodut-sopimukset {}) vastaus {:hallintayksikot (async/<! hallintayksikot) :hankkeet (async/<! hankkeet) :urakoitsijat (async/<! urakoitsijat) :sopimukset (async/<! sopimukset)}] (if (some k/virhe? (vals vastaus)) (fail! vastaus) (tulos! (assoc vastaus :hallintayksikot (namespacefy (:hallintayksikot vastaus) {:ns :harja.domain.organisaatio}))))) (catch :default e (fail! nil) (throw e))))) app) LomakevaihtoehdotHaettu (process-event [{tulos :tulos} app] (assoc app :haetut-hallintayksikot (remove (comp (partial = "Kanavat ja avattavat sillat") ::o/nimi) (sort-by ::o/nimi (:hallintayksikot tulos))) :haetut-urakoitsijat (sort-by ::o/nimi (:urakoitsijat tulos)) :haetut-hankkeet (sort-by ::h/nimi (remove #(pvm/jalkeen? (pvm/nyt) (::h/loppupvm %)) (:hankkeet tulos))) :haetut-sopimukset (sort-by ::s/alkupvm pvm/jalkeen? (:sopimukset tulos)))) LomakevaihtoehdotEiHaettu (process-event [_ app] (viesti/nayta! "Hupsista, ongelmia Harjan kanssa juttelussa." :danger) app))
null
https://raw.githubusercontent.com/finnishtransportagency/harja/af09d60911ed31ea98634a9d5c7f4b062e63504f/src/cljs/harja/tiedot/vesivaylat/hallinta/urakoiden_luonti.cljs
clojure
(ns harja.tiedot.vesivaylat.hallinta.urakoiden-luonti (:require [reagent.core :refer [atom]] [harja.asiakas.kommunikaatio :as k] [harja.loki :refer [log tarkkaile!]] [cljs.core.async :as async] [harja.ui.kartta.esitettavat-asiat :refer [kartalla-esitettavaan-muotoon]] [tuck.core :as tuck] [cljs.pprint :refer [pprint]] [harja.tyokalut.functor :refer [fmap]] [harja.domain.urakka :as u] [harja.domain.organisaatio :as o] [harja.domain.sopimus :as s] [harja.domain.hanke :as h] [harja.ui.viesti :as viesti] [namespacefy.core :refer [namespacefy]] [harja.tyokalut.local-storage :refer [local-storage-atom]] [harja.pvm :as pvm] [harja.id :refer [id-olemassa?]]) (:require-macros [cljs.core.async.macros :refer [go]])) (def tyhja-sopimus {::s/nimi nil ::s/alku nil ::s/loppu nil ::s/paasopimus-id nil ::s/id nil}) (def uusi-urakka {::u/sopimukset [tyhja-sopimus]}) (defonce tila (atom {:nakymassa? false :valittu-urakka nil :tallennus-kaynnissa? false :urakoiden-haku-kaynnissa? false :haetut-urakat nil :haetut-hallintayksikot nil :haetut-urakoitsijat nil :haetut-hankkeet nil :haetut-sopimukset nil :kaynnissa-olevat-sahkelahetykset #{}})) (defn sopimukset-paasopimuksella [sopimukset paasopimus] (->> sopimukset Asetetaan sopimuksille , mikä sopimus on niiden pääsopimus itse pääsopimukselle asetetaan paasopimus - id : (map #(assoc % ::s/paasopimus-id (when (not= (::s/id %) (::s/id paasopimus)) (::s/id paasopimus)))))) (defn vapaa-sopimus? [s] (nil? (get-in s [::s/urakka ::u/id]))) (defn sopiva-sopimus-urakalle? [u s] (or (vapaa-sopimus? s) (= (::u/id u) (get-in s [::s/urakka ::u/id])))) (defn vapaat-sopimukset [urakka sopimukset urakan-sopimukset] (->> sopimukset (filter (partial sopiva-sopimus-urakalle? urakka)) (remove (comp (into #{} (keep ::s/id urakan-sopimukset)) ::s/id)))) (defn uusin-tieto [hanke sopimukset urakoitsija urakka] (sort-by #(or (:muokattu %) (:luotu %)) pvm/jalkeen? (conj sopimukset hanke urakoitsija urakka))) (defn- lahetykset-uusimmasta-vanhimpaan [lahetykset] (sort-by :lahetetty pvm/jalkeen? lahetykset)) (defn uusin-lahetys [lahetykset] (first (lahetykset-uusimmasta-vanhimpaan lahetykset))) (defn uusin-onnistunut-lahetys [lahetykset] (first (filter :onnistui (lahetykset-uusimmasta-vanhimpaan lahetykset)))) (defrecord ValitseUrakka [urakka]) (defrecord Nakymassa? [nakymassa?]) (defrecord UusiUrakka []) (defrecord TallennaUrakka [urakka]) (defrecord UrakkaTallennettu [urakka]) (defrecord UrakkaEiTallennettu [virhe]) (defrecord UrakkaaMuokattu [urakka]) (defrecord HaeUrakat []) (defrecord UrakatHaettu [urakat]) (defrecord UrakatEiHaettu [virhe]) (defrecord PaivitaSopimuksetGrid [sopimukset]) (defrecord HaeLomakevaihtoehdot []) (defrecord LomakevaihtoehdotHaettu [tulos]) (defrecord LomakevaihtoehdotEiHaettu [virhe]) (extend-protocol tuck/Event ValitseUrakka (process-event [{urakka :urakka} app] (assoc app :valittu-urakka urakka)) Nakymassa? (process-event [{nakymassa? :nakymassa?} app] (assoc app :nakymassa? nakymassa?)) UusiUrakka (process-event [_ app] (assoc app :valittu-urakka uusi-urakka)) TallennaUrakka (process-event [{urakka :urakka} app] (assert (some? (:haetut-urakat app)) "Urakkaa ei voi yrittää tallentaa, ennen kuin urakoiden haku on valmis.") (let [tulos! (tuck/send-async! ->UrakkaTallennettu) fail! (tuck/send-async! ->UrakkaEiTallennettu)] (go (try (let [vastaus (async/<! (k/post! :tallenna-vesivaylaurakka (update urakka ::u/sopimukset #(->> % grid antaa id : n , " oikea i d " , kun valitaan . on neg . i d vain , . (filter (comp id-olemassa? ::s/id))))))] (if (k/virhe? vastaus) (fail! vastaus) (tulos! vastaus))) (catch :default e (fail! nil) (throw e))))) (assoc app :tallennus-kaynnissa? true)) UrakkaTallennettu (process-event [{urakka :urakka} app] (viesti/nayta! "Urakka tallennettu!") (let [vanhat (group-by ::u/id (:haetut-urakat app)) uusi {(::u/id urakka) [urakka]}] Yhdistetään tallennettu . tultaessa Grid kaikki hankkeet , mutta yritetään tässä aikaan (assoc app :haetut-urakat (sort-by ::u/alkupvm pvm/jalkeen? (vec (apply concat (vals (merge vanhat uusi))))) :tallennus-kaynnissa? false :valittu-urakka nil))) UrakkaEiTallennettu (process-event [{virhe :virhe} app] (viesti/nayta! [:span "Virhe tallennuksessa! Urakkaa ei tallennettu."] :danger) (assoc app :tallennus-kaynnissa? false :valittu-urakka nil)) UrakkaaMuokattu (process-event [{urakka :urakka} app] (assoc app :valittu-urakka urakka)) HaeUrakat (process-event [_ app] (let [tulos! (tuck/send-async! ->UrakatHaettu) fail! (tuck/send-async! ->UrakatEiHaettu)] (go (try (let [vastaus (async/<! (k/post! :hae-harjassa-luodut-urakat {}))] (if (k/virhe? vastaus) (fail! vastaus) (tulos! vastaus))) (catch :default e (fail! nil) (throw e))))) (assoc app :urakoiden-haku-kaynnissa? true)) UrakatHaettu (process-event [{urakat :urakat} app] (assoc app :haetut-urakat urakat :urakoiden-haku-kaynnissa? false)) UrakatEiHaettu (process-event [_ app] (viesti/nayta! [:span "Virhe urakoiden haussa!"] :danger) (assoc app :urakoiden-haku-kaynnissa? false)) PaivitaSopimuksetGrid (process-event [{sopimukset :sopimukset} {urakka :valittu-urakka :as app}] (let [urakan-sopimukset-ilman-poistettuja (remove (comp (into #{} (map ::s/id (filter :poistettu sopimukset))) ::s/id) (::u/sopimukset urakka)) paasopimus (s/ainoa-paasopimus urakan-sopimukset-ilman-poistettuja) gridissä , poista pääsopimusmerkintä - yhtäkään sopimusta ei . paasopimus-id (when ((into #{} (map ::s/id sopimukset)) (::s/id paasopimus)) (::s/id paasopimus))] (->> sopimukset Asetetaan sopimukset viittaamaan pääsopimukseen (map #(assoc % ::s/paasopimus-id paasopimus-id)) Jos sopimus on pääsopimus , : paasopimus - id asetetaan nilliksi (map #(update % ::s/paasopimus-id (fn [ps] (when-not (= ps (::s/id %)) ps)))) (assoc-in app [:valittu-urakka ::u/sopimukset])))) HaeLomakevaihtoehdot (process-event [_ app] (let [tulos! (tuck/send-async! ->LomakevaihtoehdotHaettu) fail! (tuck/send-async! ->LomakevaihtoehdotEiHaettu)] (go (try (let [hallintayksikot (k/post! :hallintayksikot {:liikennemuoto :vesi}) hankkeet (k/post! :hae-harjassa-luodut-hankkeet {}) urakoitsijat (k/post! :hae-urakoitsijat-urakkatietoineen {}) sopimukset (k/post! :hae-harjassa-luodut-sopimukset {}) vastaus {:hallintayksikot (async/<! hallintayksikot) :hankkeet (async/<! hankkeet) :urakoitsijat (async/<! urakoitsijat) :sopimukset (async/<! sopimukset)}] (if (some k/virhe? (vals vastaus)) (fail! vastaus) (tulos! (assoc vastaus :hallintayksikot (namespacefy (:hallintayksikot vastaus) {:ns :harja.domain.organisaatio}))))) (catch :default e (fail! nil) (throw e))))) app) LomakevaihtoehdotHaettu (process-event [{tulos :tulos} app] (assoc app :haetut-hallintayksikot (remove (comp (partial = "Kanavat ja avattavat sillat") ::o/nimi) (sort-by ::o/nimi (:hallintayksikot tulos))) :haetut-urakoitsijat (sort-by ::o/nimi (:urakoitsijat tulos)) :haetut-hankkeet (sort-by ::h/nimi (remove #(pvm/jalkeen? (pvm/nyt) (::h/loppupvm %)) (:hankkeet tulos))) :haetut-sopimukset (sort-by ::s/alkupvm pvm/jalkeen? (:sopimukset tulos)))) LomakevaihtoehdotEiHaettu (process-event [_ app] (viesti/nayta! "Hupsista, ongelmia Harjan kanssa juttelussa." :danger) app))
36dc51137f513f1105e7fe6f09e2ffce11157c97bd8f1edae350044f1c97145e
amnh/PCG
DiscreteWithTCM.hs
----------------------------------------------------------------------------- -- | -- Module : Bio.Metadata.DiscreteWithTCM Copyright : ( c ) 2015 - 2021 Ward Wheeler -- License : BSD-style -- -- Maintainer : -- Stability : provisional -- Portability : portable -- ----------------------------------------------------------------------------- module Bio.Metadata.DiscreteWithTCM ( DiscreteCharacterMetadata(..) , DiscreteWithTcmCharacterMetadata() , DiscreteWithTCMCharacterMetadataDec() , GeneralCharacterMetadata(..) , HasCharacterAlphabet(..) , HasCharacterName(..) , HasCharacterWeight(..) , GetSymbolChangeMatrix(..) , GetPairwiseTransitionCostMatrix(..) , GetSparseTransitionCostMatrix(..) , discreteMetadataFromTCM ) where import Bio.Metadata.DiscreteWithTCM.Class import Bio.Metadata.DiscreteWithTCM.Internal
null
https://raw.githubusercontent.com/amnh/PCG/9341efe0ec2053302c22b4466157d0a24ed18154/lib/core/data-structures/src/Bio/Metadata/DiscreteWithTCM.hs
haskell
--------------------------------------------------------------------------- | Module : Bio.Metadata.DiscreteWithTCM License : BSD-style Maintainer : Stability : provisional Portability : portable ---------------------------------------------------------------------------
Copyright : ( c ) 2015 - 2021 Ward Wheeler module Bio.Metadata.DiscreteWithTCM ( DiscreteCharacterMetadata(..) , DiscreteWithTcmCharacterMetadata() , DiscreteWithTCMCharacterMetadataDec() , GeneralCharacterMetadata(..) , HasCharacterAlphabet(..) , HasCharacterName(..) , HasCharacterWeight(..) , GetSymbolChangeMatrix(..) , GetPairwiseTransitionCostMatrix(..) , GetSparseTransitionCostMatrix(..) , discreteMetadataFromTCM ) where import Bio.Metadata.DiscreteWithTCM.Class import Bio.Metadata.DiscreteWithTCM.Internal
87dc52c0b4cdf8ae584351bce0c1625ecc8a9a6b8e4e97e81f8dab2cb0764aae
cmr-exchange/cmr-client
const.cljc
(ns cmr.client.common.const "Constants defined and/or used by the CMR client.") (def hosts "A map of the supported CMR hosts, where the key is the target deployment environment." {:prod "" :uat "" :sit "" :local ""}) (def deployment-type "A map of the CMR deployment types where the key is the target deployment environment and the value is the deployment type." {:prod :service :uat :service :sit :service :local :local}) (def endpoints "A map of CMR service endpoints for each deployment type." {:access-control {:service "/access-control" :local ":3011"} :graph {:service "/graph" :local ":3012"} :ingest {:service "/ingest" :local ":3002"} :search {:service "/search" :local ":3003"} ;; Local-only endpoints :bootstrap {:local ":3006"} :cubby {:local ":3007"} :index-set {:local ":3005"} :indexer {:local ":3004"} :metadata-db {:local ":3001"}}) (def default-environment-type "Default deployment type for the CMR client." :local) (def default-endpoints "A map of the CMR client's default local endpoints." {:access-control (str (default-environment-type hosts) (get-in endpoints [:access-control :local])) :graph (str (default-environment-type hosts) (get-in endpoints [:graph :local])) :ingest (str (default-environment-type hosts) (get-in endpoints [:ingest :local])) :search (str (default-environment-type hosts) (get-in endpoints [:search :local]))})
null
https://raw.githubusercontent.com/cmr-exchange/cmr-client/0b4dd4114e3b5ed28fc5b57db0f8dcd8773c1c14/src/cljc/cmr/client/common/const.cljc
clojure
Local-only endpoints
(ns cmr.client.common.const "Constants defined and/or used by the CMR client.") (def hosts "A map of the supported CMR hosts, where the key is the target deployment environment." {:prod "" :uat "" :sit "" :local ""}) (def deployment-type "A map of the CMR deployment types where the key is the target deployment environment and the value is the deployment type." {:prod :service :uat :service :sit :service :local :local}) (def endpoints "A map of CMR service endpoints for each deployment type." {:access-control {:service "/access-control" :local ":3011"} :graph {:service "/graph" :local ":3012"} :ingest {:service "/ingest" :local ":3002"} :search {:service "/search" :local ":3003"} :bootstrap {:local ":3006"} :cubby {:local ":3007"} :index-set {:local ":3005"} :indexer {:local ":3004"} :metadata-db {:local ":3001"}}) (def default-environment-type "Default deployment type for the CMR client." :local) (def default-endpoints "A map of the CMR client's default local endpoints." {:access-control (str (default-environment-type hosts) (get-in endpoints [:access-control :local])) :graph (str (default-environment-type hosts) (get-in endpoints [:graph :local])) :ingest (str (default-environment-type hosts) (get-in endpoints [:ingest :local])) :search (str (default-environment-type hosts) (get-in endpoints [:search :local]))})
a8c74744fd1e68ccd181138439ad95378c32c03dcd65dcba047036179f4bbe55
mankyKitty/cautious-sniffle
TestOpts.hs
module General.TestOpts ( OverrideWDUrl (..) ) where import Test.Tasty.Options (IsOption (..)) import Servant.Client.Core (BaseUrl, parseBaseUrl) newtype OverrideWDUrl = OverrideWDUrl (Maybe BaseUrl) instance IsOption OverrideWDUrl where defaultValue = OverrideWDUrl Nothing parseValue = fmap (OverrideWDUrl . Just) . parseBaseUrl optionName = pure "existing-wd" optionHelp = pure "Provide the url of a running selenium/driver instance"
null
https://raw.githubusercontent.com/mankyKitty/cautious-sniffle/8916ef6e2d310158a76f8f573841e09ce3a0d7da/test/General/TestOpts.hs
haskell
module General.TestOpts ( OverrideWDUrl (..) ) where import Test.Tasty.Options (IsOption (..)) import Servant.Client.Core (BaseUrl, parseBaseUrl) newtype OverrideWDUrl = OverrideWDUrl (Maybe BaseUrl) instance IsOption OverrideWDUrl where defaultValue = OverrideWDUrl Nothing parseValue = fmap (OverrideWDUrl . Just) . parseBaseUrl optionName = pure "existing-wd" optionHelp = pure "Provide the url of a running selenium/driver instance"
8598dc2f8c0faa5d5067b16958865fabc7b05c249c67d3d0ac07ac333c422945
NorfairKing/smos
Stuck.hs
# LANGUAGE RecordWildCards # module Smos.Query.Commands.Stuck where import Conduit import qualified Data.Conduit.List as C import Smos.Query.Commands.Import import Smos.Report.Stuck import Smos.Report.Time smosQueryStuck :: StuckSettings -> Q () smosQueryStuck StuckSettings {..} = do now <- liftIO getZonedTime stuckReport <- fmap makeStuckReport $ sourceToList $ streamSmosProjectsQ .| smosMFilter (FilterFst <$> stuckSetFilter) .| C.map (uncurry (makeStuckReportEntry (zonedTimeZone now))) .| C.catMaybes colourSettings <- asks envColourSettings outputChunks $ renderStuckReport colourSettings stuckSetThreshold (zonedTimeToUTC now) stuckReport renderStuckReport :: ColourSettings -> Time -> UTCTime -> StuckReport -> [Chunk] renderStuckReport colourSettings threshold now = formatAsBicolourTable colourSettings . map (formatStuckReportEntry threshold now) . stuckReportEntries
null
https://raw.githubusercontent.com/NorfairKing/smos/91efacaede3574e2f8f9d9601bf0383897eebfd8/smos-query/src/Smos/Query/Commands/Stuck.hs
haskell
# LANGUAGE RecordWildCards # module Smos.Query.Commands.Stuck where import Conduit import qualified Data.Conduit.List as C import Smos.Query.Commands.Import import Smos.Report.Stuck import Smos.Report.Time smosQueryStuck :: StuckSettings -> Q () smosQueryStuck StuckSettings {..} = do now <- liftIO getZonedTime stuckReport <- fmap makeStuckReport $ sourceToList $ streamSmosProjectsQ .| smosMFilter (FilterFst <$> stuckSetFilter) .| C.map (uncurry (makeStuckReportEntry (zonedTimeZone now))) .| C.catMaybes colourSettings <- asks envColourSettings outputChunks $ renderStuckReport colourSettings stuckSetThreshold (zonedTimeToUTC now) stuckReport renderStuckReport :: ColourSettings -> Time -> UTCTime -> StuckReport -> [Chunk] renderStuckReport colourSettings threshold now = formatAsBicolourTable colourSettings . map (formatStuckReportEntry threshold now) . stuckReportEntries
1428fafaad23a6049b1155c7636b072eb4a591473d9944719f8c57cdc7b7c57b
poroh/ersip
ersip_sdp_attr_rtpmap_test.erl
%% Copyright ( c ) 2020 Dmitry Poroh %% All rights reserved. Distributed under the terms of the MIT License . See the LICENSE file . %% SDP media attribute rtpmap %% -module(ersip_sdp_attr_rtpmap_test). -include_lib("eunit/include/eunit.hrl"). %%%=================================================================== %%% Cases %%%=================================================================== parse_test() -> RtpmapBin0 = <<"99 AMR-WB/16000">>, {ok, Rtpmap0} = ersip_sdp_attr_rtpmap:parse(RtpmapBin0), ?assertEqual(99, ersip_sdp_attr_rtpmap:payload_type(Rtpmap0)), ?assertEqual(<<"AMR-WB">>, ersip_sdp_attr_rtpmap:encoding_name(Rtpmap0)), ?assertEqual(16000, ersip_sdp_attr_rtpmap:clock_rate(Rtpmap0)), ?assertEqual(undefined, ersip_sdp_attr_rtpmap:encoding_params(Rtpmap0)), ?assertEqual(RtpmapBin0, ersip_sdp_attr_rtpmap:assemble_bin(Rtpmap0)), RtpmapBin1 = <<"100 H264/90000/2">>, {ok, Rtpmap1} = ersip_sdp_attr_rtpmap:parse(RtpmapBin1), ?assertEqual(100, ersip_sdp_attr_rtpmap:payload_type(Rtpmap1)), ?assertEqual(<<"H264">>, ersip_sdp_attr_rtpmap:encoding_name(Rtpmap1)), ?assertEqual(90000, ersip_sdp_attr_rtpmap:clock_rate(Rtpmap1)), ?assertEqual(2, ersip_sdp_attr_rtpmap:encoding_params(Rtpmap1)), ?assertEqual(RtpmapBin1, ersip_sdp_attr_rtpmap:assemble_bin(Rtpmap1)), {ok, Rtpmap2} = ersip_sdp_attr_rtpmap:parse(<<"101 telephone-event/8000">>), ?assertEqual(101, ersip_sdp_attr_rtpmap:payload_type(Rtpmap2)), ?assertEqual(<<"telephone-event">>, ersip_sdp_attr_rtpmap:encoding_name(Rtpmap2)), ?assertEqual(8000, ersip_sdp_attr_rtpmap:clock_rate(Rtpmap2)), ?assertEqual(undefined, ersip_sdp_attr_rtpmap:encoding_params(Rtpmap2)), ok. parse_error_test() -> ?assertEqual( {error, {invalid_rtpmap, {no_separator, $/, <<"A">>}}}, ersip_sdp_attr_rtpmap:parse(<<"99 AMR-WB/16000A">>) ), ?assertEqual( {error, {invalid_rtpmap, {invalid_integer, <<" AMR-WB/16000">>}}}, ersip_sdp_attr_rtpmap:parse(<<" AMR-WB/16000">>) ), ?assertEqual( {error, {invalid_rtpmap, {invalid_integer, <<"A">>}}}, ersip_sdp_attr_rtpmap:parse(<<"0 AMR-WB/16000/A">>) ), ?assertEqual( {error, {invalid_rtpmap, {no_separator, $/, <<" Garbage">>}}}, ersip_sdp_attr_rtpmap:parse(<<"99 AMR-WB/16000 Garbage">>) ), ?assertEqual( {error, {invalid_rtpmap, {invalid_encoding_params, <<" Garbage">>}}}, ersip_sdp_attr_rtpmap:parse(<<"99 AMR-WB/16000/2 Garbage">>) ), ok.
null
https://raw.githubusercontent.com/poroh/ersip/e408e8f3bbb45572118385b9df40d6e5b0dee714/test/sdp/media/ersip_sdp_attr_rtpmap_test.erl
erlang
All rights reserved. =================================================================== Cases ===================================================================
Copyright ( c ) 2020 Dmitry Poroh Distributed under the terms of the MIT License . See the LICENSE file . SDP media attribute rtpmap -module(ersip_sdp_attr_rtpmap_test). -include_lib("eunit/include/eunit.hrl"). parse_test() -> RtpmapBin0 = <<"99 AMR-WB/16000">>, {ok, Rtpmap0} = ersip_sdp_attr_rtpmap:parse(RtpmapBin0), ?assertEqual(99, ersip_sdp_attr_rtpmap:payload_type(Rtpmap0)), ?assertEqual(<<"AMR-WB">>, ersip_sdp_attr_rtpmap:encoding_name(Rtpmap0)), ?assertEqual(16000, ersip_sdp_attr_rtpmap:clock_rate(Rtpmap0)), ?assertEqual(undefined, ersip_sdp_attr_rtpmap:encoding_params(Rtpmap0)), ?assertEqual(RtpmapBin0, ersip_sdp_attr_rtpmap:assemble_bin(Rtpmap0)), RtpmapBin1 = <<"100 H264/90000/2">>, {ok, Rtpmap1} = ersip_sdp_attr_rtpmap:parse(RtpmapBin1), ?assertEqual(100, ersip_sdp_attr_rtpmap:payload_type(Rtpmap1)), ?assertEqual(<<"H264">>, ersip_sdp_attr_rtpmap:encoding_name(Rtpmap1)), ?assertEqual(90000, ersip_sdp_attr_rtpmap:clock_rate(Rtpmap1)), ?assertEqual(2, ersip_sdp_attr_rtpmap:encoding_params(Rtpmap1)), ?assertEqual(RtpmapBin1, ersip_sdp_attr_rtpmap:assemble_bin(Rtpmap1)), {ok, Rtpmap2} = ersip_sdp_attr_rtpmap:parse(<<"101 telephone-event/8000">>), ?assertEqual(101, ersip_sdp_attr_rtpmap:payload_type(Rtpmap2)), ?assertEqual(<<"telephone-event">>, ersip_sdp_attr_rtpmap:encoding_name(Rtpmap2)), ?assertEqual(8000, ersip_sdp_attr_rtpmap:clock_rate(Rtpmap2)), ?assertEqual(undefined, ersip_sdp_attr_rtpmap:encoding_params(Rtpmap2)), ok. parse_error_test() -> ?assertEqual( {error, {invalid_rtpmap, {no_separator, $/, <<"A">>}}}, ersip_sdp_attr_rtpmap:parse(<<"99 AMR-WB/16000A">>) ), ?assertEqual( {error, {invalid_rtpmap, {invalid_integer, <<" AMR-WB/16000">>}}}, ersip_sdp_attr_rtpmap:parse(<<" AMR-WB/16000">>) ), ?assertEqual( {error, {invalid_rtpmap, {invalid_integer, <<"A">>}}}, ersip_sdp_attr_rtpmap:parse(<<"0 AMR-WB/16000/A">>) ), ?assertEqual( {error, {invalid_rtpmap, {no_separator, $/, <<" Garbage">>}}}, ersip_sdp_attr_rtpmap:parse(<<"99 AMR-WB/16000 Garbage">>) ), ?assertEqual( {error, {invalid_rtpmap, {invalid_encoding_params, <<" Garbage">>}}}, ersip_sdp_attr_rtpmap:parse(<<"99 AMR-WB/16000/2 Garbage">>) ), ok.
4bfc34ad878e5f5464207eaaaea37aaee435501f8928822bb39bde227a59485c
reanimate/reanimate
doc_calligra.hs
#!/usr/bin/env stack -- stack runghc --package reanimate {-# LANGUAGE OverloadedStrings #-} module Main (main) where import Reanimate import Reanimate.LaTeX import Reanimate.Builtin.Documentation main :: IO () main = reanimate $ docEnv $ staticFrame 1 $ center $ withStrokeWidth 0 $ withFillOpacity 1 $ scale 4 $ latexCfg calligra "calligra"
null
https://raw.githubusercontent.com/reanimate/reanimate/5ea023980ff7f488934d40593cc5069f5fd038b0/examples/doc_calligra.hs
haskell
stack runghc --package reanimate # LANGUAGE OverloadedStrings #
#!/usr/bin/env stack module Main (main) where import Reanimate import Reanimate.LaTeX import Reanimate.Builtin.Documentation main :: IO () main = reanimate $ docEnv $ staticFrame 1 $ center $ withStrokeWidth 0 $ withFillOpacity 1 $ scale 4 $ latexCfg calligra "calligra"
ab3c88c6ed2bfebf04ff5a6a3902f8afaec82647fa20f85753a4efaad1b8b82d
haskell-mafia/boris
test-io.hs
import Disorder.Core.Main import qualified Test.IO.Boris.Service.Git import qualified Test.IO.Boris.Service.Workspace main :: IO () main = disorderMain [ Test.IO.Boris.Service.Git.tests , Test.IO.Boris.Service.Workspace.tests ]
null
https://raw.githubusercontent.com/haskell-mafia/boris/fb670071600e8b2d8dbb9191fcf6bf8488f83f5a/boris-service/test/test-io.hs
haskell
import Disorder.Core.Main import qualified Test.IO.Boris.Service.Git import qualified Test.IO.Boris.Service.Workspace main :: IO () main = disorderMain [ Test.IO.Boris.Service.Git.tests , Test.IO.Boris.Service.Workspace.tests ]
6cb51dddfb5a71636adb2983ef28ec8db5c802f61aeacec2f1c16b71a0a72a57
jeapostrophe/lux
val-demo.rkt
#lang racket/base (require racket/match racket/fixnum racket/gui/base racket/class (prefix-in pict: pict) (prefix-in image: 2htdp/image) lux lux/chaos/gui lux/chaos/gui/val lux/chaos/gui/key) (define MODES (list (pict:arrowhead 30 0) (image:add-line (image:rectangle 100 100 "solid" "darkolivegreen") 25 25 75 75 (image:make-pen "goldenrod" 30 "solid" "round" "round")))) (struct demo (g/v mode) #:methods gen:word [(define (word-fps w) 60.0) (define (word-label s ft) (lux-standard-label "Values" ft)) (define (word-output w) (match-define (demo g/v mode-n) w) (g/v (list-ref MODES mode-n))) (define (word-event w e) (match-define (demo g/v mode-n) w) (define closed? #f) (cond [(eq? e 'close) #f] [(and (key-event? e) (not (eq? 'release (send e get-key-code)))) (demo g/v (fxmodulo (fx+ 1 mode-n) (length MODES)))] [else (demo g/v mode-n)])) (define (word-tick w) w)]) (module+ main (call-with-chaos (make-gui) (λ () (fiat-lux (demo (make-gui/val) 0)))))
null
https://raw.githubusercontent.com/jeapostrophe/lux/f5d7c1276072f9ea4107b3f8a2d049e0b174c7ba/examples/val-demo.rkt
racket
#lang racket/base (require racket/match racket/fixnum racket/gui/base racket/class (prefix-in pict: pict) (prefix-in image: 2htdp/image) lux lux/chaos/gui lux/chaos/gui/val lux/chaos/gui/key) (define MODES (list (pict:arrowhead 30 0) (image:add-line (image:rectangle 100 100 "solid" "darkolivegreen") 25 25 75 75 (image:make-pen "goldenrod" 30 "solid" "round" "round")))) (struct demo (g/v mode) #:methods gen:word [(define (word-fps w) 60.0) (define (word-label s ft) (lux-standard-label "Values" ft)) (define (word-output w) (match-define (demo g/v mode-n) w) (g/v (list-ref MODES mode-n))) (define (word-event w e) (match-define (demo g/v mode-n) w) (define closed? #f) (cond [(eq? e 'close) #f] [(and (key-event? e) (not (eq? 'release (send e get-key-code)))) (demo g/v (fxmodulo (fx+ 1 mode-n) (length MODES)))] [else (demo g/v mode-n)])) (define (word-tick w) w)]) (module+ main (call-with-chaos (make-gui) (λ () (fiat-lux (demo (make-gui/val) 0)))))
df32cc2b4c612a1f722f21f00c8d3e3187d4feabe31ee843634a72fe63fa77aa
cram2/cram
asynchronous-process-module-tests.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 the Intelligent Autonomous Systems Group/ ;;; Technische Universitaet Muenchen 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-process-module-tests) (def-asynchronous-process-module asynchronous-test-module ()) (defmethod on-input ((module asynchronous-test-module) input-designator) (funcall (desig:reference input-designator) module input-designator)) (defmethod synchronization-fluent ((module asynchronous-test-module) input) (declare (ignore input)) (cpl:make-fluent :value t)) (define-test test-finish (let* ((executed nil) (designator (desig:make-designator :test (lambda (module input) (declare (ignore input)) (setf executed t) (finish-process-module module))))) (cpl:top-level (with-process-modules-running ((:module asynchronous-test-module)) (pm-execute :module designator) (monitor-process-module :module))) (assert-true executed))) (define-test test-asynchronous-execution (let* ((time-1 nil) (time-2 nil) (designator (desig:make-designator :test (lambda (module input) (declare (ignore input)) (sleep 0.2) (setf time-1 (get-internal-real-time)) (finish-process-module module))))) (cpl:top-level (with-process-modules-running ((:module asynchronous-test-module)) (pm-execute :module designator) (setf time-2 (get-internal-real-time)) (monitor-process-module :module))) (assert-true (> time-1 time-2)))) (define-test test-2-asynchronous-executions (let* ((time-1 nil) (time-2 nil) (time-3 nil) (designator-1 (desig:make-designator :test (lambda (module input) (sleep 0.2) (setf time-1 (get-internal-real-time)) (finish-process-module module :designator input)))) (designator-2 (desig:make-designator :test (lambda (module input) (sleep 0.2) (setf time-2 (get-internal-real-time)) (finish-process-module module :designator input))))) (cpl:top-level (with-process-modules-running ((:module asynchronous-test-module)) (pm-execute :module designator-1) (pm-execute :module designator-2) (setf time-3 (get-internal-real-time)) (monitor-process-module :module))) (assert-true (> time-1 time-3)) (assert-true (> time-2 time-3)))) (define-test test-monitoring-separately (let* ((time-1 nil) (time-2 nil) (time-3 nil) (designator-1 (desig:make-designator :test (lambda (module input) (sb-thread:make-thread (lambda () (sleep 0.2) (setf time-1 (get-internal-real-time)) (finish-process-module module :designator input)))))) (designator-2 (desig:make-designator :test (lambda (module input) (sb-thread:make-thread (lambda () (setf time-2 (get-internal-real-time)) (finish-process-module module :designator input))))))) (cpl:top-level (with-process-modules-running ((:module asynchronous-test-module)) (pm-execute :module designator-1) (pm-execute :module designator-2) (monitor-process-module :module :designators designator-2) (setf time-3 (get-internal-real-time)) (monitor-process-module :module :designators designator-1))) (assert-true (> time-1 time-3)) (assert-true (<= time-2 time-3)))) (define-test test-failure (let* ((condition (make-condition 'process-module-test-error)) (designator (desig:make-designator :test (lambda (module input) (declare (ignore input)) (fail-process-module module condition)))) (received-condition nil)) (cpl:top-level (with-process-modules-running ((:module asynchronous-test-module)) (pm-execute :module designator) (handler-case (monitor-process-module :module) (process-module-test-error (thrown-condition) (setf received-condition thrown-condition))))) (assert-eq condition received-condition))) (define-test test-specific-failure (let* ((condition-1 (make-condition 'process-module-test-error)) (condition-2 (make-condition 'process-module-test-error)) (designator-1 (desig:make-designator :test (lambda (module input) (sb-thread:make-thread (lambda () (sleep 0.1) (fail-process-module module condition-1 :designator input)))))) (designator-2 (desig:make-designator :test (lambda (module input) (sb-thread:make-thread (lambda () (fail-process-module module condition-2 :designator input)))))) (received-condition nil)) (cpl:top-level (with-process-modules-running ((:module asynchronous-test-module)) (pm-execute :module designator-1) (pm-execute :module designator-2) (handler-case (monitor-process-module :module :designators designator-1) (process-module-test-error (thrown-condition) (setf received-condition thrown-condition))))) (assert-eq condition-1 received-condition)))
null
https://raw.githubusercontent.com/cram2/cram/dcb73031ee944d04215bbff9e98b9e8c210ef6c5/cram_core/cram_process_modules/test/asynchronous-process-module-tests.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. Technische Universitaet Muenchen nor the names of its 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.
Copyright ( c ) 2012 , < > * Neither the name of the Intelligent Autonomous Systems Group/ 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-process-module-tests) (def-asynchronous-process-module asynchronous-test-module ()) (defmethod on-input ((module asynchronous-test-module) input-designator) (funcall (desig:reference input-designator) module input-designator)) (defmethod synchronization-fluent ((module asynchronous-test-module) input) (declare (ignore input)) (cpl:make-fluent :value t)) (define-test test-finish (let* ((executed nil) (designator (desig:make-designator :test (lambda (module input) (declare (ignore input)) (setf executed t) (finish-process-module module))))) (cpl:top-level (with-process-modules-running ((:module asynchronous-test-module)) (pm-execute :module designator) (monitor-process-module :module))) (assert-true executed))) (define-test test-asynchronous-execution (let* ((time-1 nil) (time-2 nil) (designator (desig:make-designator :test (lambda (module input) (declare (ignore input)) (sleep 0.2) (setf time-1 (get-internal-real-time)) (finish-process-module module))))) (cpl:top-level (with-process-modules-running ((:module asynchronous-test-module)) (pm-execute :module designator) (setf time-2 (get-internal-real-time)) (monitor-process-module :module))) (assert-true (> time-1 time-2)))) (define-test test-2-asynchronous-executions (let* ((time-1 nil) (time-2 nil) (time-3 nil) (designator-1 (desig:make-designator :test (lambda (module input) (sleep 0.2) (setf time-1 (get-internal-real-time)) (finish-process-module module :designator input)))) (designator-2 (desig:make-designator :test (lambda (module input) (sleep 0.2) (setf time-2 (get-internal-real-time)) (finish-process-module module :designator input))))) (cpl:top-level (with-process-modules-running ((:module asynchronous-test-module)) (pm-execute :module designator-1) (pm-execute :module designator-2) (setf time-3 (get-internal-real-time)) (monitor-process-module :module))) (assert-true (> time-1 time-3)) (assert-true (> time-2 time-3)))) (define-test test-monitoring-separately (let* ((time-1 nil) (time-2 nil) (time-3 nil) (designator-1 (desig:make-designator :test (lambda (module input) (sb-thread:make-thread (lambda () (sleep 0.2) (setf time-1 (get-internal-real-time)) (finish-process-module module :designator input)))))) (designator-2 (desig:make-designator :test (lambda (module input) (sb-thread:make-thread (lambda () (setf time-2 (get-internal-real-time)) (finish-process-module module :designator input))))))) (cpl:top-level (with-process-modules-running ((:module asynchronous-test-module)) (pm-execute :module designator-1) (pm-execute :module designator-2) (monitor-process-module :module :designators designator-2) (setf time-3 (get-internal-real-time)) (monitor-process-module :module :designators designator-1))) (assert-true (> time-1 time-3)) (assert-true (<= time-2 time-3)))) (define-test test-failure (let* ((condition (make-condition 'process-module-test-error)) (designator (desig:make-designator :test (lambda (module input) (declare (ignore input)) (fail-process-module module condition)))) (received-condition nil)) (cpl:top-level (with-process-modules-running ((:module asynchronous-test-module)) (pm-execute :module designator) (handler-case (monitor-process-module :module) (process-module-test-error (thrown-condition) (setf received-condition thrown-condition))))) (assert-eq condition received-condition))) (define-test test-specific-failure (let* ((condition-1 (make-condition 'process-module-test-error)) (condition-2 (make-condition 'process-module-test-error)) (designator-1 (desig:make-designator :test (lambda (module input) (sb-thread:make-thread (lambda () (sleep 0.1) (fail-process-module module condition-1 :designator input)))))) (designator-2 (desig:make-designator :test (lambda (module input) (sb-thread:make-thread (lambda () (fail-process-module module condition-2 :designator input)))))) (received-condition nil)) (cpl:top-level (with-process-modules-running ((:module asynchronous-test-module)) (pm-execute :module designator-1) (pm-execute :module designator-2) (handler-case (monitor-process-module :module :designators designator-1) (process-module-test-error (thrown-condition) (setf received-condition thrown-condition))))) (assert-eq condition-1 received-condition)))
7532f3e48c41c0f550282f0fcc2bb232629474d1ef19c3204f57924215166746
nick8325/quickspec
Resolve.hs
-- A data structure for resolving typeclass instances and similar at runtime. -- -- Takes as input a set of functions ("instances"), and a type, and -- tries to build a value of that type from the instances given. -- -- For example, given the instances -- ordList :: Dict (Arbitrary a) -> Dict (Arbitrary [a]) ordChar : : Dict ( Arbitrary ) and the target type Dict ( Arbitrary [ ] ) , it will produce the value ordList : : Dict ( Arbitrary [ ] ) . -- The instances can in fact be arbitrary functions - though -- their types must be such that the instance search will terminate. {-# OPTIONS_HADDOCK hide #-} # LANGUAGE RankNTypes , ScopedTypeVariables # module QuickSpec.Internal.Haskell.Resolve(Instances(..), inst, valueInst, findInstance, findValue) where import Twee.Base import QuickSpec.Internal.Type import Data.MemoUgly import Data.Functor.Identity import Data.Maybe import Data.Proxy import Control.Monad import Data.Semigroup(Semigroup(..)) -- A set of instances. data Instances = Instances { -- The available instances. -- Each instance is a unary function; 'inst' sees to this. is_instances :: [Poly (Value Identity)], -- The resulting instance search function (memoised). is_find :: Type -> [Value Identity] } -- A smart constructor for Instances. makeInstances :: [Poly (Value Identity)] -> Instances makeInstances is = inst where inst = Instances is (memo (find_ inst . canonicaliseType)) instance Semigroup Instances where x <> y = makeInstances (is_instances x ++ is_instances y) instance Monoid Instances where mempty = makeInstances [] mappend = (<>) -- Create a single instance. inst :: Typeable a => a -> Instances inst x = valueInst (toValue (Identity x)) valueInst :: Value Identity -> Instances valueInst x = polyInst (poly x) where polyInst :: Poly (Value Identity) -> Instances polyInst x = -- Transform x into a single-argument function -- (see comment about is_instances). case typ x of -- A function of type a -> (b -> c) gets uncurried. App (F _ Arrow) (Cons _ (Cons (App (F _ Arrow) _) Empty)) -> polyInst (apply uncur x) App (F _ Arrow) _ -> makeInstances [x] -- A plain old value x (not a function) turns into \() -> x. _ -> makeInstances [apply delay x] where uncur = toPolyValue (uncurry :: (A -> B -> C) -> (A, B) -> C) delay = toPolyValue ((\x () -> x) :: A -> () -> A) Construct a value of a particular type . -- If the type is polymorphic, may return an instance of it. findValue :: Instances -> Type -> Maybe (Value Identity) findValue insts = listToMaybe . is_find insts . skolemiseTypeVars -- Given a type a, construct a value of type f a. -- If the type is polymorphic, may return an instance of it. findInstance :: forall f. Typeable f => Instances -> Type -> Maybe (Value f) findInstance insts ty = unwrapFunctor runIdentity <$> findValue insts ty' where ty' = typeRep (Proxy :: Proxy f) `applyType` ty -- The unmemoised version of the search algorithm. -- Knows how to apply unary functions, and also knows how to generate: -- * The unit type () -- * Pairs (a, b) - search for a and then for b These two are important because instValue encodes other instances -- using them. -- -- Invariant: the type of the returned value is an instance of the argument type. find_ :: Instances -> Type -> [Value Identity] find_ _ (App (F _ unit) Empty) | unit == tyCon (Proxy :: Proxy ()) = return (toValue (Identity ())) find_ insts (App (F _ pair) (Cons ty1 (Cons ty2 Empty))) | pair == tyCon (Proxy :: Proxy (,)) = do x <- is_find insts ty1 sub <- maybeToList (match ty1 (typ x)) -- N.B.: subst sub ty2 because searching for x may have constrained y's type y <- is_find insts (subst sub ty2) sub <- maybeToList (match ty2 (typ y)) return (pairValues (liftM2 (,)) (typeSubst sub x) y) find_ insts ty = do -- Find a function whose result type unifies with ty. -- Rename it to avoid clashes with ty. fun <- fmap (polyRename ty) (is_instances insts) App (F _ Arrow) (Cons arg (Cons res Empty)) <- return (typ fun) sub <- maybeToList (unify ty res) fun <- return (typeSubst sub fun) arg <- return (typeSubst sub arg) -- Find an argument for that function and apply the function. val <- is_find insts arg sub <- maybeToList (match arg (typ val)) return (apply (typeSubst sub fun) val)
null
https://raw.githubusercontent.com/nick8325/quickspec/cb61f719d3d667674431867037ff44dec22ca4f9/src/QuickSpec/Internal/Haskell/Resolve.hs
haskell
A data structure for resolving typeclass instances and similar at runtime. Takes as input a set of functions ("instances"), and a type, and tries to build a value of that type from the instances given. For example, given the instances ordList :: Dict (Arbitrary a) -> Dict (Arbitrary [a]) their types must be such that the instance search will terminate. # OPTIONS_HADDOCK hide # A set of instances. The available instances. Each instance is a unary function; 'inst' sees to this. The resulting instance search function (memoised). A smart constructor for Instances. Create a single instance. Transform x into a single-argument function (see comment about is_instances). A function of type a -> (b -> c) gets uncurried. A plain old value x (not a function) turns into \() -> x. If the type is polymorphic, may return an instance of it. Given a type a, construct a value of type f a. If the type is polymorphic, may return an instance of it. The unmemoised version of the search algorithm. Knows how to apply unary functions, and also knows how to generate: * The unit type () * Pairs (a, b) - search for a and then for b using them. Invariant: the type of the returned value is an instance of the argument type. N.B.: subst sub ty2 because searching for x may have constrained y's type Find a function whose result type unifies with ty. Rename it to avoid clashes with ty. Find an argument for that function and apply the function.
ordChar : : Dict ( Arbitrary ) and the target type Dict ( Arbitrary [ ] ) , it will produce the value ordList : : Dict ( Arbitrary [ ] ) . The instances can in fact be arbitrary functions - though # LANGUAGE RankNTypes , ScopedTypeVariables # module QuickSpec.Internal.Haskell.Resolve(Instances(..), inst, valueInst, findInstance, findValue) where import Twee.Base import QuickSpec.Internal.Type import Data.MemoUgly import Data.Functor.Identity import Data.Maybe import Data.Proxy import Control.Monad import Data.Semigroup(Semigroup(..)) data Instances = Instances { is_instances :: [Poly (Value Identity)], is_find :: Type -> [Value Identity] } makeInstances :: [Poly (Value Identity)] -> Instances makeInstances is = inst where inst = Instances is (memo (find_ inst . canonicaliseType)) instance Semigroup Instances where x <> y = makeInstances (is_instances x ++ is_instances y) instance Monoid Instances where mempty = makeInstances [] mappend = (<>) inst :: Typeable a => a -> Instances inst x = valueInst (toValue (Identity x)) valueInst :: Value Identity -> Instances valueInst x = polyInst (poly x) where polyInst :: Poly (Value Identity) -> Instances polyInst x = case typ x of App (F _ Arrow) (Cons _ (Cons (App (F _ Arrow) _) Empty)) -> polyInst (apply uncur x) App (F _ Arrow) _ -> makeInstances [x] _ -> makeInstances [apply delay x] where uncur = toPolyValue (uncurry :: (A -> B -> C) -> (A, B) -> C) delay = toPolyValue ((\x () -> x) :: A -> () -> A) Construct a value of a particular type . findValue :: Instances -> Type -> Maybe (Value Identity) findValue insts = listToMaybe . is_find insts . skolemiseTypeVars findInstance :: forall f. Typeable f => Instances -> Type -> Maybe (Value f) findInstance insts ty = unwrapFunctor runIdentity <$> findValue insts ty' where ty' = typeRep (Proxy :: Proxy f) `applyType` ty These two are important because instValue encodes other instances find_ :: Instances -> Type -> [Value Identity] find_ _ (App (F _ unit) Empty) | unit == tyCon (Proxy :: Proxy ()) = return (toValue (Identity ())) find_ insts (App (F _ pair) (Cons ty1 (Cons ty2 Empty))) | pair == tyCon (Proxy :: Proxy (,)) = do x <- is_find insts ty1 sub <- maybeToList (match ty1 (typ x)) y <- is_find insts (subst sub ty2) sub <- maybeToList (match ty2 (typ y)) return (pairValues (liftM2 (,)) (typeSubst sub x) y) find_ insts ty = do fun <- fmap (polyRename ty) (is_instances insts) App (F _ Arrow) (Cons arg (Cons res Empty)) <- return (typ fun) sub <- maybeToList (unify ty res) fun <- return (typeSubst sub fun) arg <- return (typeSubst sub arg) val <- is_find insts arg sub <- maybeToList (match arg (typ val)) return (apply (typeSubst sub fun) val)
a171da674a5a8fb836a5b3e0c3eb2b693518e2bf5a9200013ea9869c943afc12
rksm/clj-org-analyzer
calendar.cljs
(ns org-analyzer.view.calendar (:require [org-analyzer.view.util :as util] [org-analyzer.view.dom :as dom] [org-analyzer.view.selection :as sel] [org-analyzer.view.geo :as geo] [clojure.string :refer [lower-case replace]] [reagent.core :as r :refer [cursor]] [reagent.ratom :refer [atom reaction] :rename {atom ratom}] [clojure.set :refer [union difference]])) ;; -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- (defn event-handlers [app-state dom-state] (letfn [(add-selection? [] (-> @dom-state :keys :shift-down?)) (remove-from-selection? [] (-> @dom-state :keys :alt-down?)) (on-click-month [_evt days] (let [dates (into #{} (map :date days))] (swap! app-state update :selected-days #(cond (add-selection?) (union % dates) (remove-from-selection?) (difference % dates) :else dates)))) (on-click-week [_evt _week-no days] (let [dates (into #{} (map :date days))] (swap! app-state update :selected-days #(cond (add-selection?) (union % dates) (remove-from-selection?) (difference % dates) :else dates)))) (on-mouse-over-day [date] (when (not (:selecting? @app-state)) (swap! app-state assoc :hovered-over-date date))) (on-mouse-out-day [] (swap! app-state assoc :hovered-over-date nil)) (on-click-day [_evt date] (swap! app-state update :selected-days #(cond (add-selection?) (conj % date) (remove-from-selection?) (difference % #{date}) (= % #{date}) #{} :else #{date})))] {:on-click-month on-click-month :on-click-week on-click-week :on-mouse-over-day on-mouse-over-day :on-mouse-out-day on-mouse-out-day :on-click-day on-click-day})) ;; -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- ;; rectangle selection helpers (defn- mark-days-as-potentially-selected [app-state dom-state sel-state] (let [sel-bounds (:global-bounds sel-state) contained (into #{} (for [[day day-bounds] (:day-bounding-boxes @dom-state) :when (geo/contains-rect? sel-bounds day-bounds)] day))] (swap! app-state assoc :selected-days-preview contained))) (defn- commit-potentially-selected! [selected-days selected-days-preview valid-selection? dom-state] (let [add-selection? (-> @dom-state :keys :shift-down?) remove-from-selection? (-> @dom-state :keys :alt-down?) selected (cond remove-from-selection? (difference @selected-days @selected-days-preview) add-selection? (union @selected-days-preview @selected-days) :else @selected-days-preview)] (reset! selected-days-preview #{}) (when valid-selection? (reset! selected-days selected)))) ;; -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- (defn- emph-css-class [count max-count] (-> count (/ max-count) (* 10) js/Math.round ((partial str "emph-")))) (defn day-view [dom-state event-handlers {:keys [date] :as _day} {:keys [clocks-by-day selected-days max-weight] :as _calendar-state} highlighted-days] (let [clocks (get @clocks-by-day date) selected? (@selected-days date) highlighted? (@highlighted-days date)] [:div.day {:key date :id date :class [(emph-css-class (util/sum-clocks-mins clocks) @max-weight) (when selected? "selected") (when highlighted? "highlighted")] :ref (fn [el] (if el (swap! dom-state assoc-in [:day-bounding-boxes date] (dom/global-bounds el)) (swap! dom-state update :day-bounding-boxes #(dissoc % date)))) :on-mouse-over #((:on-mouse-over-day event-handlers) date) :on-mouse-out #((:on-mouse-out-day event-handlers)) :on-click #((:on-click-day event-handlers) % date)}])) (defn week-view [dom-state event-handlers week calendar-state highlighted-days] (let [[{week-date :date week-no :week}] week] [:div.week {:key week-date} [:div.week-no {:on-click #((:on-click-week event-handlers) % week-no week)} [:span week-no]] (doall (map #(day-view dom-state event-handlers % calendar-state highlighted-days) week))])) (defn month-view [dom-state event-handlers [date days-in-month] calendar-state highlighted-days] [:div.month {:key date :class (lower-case (:month (first days-in-month)))} [:div.month-date {:on-click #((:on-click-month event-handlers) % days-in-month)} [:span date]] [:div.weeks (doall (map #(week-view dom-state event-handlers % calendar-state highlighted-days) (util/weeks days-in-month)))]]) (defn by-month-excluding-empty-start-and-end-month "Return the by-month sorted dates map without leading and trailing month for which no clock exists." [by-month clocks-by-day] (let [non-empty-days (set (keys (filter (comp not-empty val) clocks-by-day))) not-empty-month? (fn [month-string] (not-any? non-empty-days (map :date (get by-month month-string)))) month-strings (set (keys by-month)) empty-start-month (take-while not-empty-month? month-strings) empty-end-month (take-while not-empty-month? (reverse month-strings))] (into (sorted-map-by <) (select-keys by-month (difference month-strings empty-start-month empty-end-month))))) (defn calendar-view [app-state dom-state event-handlers] (let [clocks-by-day (cursor app-state [:clocks-by-day-filtered]) calendar-state {:max-weight (reaction (->> @clocks-by-day (map (comp util/sum-clocks-mins second)) (reduce max))) :clocks-by-day clocks-by-day :selected-days (reaction (union (:selected-days @app-state) (:selected-days-preview @app-state)))} ;; -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- selecting? (cursor app-state [:selecting?]) selected-days (cursor app-state [:selected-days]) selected-days-preview (cursor app-state [:selected-days-preview]) by-month (into (sorted-map-by <) (->> @app-state :calendar vals flatten (group-by #(replace (:date %) #"^([0-9]+-[0-9]+).*" "$1")))) by-month (if (or (not-empty (:search-input @app-state)) (:print? @app-state)) (by-month-excluding-empty-start-and-end-month by-month @clocks-by-day) by-month) ;; -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- highlighted-days (reaction (set (let [highlighted-locations (-> @app-state :highlighted-entries)] (for [[date clocks] (-> @app-state :clocks-by-day) :when (first (filter #(highlighted-locations (:location %)) clocks))] date))))] [:div.calendar-selection.noselect (sel/drag-mouse-handlers (:sel-rect @dom-state) :on-selection-start #(reset! selecting? true) :on-selection-end #(do (reset! selecting? false) (let [valid-selection? (> (geo/area (:global-bounds %)) 25)] (commit-potentially-selected! selected-days selected-days-preview valid-selection? dom-state))) :on-selection-change #(when @selecting? (mark-days-as-potentially-selected app-state dom-state %))) (when @selecting? [:div.selection {:style (let [[x y w h] (:relative-bounds @(:sel-rect @dom-state))] {:left x :top y :width w :height h})}]) [:div.calendar (doall (map #(month-view dom-state event-handlers % calendar-state highlighted-days) by-month))]]))
null
https://raw.githubusercontent.com/rksm/clj-org-analyzer/19da62aa4dcf1090be8f574f6f2d4c7e116163a8/src/org_analyzer/view/calendar.cljs
clojure
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- rectangle selection helpers -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
(ns org-analyzer.view.calendar (:require [org-analyzer.view.util :as util] [org-analyzer.view.dom :as dom] [org-analyzer.view.selection :as sel] [org-analyzer.view.geo :as geo] [clojure.string :refer [lower-case replace]] [reagent.core :as r :refer [cursor]] [reagent.ratom :refer [atom reaction] :rename {atom ratom}] [clojure.set :refer [union difference]])) (defn event-handlers [app-state dom-state] (letfn [(add-selection? [] (-> @dom-state :keys :shift-down?)) (remove-from-selection? [] (-> @dom-state :keys :alt-down?)) (on-click-month [_evt days] (let [dates (into #{} (map :date days))] (swap! app-state update :selected-days #(cond (add-selection?) (union % dates) (remove-from-selection?) (difference % dates) :else dates)))) (on-click-week [_evt _week-no days] (let [dates (into #{} (map :date days))] (swap! app-state update :selected-days #(cond (add-selection?) (union % dates) (remove-from-selection?) (difference % dates) :else dates)))) (on-mouse-over-day [date] (when (not (:selecting? @app-state)) (swap! app-state assoc :hovered-over-date date))) (on-mouse-out-day [] (swap! app-state assoc :hovered-over-date nil)) (on-click-day [_evt date] (swap! app-state update :selected-days #(cond (add-selection?) (conj % date) (remove-from-selection?) (difference % #{date}) (= % #{date}) #{} :else #{date})))] {:on-click-month on-click-month :on-click-week on-click-week :on-mouse-over-day on-mouse-over-day :on-mouse-out-day on-mouse-out-day :on-click-day on-click-day})) (defn- mark-days-as-potentially-selected [app-state dom-state sel-state] (let [sel-bounds (:global-bounds sel-state) contained (into #{} (for [[day day-bounds] (:day-bounding-boxes @dom-state) :when (geo/contains-rect? sel-bounds day-bounds)] day))] (swap! app-state assoc :selected-days-preview contained))) (defn- commit-potentially-selected! [selected-days selected-days-preview valid-selection? dom-state] (let [add-selection? (-> @dom-state :keys :shift-down?) remove-from-selection? (-> @dom-state :keys :alt-down?) selected (cond remove-from-selection? (difference @selected-days @selected-days-preview) add-selection? (union @selected-days-preview @selected-days) :else @selected-days-preview)] (reset! selected-days-preview #{}) (when valid-selection? (reset! selected-days selected)))) (defn- emph-css-class [count max-count] (-> count (/ max-count) (* 10) js/Math.round ((partial str "emph-")))) (defn day-view [dom-state event-handlers {:keys [date] :as _day} {:keys [clocks-by-day selected-days max-weight] :as _calendar-state} highlighted-days] (let [clocks (get @clocks-by-day date) selected? (@selected-days date) highlighted? (@highlighted-days date)] [:div.day {:key date :id date :class [(emph-css-class (util/sum-clocks-mins clocks) @max-weight) (when selected? "selected") (when highlighted? "highlighted")] :ref (fn [el] (if el (swap! dom-state assoc-in [:day-bounding-boxes date] (dom/global-bounds el)) (swap! dom-state update :day-bounding-boxes #(dissoc % date)))) :on-mouse-over #((:on-mouse-over-day event-handlers) date) :on-mouse-out #((:on-mouse-out-day event-handlers)) :on-click #((:on-click-day event-handlers) % date)}])) (defn week-view [dom-state event-handlers week calendar-state highlighted-days] (let [[{week-date :date week-no :week}] week] [:div.week {:key week-date} [:div.week-no {:on-click #((:on-click-week event-handlers) % week-no week)} [:span week-no]] (doall (map #(day-view dom-state event-handlers % calendar-state highlighted-days) week))])) (defn month-view [dom-state event-handlers [date days-in-month] calendar-state highlighted-days] [:div.month {:key date :class (lower-case (:month (first days-in-month)))} [:div.month-date {:on-click #((:on-click-month event-handlers) % days-in-month)} [:span date]] [:div.weeks (doall (map #(week-view dom-state event-handlers % calendar-state highlighted-days) (util/weeks days-in-month)))]]) (defn by-month-excluding-empty-start-and-end-month "Return the by-month sorted dates map without leading and trailing month for which no clock exists." [by-month clocks-by-day] (let [non-empty-days (set (keys (filter (comp not-empty val) clocks-by-day))) not-empty-month? (fn [month-string] (not-any? non-empty-days (map :date (get by-month month-string)))) month-strings (set (keys by-month)) empty-start-month (take-while not-empty-month? month-strings) empty-end-month (take-while not-empty-month? (reverse month-strings))] (into (sorted-map-by <) (select-keys by-month (difference month-strings empty-start-month empty-end-month))))) (defn calendar-view [app-state dom-state event-handlers] (let [clocks-by-day (cursor app-state [:clocks-by-day-filtered]) calendar-state {:max-weight (reaction (->> @clocks-by-day (map (comp util/sum-clocks-mins second)) (reduce max))) :clocks-by-day clocks-by-day :selected-days (reaction (union (:selected-days @app-state) (:selected-days-preview @app-state)))} selecting? (cursor app-state [:selecting?]) selected-days (cursor app-state [:selected-days]) selected-days-preview (cursor app-state [:selected-days-preview]) by-month (into (sorted-map-by <) (->> @app-state :calendar vals flatten (group-by #(replace (:date %) #"^([0-9]+-[0-9]+).*" "$1")))) by-month (if (or (not-empty (:search-input @app-state)) (:print? @app-state)) (by-month-excluding-empty-start-and-end-month by-month @clocks-by-day) by-month) highlighted-days (reaction (set (let [highlighted-locations (-> @app-state :highlighted-entries)] (for [[date clocks] (-> @app-state :clocks-by-day) :when (first (filter #(highlighted-locations (:location %)) clocks))] date))))] [:div.calendar-selection.noselect (sel/drag-mouse-handlers (:sel-rect @dom-state) :on-selection-start #(reset! selecting? true) :on-selection-end #(do (reset! selecting? false) (let [valid-selection? (> (geo/area (:global-bounds %)) 25)] (commit-potentially-selected! selected-days selected-days-preview valid-selection? dom-state))) :on-selection-change #(when @selecting? (mark-days-as-potentially-selected app-state dom-state %))) (when @selecting? [:div.selection {:style (let [[x y w h] (:relative-bounds @(:sel-rect @dom-state))] {:left x :top y :width w :height h})}]) [:div.calendar (doall (map #(month-view dom-state event-handlers % calendar-state highlighted-days) by-month))]]))
6b65e912e819247ed03ea833fc0a32a859c649b79efa0abaafb80da09bfd9c5f
razum2um/cljsh
core_test.clj
(ns cljsh.core-test (:require [clojure.test :refer :all] [cljsh.core :refer :all])) (deftest a-test (testing "FIXME, I fail." (is (= 0 1))))
null
https://raw.githubusercontent.com/razum2um/cljsh/b2ebe284fea5dce618786111524735c73ff1be63/test/cljsh/core_test.clj
clojure
(ns cljsh.core-test (:require [clojure.test :refer :all] [cljsh.core :refer :all])) (deftest a-test (testing "FIXME, I fail." (is (= 0 1))))
fd0389684b7fba16991ab516cb73f514fe78a20971f76a681b4e850876e9d0f2
thijs/android-ecl-bootstrap
cross-compile-64.lisp
Original file by for ECL . ;;; ;;; This is a much simplified version for EQL5. If you are on 64 bit Linux , you should not need to modify / adapt anything . ;;; requires NDK 18b standalone toolchain ;;; ( See examples ' my ' and ' REPL ' for integrating with ASDF / Quicklisp ) (pushnew :android *features*) (pushnew :aarch64 *features*) (require :cmp) (defpackage :cross (:use :common-lisp) (:export #:compile-file* #:build-static-library* #:build-shared-library* #:build-fasl* )) (in-package :cross) (defmacro with-android-env (() &body body) `(let* ((toolchain (ext:getenv "ANDROID_NDK_TOOLCHAIN_64")) (ecl-android (ext:getenv "ECL_ANDROID_64")) (compiler::*ecl-include-directory* (x:cc ecl-android "/include/")) (compiler::*ecl-library-directory* (x:cc ecl-android "/lib/")) ;; aarch64 (arm 64bit) (compiler::*cc* (x:cc toolchain "/bin/aarch64-linux-android-clang")) (compiler::*ld* (x:cc toolchain "/bin/aarch64-linux-android-ld")) (compiler::*ar* (x:cc toolchain "/bin/aarch64-linux-android-ar")) (compiler::*ranlib* (x:cc toolchain "/bin/aarch64-linux-android-ranlib")) (compiler::*cc-flags* (x:join (list "-DANDROID -DPLATFORM_ANDROID" "-O2 -fPIC -fno-common -D_THREAD_SAFE" (x:cc "-I" ecl-android "/build/gmp"))))) ,@body)) (defun compile-file* (file &optional (system-p t)) (with-android-env () (compile-file file :system-p system-p))) (defun build-static-library* (name &rest arguments) (with-android-env () (apply 'c:build-static-library name arguments))) (defun build-shared-library* (name &rest arguments) (with-android-env () ;; (apply 'c:build-fasl name arguments) (apply 'c:build-shared-library name arguments) )) (defun build-fasl* (name &rest arguments) (with-android-env () (let ((compiler::*ld-rpath* nil)) (apply 'c:build-fasl name arguments)))) (format t "~%*** cross compiling for 'aarch64' ***~%")
null
https://raw.githubusercontent.com/thijs/android-ecl-bootstrap/f8ae88619aad980505e9a01b898089254e6f26a4/example/app/src/main/lisp/utils/cross-compile-64.lisp
lisp
This is a much simplified version for EQL5. aarch64 (arm 64bit) (apply 'c:build-fasl name arguments)
Original file by for ECL . If you are on 64 bit Linux , you should not need to modify / adapt anything . requires NDK 18b standalone toolchain ( See examples ' my ' and ' REPL ' for integrating with ASDF / Quicklisp ) (pushnew :android *features*) (pushnew :aarch64 *features*) (require :cmp) (defpackage :cross (:use :common-lisp) (:export #:compile-file* #:build-static-library* #:build-shared-library* #:build-fasl* )) (in-package :cross) (defmacro with-android-env (() &body body) `(let* ((toolchain (ext:getenv "ANDROID_NDK_TOOLCHAIN_64")) (ecl-android (ext:getenv "ECL_ANDROID_64")) (compiler::*ecl-include-directory* (x:cc ecl-android "/include/")) (compiler::*ecl-library-directory* (x:cc ecl-android "/lib/")) (compiler::*cc* (x:cc toolchain "/bin/aarch64-linux-android-clang")) (compiler::*ld* (x:cc toolchain "/bin/aarch64-linux-android-ld")) (compiler::*ar* (x:cc toolchain "/bin/aarch64-linux-android-ar")) (compiler::*ranlib* (x:cc toolchain "/bin/aarch64-linux-android-ranlib")) (compiler::*cc-flags* (x:join (list "-DANDROID -DPLATFORM_ANDROID" "-O2 -fPIC -fno-common -D_THREAD_SAFE" (x:cc "-I" ecl-android "/build/gmp"))))) ,@body)) (defun compile-file* (file &optional (system-p t)) (with-android-env () (compile-file file :system-p system-p))) (defun build-static-library* (name &rest arguments) (with-android-env () (apply 'c:build-static-library name arguments))) (defun build-shared-library* (name &rest arguments) (with-android-env () (apply 'c:build-shared-library name arguments) )) (defun build-fasl* (name &rest arguments) (with-android-env () (let ((compiler::*ld-rpath* nil)) (apply 'c:build-fasl name arguments)))) (format t "~%*** cross compiling for 'aarch64' ***~%")
69bfccafc745ff58d91a678314d9d4570c773a5222e0e1a8c5e5ddedb81640d3
davidar/stochaskell
coal2.hs
~coalMove :: R -> Model -> P Model~ coalMove t m = do let (e,p,b,d) = coalMoveProbs m mixture' [(e, coalMoveRate t m) ,(p, coalMovePoint t m) ,(b, coalMoveBirth t m) ,(d, coalMoveDeath t m)]
null
https://raw.githubusercontent.com/davidar/stochaskell/d28f9245f5e07c004fb8fd3c828ac2e1cc561673/docs/poster/coal2.hs
haskell
~coalMove :: R -> Model -> P Model~ coalMove t m = do let (e,p,b,d) = coalMoveProbs m mixture' [(e, coalMoveRate t m) ,(p, coalMovePoint t m) ,(b, coalMoveBirth t m) ,(d, coalMoveDeath t m)]
150971e0e601544a1e3b5034b54585eb77db1b3ec07259c9887accadc805d04d
mbj/stratosphere
Group.hs
module Stratosphere.XRay.Group ( module Exports, Group(..), mkGroup ) where import qualified Data.Aeson as JSON import qualified Stratosphere.Prelude as Prelude import Stratosphere.Property import {-# SOURCE #-} Stratosphere.XRay.Group.InsightsConfigurationProperty as Exports import {-# SOURCE #-} Stratosphere.XRay.Group.TagsItemsProperty as Exports import Stratosphere.ResourceProperties import Stratosphere.Value data Group = Group {filterExpression :: (Prelude.Maybe (Value Prelude.Text)), groupName :: (Prelude.Maybe (Value Prelude.Text)), insightsConfiguration :: (Prelude.Maybe InsightsConfigurationProperty), tags :: (Prelude.Maybe [TagsItemsProperty])} mkGroup :: Group mkGroup = Group {filterExpression = Prelude.Nothing, groupName = Prelude.Nothing, insightsConfiguration = Prelude.Nothing, tags = Prelude.Nothing} instance ToResourceProperties Group where toResourceProperties Group {..} = ResourceProperties {awsType = "AWS::XRay::Group", supportsTags = Prelude.True, properties = Prelude.fromList (Prelude.catMaybes [(JSON..=) "FilterExpression" Prelude.<$> filterExpression, (JSON..=) "GroupName" Prelude.<$> groupName, (JSON..=) "InsightsConfiguration" Prelude.<$> insightsConfiguration, (JSON..=) "Tags" Prelude.<$> tags])} instance JSON.ToJSON Group where toJSON Group {..} = JSON.object (Prelude.fromList (Prelude.catMaybes [(JSON..=) "FilterExpression" Prelude.<$> filterExpression, (JSON..=) "GroupName" Prelude.<$> groupName, (JSON..=) "InsightsConfiguration" Prelude.<$> insightsConfiguration, (JSON..=) "Tags" Prelude.<$> tags])) instance Property "FilterExpression" Group where type PropertyType "FilterExpression" Group = Value Prelude.Text set newValue Group {..} = Group {filterExpression = Prelude.pure newValue, ..} instance Property "GroupName" Group where type PropertyType "GroupName" Group = Value Prelude.Text set newValue Group {..} = Group {groupName = Prelude.pure newValue, ..} instance Property "InsightsConfiguration" Group where type PropertyType "InsightsConfiguration" Group = InsightsConfigurationProperty set newValue Group {..} = Group {insightsConfiguration = Prelude.pure newValue, ..} instance Property "Tags" Group where type PropertyType "Tags" Group = [TagsItemsProperty] set newValue Group {..} = Group {tags = Prelude.pure newValue, ..}
null
https://raw.githubusercontent.com/mbj/stratosphere/c70f301715425247efcda29af4f3fcf7ec04aa2f/services/xray/gen/Stratosphere/XRay/Group.hs
haskell
# SOURCE # # SOURCE #
module Stratosphere.XRay.Group ( module Exports, Group(..), mkGroup ) where import qualified Data.Aeson as JSON import qualified Stratosphere.Prelude as Prelude import Stratosphere.Property import Stratosphere.ResourceProperties import Stratosphere.Value data Group = Group {filterExpression :: (Prelude.Maybe (Value Prelude.Text)), groupName :: (Prelude.Maybe (Value Prelude.Text)), insightsConfiguration :: (Prelude.Maybe InsightsConfigurationProperty), tags :: (Prelude.Maybe [TagsItemsProperty])} mkGroup :: Group mkGroup = Group {filterExpression = Prelude.Nothing, groupName = Prelude.Nothing, insightsConfiguration = Prelude.Nothing, tags = Prelude.Nothing} instance ToResourceProperties Group where toResourceProperties Group {..} = ResourceProperties {awsType = "AWS::XRay::Group", supportsTags = Prelude.True, properties = Prelude.fromList (Prelude.catMaybes [(JSON..=) "FilterExpression" Prelude.<$> filterExpression, (JSON..=) "GroupName" Prelude.<$> groupName, (JSON..=) "InsightsConfiguration" Prelude.<$> insightsConfiguration, (JSON..=) "Tags" Prelude.<$> tags])} instance JSON.ToJSON Group where toJSON Group {..} = JSON.object (Prelude.fromList (Prelude.catMaybes [(JSON..=) "FilterExpression" Prelude.<$> filterExpression, (JSON..=) "GroupName" Prelude.<$> groupName, (JSON..=) "InsightsConfiguration" Prelude.<$> insightsConfiguration, (JSON..=) "Tags" Prelude.<$> tags])) instance Property "FilterExpression" Group where type PropertyType "FilterExpression" Group = Value Prelude.Text set newValue Group {..} = Group {filterExpression = Prelude.pure newValue, ..} instance Property "GroupName" Group where type PropertyType "GroupName" Group = Value Prelude.Text set newValue Group {..} = Group {groupName = Prelude.pure newValue, ..} instance Property "InsightsConfiguration" Group where type PropertyType "InsightsConfiguration" Group = InsightsConfigurationProperty set newValue Group {..} = Group {insightsConfiguration = Prelude.pure newValue, ..} instance Property "Tags" Group where type PropertyType "Tags" Group = [TagsItemsProperty] set newValue Group {..} = Group {tags = Prelude.pure newValue, ..}
563425eaf383184101ef33e5febfde553d07710b26703486d4c776a6a0b13a4b
ocaml-ppx/ppxlib
expansion_helpers.mli
(** Various helpers for expansion, such as quoting expressions in their context, or mangling names. *) open Import * { 2 Mangling } (** Derive mangled names from type names in a deriver. For instance, the [t] can be turned into [t_of_yojson] or [yojson_of_t] with the functions from this module. *) (** Specification for name mangling. *) type affix = | Prefix of string (** [Prefix p] adds prefix [p]. *) | Suffix of string (** [Suffix s] adds suffix [s]. *) | PrefixSuffix of string * string * [ PrefixSuffix ( p , s ) ] adds both prefix [ p ] and suffix [ s ] . val mangle : ?fixpoint:string -> affix -> string -> string (** [mangle ~fixpoint affix s] derives a mangled name from [s] with the mangling specified by [affix]. If [s] is equal to [fixpoint] (["t"] by default), then [s] is omitted from the mangled name. *) val mangle_type_decl : ?fixpoint:string -> affix -> type_declaration -> string (** [mangle_type_decl ~fixpoint affix td] does the same as {!mangle}, but for the name of [td]. *) val mangle_lid : ?fixpoint:string -> affix -> Longident.t -> Longident.t (** [mangle_lid ~fixpoint affix lid] does the same as {!mangle}, but for the last component of [lid]. *) * { 2 Quoting } module Quoter = Quoter
null
https://raw.githubusercontent.com/ocaml-ppx/ppxlib/1110af2ea18f351cc3f2ccbee8444bb2a4b257b7/src/expansion_helpers.mli
ocaml
* Various helpers for expansion, such as quoting expressions in their context, or mangling names. * Derive mangled names from type names in a deriver. For instance, the [t] can be turned into [t_of_yojson] or [yojson_of_t] with the functions from this module. * Specification for name mangling. * [Prefix p] adds prefix [p]. * [Suffix s] adds suffix [s]. * [mangle ~fixpoint affix s] derives a mangled name from [s] with the mangling specified by [affix]. If [s] is equal to [fixpoint] (["t"] by default), then [s] is omitted from the mangled name. * [mangle_type_decl ~fixpoint affix td] does the same as {!mangle}, but for the name of [td]. * [mangle_lid ~fixpoint affix lid] does the same as {!mangle}, but for the last component of [lid].
open Import * { 2 Mangling } type affix = | PrefixSuffix of string * string * [ PrefixSuffix ( p , s ) ] adds both prefix [ p ] and suffix [ s ] . val mangle : ?fixpoint:string -> affix -> string -> string val mangle_type_decl : ?fixpoint:string -> affix -> type_declaration -> string val mangle_lid : ?fixpoint:string -> affix -> Longident.t -> Longident.t * { 2 Quoting } module Quoter = Quoter
b8de846589ba5e29b61b3ac9fdc1945237a35dd716cd068c6743fb9f8645105d
comoyo/condensation
stack.clj
(ns com.comoyo.condensation.stack (:refer-clojure :exclude [update]) (:require [clojure.data.json :as json] [clojure.set :as set] [amazonica.aws.cloudformation :as cf] [org.tobereplaced.lettercase :as lc]) (:import [com.amazonaws.AmazonServiceException])) (def ^:const ^:private default-timeout-ms (* 10 60 1000)) (def ^:const ^:private status-successfully-complete #{:create-complete :update-complete}) (def ^:const ^:private status-successfully-rolled-back #{:rollback-complete :update-rollback-complete}) (def ^:const ^:private status-in-progress #{:create-in-progress :delete-in-progress :rollback-in-progress :update-complete-cleanup-in-progress :update-in-progress :update-rollback-complete-cleanup-in-progress :update-rollback-in-progress}) (def ^:const ^:private status-ready (set/union status-successfully-complete status-successfully-rolled-back)) (defn- outputs-vector->keywords-map [outputs] {:pre [(vector? outputs)]} (reduce #(assoc %1 (keyword (lc/lower-hyphen (:output-key %2))) (:output-value %2)) {} outputs)) (defn get-outputs "Get the Outputs for a stack in a keyword map." [stack-name] (outputs-vector->keywords-map (:outputs (first (:stacks (cf/describe-stacks :stack-name stack-name)))))) (defn- get-status-from-map [stacks-map] {:pre [(= 1 (count (:stacks stacks-map)))] :post [(keyword? %)]} (lc/lower-hyphen-keyword (:stack-status (first (:stacks stacks-map))))) (defn get-stack-status "Get the status of a stack as a keyword." [stack-name] (try (get-status-from-map (cf/describe-stacks :stack-name stack-name)) (catch com.amazonaws.AmazonServiceException _))) (defn stack-exists? "Check if a stack exists." [stack-name] (not (nil? (get-stack-status stack-name)))) (defn stack-ready? "Check if stack is ready, that is, not being updated or in an invalid state." [stack-name] (contains? status-ready (get-stack-status stack-name))) (defn stack-successfully-rolled-back? "Check if a stack has been successfully rolled back." [stack-name] (contains? status-successfully-rolled-back (get-stack-status stack-name))) (defn stack-in-progress? "Check if a stack is being updated." [stack-name] (contains? status-in-progress (get-stack-status stack-name))) (defn- wait-for-stack-ms [stack-name timeout-ms] (let [future-stack (future (loop [] (if (stack-ready? stack-name) (not (stack-successfully-rolled-back? stack-name)) (when (stack-in-progress? stack-name) (do (Thread/sleep 10000) (recur))))))] (deref future-stack timeout-ms nil))) (defn- wait-for-stack-deleted-ms [stack-name timeout-ms] (let [future-stack (future (loop [] (if (stack-in-progress? stack-name) (do (Thread/sleep 10000) (recur)) (not (stack-exists? stack-name)))))] (deref future-stack timeout-ms nil))) (defn- create [stack-name template capabilities] (cf/create-stack :stack-name stack-name :template-body (json/write-str template) :capabilities capabilities)) (defn- update [stack-name template capabilities] (cf/update-stack :stack-name stack-name :template-body (json/write-str template) :capabilities capabilities)) (defn- create-or-update [stack-name template capabilities] (if (stack-exists? stack-name) (if (stack-ready? stack-name) (update stack-name template capabilities) (throw (RuntimeException. (str "Stack " stack-name " in invalid state.")))) (create stack-name template capabilities))) (defn create-or-update-stack "Create a stack if it does not exist, update if it does." [& {:keys [stack-name template capabilities wait? wait-timeout-ms] :or {capabilities ["CAPABILITY_IAM"] wait? true wait-timeout-ms default-timeout-ms}}] {:pre [(string? stack-name) (map? template)]} (let [result-map (create-or-update stack-name template capabilities)] (if wait? (wait-for-stack-ms stack-name wait-timeout-ms) result-map))) (defn delete-stack "Delete a stack." [& {:keys [stack-name wait? wait-timeout-ms] :or {wait? true wait-timeout-ms default-timeout-ms}}] {:pre [(string? stack-name)]} (let [result-map (cf/delete-stack :stack-name stack-name)] (if wait? (wait-for-stack-deleted-ms stack-name wait-timeout-ms) result-map)))
null
https://raw.githubusercontent.com/comoyo/condensation/12eefa23af9d6610e012f3a23df4b3e1a73ef448/src/com/comoyo/condensation/stack.clj
clojure
(ns com.comoyo.condensation.stack (:refer-clojure :exclude [update]) (:require [clojure.data.json :as json] [clojure.set :as set] [amazonica.aws.cloudformation :as cf] [org.tobereplaced.lettercase :as lc]) (:import [com.amazonaws.AmazonServiceException])) (def ^:const ^:private default-timeout-ms (* 10 60 1000)) (def ^:const ^:private status-successfully-complete #{:create-complete :update-complete}) (def ^:const ^:private status-successfully-rolled-back #{:rollback-complete :update-rollback-complete}) (def ^:const ^:private status-in-progress #{:create-in-progress :delete-in-progress :rollback-in-progress :update-complete-cleanup-in-progress :update-in-progress :update-rollback-complete-cleanup-in-progress :update-rollback-in-progress}) (def ^:const ^:private status-ready (set/union status-successfully-complete status-successfully-rolled-back)) (defn- outputs-vector->keywords-map [outputs] {:pre [(vector? outputs)]} (reduce #(assoc %1 (keyword (lc/lower-hyphen (:output-key %2))) (:output-value %2)) {} outputs)) (defn get-outputs "Get the Outputs for a stack in a keyword map." [stack-name] (outputs-vector->keywords-map (:outputs (first (:stacks (cf/describe-stacks :stack-name stack-name)))))) (defn- get-status-from-map [stacks-map] {:pre [(= 1 (count (:stacks stacks-map)))] :post [(keyword? %)]} (lc/lower-hyphen-keyword (:stack-status (first (:stacks stacks-map))))) (defn get-stack-status "Get the status of a stack as a keyword." [stack-name] (try (get-status-from-map (cf/describe-stacks :stack-name stack-name)) (catch com.amazonaws.AmazonServiceException _))) (defn stack-exists? "Check if a stack exists." [stack-name] (not (nil? (get-stack-status stack-name)))) (defn stack-ready? "Check if stack is ready, that is, not being updated or in an invalid state." [stack-name] (contains? status-ready (get-stack-status stack-name))) (defn stack-successfully-rolled-back? "Check if a stack has been successfully rolled back." [stack-name] (contains? status-successfully-rolled-back (get-stack-status stack-name))) (defn stack-in-progress? "Check if a stack is being updated." [stack-name] (contains? status-in-progress (get-stack-status stack-name))) (defn- wait-for-stack-ms [stack-name timeout-ms] (let [future-stack (future (loop [] (if (stack-ready? stack-name) (not (stack-successfully-rolled-back? stack-name)) (when (stack-in-progress? stack-name) (do (Thread/sleep 10000) (recur))))))] (deref future-stack timeout-ms nil))) (defn- wait-for-stack-deleted-ms [stack-name timeout-ms] (let [future-stack (future (loop [] (if (stack-in-progress? stack-name) (do (Thread/sleep 10000) (recur)) (not (stack-exists? stack-name)))))] (deref future-stack timeout-ms nil))) (defn- create [stack-name template capabilities] (cf/create-stack :stack-name stack-name :template-body (json/write-str template) :capabilities capabilities)) (defn- update [stack-name template capabilities] (cf/update-stack :stack-name stack-name :template-body (json/write-str template) :capabilities capabilities)) (defn- create-or-update [stack-name template capabilities] (if (stack-exists? stack-name) (if (stack-ready? stack-name) (update stack-name template capabilities) (throw (RuntimeException. (str "Stack " stack-name " in invalid state.")))) (create stack-name template capabilities))) (defn create-or-update-stack "Create a stack if it does not exist, update if it does." [& {:keys [stack-name template capabilities wait? wait-timeout-ms] :or {capabilities ["CAPABILITY_IAM"] wait? true wait-timeout-ms default-timeout-ms}}] {:pre [(string? stack-name) (map? template)]} (let [result-map (create-or-update stack-name template capabilities)] (if wait? (wait-for-stack-ms stack-name wait-timeout-ms) result-map))) (defn delete-stack "Delete a stack." [& {:keys [stack-name wait? wait-timeout-ms] :or {wait? true wait-timeout-ms default-timeout-ms}}] {:pre [(string? stack-name)]} (let [result-map (cf/delete-stack :stack-name stack-name)] (if wait? (wait-for-stack-deleted-ms stack-name wait-timeout-ms) result-map)))
b8d6697a9b84ff387d2d8c3b150e2f154c2cbe39c32f492e0dca7f42339b7afa
footprintanalytics/footprint-web
failure_test.clj
(ns metabase.query-processor-test.failure-test "Tests for how the query processor as a whole handles failures." (:require [clojure.test :refer :all] [metabase.query-processor :as qp] [metabase.query-processor.interface :as qp.i] [metabase.test :as mt] [metabase.util.schema :as su] [schema.core :as s])) (use-fixtures :each (fn [thunk] (mt/with-log-level :fatal (thunk)))) (defn- bad-query [] {:database (mt/id) :type :query :query {:source-table (mt/id :venues) :fields [["datetime_field" (mt/id :venues :id) "MONTH"]]}}) (defn- bad-query-schema [] {:database (s/eq (mt/id)) :type (s/eq :query) :query {:source-table (s/eq (mt/id :venues)) :fields (s/eq [["datetime_field" (mt/id :venues :id) "MONTH"]])}}) (defn- bad-query-preprocessed-schema [] {:database (s/eq (mt/id)) :type (s/eq :query) :query {:source-table (s/eq (mt/id :venues)) :fields (s/eq [[:field (mt/id :venues :id) {:temporal-unit :month}]]) :limit (s/eq qp.i/absolute-max-results) s/Keyword s/Any} (s/optional-key :driver) (s/eq :h2) s/Keyword s/Any}) (def ^:private bad-query-native-schema {:query (s/eq (str "SELECT parsedatetime(formatdatetime(\"PUBLIC\".\"VENUES\".\"ID\", 'yyyyMM'), 'yyyyMM') AS \"ID\" " "FROM \"PUBLIC\".\"VENUES\" " "LIMIT 1048575")) :params (s/eq nil)}) (deftest process-userland-query-test (testing "running a bad query via `process-query` should return stacktrace, query, preprocessed query, and native query" (is (schema= {:status (s/eq :failed) :class Class :error s/Str :stacktrace [su/NonBlankString] ;; `:database` is removed by the catch-exceptions middleware for historical reasons :json_query (bad-query-schema) :preprocessed (bad-query-preprocessed-schema) :native bad-query-native-schema s/Keyword s/Any} (qp/process-userland-query (bad-query)))))) (deftest process-query-and-save-execution-test (testing "running via `process-query-and-save-execution!` should return similar info and a bunch of other nonsense too" (is (schema= {:database_id (s/eq (mt/id)) :started_at java.time.ZonedDateTime :json_query (bad-query-schema) :native bad-query-native-schema :status (s/eq :failed) :class Class :stacktrace [su/NonBlankString] :context (s/eq :question) :error su/NonBlankString :row_count (s/eq 0) :running_time (s/constrained s/Int (complement neg?)) :preprocessed (bad-query-preprocessed-schema) :data {:rows (s/eq []) :cols (s/eq [])} s/Keyword s/Any} (qp/process-query-and-save-execution! (bad-query) {:context :question})))))
null
https://raw.githubusercontent.com/footprintanalytics/footprint-web/d3090d943dd9fcea493c236f79e7ef8a36ae17fc/test/metabase/query_processor_test/failure_test.clj
clojure
`:database` is removed by the catch-exceptions middleware for historical reasons
(ns metabase.query-processor-test.failure-test "Tests for how the query processor as a whole handles failures." (:require [clojure.test :refer :all] [metabase.query-processor :as qp] [metabase.query-processor.interface :as qp.i] [metabase.test :as mt] [metabase.util.schema :as su] [schema.core :as s])) (use-fixtures :each (fn [thunk] (mt/with-log-level :fatal (thunk)))) (defn- bad-query [] {:database (mt/id) :type :query :query {:source-table (mt/id :venues) :fields [["datetime_field" (mt/id :venues :id) "MONTH"]]}}) (defn- bad-query-schema [] {:database (s/eq (mt/id)) :type (s/eq :query) :query {:source-table (s/eq (mt/id :venues)) :fields (s/eq [["datetime_field" (mt/id :venues :id) "MONTH"]])}}) (defn- bad-query-preprocessed-schema [] {:database (s/eq (mt/id)) :type (s/eq :query) :query {:source-table (s/eq (mt/id :venues)) :fields (s/eq [[:field (mt/id :venues :id) {:temporal-unit :month}]]) :limit (s/eq qp.i/absolute-max-results) s/Keyword s/Any} (s/optional-key :driver) (s/eq :h2) s/Keyword s/Any}) (def ^:private bad-query-native-schema {:query (s/eq (str "SELECT parsedatetime(formatdatetime(\"PUBLIC\".\"VENUES\".\"ID\", 'yyyyMM'), 'yyyyMM') AS \"ID\" " "FROM \"PUBLIC\".\"VENUES\" " "LIMIT 1048575")) :params (s/eq nil)}) (deftest process-userland-query-test (testing "running a bad query via `process-query` should return stacktrace, query, preprocessed query, and native query" (is (schema= {:status (s/eq :failed) :class Class :error s/Str :stacktrace [su/NonBlankString] :json_query (bad-query-schema) :preprocessed (bad-query-preprocessed-schema) :native bad-query-native-schema s/Keyword s/Any} (qp/process-userland-query (bad-query)))))) (deftest process-query-and-save-execution-test (testing "running via `process-query-and-save-execution!` should return similar info and a bunch of other nonsense too" (is (schema= {:database_id (s/eq (mt/id)) :started_at java.time.ZonedDateTime :json_query (bad-query-schema) :native bad-query-native-schema :status (s/eq :failed) :class Class :stacktrace [su/NonBlankString] :context (s/eq :question) :error su/NonBlankString :row_count (s/eq 0) :running_time (s/constrained s/Int (complement neg?)) :preprocessed (bad-query-preprocessed-schema) :data {:rows (s/eq []) :cols (s/eq [])} s/Keyword s/Any} (qp/process-query-and-save-execution! (bad-query) {:context :question})))))
94992522e00e88070238a5b8430adb15c290ddb99b991987107ba71419440100
dongcarl/guix
pm.scm
;;; GNU Guix --- Functional package management for GNU Copyright © 2017 < > ;;; ;;; This file is part of GNU Guix. ;;; GNU is free software ; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation , either version 3 of the License , or ;;; (at your option) any later version. ;;; ;;; GNU Guix is distributed in the hope that it will be useful, ;;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;;; GNU General Public License for more details. ;;; You should have received a copy of the GNU General Public License along with GNU . If not , see < / > . (define-module (gnu services pm) #:use-module (guix gexp) #:use-module (guix packages) #:use-module (guix records) #:use-module (gnu packages admin) #:use-module (gnu packages linux) #:use-module (gnu services) #:use-module (gnu services base) #:use-module (gnu services configuration) #:use-module (gnu services shepherd) #:use-module (gnu system shadow) #:export (tlp-service-type tlp-configuration thermald-configuration thermald-service-type)) (define (uglify-field-name field-name) (let ((str (symbol->string field-name))) (string-join (string-split (string-upcase (if (string-suffix? "?" str) (substring str 0 (1- (string-length str))) str)) #\-) "_"))) (define (serialize-field field-name val) (format #t "~a=~a\n" (uglify-field-name field-name) val)) (define (serialize-boolean field-name val) (serialize-field field-name (if val "1" "0"))) (define-maybe boolean) (define (serialize-string field-name val) (serialize-field field-name val)) (define-maybe string) (define (space-separated-string-list? val) (and (list? val) (and-map (lambda (x) (and (string? x) (not (string-index x #\space)))) val))) (define (serialize-space-separated-string-list field-name val) (serialize-field field-name (format #f "~s" (string-join val " ")))) (define-maybe space-separated-string-list) (define (non-negative-integer? val) (and (exact-integer? val) (not (negative? val)))) (define (serialize-non-negative-integer field-name val) (serialize-field field-name val)) (define-maybe non-negative-integer) (define (on-off-boolean? val) (boolean? val)) (define (serialize-on-off-boolean field-name val) (serialize-field field-name (if val "on" "off"))) (define-maybe on-off-boolean) (define (y-n-boolean? val) (boolean? val)) (define (serialize-y-n-boolean field-name val) (serialize-field field-name (if val "Y" "N"))) (define-configuration tlp-configuration (tlp (package tlp) "The TLP package.") (tlp-enable? (boolean #t) "Set to true if you wish to enable TLP.") (tlp-default-mode (string "AC") "Default mode when no power supply can be detected. Alternatives are AC and BAT.") (disk-idle-secs-on-ac (non-negative-integer 0) "Number of seconds Linux kernel has to wait after the disk goes idle, before syncing on AC.") (disk-idle-secs-on-bat (non-negative-integer 2) "Same as @code{disk-idle-ac} but on BAT mode.") (max-lost-work-secs-on-ac (non-negative-integer 15) "Dirty pages flushing periodicity, expressed in seconds.") (max-lost-work-secs-on-bat (non-negative-integer 60) "Same as @code{max-lost-work-secs-on-ac} but on BAT mode.") (cpu-scaling-governor-on-ac (maybe-space-separated-string-list 'disabled) "CPU frequency scaling governor on AC mode. With intel_pstate driver, alternatives are powersave and performance. With acpi-cpufreq driver, alternatives are ondemand, powersave, performance and conservative.") (cpu-scaling-governor-on-bat (maybe-space-separated-string-list 'disabled) "Same as @code{cpu-scaling-governor-on-ac} but on BAT mode.") (cpu-scaling-min-freq-on-ac (maybe-non-negative-integer 'disabled) "Set the min available frequency for the scaling governor on AC.") (cpu-scaling-max-freq-on-ac (maybe-non-negative-integer 'disabled) "Set the max available frequency for the scaling governor on AC.") (cpu-scaling-min-freq-on-bat (maybe-non-negative-integer 'disabled) "Set the min available frequency for the scaling governor on BAT.") (cpu-scaling-max-freq-on-bat (maybe-non-negative-integer 'disabled) "Set the max available frequency for the scaling governor on BAT.") (cpu-min-perf-on-ac (maybe-non-negative-integer 'disabled) "Limit the min P-state to control the power dissipation of the CPU, in AC mode. Values are stated as a percentage of the available performance.") (cpu-max-perf-on-ac (maybe-non-negative-integer 'disabled) "Limit the max P-state to control the power dissipation of the CPU, in AC mode. Values are stated as a percentage of the available performance.") (cpu-min-perf-on-bat (maybe-non-negative-integer 'disabled) "Same as @code{cpu-min-perf-on-ac} on BAT mode.") (cpu-max-perf-on-bat (maybe-non-negative-integer 'disabled) "Same as @code{cpu-max-perf-on-ac} on BAT mode.") (cpu-boost-on-ac? (maybe-boolean 'disabled) "Enable CPU turbo boost feature on AC mode.") (cpu-boost-on-bat? (maybe-boolean 'disabled) "Same as @code{cpu-boost-on-ac?} on BAT mode.") (sched-powersave-on-ac? (boolean #f) "Allow Linux kernel to minimize the number of CPU cores/hyper-threads used under light load conditions.") (sched-powersave-on-bat? (boolean #t) "Same as @code{sched-powersave-on-ac?} but on BAT mode.") (nmi-watchdog? (boolean #f) "Enable Linux kernel NMI watchdog.") (phc-controls (maybe-string 'disabled) "For Linux kernels with PHC patch applied, change CPU voltages. An example value would be @samp{\"F:V F:V F:V F:V\"}.") (energy-perf-policy-on-ac (string "performance") "Set CPU performance versus energy saving policy on AC. Alternatives are performance, normal, powersave.") (energy-perf-policy-on-bat (string "powersave") "Same as @code{energy-perf-policy-ac} but on BAT mode.") (disks-devices (space-separated-string-list '("sda")) "Hard disk devices.") (disk-apm-level-on-ac (space-separated-string-list '("254" "254")) "Hard disk advanced power management level.") (disk-apm-level-on-bat (space-separated-string-list '("128" "128")) "Same as @code{disk-apm-bat} but on BAT mode.") (disk-spindown-timeout-on-ac (maybe-space-separated-string-list 'disabled) "Hard disk spin down timeout. One value has to be specified for each declared hard disk.") (disk-spindown-timeout-on-bat (maybe-space-separated-string-list 'disabled) "Same as @code{disk-spindown-timeout-on-ac} but on BAT mode.") (disk-iosched (maybe-space-separated-string-list 'disabled) "Select IO scheduler for disk devices. One value has to be specified for each declared hard disk. Example alternatives are cfq, deadline and noop.") (sata-linkpwr-on-ac (string "max_performance") "SATA aggressive link power management (ALPM) level. Alternatives are min_power, medium_power, max_performance.") (sata-linkpwr-on-bat (string "min_power") "Same as @code{sata-linkpwr-ac} but on BAT mode.") (sata-linkpwr-blacklist (maybe-string 'disabled) "Exclude specified SATA host devices for link power management.") (ahci-runtime-pm-on-ac? (maybe-on-off-boolean 'disabled) "Enable Runtime Power Management for AHCI controller and disks on AC mode.") (ahci-runtime-pm-on-bat? (maybe-on-off-boolean 'disabled) "Same as @code{ahci-runtime-pm-on-ac} on BAT mode.") (ahci-runtime-pm-timeout (non-negative-integer 15) "Seconds of inactivity before disk is suspended.") (pcie-aspm-on-ac (string "performance") "PCI Express Active State Power Management level. Alternatives are default, performance, powersave.") (pcie-aspm-on-bat (string "powersave") "Same as @code{pcie-aspm-ac} but on BAT mode.") (radeon-power-profile-on-ac (string "high") "Radeon graphics clock speed level. Alternatives are low, mid, high, auto, default.") (radeon-power-profile-on-bat (string "low") "Same as @code{radeon-power-ac} but on BAT mode.") (radeon-dpm-state-on-ac (string "performance") "Radeon dynamic power management method (DPM). Alternatives are battery, performance.") (radeon-dpm-state-on-bat (string "battery") "Same as @code{radeon-dpm-state-ac} but on BAT mode.") (radeon-dpm-perf-level-on-ac (string "auto") "Radeon DPM performance level. Alternatives are auto, low, high.") (radeon-dpm-perf-level-on-bat (string "auto") "Same as @code{radeon-dpm-perf-ac} but on BAT mode.") (wifi-pwr-on-ac? (on-off-boolean #f) "Wifi power saving mode.") (wifi-pwr-on-bat? (on-off-boolean #t) "Same as @code{wifi-power-ac?} but on BAT mode.") (wol-disable? (y-n-boolean #t) "Disable wake on LAN.") (sound-power-save-on-ac (non-negative-integer 0) "Timeout duration in seconds before activating audio power saving on Intel HDA and AC97 devices. A value of 0 disables power saving.") (sound-power-save-on-bat (non-negative-integer 1) "Same as @code{sound-powersave-ac} but on BAT mode.") (sound-power-save-controller? (y-n-boolean #t) "Disable controller in powersaving mode on Intel HDA devices.") (bay-poweroff-on-bat? (boolean #f) "Enable optical drive in UltraBay/MediaBay on BAT mode. Drive can be powered on again by releasing (and reinserting) the eject lever or by pressing the disc eject button on newer models.") (bay-device (string "sr0") "Name of the optical drive device to power off.") (runtime-pm-on-ac (string "on") "Runtime Power Management for PCI(e) bus devices. Alternatives are on and auto.") (runtime-pm-on-bat (string "auto") "Same as @code{runtime-pm-ac} but on BAT mode.") (runtime-pm-all? (boolean #t) "Runtime Power Management for all PCI(e) bus devices, except blacklisted ones.") (runtime-pm-blacklist (maybe-space-separated-string-list 'disabled) "Exclude specified PCI(e) device addresses from Runtime Power Management.") (runtime-pm-driver-blacklist (space-separated-string-list '("radeon" "nouveau")) "Exclude PCI(e) devices assigned to the specified drivers from Runtime Power Management.") (usb-autosuspend? (boolean #t) "Enable USB autosuspend feature.") (usb-blacklist (maybe-string 'disabled) "Exclude specified devices from USB autosuspend.") (usb-blacklist-wwan? (boolean #t) "Exclude WWAN devices from USB autosuspend.") (usb-whitelist (maybe-string 'disabled) "Include specified devices into USB autosuspend, even if they are already excluded by the driver or via @code{usb-blacklist-wwan?}.") (usb-autosuspend-disable-on-shutdown? (maybe-boolean 'disabled) "Enable USB autosuspend before shutdown.") (restore-device-state-on-startup? (boolean #f) "Restore radio device state (bluetooth, wifi, wwan) from previous shutdown on system startup.")) (define (tlp-shepherd-service config) (let* ((tlp-bin (file-append (tlp-configuration-tlp config) "/bin/tlp")) (tlp-action (lambda args #~(lambda _ (zero? (system* #$tlp-bin #$@args)))))) (list (shepherd-service (documentation "Run TLP script.") (provision '(tlp)) (requirement '(user-processes)) (start (tlp-action "init" "start")) (stop (tlp-action "init" "stop")))))) (define (tlp-activation config) (let* ((config-str (with-output-to-string (lambda () (serialize-configuration config tlp-configuration-fields)))) (config-file (plain-file "tlp" config-str))) (with-imported-modules '((guix build utils)) #~(begin (use-modules (guix build utils)) (copy-file #$config-file "/etc/tlp.conf"))))) (define tlp-service-type (service-type (name 'tlp) (extensions (list (service-extension shepherd-root-service-type tlp-shepherd-service) (service-extension udev-service-type (compose list tlp-configuration-tlp)) (service-extension activation-service-type tlp-activation))) (default-value (tlp-configuration)) (description "Run TLP, a power management tool."))) (define (generate-tlp-documentation) (generate-documentation `((tlp-configuration ,tlp-configuration-fields)) 'tlp-configuration)) ;;; ;;; thermald ;;; ;;; This service implements cpu scaling. Helps prevent overheating! (define-record-type* <thermald-configuration> thermald-configuration make-thermald-configuration thermald-configuration? (ignore-cpuid-check? thermald-ignore-cpuid-check? ;boolean (default #f)) (thermald thermald-thermald ;package (default thermald))) (define (thermald-shepherd-service config) (list (shepherd-service (provision '(thermald)) (documentation "Run thermald cpu frequency scaling.") (start #~(make-forkexec-constructor '(#$(file-append (thermald-thermald config) "/sbin/thermald") "--no-daemon" #$@(if (thermald-ignore-cpuid-check? config) '("--ignore-cpuid-check") '())))) (stop #~(make-kill-destructor))))) (define thermald-service-type (service-type (name 'thermald) (extensions (list (service-extension shepherd-root-service-type thermald-shepherd-service))) (default-value (thermald-configuration)) (description "Run thermald, a CPU frequency scaling service that helps prevent overheating.")))
null
https://raw.githubusercontent.com/dongcarl/guix/82543e9649da2da9a5285ede4ec4f718fd740fcb/gnu/services/pm.scm
scheme
GNU Guix --- Functional package management for GNU This file is part of GNU Guix. you can redistribute it and/or modify (at your option) any later version. GNU Guix is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. thermald This service implements cpu scaling. Helps prevent overheating! boolean package
Copyright © 2017 < > it under the terms of the GNU General Public License as published by the Free Software Foundation , either version 3 of the License , or You should have received a copy of the GNU General Public License along with GNU . If not , see < / > . (define-module (gnu services pm) #:use-module (guix gexp) #:use-module (guix packages) #:use-module (guix records) #:use-module (gnu packages admin) #:use-module (gnu packages linux) #:use-module (gnu services) #:use-module (gnu services base) #:use-module (gnu services configuration) #:use-module (gnu services shepherd) #:use-module (gnu system shadow) #:export (tlp-service-type tlp-configuration thermald-configuration thermald-service-type)) (define (uglify-field-name field-name) (let ((str (symbol->string field-name))) (string-join (string-split (string-upcase (if (string-suffix? "?" str) (substring str 0 (1- (string-length str))) str)) #\-) "_"))) (define (serialize-field field-name val) (format #t "~a=~a\n" (uglify-field-name field-name) val)) (define (serialize-boolean field-name val) (serialize-field field-name (if val "1" "0"))) (define-maybe boolean) (define (serialize-string field-name val) (serialize-field field-name val)) (define-maybe string) (define (space-separated-string-list? val) (and (list? val) (and-map (lambda (x) (and (string? x) (not (string-index x #\space)))) val))) (define (serialize-space-separated-string-list field-name val) (serialize-field field-name (format #f "~s" (string-join val " ")))) (define-maybe space-separated-string-list) (define (non-negative-integer? val) (and (exact-integer? val) (not (negative? val)))) (define (serialize-non-negative-integer field-name val) (serialize-field field-name val)) (define-maybe non-negative-integer) (define (on-off-boolean? val) (boolean? val)) (define (serialize-on-off-boolean field-name val) (serialize-field field-name (if val "on" "off"))) (define-maybe on-off-boolean) (define (y-n-boolean? val) (boolean? val)) (define (serialize-y-n-boolean field-name val) (serialize-field field-name (if val "Y" "N"))) (define-configuration tlp-configuration (tlp (package tlp) "The TLP package.") (tlp-enable? (boolean #t) "Set to true if you wish to enable TLP.") (tlp-default-mode (string "AC") "Default mode when no power supply can be detected. Alternatives are AC and BAT.") (disk-idle-secs-on-ac (non-negative-integer 0) "Number of seconds Linux kernel has to wait after the disk goes idle, before syncing on AC.") (disk-idle-secs-on-bat (non-negative-integer 2) "Same as @code{disk-idle-ac} but on BAT mode.") (max-lost-work-secs-on-ac (non-negative-integer 15) "Dirty pages flushing periodicity, expressed in seconds.") (max-lost-work-secs-on-bat (non-negative-integer 60) "Same as @code{max-lost-work-secs-on-ac} but on BAT mode.") (cpu-scaling-governor-on-ac (maybe-space-separated-string-list 'disabled) "CPU frequency scaling governor on AC mode. With intel_pstate driver, alternatives are powersave and performance. With acpi-cpufreq driver, alternatives are ondemand, powersave, performance and conservative.") (cpu-scaling-governor-on-bat (maybe-space-separated-string-list 'disabled) "Same as @code{cpu-scaling-governor-on-ac} but on BAT mode.") (cpu-scaling-min-freq-on-ac (maybe-non-negative-integer 'disabled) "Set the min available frequency for the scaling governor on AC.") (cpu-scaling-max-freq-on-ac (maybe-non-negative-integer 'disabled) "Set the max available frequency for the scaling governor on AC.") (cpu-scaling-min-freq-on-bat (maybe-non-negative-integer 'disabled) "Set the min available frequency for the scaling governor on BAT.") (cpu-scaling-max-freq-on-bat (maybe-non-negative-integer 'disabled) "Set the max available frequency for the scaling governor on BAT.") (cpu-min-perf-on-ac (maybe-non-negative-integer 'disabled) "Limit the min P-state to control the power dissipation of the CPU, in AC mode. Values are stated as a percentage of the available performance.") (cpu-max-perf-on-ac (maybe-non-negative-integer 'disabled) "Limit the max P-state to control the power dissipation of the CPU, in AC mode. Values are stated as a percentage of the available performance.") (cpu-min-perf-on-bat (maybe-non-negative-integer 'disabled) "Same as @code{cpu-min-perf-on-ac} on BAT mode.") (cpu-max-perf-on-bat (maybe-non-negative-integer 'disabled) "Same as @code{cpu-max-perf-on-ac} on BAT mode.") (cpu-boost-on-ac? (maybe-boolean 'disabled) "Enable CPU turbo boost feature on AC mode.") (cpu-boost-on-bat? (maybe-boolean 'disabled) "Same as @code{cpu-boost-on-ac?} on BAT mode.") (sched-powersave-on-ac? (boolean #f) "Allow Linux kernel to minimize the number of CPU cores/hyper-threads used under light load conditions.") (sched-powersave-on-bat? (boolean #t) "Same as @code{sched-powersave-on-ac?} but on BAT mode.") (nmi-watchdog? (boolean #f) "Enable Linux kernel NMI watchdog.") (phc-controls (maybe-string 'disabled) "For Linux kernels with PHC patch applied, change CPU voltages. An example value would be @samp{\"F:V F:V F:V F:V\"}.") (energy-perf-policy-on-ac (string "performance") "Set CPU performance versus energy saving policy on AC. Alternatives are performance, normal, powersave.") (energy-perf-policy-on-bat (string "powersave") "Same as @code{energy-perf-policy-ac} but on BAT mode.") (disks-devices (space-separated-string-list '("sda")) "Hard disk devices.") (disk-apm-level-on-ac (space-separated-string-list '("254" "254")) "Hard disk advanced power management level.") (disk-apm-level-on-bat (space-separated-string-list '("128" "128")) "Same as @code{disk-apm-bat} but on BAT mode.") (disk-spindown-timeout-on-ac (maybe-space-separated-string-list 'disabled) "Hard disk spin down timeout. One value has to be specified for each declared hard disk.") (disk-spindown-timeout-on-bat (maybe-space-separated-string-list 'disabled) "Same as @code{disk-spindown-timeout-on-ac} but on BAT mode.") (disk-iosched (maybe-space-separated-string-list 'disabled) "Select IO scheduler for disk devices. One value has to be specified for each declared hard disk. Example alternatives are cfq, deadline and noop.") (sata-linkpwr-on-ac (string "max_performance") "SATA aggressive link power management (ALPM) level. Alternatives are min_power, medium_power, max_performance.") (sata-linkpwr-on-bat (string "min_power") "Same as @code{sata-linkpwr-ac} but on BAT mode.") (sata-linkpwr-blacklist (maybe-string 'disabled) "Exclude specified SATA host devices for link power management.") (ahci-runtime-pm-on-ac? (maybe-on-off-boolean 'disabled) "Enable Runtime Power Management for AHCI controller and disks on AC mode.") (ahci-runtime-pm-on-bat? (maybe-on-off-boolean 'disabled) "Same as @code{ahci-runtime-pm-on-ac} on BAT mode.") (ahci-runtime-pm-timeout (non-negative-integer 15) "Seconds of inactivity before disk is suspended.") (pcie-aspm-on-ac (string "performance") "PCI Express Active State Power Management level. Alternatives are default, performance, powersave.") (pcie-aspm-on-bat (string "powersave") "Same as @code{pcie-aspm-ac} but on BAT mode.") (radeon-power-profile-on-ac (string "high") "Radeon graphics clock speed level. Alternatives are low, mid, high, auto, default.") (radeon-power-profile-on-bat (string "low") "Same as @code{radeon-power-ac} but on BAT mode.") (radeon-dpm-state-on-ac (string "performance") "Radeon dynamic power management method (DPM). Alternatives are battery, performance.") (radeon-dpm-state-on-bat (string "battery") "Same as @code{radeon-dpm-state-ac} but on BAT mode.") (radeon-dpm-perf-level-on-ac (string "auto") "Radeon DPM performance level. Alternatives are auto, low, high.") (radeon-dpm-perf-level-on-bat (string "auto") "Same as @code{radeon-dpm-perf-ac} but on BAT mode.") (wifi-pwr-on-ac? (on-off-boolean #f) "Wifi power saving mode.") (wifi-pwr-on-bat? (on-off-boolean #t) "Same as @code{wifi-power-ac?} but on BAT mode.") (wol-disable? (y-n-boolean #t) "Disable wake on LAN.") (sound-power-save-on-ac (non-negative-integer 0) "Timeout duration in seconds before activating audio power saving on Intel HDA and AC97 devices. A value of 0 disables power saving.") (sound-power-save-on-bat (non-negative-integer 1) "Same as @code{sound-powersave-ac} but on BAT mode.") (sound-power-save-controller? (y-n-boolean #t) "Disable controller in powersaving mode on Intel HDA devices.") (bay-poweroff-on-bat? (boolean #f) "Enable optical drive in UltraBay/MediaBay on BAT mode. Drive can be powered on again by releasing (and reinserting) the eject lever or by pressing the disc eject button on newer models.") (bay-device (string "sr0") "Name of the optical drive device to power off.") (runtime-pm-on-ac (string "on") "Runtime Power Management for PCI(e) bus devices. Alternatives are on and auto.") (runtime-pm-on-bat (string "auto") "Same as @code{runtime-pm-ac} but on BAT mode.") (runtime-pm-all? (boolean #t) "Runtime Power Management for all PCI(e) bus devices, except blacklisted ones.") (runtime-pm-blacklist (maybe-space-separated-string-list 'disabled) "Exclude specified PCI(e) device addresses from Runtime Power Management.") (runtime-pm-driver-blacklist (space-separated-string-list '("radeon" "nouveau")) "Exclude PCI(e) devices assigned to the specified drivers from Runtime Power Management.") (usb-autosuspend? (boolean #t) "Enable USB autosuspend feature.") (usb-blacklist (maybe-string 'disabled) "Exclude specified devices from USB autosuspend.") (usb-blacklist-wwan? (boolean #t) "Exclude WWAN devices from USB autosuspend.") (usb-whitelist (maybe-string 'disabled) "Include specified devices into USB autosuspend, even if they are already excluded by the driver or via @code{usb-blacklist-wwan?}.") (usb-autosuspend-disable-on-shutdown? (maybe-boolean 'disabled) "Enable USB autosuspend before shutdown.") (restore-device-state-on-startup? (boolean #f) "Restore radio device state (bluetooth, wifi, wwan) from previous shutdown on system startup.")) (define (tlp-shepherd-service config) (let* ((tlp-bin (file-append (tlp-configuration-tlp config) "/bin/tlp")) (tlp-action (lambda args #~(lambda _ (zero? (system* #$tlp-bin #$@args)))))) (list (shepherd-service (documentation "Run TLP script.") (provision '(tlp)) (requirement '(user-processes)) (start (tlp-action "init" "start")) (stop (tlp-action "init" "stop")))))) (define (tlp-activation config) (let* ((config-str (with-output-to-string (lambda () (serialize-configuration config tlp-configuration-fields)))) (config-file (plain-file "tlp" config-str))) (with-imported-modules '((guix build utils)) #~(begin (use-modules (guix build utils)) (copy-file #$config-file "/etc/tlp.conf"))))) (define tlp-service-type (service-type (name 'tlp) (extensions (list (service-extension shepherd-root-service-type tlp-shepherd-service) (service-extension udev-service-type (compose list tlp-configuration-tlp)) (service-extension activation-service-type tlp-activation))) (default-value (tlp-configuration)) (description "Run TLP, a power management tool."))) (define (generate-tlp-documentation) (generate-documentation `((tlp-configuration ,tlp-configuration-fields)) 'tlp-configuration)) (define-record-type* <thermald-configuration> thermald-configuration make-thermald-configuration thermald-configuration? (default #f)) (default thermald))) (define (thermald-shepherd-service config) (list (shepherd-service (provision '(thermald)) (documentation "Run thermald cpu frequency scaling.") (start #~(make-forkexec-constructor '(#$(file-append (thermald-thermald config) "/sbin/thermald") "--no-daemon" #$@(if (thermald-ignore-cpuid-check? config) '("--ignore-cpuid-check") '())))) (stop #~(make-kill-destructor))))) (define thermald-service-type (service-type (name 'thermald) (extensions (list (service-extension shepherd-root-service-type thermald-shepherd-service))) (default-value (thermald-configuration)) (description "Run thermald, a CPU frequency scaling service that helps prevent overheating.")))
36895f8dfd3e1fe2a5ec4e69f781c9ee4f76c64e08b47afd092101557566e114
AeroNotix/raft
serialization.lisp
(defpackage :raft/serialization (:use :cl) (:export #:serializer #:make-basic-serializer #:cl-store-serializer)) (in-package :raft/serialization) (defclass serializer () () (:documentation "base class for serializers")) (defgeneric serialize (serializer thing stream)) (defgeneric deserialize (serialize stream)) (defclass cl-store-serializer (serializer) () (:documentation "Very basic serializer which uses cl-store, please note that cl-store is a very inefficient format but provides simple APIs which map bytes to a legitimate CLOS instance easily")) (defun make-basic-serializer () (make-instance 'cl-store-serializer)) (defmethod serialize ((s cl-store-serializer) thing (stream stream)) (declare (ignore s)) (cl-store:store thing stream)) (defmethod deserialize ((s cl-store-serializer) (stream stream)) (declare (ignore s)) (cl-store:restore stream))
null
https://raw.githubusercontent.com/AeroNotix/raft/08921ac93f235595b2f0a344704ad2dad4e8ee1a/serialization.lisp
lisp
(defpackage :raft/serialization (:use :cl) (:export #:serializer #:make-basic-serializer #:cl-store-serializer)) (in-package :raft/serialization) (defclass serializer () () (:documentation "base class for serializers")) (defgeneric serialize (serializer thing stream)) (defgeneric deserialize (serialize stream)) (defclass cl-store-serializer (serializer) () (:documentation "Very basic serializer which uses cl-store, please note that cl-store is a very inefficient format but provides simple APIs which map bytes to a legitimate CLOS instance easily")) (defun make-basic-serializer () (make-instance 'cl-store-serializer)) (defmethod serialize ((s cl-store-serializer) thing (stream stream)) (declare (ignore s)) (cl-store:store thing stream)) (defmethod deserialize ((s cl-store-serializer) (stream stream)) (declare (ignore s)) (cl-store:restore stream))
85cafff779ffac1b231745ec0a2ce52796d26f5f3832d742e92aae3ed298198e
unclebob/WTFisaMonad
monads.clj
(defn square [n] (* n n)) (defn enlist1 [f] (partial map f)) (def square-list (enlist1 square)) (map (fn [a] (map (fn [b] (* a b)) '(1 2 3))) '(4 5 6) )
null
https://raw.githubusercontent.com/unclebob/WTFisaMonad/8f23ca2a212882d08793e348ce7cb670c6da1a80/src/monads.clj
clojure
(defn square [n] (* n n)) (defn enlist1 [f] (partial map f)) (def square-list (enlist1 square)) (map (fn [a] (map (fn [b] (* a b)) '(1 2 3))) '(4 5 6) )
cc65659e7f75445b6a5c980778a9fa03a96ddbaa37676bcbf2ce571ee74e1b26
sbcl/sbcl
target-c-call.lisp
;;;; FIXME: This file and host-c-call.lisp are separate from the rest of the alien source code for historical reasons : CMU CL ;;;; made a distinction between the stuff in the C-CALL package and stuff in the ALIEN package . There 's no obvious boundary there , though , and SBCL does n't try to make this distinction , ;;;; so it might make sense to just merge these files in with the ;;;; rest of the SB-ALIEN code. 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-ALIEN") ;;;; extra types (define-alien-type char (integer 8)) (define-alien-type short (integer 16)) (define-alien-type int (integer 32)) #-(and win32 x86-64) (define-alien-type long (integer #.sb-vm:n-machine-word-bits)) #+(and win32 x86-64) (define-alien-type long (integer 32)) (define-alien-type long-long (integer 64)) (define-alien-type unsigned-char (unsigned 8)) (define-alien-type unsigned-short (unsigned 16)) (define-alien-type unsigned-int (unsigned 32)) #-(and win32 x86-64) (define-alien-type unsigned-long (unsigned #.sb-vm:n-machine-word-bits)) #+(and win32 x86-64) (define-alien-type unsigned-long (unsigned 32)) (define-alien-type unsigned-long-long (unsigned 64)) (define-alien-type float single-float) (define-alien-type double double-float) (define-alien-type utf8-string (c-string :external-format :utf8)) (eval-when (:compile-toplevel :load-toplevel :execute) (define-alien-type-translator void () (parse-alien-type '(values) (sb-kernel:make-null-lexenv)))) (defun default-c-string-external-format () (or *default-c-string-external-format* (setf *default-c-string-external-format* (sb-impl::default-external-format)))) (defun %naturalize-c-string (sap) (declare (type system-area-pointer sap)) It can be assumed that any modern implementation of strlen ( ) reads 4 , 8 , 16 , or possibly even 32 bytes at a time when searching for the ' \0 ' terminator . As such , we expect it to be on average much faster than a loop over SAP - REF-8 . ;; And much to my surprise, the foreign call overhead on x86-64 is so small that ;; there is not a minimum threshold length below which the foreign call costs too much. With as few as 5 characters in the string , I saw 2x speedup . ;; Below that, it's about the same to do a foreign call versus staying in lisp. ;; The limiting case of a 0 length string would be faster without the foreign call, ;; but pre-checking would slow down every other case. (let* ((length (alien-funcall (extern-alien "strlen" (function size-t system-area-pointer)) sap)) (result (make-string length :element-type 'base-char))) COPY - UB8 pins the lisp string , no need to do it here (sb-kernel:copy-ub8-from-system-area sap 0 result 0 length) result))
null
https://raw.githubusercontent.com/sbcl/sbcl/ec7cc7f9fa46d0ac85e68257449d71a412452fab/src/code/target-c-call.lisp
lisp
FIXME: This file and host-c-call.lisp are separate from the made a distinction between the stuff in the C-CALL package and so it might make sense to just merge these files in with the rest of the SB-ALIEN code. 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. extra types And much to my surprise, the foreign call overhead on x86-64 is so small that there is not a minimum threshold length below which the foreign call costs too much. Below that, it's about the same to do a foreign call versus staying in lisp. The limiting case of a 0 length string would be faster without the foreign call, but pre-checking would slow down every other case.
rest of the alien source code for historical reasons : CMU CL stuff in the ALIEN package . There 's no obvious boundary there , though , and SBCL does n't try to make this distinction , 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-ALIEN") (define-alien-type char (integer 8)) (define-alien-type short (integer 16)) (define-alien-type int (integer 32)) #-(and win32 x86-64) (define-alien-type long (integer #.sb-vm:n-machine-word-bits)) #+(and win32 x86-64) (define-alien-type long (integer 32)) (define-alien-type long-long (integer 64)) (define-alien-type unsigned-char (unsigned 8)) (define-alien-type unsigned-short (unsigned 16)) (define-alien-type unsigned-int (unsigned 32)) #-(and win32 x86-64) (define-alien-type unsigned-long (unsigned #.sb-vm:n-machine-word-bits)) #+(and win32 x86-64) (define-alien-type unsigned-long (unsigned 32)) (define-alien-type unsigned-long-long (unsigned 64)) (define-alien-type float single-float) (define-alien-type double double-float) (define-alien-type utf8-string (c-string :external-format :utf8)) (eval-when (:compile-toplevel :load-toplevel :execute) (define-alien-type-translator void () (parse-alien-type '(values) (sb-kernel:make-null-lexenv)))) (defun default-c-string-external-format () (or *default-c-string-external-format* (setf *default-c-string-external-format* (sb-impl::default-external-format)))) (defun %naturalize-c-string (sap) (declare (type system-area-pointer sap)) It can be assumed that any modern implementation of strlen ( ) reads 4 , 8 , 16 , or possibly even 32 bytes at a time when searching for the ' \0 ' terminator . As such , we expect it to be on average much faster than a loop over SAP - REF-8 . With as few as 5 characters in the string , I saw 2x speedup . (let* ((length (alien-funcall (extern-alien "strlen" (function size-t system-area-pointer)) sap)) (result (make-string length :element-type 'base-char))) COPY - UB8 pins the lisp string , no need to do it here (sb-kernel:copy-ub8-from-system-area sap 0 result 0 length) result))
55f6f30fb5e59455eaf96690327a6492d408a65529e6baf0f2bd10fb9ea2fa64
ivanjovanovic/sicp
e-5.5.scm
Exercise 5.5 . Hand - simulate the factorial and Fibonacci machines , using some nontrivial input ( requiring execution of at least one ; recursive call). Show the contents of the stack at each significant ; point in the execution. ; ------------------------------------------------------------ Lets take the smallest after the trivial cases , n = 3 ; start n = 3 , val = whatever , continue = after - fact ; stack = empty ; after 1st loop n = 2 , val = whatever stack = 3 | fact - done ; after 2nd loop n = 1 , val = whatever stack = 2 | after - fact | 3 | fact - done ; after 3rd loop n = 1 , val = 1 stack = 2 | after - fact | 3 | fact - done ; ; jumped to after-fact n = 1 , val = 2 stack = 3 | fact - done ; ; jumped to after-fact n = 1 , val = 6 ; stack = empty ; ; jumped to fact-done n = 1 , val = 6 ; stack = empty
null
https://raw.githubusercontent.com/ivanjovanovic/sicp/a3bfbae0a0bda414b042e16bbb39bf39cd3c38f8/5.1/e-5.5.scm
scheme
recursive call). Show the contents of the stack at each significant point in the execution. ------------------------------------------------------------ start stack = empty jumped to after-fact jumped to after-fact stack = empty jumped to fact-done stack = empty
Exercise 5.5 . Hand - simulate the factorial and Fibonacci machines , using some nontrivial input ( requiring execution of at least one Lets take the smallest after the trivial cases , n = 3 n = 3 , val = whatever , continue = after - fact after 1st loop n = 2 , val = whatever stack = 3 | fact - done after 2nd loop n = 1 , val = whatever stack = 2 | after - fact | 3 | fact - done after 3rd loop n = 1 , val = 1 stack = 2 | after - fact | 3 | fact - done n = 1 , val = 2 stack = 3 | fact - done n = 1 , val = 6 n = 1 , val = 6
9913b7549a446756959684f2f57778dd957c2d57626be250ee85359256bb9966
zeromq/chumak
subscriber.erl
This Source Code Form is subject to the terms of the Mozilla Public License , v. 2.0 . If a copy of the MPL was not distributed with this file , You can obtain one at /. -module(subscriber). -export([main/1]). main(Topic) -> application:start(chumak), {ok, Socket} = chumak:socket(sub), chumak:subscribe(Socket, Topic), case chumak:connect(Socket, tcp, "localhost", 5555) of {ok, _BindPid} -> io:format("Binding OK with Pid: ~p\n", [Socket]); {error, Reason} -> io:format("Connection Failed for this reason: ~p\n", [Reason]); X -> io:format("Unhandled reply for bind ~p \n", [X]) end, loop(Socket). loop(Socket) -> {ok, Data1} = chumak:recv_multipart(Socket), io:format("Received by multipart ~p\n", [Data1]), {ok, Data2} = chumak:recv(Socket), io:format("Received ~p\n", [Data2]), loop(Socket).
null
https://raw.githubusercontent.com/zeromq/chumak/02f56f153d0c6988858483c9dd0a1c233e2aa342/examples/subscriber.erl
erlang
This Source Code Form is subject to the terms of the Mozilla Public License , v. 2.0 . If a copy of the MPL was not distributed with this file , You can obtain one at /. -module(subscriber). -export([main/1]). main(Topic) -> application:start(chumak), {ok, Socket} = chumak:socket(sub), chumak:subscribe(Socket, Topic), case chumak:connect(Socket, tcp, "localhost", 5555) of {ok, _BindPid} -> io:format("Binding OK with Pid: ~p\n", [Socket]); {error, Reason} -> io:format("Connection Failed for this reason: ~p\n", [Reason]); X -> io:format("Unhandled reply for bind ~p \n", [X]) end, loop(Socket). loop(Socket) -> {ok, Data1} = chumak:recv_multipart(Socket), io:format("Received by multipart ~p\n", [Data1]), {ok, Data2} = chumak:recv(Socket), io:format("Received ~p\n", [Data2]), loop(Socket).
8e361db6a0bb5a4e0409ee30758af418850b2a2bb64b7aca051ca9ed8d36be7f
mit-plv/riscv-semantics
CleanTest.hs
# LANGUAGE MultiParamTypeClasses , FlexibleInstances , ScopedTypeVariables , InstanceSigs , AllowAmbiguousTypes , FlexibleContexts # module Platform.CleanTest where import Spec.Machine import Spec.Decode import Utility.Utility import Spec.CSRFileIO import qualified Spec.CSRField as Field import Data.Bits import Data.Int import Data.Word import Data.Char import Data.Maybe import Data.IORef import Data.Array.IO import System.Posix.Types import System.IO.Error import qualified Data.Map.Strict as S import Control.Monad.State import Control.Monad.Trans.Maybe import Debug.Trace as T import Platform.Pty import Platform.Plic import Platform.Clint import Control.Concurrent.MVar data VerifMinimal64 = VerifMinimal64 { registers :: IOUArray Register Int64 , fpregisters :: IOUArray Register Int32, csrs :: CSRFile, privMode :: IORef PrivMode, pc :: IORef Int64, nextPC :: IORef Int64, mem :: IOUArray Int Word8, plic :: Plic, clint :: (IORef Int64, MVar Int64), console :: (MVar [Word8], Fd), reservation :: IORef (Maybe Int), -- Verification Packet exception :: IORef Bool, interrupt :: IORef Bool, valid_dst :: IORef Bool, valid_addr :: IORef Bool, instruction :: IORef Int32, cause :: IORef Int32, d :: IORef Word64, dst :: IORef Int64, addrPacket :: IORef Word64, pcPacket :: IORef Int64, valid_timer :: IORef Bool, timer :: IORef Int64, mipPacket:: IORef Int64 } type IOState = StateT VerifMinimal64 IO type LoadFunc = IOState Int32 type StoreFunc = Int32 -> IOState () rvGetChar :: IOState Int32 rvGetChar = do refs <- get mWord <- liftIO $ readPty (fst (console refs)) lift $ putStrLn "Get Char happened" case mWord of Nothing -> return $ -1 Just a -> return $ fromIntegral a rvPutChar :: Int32 -> IOState () rvPutChar val = do refs <- get liftIO $ writePty (snd (console refs)) (fromIntegral val) rvZero = return 0 rvNull val = return () getMTime :: LoadFunc getMTime = undefined Ignore writes to . setMTime :: StoreFunc setMTime _ = return () readPlicWrap addr = do refs <- get (val, interrupt) <- lift $ readPlic (plic refs) addr when (interrupt == Set) (do lift $ putStrLn "Set external interrupt from read" setCSRField Field.MEIP 1) when (interrupt == Reset) (do lift $ putStrLn "Reset external initerrupt" setCSRField Field.MEIP 0) return val writePlicWrap addr val = do refs <- get interrupt <- lift $ writePlic (plic refs) addr val when (interrupt == Set) (do lift $ putStrLn "Set external interrupt from write" setCSRField Field.MEIP 1) when (interrupt == Reset) (do lift $ putStrLn "Reset external interrupt from write" setCSRField Field.MEIP 0) return () readClintWrap addr = do refs <- get let (mtimecmp,rtc) = clint refs mint <- lift $ readClint mtimecmp rtc addr lift $ writeIORef (valid_timer refs) True when (addr == 0xbff8) . lift . writeIORef (timer refs) . fromIntegral . fromJust $ mint lift . " readClint " + + show mint + + " at addr " + + show addr case mint of Just a -> return a Nothing -> return 0 --Impossible writeClintWrap addr val = do refs <- get let (mtimecmp,rtc) = clint refs lift . putStrLn $ "writeClint " ++ show val ++ " at addr " ++ show addr lift $ writeClint mtimecmp addr val setCSRField Field.MTIP 0 Addresses for / mtimecmp chosen for compatibility , and . memMapTable :: S.Map MachineInt (LoadFunc, StoreFunc) memMapTable = S.fromList [ -- Pty (0xfff0, (rvZero, rvPutChar)), (0xfff4, (rvGetChar, rvNull)), Plic (0x4000000, (readPlicWrap 0x200000, writePlicWrap 0x200000)), (0x4000004, (readPlicWrap 0x200004, writePlicWrap 0x200004)), (0x2000000, (fmap fromIntegral $ getCSRField Field.MSIP, setCSRField Field.SSIP)), (0x200bff8, (readClintWrap 0xbff8, writeClintWrap 0xbff8)), (0x200bffc, (readClintWrap 0xbffc, writeClintWrap 0xbffc)), (0x2004000, (readClintWrap 0x4000, writeClintWrap 0x4000)), (0x2004004, (readClintWrap 0x4004, writeClintWrap 0x4004)) ] mtimecmp_addr = 0x4000 :: Int64 instance RiscvMachine IOState Int64 where getRegister reg = do if reg == 0 then return 0 else do refs <- get lift $! readArray (registers refs) reg setRegister reg val = do refs <- get if reg == 0 then do -- lift $ writeIORef (valid_dst refs) True -- lift $ writeIORef (dst refs) reg -- lift $ writeIORef (d refs) $ fromIntegral val return () else do lift $ writeIORef (valid_dst refs) True lift $ writeIORef (dst refs) reg lift $ writeIORef (d refs) $ fromIntegral val lift $! writeArray (registers refs) reg val getFPRegister reg = do refs <- get lift $! readArray (fpregisters refs) reg setFPRegister reg val = do refs <- get lift $! writeArray (fpregisters refs) reg val getPC = do refs <- get lift $! readIORef (pc refs) setPC npc = do refs <- get lift $! writeIORef (nextPC refs) npc getPrivMode = do refs <- get lift $! readIORef (privMode refs) setPrivMode val = do refs <- get lift $! writeIORef (privMode refs) val commit = do refs <- get npc <- lift $ readIORef (nextPC refs) lift $! writeIORef (pc refs) npc -- -- Wrap Memory instance: loadByte s addr = case S.lookup (fromIntegral addr) memMapTable of Just _ -> error "loadByte on MMIO unsupported" Nothing -> do refs <- get fmap fromIntegral . lift $ readArray (mem refs) (fromIntegral addr) loadHalf s addr = case S.lookup (fromIntegral addr) memMapTable of Just _ -> error "loadHalf on MMIO unsupported" Nothing -> do refs <- get b0 <- lift . readArray (mem refs) $ fromIntegral addr b1 <- lift . readArray (mem refs) $ fromIntegral (addr + 1) return (combineBytes [b0,b1]) loadWord :: forall s. (Integral s) => SourceType -> s -> IOState Int32 loadWord s ad = do val <- (case S.lookup ((fromIntegral:: s -> MachineInt) ad) memMapTable of Just (getFunc, _) -> getFunc Nothing -> do refs <- get b0 <- lift . readArray (mem refs) $! fromIntegral ad b1 <- lift . readArray (mem refs) $! fromIntegral (ad + 1) b2 <- lift . readArray (mem refs) $! fromIntegral (ad + 2) b3 <- lift . readArray (mem refs) $! fromIntegral (ad + 3) return (combineBytes [b0,b1,b2,b3])) return val loadDouble s addr = do res_bot <- loadWord s addr res_top <- loadWord s (addr+4) let bytes_bot = splitWord res_bot let bytes_top = splitWord res_top return (combineBytes $ bytes_bot ++ bytes_top) storeByte s addr val = case S.lookup (fromIntegral addr) memMapTable of Just _ -> error "storeByte on MMIO unsupported" Nothing -> do refs <- get lift $ writeArray (mem refs) (fromIntegral addr) (fromIntegral val) -- Convert from Int8 to Word8 storeHalf s addr val = case S.lookup (fromIntegral addr) memMapTable of Just _ -> error "storeHald on MMIO unsupported" Nothing -> do let bytes = splitHalf val refs <- get forM_ (zip bytes [addr + i| i<- [0..]]) $ (\(x,addr)-> lift $ writeArray (mem refs) (fromIntegral addr) (fromIntegral x)) storeWord :: forall s. (Integral s, Bits s) => SourceType -> s -> Int32 -> IOState () storeWord s addr val = do refs <- get lift $ writeIORef (valid_addr refs) True lift $ writeIORef (addrPacket refs) $ fromIntegral addr lift $ writeIORef (d refs) . fromIntegral $ (fromIntegral val :: Word32) when ( addr > = 0x2000000 & & addr < 0x20c0000 ) .lift $ putStrLn ( " write to the clint : " + + show ( fromIntegral addr ) ) case S.lookup ((fromIntegral:: s -> MachineInt) addr) memMapTable of Just (_, setFunc) -> setFunc val Nothing -> do let bytes = splitWord val -- refs <- get forM_ (zip bytes [addr + i| i<- [0..]]) $ (\(x,addr)-> lift $ writeArray (mem refs) (fromIntegral addr) (fromIntegral x)) storeDouble s addr val = case (S.lookup (fromIntegral addr) memMapTable,S.lookup (fromIntegral (addr+4)) memMapTable) of (Just (_, setFunc1 ),Just (_, setFunc2 )) -> do setFunc1 $ fromIntegral (val .&. 0xFFFFFFFF) setFunc2 $ fromIntegral (shiftR val 32) (Nothing, Nothing) -> do let bytes = splitDouble val refs <- get forM_ (zip bytes [addr + i| i<- [0..]]) $ (\(x,addr)-> lift $ writeArray (mem refs) (fromIntegral addr) (fromIntegral x)) _ -> error "storeDouble half within MMIO, half without that's SOOOO wrong" makeReservation addr = do refs <- get lift $ writeIORef (reservation refs) (Just $ fromIntegral addr) checkReservation addr = do refs <- get res <- lift $ readIORef (reservation refs) return (Just (fromIntegral addr) == res) clearReservation addr = do refs <- get lift $ writeIORef (reservation refs) Nothing fence a b = return () -- -- CSRs: getCSRField field = do refs <- get lift $! readArray (csrs refs) field unsafeSetCSRField :: forall s. (Integral s) => Field.CSRField -> s -> IOState () CSRS are not refs in there , because I am lazy . refs <- get lift $! writeArray (csrs refs) field ((fromIntegral:: s -> MachineInt) val) flushTLB = return () getPlatform = return (Platform { dirtyHardware = return False, writePlatformCSRField = \field value -> return value })
null
https://raw.githubusercontent.com/mit-plv/riscv-semantics/1c0da3cac9d3f8dd813d26c0d2fbaccbb2210313/src/Platform/CleanTest.hs
haskell
Verification Packet Impossible Pty lift $ writeIORef (valid_dst refs) True lift $ writeIORef (dst refs) reg lift $ writeIORef (d refs) $ fromIntegral val -- Wrap Memory instance: Convert from Int8 to Word8 refs <- get -- CSRs:
# LANGUAGE MultiParamTypeClasses , FlexibleInstances , ScopedTypeVariables , InstanceSigs , AllowAmbiguousTypes , FlexibleContexts # module Platform.CleanTest where import Spec.Machine import Spec.Decode import Utility.Utility import Spec.CSRFileIO import qualified Spec.CSRField as Field import Data.Bits import Data.Int import Data.Word import Data.Char import Data.Maybe import Data.IORef import Data.Array.IO import System.Posix.Types import System.IO.Error import qualified Data.Map.Strict as S import Control.Monad.State import Control.Monad.Trans.Maybe import Debug.Trace as T import Platform.Pty import Platform.Plic import Platform.Clint import Control.Concurrent.MVar data VerifMinimal64 = VerifMinimal64 { registers :: IOUArray Register Int64 , fpregisters :: IOUArray Register Int32, csrs :: CSRFile, privMode :: IORef PrivMode, pc :: IORef Int64, nextPC :: IORef Int64, mem :: IOUArray Int Word8, plic :: Plic, clint :: (IORef Int64, MVar Int64), console :: (MVar [Word8], Fd), reservation :: IORef (Maybe Int), exception :: IORef Bool, interrupt :: IORef Bool, valid_dst :: IORef Bool, valid_addr :: IORef Bool, instruction :: IORef Int32, cause :: IORef Int32, d :: IORef Word64, dst :: IORef Int64, addrPacket :: IORef Word64, pcPacket :: IORef Int64, valid_timer :: IORef Bool, timer :: IORef Int64, mipPacket:: IORef Int64 } type IOState = StateT VerifMinimal64 IO type LoadFunc = IOState Int32 type StoreFunc = Int32 -> IOState () rvGetChar :: IOState Int32 rvGetChar = do refs <- get mWord <- liftIO $ readPty (fst (console refs)) lift $ putStrLn "Get Char happened" case mWord of Nothing -> return $ -1 Just a -> return $ fromIntegral a rvPutChar :: Int32 -> IOState () rvPutChar val = do refs <- get liftIO $ writePty (snd (console refs)) (fromIntegral val) rvZero = return 0 rvNull val = return () getMTime :: LoadFunc getMTime = undefined Ignore writes to . setMTime :: StoreFunc setMTime _ = return () readPlicWrap addr = do refs <- get (val, interrupt) <- lift $ readPlic (plic refs) addr when (interrupt == Set) (do lift $ putStrLn "Set external interrupt from read" setCSRField Field.MEIP 1) when (interrupt == Reset) (do lift $ putStrLn "Reset external initerrupt" setCSRField Field.MEIP 0) return val writePlicWrap addr val = do refs <- get interrupt <- lift $ writePlic (plic refs) addr val when (interrupt == Set) (do lift $ putStrLn "Set external interrupt from write" setCSRField Field.MEIP 1) when (interrupt == Reset) (do lift $ putStrLn "Reset external interrupt from write" setCSRField Field.MEIP 0) return () readClintWrap addr = do refs <- get let (mtimecmp,rtc) = clint refs mint <- lift $ readClint mtimecmp rtc addr lift $ writeIORef (valid_timer refs) True when (addr == 0xbff8) . lift . writeIORef (timer refs) . fromIntegral . fromJust $ mint lift . " readClint " + + show mint + + " at addr " + + show addr case mint of Just a -> return a writeClintWrap addr val = do refs <- get let (mtimecmp,rtc) = clint refs lift . putStrLn $ "writeClint " ++ show val ++ " at addr " ++ show addr lift $ writeClint mtimecmp addr val setCSRField Field.MTIP 0 Addresses for / mtimecmp chosen for compatibility , and . memMapTable :: S.Map MachineInt (LoadFunc, StoreFunc) memMapTable = S.fromList [ (0xfff0, (rvZero, rvPutChar)), (0xfff4, (rvGetChar, rvNull)), Plic (0x4000000, (readPlicWrap 0x200000, writePlicWrap 0x200000)), (0x4000004, (readPlicWrap 0x200004, writePlicWrap 0x200004)), (0x2000000, (fmap fromIntegral $ getCSRField Field.MSIP, setCSRField Field.SSIP)), (0x200bff8, (readClintWrap 0xbff8, writeClintWrap 0xbff8)), (0x200bffc, (readClintWrap 0xbffc, writeClintWrap 0xbffc)), (0x2004000, (readClintWrap 0x4000, writeClintWrap 0x4000)), (0x2004004, (readClintWrap 0x4004, writeClintWrap 0x4004)) ] mtimecmp_addr = 0x4000 :: Int64 instance RiscvMachine IOState Int64 where getRegister reg = do if reg == 0 then return 0 else do refs <- get lift $! readArray (registers refs) reg setRegister reg val = do refs <- get if reg == 0 then do return () else do lift $ writeIORef (valid_dst refs) True lift $ writeIORef (dst refs) reg lift $ writeIORef (d refs) $ fromIntegral val lift $! writeArray (registers refs) reg val getFPRegister reg = do refs <- get lift $! readArray (fpregisters refs) reg setFPRegister reg val = do refs <- get lift $! writeArray (fpregisters refs) reg val getPC = do refs <- get lift $! readIORef (pc refs) setPC npc = do refs <- get lift $! writeIORef (nextPC refs) npc getPrivMode = do refs <- get lift $! readIORef (privMode refs) setPrivMode val = do refs <- get lift $! writeIORef (privMode refs) val commit = do refs <- get npc <- lift $ readIORef (nextPC refs) lift $! writeIORef (pc refs) npc loadByte s addr = case S.lookup (fromIntegral addr) memMapTable of Just _ -> error "loadByte on MMIO unsupported" Nothing -> do refs <- get fmap fromIntegral . lift $ readArray (mem refs) (fromIntegral addr) loadHalf s addr = case S.lookup (fromIntegral addr) memMapTable of Just _ -> error "loadHalf on MMIO unsupported" Nothing -> do refs <- get b0 <- lift . readArray (mem refs) $ fromIntegral addr b1 <- lift . readArray (mem refs) $ fromIntegral (addr + 1) return (combineBytes [b0,b1]) loadWord :: forall s. (Integral s) => SourceType -> s -> IOState Int32 loadWord s ad = do val <- (case S.lookup ((fromIntegral:: s -> MachineInt) ad) memMapTable of Just (getFunc, _) -> getFunc Nothing -> do refs <- get b0 <- lift . readArray (mem refs) $! fromIntegral ad b1 <- lift . readArray (mem refs) $! fromIntegral (ad + 1) b2 <- lift . readArray (mem refs) $! fromIntegral (ad + 2) b3 <- lift . readArray (mem refs) $! fromIntegral (ad + 3) return (combineBytes [b0,b1,b2,b3])) return val loadDouble s addr = do res_bot <- loadWord s addr res_top <- loadWord s (addr+4) let bytes_bot = splitWord res_bot let bytes_top = splitWord res_top return (combineBytes $ bytes_bot ++ bytes_top) storeByte s addr val = case S.lookup (fromIntegral addr) memMapTable of Just _ -> error "storeByte on MMIO unsupported" Nothing -> do refs <- get storeHalf s addr val = case S.lookup (fromIntegral addr) memMapTable of Just _ -> error "storeHald on MMIO unsupported" Nothing -> do let bytes = splitHalf val refs <- get forM_ (zip bytes [addr + i| i<- [0..]]) $ (\(x,addr)-> lift $ writeArray (mem refs) (fromIntegral addr) (fromIntegral x)) storeWord :: forall s. (Integral s, Bits s) => SourceType -> s -> Int32 -> IOState () storeWord s addr val = do refs <- get lift $ writeIORef (valid_addr refs) True lift $ writeIORef (addrPacket refs) $ fromIntegral addr lift $ writeIORef (d refs) . fromIntegral $ (fromIntegral val :: Word32) when ( addr > = 0x2000000 & & addr < 0x20c0000 ) .lift $ putStrLn ( " write to the clint : " + + show ( fromIntegral addr ) ) case S.lookup ((fromIntegral:: s -> MachineInt) addr) memMapTable of Just (_, setFunc) -> setFunc val Nothing -> do let bytes = splitWord val forM_ (zip bytes [addr + i| i<- [0..]]) $ (\(x,addr)-> lift $ writeArray (mem refs) (fromIntegral addr) (fromIntegral x)) storeDouble s addr val = case (S.lookup (fromIntegral addr) memMapTable,S.lookup (fromIntegral (addr+4)) memMapTable) of (Just (_, setFunc1 ),Just (_, setFunc2 )) -> do setFunc1 $ fromIntegral (val .&. 0xFFFFFFFF) setFunc2 $ fromIntegral (shiftR val 32) (Nothing, Nothing) -> do let bytes = splitDouble val refs <- get forM_ (zip bytes [addr + i| i<- [0..]]) $ (\(x,addr)-> lift $ writeArray (mem refs) (fromIntegral addr) (fromIntegral x)) _ -> error "storeDouble half within MMIO, half without that's SOOOO wrong" makeReservation addr = do refs <- get lift $ writeIORef (reservation refs) (Just $ fromIntegral addr) checkReservation addr = do refs <- get res <- lift $ readIORef (reservation refs) return (Just (fromIntegral addr) == res) clearReservation addr = do refs <- get lift $ writeIORef (reservation refs) Nothing fence a b = return () getCSRField field = do refs <- get lift $! readArray (csrs refs) field unsafeSetCSRField :: forall s. (Integral s) => Field.CSRField -> s -> IOState () CSRS are not refs in there , because I am lazy . refs <- get lift $! writeArray (csrs refs) field ((fromIntegral:: s -> MachineInt) val) flushTLB = return () getPlatform = return (Platform { dirtyHardware = return False, writePlatformCSRField = \field value -> return value })
86750ada35779c1bffce0dec7fbfcc3d474d9d7c7e6fb0093b766925c0e79ddd
conscell/hugs-android
MArray.hs
----------------------------------------------------------------------------- -- | -- Module : Data.Array.MArray Copyright : ( c ) The University of Glasgow 2001 -- License : BSD-style (see the file libraries/base/LICENSE) -- -- Maintainer : -- Stability : experimental -- Portability : non-portable (uses Data.Array.Base) -- -- An overloaded interface to mutable arrays. For array types which can be used with this interface , see " Data . Array . IO " , " Data . Array . ST " , and " Data . Array . Storable " . -- ----------------------------------------------------------------------------- module Data.Array.MArray ( -- * Class of mutable array types MArray, -- :: (* -> * -> *) -> * -> (* -> *) -> class -- * The @Ix@ class and operations module Data.Ix, -- * Constructing mutable arrays : : ( MArray a e m , Ix i ) = > ( i , i ) - > e - > m ( a i e ) : : ( MArray a e m , Ix i ) = > ( i , i ) - > m ( a i e ) : : ( MArray a e m , Ix i ) = > ( i , i ) - > [ e ] - > m ( a i e ) -- * Reading and writing mutable arrays : : ( MArray a e m , Ix i ) = > a i e - > i - > m e : : ( MArray a e m , Ix i ) = > a i e - > i - > e - > m ( ) -- * Derived arrays : : ( MArray a e ' m , MArray a e m , Ix i ) = > ( e ' - > e ) - > a i e ' - > m ( a i e ) : : ( MArray a e m , Ix i , Ix j ) = > ( i , i ) - > ( i - > j ) - > a j e - > m ( a i e ) -- * Deconstructing mutable arrays : : ( MArray a e m , Ix i ) = > a i e - > m ( i , i ) : : ( MArray a e m , Ix i ) = > a i e - > m [ e ] : : ( MArray a e m , Ix i ) = > a i e - > m [ ( i , e ) ] -- * Conversions between mutable and immutable arrays : : ( Ix i , MArray a e m , IArray b e ) = > a i e - > m ( b i e ) : : ( Ix i , MArray a e m , IArray b e ) = > a i e - > m ( b i e ) : : ( Ix i , IArray a e , MArray b e m ) = > a i e - > m ( b i e ) : : ( Ix i , IArray a e , MArray b e m ) = > a i e - > m ( b i e ) ) where import Prelude import Data.Ix import Data.Array.Base
null
https://raw.githubusercontent.com/conscell/hugs-android/31e5861bc1a1dd9931e6b2471a9f45c14e3c6c7e/hugs/lib/hugs/packages/base/Data/Array/MArray.hs
haskell
--------------------------------------------------------------------------- | Module : Data.Array.MArray License : BSD-style (see the file libraries/base/LICENSE) Maintainer : Stability : experimental Portability : non-portable (uses Data.Array.Base) An overloaded interface to mutable arrays. For array types which can be --------------------------------------------------------------------------- * Class of mutable array types :: (* -> * -> *) -> * -> (* -> *) -> class * The @Ix@ class and operations * Constructing mutable arrays * Reading and writing mutable arrays * Derived arrays * Deconstructing mutable arrays * Conversions between mutable and immutable arrays
Copyright : ( c ) The University of Glasgow 2001 used with this interface , see " Data . Array . IO " , " Data . Array . ST " , and " Data . Array . Storable " . module Data.Array.MArray ( module Data.Ix, : : ( MArray a e m , Ix i ) = > ( i , i ) - > e - > m ( a i e ) : : ( MArray a e m , Ix i ) = > ( i , i ) - > m ( a i e ) : : ( MArray a e m , Ix i ) = > ( i , i ) - > [ e ] - > m ( a i e ) : : ( MArray a e m , Ix i ) = > a i e - > i - > m e : : ( MArray a e m , Ix i ) = > a i e - > i - > e - > m ( ) : : ( MArray a e ' m , MArray a e m , Ix i ) = > ( e ' - > e ) - > a i e ' - > m ( a i e ) : : ( MArray a e m , Ix i , Ix j ) = > ( i , i ) - > ( i - > j ) - > a j e - > m ( a i e ) : : ( MArray a e m , Ix i ) = > a i e - > m ( i , i ) : : ( MArray a e m , Ix i ) = > a i e - > m [ e ] : : ( MArray a e m , Ix i ) = > a i e - > m [ ( i , e ) ] : : ( Ix i , MArray a e m , IArray b e ) = > a i e - > m ( b i e ) : : ( Ix i , MArray a e m , IArray b e ) = > a i e - > m ( b i e ) : : ( Ix i , IArray a e , MArray b e m ) = > a i e - > m ( b i e ) : : ( Ix i , IArray a e , MArray b e m ) = > a i e - > m ( b i e ) ) where import Prelude import Data.Ix import Data.Array.Base
d5872f45afe8f74190959a93ee920ce3491c616b05ae2685515a55709089cce8
cpeikert/Lol
KeyHomomorphicPRF.hs
| Module : Crypto . Lol . Applications . : Key - homomorphic PRF from < /~cpeikert/pubs/kh-prf.pdf [ BP14 ] > . Copyright : ( c ) , 2018 , 2018 License : GPL-3 Maintainer : Stability : experimental Portability : POSIX Key - homomorphic PRF from < /~cpeikert/pubs/kh-prf.pdf [ BP14 ] > . Module : Crypto.Lol.Applications.KeyHomomorphicPRF Description : Key-homomorphic PRF from </~cpeikert/pubs/kh-prf.pdf [BP14]>. Copyright : (c) Bogdan Manga, 2018 Chris Peikert, 2018 License : GPL-3 Maintainer : Stability : experimental Portability : POSIX Key-homomorphic PRF from </~cpeikert/pubs/kh-prf.pdf [BP14]>. -} {-# LANGUAGE ConstraintKinds #-} # LANGUAGE DataKinds # {-# LANGUAGE DefaultSignatures #-} # LANGUAGE EmptyCase # # LANGUAGE ExistentialQuantification # # LANGUAGE FlexibleContexts # # LANGUAGE FlexibleInstances # {-# LANGUAGE GADTs #-} # LANGUAGE InstanceSigs # {-# LANGUAGE KindSignatures #-} # LANGUAGE MultiParamTypeClasses # # LANGUAGE NoCUSKs # # LANGUAGE NoImplicitPrelude # # LANGUAGE NoStarIsType # # LANGUAGE PolyKinds # {-# LANGUAGE RankNTypes #-} # LANGUAGE RecordWildCards # {-# LANGUAGE ScopedTypeVariables #-} # LANGUAGE StandaloneDeriving # {-# LANGUAGE StandaloneKindSignatures #-} # LANGUAGE TemplateHaskell # # LANGUAGE TypeApplications # {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE UndecidableInstances #-} module Crypto.Lol.Applications.KeyHomomorphicPRF ( FBT(..), SFBT(..), SizeFBT, FBTC, singFBT , PRFKey, PRFParams, PRFState , genKey, genParams, prf, prfState, prfAmortized, run, runT , Vector, BitString , replicate, replicateS, fromList, fromListS, split, splitS ) where import Control.Applicative ((<$>), (<*>)) import Control.Monad.Identity import Control.Monad.Random hiding (fromList, split) import Control.Monad.State import Crypto.Lol hiding (head, replicate) import Crypto.Lol.Reflects import Data.Maybe import Data.Singletons.TH import qualified MathObj.Matrix as M singletons [d| -- A full binary tree (promoted to the type level by data -- kinds, and singleton-ized): each node is either a leaf or has two children . data FBT = Leaf | Intern FBT FBT -- promote to type family for getting number of leaves sizeFBT :: FBT -> Pos sizeFBT Leaf = O sizeFBT (Intern l r) = (sizeFBT l) `addPos` (sizeFBT r) |] -- | Kind-restricted type synonym for 'SingI' type FBTC (t :: FBT) = SingI t -- | Kind-restricted synonym for 'sing' singFBT :: FBTC t => SFBT t singFBT = sing | A PRF secret key of dimension @n@ over ring newtype PRFKey n a = Key { key :: Matrix a } | Generate an @n@-dimensional secret key over @rq@. genKey :: forall rq rnd n . (MonadRandom rnd, Random rq, Reflects n Int) => rnd (PRFKey n rq) genKey = fmap Key $ randomMtx 1 $ value @n -- | PRF public parameters for an @n@-dimension secret key over @a@, -- using a gadget indicated by @gad@. data PRFParams n gad a = Params { a0 :: (Matrix a), a1 :: (Matrix a) } -- | Generate public parameters (\( \mathbf{A}_0 \) and \( \mathbf{A}_1 \ ) ) for @n@-dimensional secret keys over a ring @rq@ -- for gadget indicated by @gad@. genParams :: forall gad rq rnd n . (MonadRandom rnd, Random rq, Reflects n Int, Gadget gad rq) => rnd (PRFParams n gad rq) genParams = let len = length $ gadget @gad @rq n = value @n in Params <$> (randomMtx n (n*len)) <*> (randomMtx n (n*len)) -- | A random matrix having a given number of rows and columns. randomMtx :: (MonadRandom rnd, Random a) => Int -> Int -> rnd (Matrix a) randomMtx r c = M.fromList r c <$> replicateM (r*c) getRandom | PRF state for tree topology @t@ with key length @n@ over @a@ , -- using gadget indicated by @gad@. data PRFState t n gad rq = PRFState { params :: PRFParams n gad rq , state' :: PRFState' t n gad rq } data PRFState' t n gad rq where L :: BitStringMatrix 'Leaf rq -> PRFState' 'Leaf n gad rq I :: BitStringMatrix ('Intern l r) rq -> PRFState' l n gad rq -- ^ left child -> PRFState' r n gad rq -- ^ right child -> PRFState' ('Intern l r) n gad rq | A ' BitString ' together with a ' Matrix . T ' data BitStringMatrix t a = BSM { bitString :: BitString (SizeFBT t), matrix :: Matrix a } root' :: PRFState' t n gad a -> BitStringMatrix t a left' :: PRFState' ('Intern l r) n gad a -> PRFState' l n gad a right' :: PRFState' ('Intern l r) n gad a -> PRFState' r n gad a root' (L a) = a root' (I a _ _) = a left' (I _ l _) = l right' (I _ _ r) = r root :: PRFState t n gad a -> BitStringMatrix t a root = root' . state' -- | Compute PRF state for a given tree and input, which includes \( \mathbf{A}_T(x ) \ ) and all intermediate values ( see Definition 2.1 -- of [BP14]). updateState' :: forall gad rq t n . Decompose gad rq => SFBT t -- ^ singleton for the tree \( T \) -> PRFParams n gad rq -> Maybe (PRFState' t n gad rq) -> BitString (SizeFBT t) -- ^ input \( x \) -> PRFState' t n gad rq updateState' t p st x = case t of SLeaf -> L $ BSM x $ if head x then a1 p else a0 p SIntern _ _ | fromMaybe False (((x ==) . bitString . root') <$> st) -> fromJust st SIntern l r -> let (xl, xr) = splitS (sSizeFBT l) x stl = updateState' l p (left' <$> st) xl str = updateState' r p (right' <$> st) xr al = matrix $ root' stl ar = matrix $ root' str ar' = reduce <$> decomposeMatrix @gad ar in I (BSM x (al*ar')) stl str updateState :: Decompose gad rq => SFBT t -> Either (PRFParams n gad rq) (PRFState t n gad rq) -> BitString (SizeFBT t) -> PRFState t n gad rq updateState t e x = let p = either id params e st' = case e of -- using fromRight gives weird error (Left _) -> Nothing (Right st) -> Just $ state' st in PRFState p $ updateState' t p st' x | Compute \ ( \lfloor s \cdot \mathbf{A}_T \rceil_p \ ) , where \ ( -- \mathbf{A}_T(x) \) comes from the given state. prfCore :: (Ring rq, Rescale rq rp) => PRFKey n rq -> PRFState t n gad rq -> Matrix rp prfCore s st = rescale <$> (key s) * matrix (root st) | " Fresh " PRF computation , with no precomputed ' PRFState ' . prf :: (Rescale rq rp, Decompose gad rq) => SFBT t -- ^ singleton for the tree \( T \) -> PRFParams n gad rq -- ^ public parameters -> PRFKey n rq -- ^ secret key \( s \) -> BitString (SizeFBT t) -- ^ input \( x \) -> Matrix rp prf = (fmap . fmap . fmap) fst . prfState | " Fresh " PRF computation that also outputs the resulting ' PRFState ' . prfState :: (Rescale rq rp, Decompose gad rq) => SFBT t -- ^ singleton for the tree \( T \) -> PRFParams n gad rq -- ^ public parameters -> PRFKey n rq -- ^ secret key \( s \) -> BitString (SizeFBT t) -- ^ input \( x \) -> (Matrix rp, PRFState t n gad rq) prfState t p s x = let st = updateState t (Left p) x in (prfCore s st, st) -- | Amortized PRF computation for a given secret key and input. The output is in a monadic context that keeps a ' PRFState ' state for -- efficient amortization across calls. prfAmortized :: (Rescale rq rp, Decompose gad rq, MonadState (Maybe (PRFState t n gad rq)) m) => SFBT t -- ^ singleton for the tree \( T \) -> PRFParams n gad rq -- ^ public parameters -> PRFKey n rq -- ^ secret key \( s \) -> BitString (SizeFBT t) -- ^ input \( x \) -> m (Matrix rp) -- ^ PRF output prfAmortized t p s x = do fbt <- get let fbt' = updateState t (maybe (Left p) Right fbt) x put $ Just fbt' return $ prfCore s fbt' -- | Run a PRF computation with some public parameters. -- E.g.: @run top params (prf key x)@ run :: State (Maybe (PRFState t n gad rq)) a -> a run = runIdentity . runT -- | More general (monad transformer) version of 'run'. runT :: (Monad m) => StateT (Maybe (PRFState t n gad rq)) m a -> m a runT = flip evalStateT Nothing -- | Canonical type-safe sized vector data Vector n a where Lone :: a -> Vector 'O a (:-) :: a -> Vector n a -> Vector ('S n) a infixr 5 :- deriving instance Show a => Show (Vector n a) instance Eq a => Eq (Vector n a) where Lone a1 == Lone a2 = a1 == a2 h1 :- t1 == h2 :- t2 = h1 == h2 && t1 == t2 | Enumerates according to the n - bit code , starting with all ' False ' instance PosC n => Enum (Vector n Bool) where toEnum = case (sing :: Sing n) of SO -> Lone . odd SS m -> withSingI m $ let thresh = 2^(sPosToInt m) num = 2 * thresh in \x -> let x' = x `mod` num in if x' < thresh then False :- toEnum x' else True :- toEnum (num - 1 - x') fromEnum = case (sing :: Sing n) of SO -> \(Lone x) -> if x then 1 else 0 SS m -> withSingI m $ let num :: Int = 2^(1 + sPosToInt m) in \(x:-xs) -> if x then num - 1 - fromEnum xs else fromEnum xs instance PosC n => Enumerable (Vector n Bool) where values = case (sing :: Sing n) of SO -> [Lone False, Lone True] SS m -> withSingI m $ let num = 2^(1 + sPosToInt m) in take num [replicate False ..] | An @n@-dimensional ' Vector ' of ' 's type BitString n = Vector n Bool head :: Vector n a -> a head (Lone a) = a head (a :- _) = a | Split a ' Vector ' into two split :: forall m n a . PosC m => Vector (m `AddPos` n) a -> (Vector m a, Vector n a) split = splitS (sing :: Sing m) -- | Alternative form of 'split' splitS :: SPos m -> Vector (m `AddPos` n) a -> (Vector m a, Vector n a) splitS m (h :- t) = case m of SO -> (Lone h, t) SS m' -> let (b, e) = splitS m' t in (h :- b, e) splitS _ (Lone _) = error "splitS: internal error; can't split a Lone" -- | Create a 'Vector' full of given value replicate :: forall n a . PosC n => a -> Vector n a replicate = replicateS (sing :: Sing n) -- | Alternative form of 'replicate' replicateS :: SPos n -> a -> Vector n a replicateS n a = case n of SO -> Lone a SS n' -> a :- replicateS n' a -- | Convert a list to a 'Vector', return 'Nothing' if lengths don't match fromList :: forall n a . PosC n => [a] -> Maybe (Vector n a) fromList = fromListS (sing :: Sing n) fromListS :: SPos n -> [a] -> Maybe (Vector n a) fromListS n xs = case n of SO -> case xs of (x:[]) -> Just (Lone x) _ -> Nothing SS n' -> case xs of (x:rest) -> (:-) x <$> fromListS n' rest _ -> Nothing sPosToInt :: SPos n -> Int sPosToInt SO = 1 sPosToInt (SS a) = 1 + sPosToInt a | Note : Making ' Vector ' an instance of ' Additive . C ' Option 1 : Two separate instances for Vector ` O Bool and Vector ( ` S n ) Bool Recursive instance requires recursive restraint Ca n't always match on these instances if we only know that n : : Pos Option 2 : One instance , using singletons and ' case ' to distinguish Ugly syntax Did n't implement ( functionality replaced by ' replicate ' ) Note: Making 'Vector' an instance of 'Additive.C' Option 1: Two separate instances for Vector `O Bool and Vector (`S n) Bool Recursive instance requires recursive restraint Can't always match on these instances if we only know that n :: Pos Option 2: One instance, using singletons and 'case' to distinguish Ugly syntax Didn't implement (functionality replaced by 'replicate') -}
null
https://raw.githubusercontent.com/cpeikert/Lol/4416ac4f03b0bff08cb1115c72a45eed1fa48ec3/lol-apps/Crypto/Lol/Applications/KeyHomomorphicPRF.hs
haskell
# LANGUAGE ConstraintKinds # # LANGUAGE DefaultSignatures # # LANGUAGE GADTs # # LANGUAGE KindSignatures # # LANGUAGE RankNTypes # # LANGUAGE ScopedTypeVariables # # LANGUAGE StandaloneKindSignatures # # LANGUAGE TypeFamilies # # LANGUAGE TypeOperators # # LANGUAGE UndecidableInstances # A full binary tree (promoted to the type level by data kinds, and singleton-ized): each node is either a leaf or promote to type family for getting number of leaves | Kind-restricted type synonym for 'SingI' | Kind-restricted synonym for 'sing' | PRF public parameters for an @n@-dimension secret key over @a@, using a gadget indicated by @gad@. | Generate public parameters (\( \mathbf{A}_0 \) and \( for gadget indicated by @gad@. | A random matrix having a given number of rows and columns. using gadget indicated by @gad@. ^ left child ^ right child | Compute PRF state for a given tree and input, which includes \( of [BP14]). ^ singleton for the tree \( T \) ^ input \( x \) using fromRight gives weird error \mathbf{A}_T(x) \) comes from the given state. ^ singleton for the tree \( T \) ^ public parameters ^ secret key \( s \) ^ input \( x \) ^ singleton for the tree \( T \) ^ public parameters ^ secret key \( s \) ^ input \( x \) | Amortized PRF computation for a given secret key and input. The efficient amortization across calls. ^ singleton for the tree \( T \) ^ public parameters ^ secret key \( s \) ^ input \( x \) ^ PRF output | Run a PRF computation with some public parameters. E.g.: @run top params (prf key x)@ | More general (monad transformer) version of 'run'. | Canonical type-safe sized vector | Alternative form of 'split' | Create a 'Vector' full of given value | Alternative form of 'replicate' | Convert a list to a 'Vector', return 'Nothing' if lengths don't match
| Module : Crypto . Lol . Applications . : Key - homomorphic PRF from < /~cpeikert/pubs/kh-prf.pdf [ BP14 ] > . Copyright : ( c ) , 2018 , 2018 License : GPL-3 Maintainer : Stability : experimental Portability : POSIX Key - homomorphic PRF from < /~cpeikert/pubs/kh-prf.pdf [ BP14 ] > . Module : Crypto.Lol.Applications.KeyHomomorphicPRF Description : Key-homomorphic PRF from </~cpeikert/pubs/kh-prf.pdf [BP14]>. Copyright : (c) Bogdan Manga, 2018 Chris Peikert, 2018 License : GPL-3 Maintainer : Stability : experimental Portability : POSIX Key-homomorphic PRF from </~cpeikert/pubs/kh-prf.pdf [BP14]>. -} # LANGUAGE DataKinds # # LANGUAGE EmptyCase # # LANGUAGE ExistentialQuantification # # LANGUAGE FlexibleContexts # # LANGUAGE FlexibleInstances # # LANGUAGE InstanceSigs # # LANGUAGE MultiParamTypeClasses # # LANGUAGE NoCUSKs # # LANGUAGE NoImplicitPrelude # # LANGUAGE NoStarIsType # # LANGUAGE PolyKinds # # LANGUAGE RecordWildCards # # LANGUAGE StandaloneDeriving # # LANGUAGE TemplateHaskell # # LANGUAGE TypeApplications # module Crypto.Lol.Applications.KeyHomomorphicPRF ( FBT(..), SFBT(..), SizeFBT, FBTC, singFBT , PRFKey, PRFParams, PRFState , genKey, genParams, prf, prfState, prfAmortized, run, runT , Vector, BitString , replicate, replicateS, fromList, fromListS, split, splitS ) where import Control.Applicative ((<$>), (<*>)) import Control.Monad.Identity import Control.Monad.Random hiding (fromList, split) import Control.Monad.State import Crypto.Lol hiding (head, replicate) import Crypto.Lol.Reflects import Data.Maybe import Data.Singletons.TH import qualified MathObj.Matrix as M singletons [d| has two children . data FBT = Leaf | Intern FBT FBT sizeFBT :: FBT -> Pos sizeFBT Leaf = O sizeFBT (Intern l r) = (sizeFBT l) `addPos` (sizeFBT r) |] type FBTC (t :: FBT) = SingI t singFBT :: FBTC t => SFBT t singFBT = sing | A PRF secret key of dimension @n@ over ring newtype PRFKey n a = Key { key :: Matrix a } | Generate an @n@-dimensional secret key over @rq@. genKey :: forall rq rnd n . (MonadRandom rnd, Random rq, Reflects n Int) => rnd (PRFKey n rq) genKey = fmap Key $ randomMtx 1 $ value @n data PRFParams n gad a = Params { a0 :: (Matrix a), a1 :: (Matrix a) } \mathbf{A}_1 \ ) ) for @n@-dimensional secret keys over a ring @rq@ genParams :: forall gad rq rnd n . (MonadRandom rnd, Random rq, Reflects n Int, Gadget gad rq) => rnd (PRFParams n gad rq) genParams = let len = length $ gadget @gad @rq n = value @n in Params <$> (randomMtx n (n*len)) <*> (randomMtx n (n*len)) randomMtx :: (MonadRandom rnd, Random a) => Int -> Int -> rnd (Matrix a) randomMtx r c = M.fromList r c <$> replicateM (r*c) getRandom | PRF state for tree topology @t@ with key length @n@ over @a@ , data PRFState t n gad rq = PRFState { params :: PRFParams n gad rq , state' :: PRFState' t n gad rq } data PRFState' t n gad rq where L :: BitStringMatrix 'Leaf rq -> PRFState' 'Leaf n gad rq I :: BitStringMatrix ('Intern l r) rq -> PRFState' ('Intern l r) n gad rq | A ' BitString ' together with a ' Matrix . T ' data BitStringMatrix t a = BSM { bitString :: BitString (SizeFBT t), matrix :: Matrix a } root' :: PRFState' t n gad a -> BitStringMatrix t a left' :: PRFState' ('Intern l r) n gad a -> PRFState' l n gad a right' :: PRFState' ('Intern l r) n gad a -> PRFState' r n gad a root' (L a) = a root' (I a _ _) = a left' (I _ l _) = l right' (I _ _ r) = r root :: PRFState t n gad a -> BitStringMatrix t a root = root' . state' \mathbf{A}_T(x ) \ ) and all intermediate values ( see Definition 2.1 updateState' :: forall gad rq t n . Decompose gad rq -> PRFParams n gad rq -> Maybe (PRFState' t n gad rq) -> PRFState' t n gad rq updateState' t p st x = case t of SLeaf -> L $ BSM x $ if head x then a1 p else a0 p SIntern _ _ | fromMaybe False (((x ==) . bitString . root') <$> st) -> fromJust st SIntern l r -> let (xl, xr) = splitS (sSizeFBT l) x stl = updateState' l p (left' <$> st) xl str = updateState' r p (right' <$> st) xr al = matrix $ root' stl ar = matrix $ root' str ar' = reduce <$> decomposeMatrix @gad ar in I (BSM x (al*ar')) stl str updateState :: Decompose gad rq => SFBT t -> Either (PRFParams n gad rq) (PRFState t n gad rq) -> BitString (SizeFBT t) -> PRFState t n gad rq updateState t e x = let p = either id params e (Left _) -> Nothing (Right st) -> Just $ state' st in PRFState p $ updateState' t p st' x | Compute \ ( \lfloor s \cdot \mathbf{A}_T \rceil_p \ ) , where \ ( prfCore :: (Ring rq, Rescale rq rp) => PRFKey n rq -> PRFState t n gad rq -> Matrix rp prfCore s st = rescale <$> (key s) * matrix (root st) | " Fresh " PRF computation , with no precomputed ' PRFState ' . prf :: (Rescale rq rp, Decompose gad rq) -> Matrix rp prf = (fmap . fmap . fmap) fst . prfState | " Fresh " PRF computation that also outputs the resulting ' PRFState ' . prfState :: (Rescale rq rp, Decompose gad rq) -> (Matrix rp, PRFState t n gad rq) prfState t p s x = let st = updateState t (Left p) x in (prfCore s st, st) output is in a monadic context that keeps a ' PRFState ' state for prfAmortized :: (Rescale rq rp, Decompose gad rq, MonadState (Maybe (PRFState t n gad rq)) m) prfAmortized t p s x = do fbt <- get let fbt' = updateState t (maybe (Left p) Right fbt) x put $ Just fbt' return $ prfCore s fbt' run :: State (Maybe (PRFState t n gad rq)) a -> a run = runIdentity . runT runT :: (Monad m) => StateT (Maybe (PRFState t n gad rq)) m a -> m a runT = flip evalStateT Nothing data Vector n a where Lone :: a -> Vector 'O a (:-) :: a -> Vector n a -> Vector ('S n) a infixr 5 :- deriving instance Show a => Show (Vector n a) instance Eq a => Eq (Vector n a) where Lone a1 == Lone a2 = a1 == a2 h1 :- t1 == h2 :- t2 = h1 == h2 && t1 == t2 | Enumerates according to the n - bit code , starting with all ' False ' instance PosC n => Enum (Vector n Bool) where toEnum = case (sing :: Sing n) of SO -> Lone . odd SS m -> withSingI m $ let thresh = 2^(sPosToInt m) num = 2 * thresh in \x -> let x' = x `mod` num in if x' < thresh then False :- toEnum x' else True :- toEnum (num - 1 - x') fromEnum = case (sing :: Sing n) of SO -> \(Lone x) -> if x then 1 else 0 SS m -> withSingI m $ let num :: Int = 2^(1 + sPosToInt m) in \(x:-xs) -> if x then num - 1 - fromEnum xs else fromEnum xs instance PosC n => Enumerable (Vector n Bool) where values = case (sing :: Sing n) of SO -> [Lone False, Lone True] SS m -> withSingI m $ let num = 2^(1 + sPosToInt m) in take num [replicate False ..] | An @n@-dimensional ' Vector ' of ' 's type BitString n = Vector n Bool head :: Vector n a -> a head (Lone a) = a head (a :- _) = a | Split a ' Vector ' into two split :: forall m n a . PosC m => Vector (m `AddPos` n) a -> (Vector m a, Vector n a) split = splitS (sing :: Sing m) splitS :: SPos m -> Vector (m `AddPos` n) a -> (Vector m a, Vector n a) splitS m (h :- t) = case m of SO -> (Lone h, t) SS m' -> let (b, e) = splitS m' t in (h :- b, e) splitS _ (Lone _) = error "splitS: internal error; can't split a Lone" replicate :: forall n a . PosC n => a -> Vector n a replicate = replicateS (sing :: Sing n) replicateS :: SPos n -> a -> Vector n a replicateS n a = case n of SO -> Lone a SS n' -> a :- replicateS n' a fromList :: forall n a . PosC n => [a] -> Maybe (Vector n a) fromList = fromListS (sing :: Sing n) fromListS :: SPos n -> [a] -> Maybe (Vector n a) fromListS n xs = case n of SO -> case xs of (x:[]) -> Just (Lone x) _ -> Nothing SS n' -> case xs of (x:rest) -> (:-) x <$> fromListS n' rest _ -> Nothing sPosToInt :: SPos n -> Int sPosToInt SO = 1 sPosToInt (SS a) = 1 + sPosToInt a | Note : Making ' Vector ' an instance of ' Additive . C ' Option 1 : Two separate instances for Vector ` O Bool and Vector ( ` S n ) Bool Recursive instance requires recursive restraint Ca n't always match on these instances if we only know that n : : Pos Option 2 : One instance , using singletons and ' case ' to distinguish Ugly syntax Did n't implement ( functionality replaced by ' replicate ' ) Note: Making 'Vector' an instance of 'Additive.C' Option 1: Two separate instances for Vector `O Bool and Vector (`S n) Bool Recursive instance requires recursive restraint Can't always match on these instances if we only know that n :: Pos Option 2: One instance, using singletons and 'case' to distinguish Ugly syntax Didn't implement (functionality replaced by 'replicate') -}
e69df69bfb87e26d6736c8d41806e90f1e7c97308f434f825379f6755768ec6a
clojure/data.xml
test_equiv.cljc
(ns clojure.data.xml.test-equiv (:require [clojure.data.xml :refer [element qname]] [clojure.test :refer [deftest is are testing]])) (deftest test-node-equivalence (are [repr1 repr2] (and (is (= repr1 repr2)) (is (= (hash repr1) (hash repr2)))) (element :foo) {:tag :foo :attrs {} :content []} (element (qname "DAV:" "foo")) {:tag (qname "DAV:" "foo") :attrs {} :content []} (element :foo {:a "b"}) {:tag :foo :attrs {:a "b"} :content []} (element :foo {:a "b"} "a" "b") {:tag :foo :attrs {:a "b"} :content ["a" "b"]}))
null
https://raw.githubusercontent.com/clojure/data.xml/12cc9934607de6cb4d75eddb1fcae30829fa4156/src/test/clojure/clojure/data/xml/test_equiv.cljc
clojure
(ns clojure.data.xml.test-equiv (:require [clojure.data.xml :refer [element qname]] [clojure.test :refer [deftest is are testing]])) (deftest test-node-equivalence (are [repr1 repr2] (and (is (= repr1 repr2)) (is (= (hash repr1) (hash repr2)))) (element :foo) {:tag :foo :attrs {} :content []} (element (qname "DAV:" "foo")) {:tag (qname "DAV:" "foo") :attrs {} :content []} (element :foo {:a "b"}) {:tag :foo :attrs {:a "b"} :content []} (element :foo {:a "b"} "a" "b") {:tag :foo :attrs {:a "b"} :content ["a" "b"]}))
9d2ca4f72976d7ebd85828655243322baa168e0f3ed33d245a51937fe42b6c9d
Apress/practical-webdev-haskell
Main.hs
module Main where import ClassyPrelude import Lib main :: IO () main = someFunc
null
https://raw.githubusercontent.com/Apress/practical-webdev-haskell/17b90c06030def254bb0497b9e357f5d3b96d0cf/03/app/Main.hs
haskell
module Main where import ClassyPrelude import Lib main :: IO () main = someFunc
025116110107522b323537919b2bfbb5ef3c98d14987e52911103d22b8826608
sergv/constrained
Constrained.hs
---------------------------------------------------------------------------- -- | -- Module : Data.Foldable.Constrained Copyright : ( c ) 2019 License : BSD-2 ( see LICENSE ) -- Maintainer : sergey@debian ---------------------------------------------------------------------------- {-# LANGUAGE BangPatterns #-} # LANGUAGE CPP # # LANGUAGE InstanceSigs # # LANGUAGE ScopedTypeVariables # # LANGUAGE ScopedTypeVariables # # LANGUAGE TypeFamilies # module Data.Foldable.Constrained ( CFoldable(..) , cfoldrM , cfoldlM , ctraverse_ , cfor_ , cmapM_ , cforM_ , csequenceA_ , csequence_ , casum , cmsum , cconcat , cconcatMap , cand , cor , cany , call , cmaximumBy , cminimumBy , cnotElem , cfind , module Data.Constrained ) where import Prelude (Bool(..), id, (.), Int, Eq(..), Num(..), ($), ($!), flip, errorWithoutStackTrace, not) import Control.Applicative import Control.Monad hiding (mapM_) import Data.Coerce import Data.Either import qualified Data.Foldable as F import Data.Functor.Compose (Compose(..)) import Data.Functor.Identity (Identity(..)) import Data.Functor.Product as Product import Data.Functor.Sum as Sum import Data.List.NonEmpty (NonEmpty(..)) import Data.Maybe import Data.Monoid import qualified Data.Monoid as Monoid import Data.Ord import Data.Semigroup (Max(..), Min(..), Option(..)) import qualified Data.Semigroup as Semigroup import GHC.Base (build) import Data.Constrained (Constrained(..)) -- | Like 'Data.Foldable.Foldable' but allows elements to have constraints on them. -- Laws are the same. class Constrained f => CFoldable f where # MINIMAL cfoldMap | cfoldr # -- | Combine the elements of a structure using a monoid. cfold :: (Monoid m, Constraints f m) => f m -> m cfold = cfoldMap id # INLINABLE cfold # -- | Map each element of the structure to a monoid, -- and combine the results. cfoldMap :: (Monoid m, Constraints f a) => (a -> m) -> f a -> m cfoldMap f = cfoldr (mappend . f) mempty This INLINE allows more list functions to fuse . See Trac # 9848 . # INLINE cfoldMap # -- | Right-associative fold of a structure. -- In the case of lists , ' cfoldr ' , when applied to a binary operator , a -- starting value (typically the right-identity of the operator), and a -- list, reduces the list using the binary operator, from right to left: -- -- > cfoldr f z [x1, x2, ..., xn] == x1 `f` (x2 `f` ... (xn `f` z)...) -- -- Note that, since the head of the resulting expression is produced by an application of the operator to the first element of the list , -- 'cfoldr' can produce a terminating expression from an infinite list. -- -- For a general 'CFoldable' structure this should be semantically identical -- to, -- @cfoldr f z = ' List.foldr ' f z . ' ctoList'@ -- cfoldr :: Constraints f a => (a -> b -> b) -> b -> f a -> b cfoldr f z t = appEndo (cfoldMap (Endo . f) t) z -- | Right-associative fold of a structure, but with strict application of -- the operator. -- cfoldr' :: Constraints f a => (a -> b -> b) -> b -> f a -> b cfoldr' f z0 xs = cfoldl f' id xs z0 where f' k x z = k $! f x z -- | Left-associative fold of a structure. -- -- In the case of lists, 'cfoldl', when applied to a binary -- operator, a starting value (typically the left-identity of the operator), -- and a list, reduces the list using the binary operator, from left to -- right: -- > cfoldl f z [ x1 , x2 , ... , xn ] = = ( ... ( ( z ` f ` x1 ) ` f ` x2 ) ` f ` ... ) ` f ` xn -- -- Note that to produce the outermost application of the operator the -- entire input list must be traversed. This means that 'cfoldl'' will -- diverge if given an infinite list. -- -- Also note that if you want an efficient left-fold, you probably want to -- use 'cfoldl'' instead of 'cfoldl'. The reason for this is that latter does not force the " inner " results ( e.g. ` f ` x1@ in the above example ) -- before applying them to the operator (e.g. to @(`f` x2)@). This results -- in a thunk chain @O(n)@ elements long, which then must be evaluated from -- the outside-in. -- -- For a general 'CFoldable' structure this should be semantically identical -- to, -- @cfoldl f z = ' List.foldl ' f z . ' ctoList'@ -- cfoldl :: Constraints f a => (b -> a -> b) -> b -> f a -> b cfoldl f z t = appEndo (getDual (cfoldMap (Dual . Endo . flip f) t)) z -- There's no point mucking around with coercions here, -- because flip forces us to build a new function anyway. -- | Left-associative fold of a structure but with strict application of -- the operator. -- -- This ensures that each step of the fold is forced to weak head normal -- form before being applied, avoiding the collection of thunks that would -- otherwise occur. This is often what you want to strictly reduce a finite list to a single , monolithic result ( e.g. ' clength ' ) . -- -- For a general 'CFoldable' structure this should be semantically identical -- to, -- @cfoldl f z = ' List.foldl '' f z . ' ctoList'@ -- cfoldl' :: Constraints f a => (b -> a -> b) -> b -> f a -> b cfoldl' f z0 xs = cfoldr f' id xs z0 where f' x k z = k $! f z x -- | A variant of 'cfoldr' that has no base case, -- and thus may only be applied to non-empty structures. -- @'cfoldr1 ' f = f . ' ctoList'@ cfoldr1 :: Constraints f a => (a -> a -> a) -> f a -> a cfoldr1 f xs = fromMaybe (errorWithoutStackTrace "foldr1: empty structure") (cfoldr mf Nothing xs) where mf x m = Just $ case m of Nothing -> x Just y -> f x y -- | A variant of 'cfoldl' that has no base case, -- and thus may only be applied to non-empty structures. -- -- @'cfoldl1' f = 'List.foldl1' f . 'ctoList'@ cfoldl1 :: Constraints f a => (a -> a -> a) -> f a -> a cfoldl1 f xs = fromMaybe (errorWithoutStackTrace "foldl1: empty structure") (cfoldl mf Nothing xs) where mf m y = Just $ case m of Nothing -> y Just x -> f x y -- | List of elements of a structure, from left to right. ctoList :: Constraints f a => f a -> [a] ctoList t = build (\ c n -> cfoldr c n t) # INLINE ctoList # -- | Test whether the structure is empty. The default implementation is -- optimized for structures that are similar to cons-lists, because there -- is no general way to do better. cnull :: Constraints f a => f a -> Bool cnull = cfoldr (\_ _ -> False) True # INLINE cnull # -- | Returns the size/length of a finite structure as an 'Int'. The -- default implementation is optimized for structures that are similar to -- cons-lists, because there is no general way to do better. clength :: Constraints f a => f a -> Int clength = cfoldl' (\c _ -> c + 1) 0 -- | Does the element occur in the structure? celem :: (Eq a, Constraints f a) => a -> f a -> Bool celem = cany . (==) # INLINE celem # -- | The largest element of a non-empty structure. cmaximum :: forall a. (Ord a, Constraints f a) => f a -> a cmaximum = maybe (errorWithoutStackTrace "maximum: empty structure") getMax . getOption . cfoldMap (Option . Just . Max) # INLINABLE cmaximum # -- | The least element of a non-empty structure. cminimum :: forall a. (Ord a, Constraints f a) => f a -> a cminimum = maybe (errorWithoutStackTrace "maximum: empty structure") getMin . getOption . cfoldMap (Option . Just . Min) # INLINABLE cminimum # -- | The 'csum' function computes the sum of the numbers of a structure. csum :: (Num a, Constraints f a) => f a -> a csum = getSum . cfoldMap Sum # INLINABLE csum # -- | The 'cproduct' function computes the product of the numbers of a -- structure. cproduct :: (Num a, Constraints f a) => f a -> a cproduct = getProduct . cfoldMap Product # INLINABLE cproduct # -- | Monadic fold over the elements of a structure, -- associating to the right, i.e. from right to left. cfoldrM :: (CFoldable f, Monad m, Constraints f a) => (a -> b -> m b) -> b -> f a -> m b cfoldrM f z0 xs = cfoldl f' return xs z0 where f' k x z = f x z >>= k -- | Monadic fold over the elements of a structure, -- associating to the left, i.e. from left to right. cfoldlM :: (CFoldable f, Monad m, Constraints f a) => (b -> a -> m b) -> b -> f a -> m b cfoldlM f z0 xs = cfoldr f' return xs z0 where f' x k z = f z x >>= k -- | Map each element of a structure to an action, evaluate these -- actions from left to right, and ignore the results. For a version that does n't ignore the results see ' ' . ctraverse_ :: (CFoldable f, Applicative f, Constraints f a) => (a -> f b) -> f a -> f () ctraverse_ f = cfoldr ((*>) . f) (pure ()) | ' cfor _ ' is ' _ ' with its arguments flipped . For a version -- that doesn't ignore the results see 'Data.Traversable.Constrained.cfor'. -- > > > for _ [ 1 .. 4 ] print 1 2 3 4 cfor_ :: (CFoldable f, Applicative f, Constraints f a) => f a -> (a -> f b) -> f () {-# INLINE cfor_ #-} cfor_ = flip ctraverse_ -- | Map each element of a structure to a monadic action, evaluate -- these actions from left to right, and ignore the results. For a -- version that doesn't ignore the results see -- 'Data.Traversable.mapM'. cmapM_ :: (CFoldable f, Monad m, Constraints f a) => (a -> m b) -> f a -> m () cmapM_ f = cfoldr ((>>) . f) (return ()) -- | 'cforM_' is 'cmapM_' with its arguments flipped. For a version that -- doesn't ignore the results see 'Data.Traversable.forM'. cforM_ :: (CFoldable f, Monad m, Constraints f a) => f a -> (a -> m b) -> m () {-# INLINE cforM_ #-} cforM_ = flip cmapM_ -- | Evaluate each action in the structure from left to right, and -- ignore the results. For a version that doesn't ignore the results -- see 'Data.Traversable.sequenceA'. csequenceA_ :: (CFoldable f, Applicative m, Constraints f (m a)) => f (m a) -> m () csequenceA_ = cfoldr (*>) (pure ()) -- | Evaluate each monadic action in the structure from left to right, -- and ignore the results. For a version that doesn't ignore the results see ' ' . csequence_ :: (CFoldable f, Monad m, Constraints f a, Constraints f (m a)) => f (m a) -> m () csequence_ = cfoldr (>>) (return ()) | The sum of a collection of actions , generalizing ' Data.Foldable.concat ' . -- asum [ Just " Hello " , Nothing , Just " World " ] -- Just "Hello" casum :: (CFoldable f, Alternative m, Constraints f (m a)) => f (m a) -> m a # INLINE casum # casum = cfoldr (<|>) empty | The sum of a collection of actions , generalizing ' Data.Foldable.concat ' . cmsum :: (CFoldable f, MonadPlus m, Constraints f (m a)) => f (m a) -> m a # INLINE cmsum # cmsum = casum -- | The concatenation of all the elements of a container of lists. cconcat :: (CFoldable f, Constraints f [a]) => f [a] -> [a] cconcat xs = build (\c n -> cfoldr (\x y -> cfoldr c y x) n xs) # INLINE cconcat # -- | Map a function over all the elements of a container and concatenate -- the resulting lists. cconcatMap :: (CFoldable f, Constraints f a) => (a -> [b]) -> f a -> [b] cconcatMap f xs = build (\c n -> cfoldr (\x b -> cfoldr c b (f x)) n xs) # INLINE cconcatMap # -- These use foldr rather than cfoldMap to avoid repeated concatenation. | ' cand ' returns the conjunction of a container of Bools . For the -- result to be 'True', the container must be finite; 'False', however, -- results from a 'False' value finitely far from the left end. cand :: (CFoldable f, Constraints f Bool) => f Bool -> Bool cand = getAll . cfoldMap All | ' cor ' returns the disjunction of a container of Bools . For the -- result to be 'False', the container must be finite; 'True', however, -- results from a 'True' value finitely far from the left end. cor :: (CFoldable f, Constraints f Bool) => f Bool -> Bool cor = getAny . cfoldMap Any -- | Determines whether any element of the structure satisfies the predicate. cany :: (CFoldable f, Constraints f a) => (a -> Bool) -> f a -> Bool cany p = getAny . cfoldMap (Any . p) -- | Determines whether all elements of the structure satisfy the predicate. call :: (CFoldable f, Constraints f a) => (a -> Bool) -> f a -> Bool call p = getAll . cfoldMap (All . p) -- | The largest element of a non-empty structure with respect to the -- given comparison function. See Note [ / minimumBy space usage ] cmaximumBy :: (CFoldable f, Constraints f a) => (a -> a -> Ordering) -> f a -> a cmaximumBy cmp = cfoldl1 max' where max' x y = case cmp x y of GT -> x _ -> y -- | The least element of a non-empty structure with respect to the -- given comparison function. See Note [ / minimumBy space usage ] cminimumBy :: (CFoldable f, Constraints f a) => (a -> a -> Ordering) -> f a -> a cminimumBy cmp = cfoldl1 min' where min' x y = case cmp x y of GT -> y _ -> x -- | 'cnotElem' is the negation of 'celem'. cnotElem :: (CFoldable f, Eq a, Constraints f a) => a -> f a -> Bool cnotElem x = not . celem x -- | The 'cfind' function takes a predicate and a structure and returns -- the leftmost element of the structure matching the predicate, or -- 'Nothing' if there is no such element. cfind :: (CFoldable f, Constraints f a) => (a -> Bool) -> f a -> Maybe a cfind p = getFirst . cfoldMap (\ x -> First (if p x then Just x else Nothing)) Note [ / minimumBy space usage ] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When the type signatures of and minimumBy were generalized to work over any Foldable instance ( instead of just lists ) , they were defined using foldr1 . This was problematic for space usage , as the semantics of and minimumBy essentially require that they examine every element of the data structure . Using to examine every element results in space usage proportional to the size of the data structure . For the common case of lists , this could be particularly bad ( see Trac # 10830 ) . For the common case of lists , switching the implementations of and minimumBy to foldl1 solves the issue , as GHC 's strictness analysis can then make these functions only use O(1 ) stack space . It is perhaps not the optimal way to fix this problem , as there are other conceivable data structures ( besides lists ) which might benefit from specialized implementations for and minimumBy ( see #comment:26 for a further discussion ) . But using foldl1 is at least always better than using , so GHC has chosen to adopt that approach for now . Note [maximumBy/minimumBy space usage] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When the type signatures of maximumBy and minimumBy were generalized to work over any Foldable instance (instead of just lists), they were defined using foldr1. This was problematic for space usage, as the semantics of maximumBy and minimumBy essentially require that they examine every element of the data structure. Using foldr1 to examine every element results in space usage proportional to the size of the data structure. For the common case of lists, this could be particularly bad (see Trac #10830). For the common case of lists, switching the implementations of maximumBy and minimumBy to foldl1 solves the issue, as GHC's strictness analysis can then make these functions only use O(1) stack space. It is perhaps not the optimal way to fix this problem, as there are other conceivable data structures (besides lists) which might benefit from specialized implementations for maximumBy and minimumBy (see #comment:26 for a further discussion). But using foldl1 is at least always better than using foldr1, so GHC has chosen to adopt that approach for now. -} instance CFoldable [] where # INLINE cfold # # INLINE cfoldMap # # INLINE cfoldr # # INLINE cfoldr ' # {-# INLINE cfoldl #-} {-# INLINE cfoldl' #-} # INLINE cfoldr1 # {-# INLINE cfoldl1 #-} {-# INLINE ctoList #-} # INLINE cnull # # INLINE clength # # INLINE celem # # INLINE cmaximum # # INLINE cminimum # {-# INLINE csum #-} # INLINE cproduct # cfold = F.fold cfoldMap = F.foldMap cfoldr = F.foldr cfoldr' = F.foldr' cfoldl = F.foldl cfoldl' = F.foldl' cfoldr1 = F.foldr1 cfoldl1 = F.foldl1 ctoList = F.toList cnull = F.null clength = F.length celem = F.elem cmaximum = F.maximum cminimum = F.minimum csum = F.sum cproduct = F.product instance CFoldable NonEmpty where # INLINE cfold # # INLINE cfoldMap # # INLINE cfoldr # # INLINE cfoldr ' # {-# INLINE cfoldl #-} {-# INLINE cfoldl' #-} # INLINE cfoldr1 # {-# INLINE cfoldl1 #-} {-# INLINE ctoList #-} # INLINE cnull # # INLINE clength # # INLINE celem # # INLINE cmaximum # # INLINE cminimum # {-# INLINE csum #-} # INLINE cproduct # cfold = F.fold cfoldMap = F.foldMap cfoldr = F.foldr cfoldr' = F.foldr' cfoldl = F.foldl cfoldl' = F.foldl' cfoldr1 = F.foldr1 cfoldl1 = F.foldl1 ctoList = F.toList cnull = F.null clength = F.length celem = F.elem cmaximum = F.maximum cminimum = F.minimum csum = F.sum cproduct = F.product instance CFoldable Identity where # INLINE cfold # # INLINE cfoldMap # # INLINE cfoldr # # INLINE cfoldr ' # {-# INLINE cfoldl #-} {-# INLINE cfoldl' #-} # INLINE cfoldr1 # {-# INLINE cfoldl1 #-} {-# INLINE ctoList #-} # INLINE cnull # # INLINE clength # # INLINE celem # # INLINE cmaximum # # INLINE cminimum # {-# INLINE csum #-} # INLINE cproduct # cfold = F.fold cfoldMap = F.foldMap cfoldr = F.foldr cfoldr' = F.foldr' cfoldl = F.foldl cfoldl' = F.foldl' cfoldr1 = F.foldr1 cfoldl1 = F.foldl1 ctoList = F.toList cnull = F.null clength = F.length celem = F.elem cmaximum = F.maximum cminimum = F.minimum csum = F.sum cproduct = F.product instance CFoldable ((,) a) where # INLINE cfold # # INLINE cfoldMap # # INLINE cfoldr # # INLINE cfoldr ' # {-# INLINE cfoldl #-} {-# INLINE cfoldl' #-} # INLINE cfoldr1 # {-# INLINE cfoldl1 #-} {-# INLINE ctoList #-} # INLINE cnull # # INLINE clength # # INLINE celem # # INLINE cmaximum # # INLINE cminimum # {-# INLINE csum #-} # INLINE cproduct # cfold = F.fold cfoldMap = F.foldMap cfoldr = F.foldr cfoldr' = F.foldr' cfoldl = F.foldl cfoldl' = F.foldl' cfoldr1 = F.foldr1 cfoldl1 = F.foldl1 ctoList = F.toList cnull = F.null clength = F.length celem = F.elem cmaximum = F.maximum cminimum = F.minimum csum = F.sum cproduct = F.product instance CFoldable Maybe where # INLINE cfold # # INLINE cfoldMap # # INLINE cfoldr # # INLINE cfoldr ' # {-# INLINE cfoldl #-} {-# INLINE cfoldl' #-} # INLINE cfoldr1 # {-# INLINE cfoldl1 #-} {-# INLINE ctoList #-} # INLINE cnull # # INLINE clength # # INLINE celem # # INLINE cmaximum # # INLINE cminimum # {-# INLINE csum #-} # INLINE cproduct # cfold = F.fold cfoldMap = F.foldMap cfoldr = F.foldr cfoldr' = F.foldr' cfoldl = F.foldl cfoldl' = F.foldl' cfoldr1 = F.foldr1 cfoldl1 = F.foldl1 ctoList = F.toList cnull = F.null clength = F.length celem = F.elem cmaximum = F.maximum cminimum = F.minimum csum = F.sum cproduct = F.product instance CFoldable (Either a) where # INLINE cfold # # INLINE cfoldMap # # INLINE cfoldr # # INLINE cfoldr ' # {-# INLINE cfoldl #-} {-# INLINE cfoldl' #-} # INLINE cfoldr1 # {-# INLINE cfoldl1 #-} {-# INLINE ctoList #-} # INLINE cnull # # INLINE clength # # INLINE celem # # INLINE cmaximum # # INLINE cminimum # {-# INLINE csum #-} # INLINE cproduct # cfold = F.fold cfoldMap = F.foldMap cfoldr = F.foldr cfoldr' = F.foldr' cfoldl = F.foldl cfoldl' = F.foldl' cfoldr1 = F.foldr1 cfoldl1 = F.foldl1 ctoList = F.toList cnull = F.null clength = F.length celem = F.elem cmaximum = F.maximum cminimum = F.minimum csum = F.sum cproduct = F.product instance CFoldable (Const a) where # INLINE cfold # # INLINE cfoldMap # # INLINE cfoldr # # INLINE cfoldr ' # {-# INLINE cfoldl #-} {-# INLINE cfoldl' #-} # INLINE cfoldr1 # {-# INLINE cfoldl1 #-} {-# INLINE ctoList #-} # INLINE cnull # # INLINE clength # # INLINE celem # # INLINE cmaximum # # INLINE cminimum # {-# INLINE csum #-} # INLINE cproduct # cfold = F.fold cfoldMap = F.foldMap cfoldr = F.foldr cfoldr' = F.foldr' cfoldl = F.foldl cfoldl' = F.foldl' cfoldr1 = F.foldr1 cfoldl1 = F.foldl1 ctoList = F.toList cnull = F.null clength = F.length celem = F.elem cmaximum = F.maximum cminimum = F.minimum csum = F.sum cproduct = F.product instance CFoldable ZipList where # INLINE cfold # # INLINE cfoldMap # # INLINE cfoldr # # INLINE cfoldr ' # {-# INLINE cfoldl #-} {-# INLINE cfoldl' #-} # INLINE cfoldr1 # {-# INLINE cfoldl1 #-} {-# INLINE ctoList #-} # INLINE cnull # # INLINE clength # # INLINE celem # # INLINE cmaximum # # INLINE cminimum # {-# INLINE csum #-} # INLINE cproduct # cfold = F.fold cfoldMap = F.foldMap cfoldr = F.foldr cfoldr' = F.foldr' cfoldl = F.foldl cfoldl' = F.foldl' cfoldr1 = F.foldr1 cfoldl1 = F.foldl1 ctoList = F.toList cnull = F.null clength = F.length celem = F.elem cmaximum = F.maximum cminimum = F.minimum csum = F.sum cproduct = F.product instance CFoldable Semigroup.Min where # INLINE cfold # # INLINE cfoldMap # # INLINE cfoldr # # INLINE cfoldr ' # {-# INLINE cfoldl #-} {-# INLINE cfoldl' #-} # INLINE cfoldr1 # {-# INLINE cfoldl1 #-} {-# INLINE ctoList #-} # INLINE cnull # # INLINE clength # # INLINE celem # # INLINE cmaximum # # INLINE cminimum # {-# INLINE csum #-} # INLINE cproduct # cfold = F.fold cfoldMap = F.foldMap cfoldr = F.foldr cfoldr' = F.foldr' cfoldl = F.foldl cfoldl' = F.foldl' cfoldr1 = F.foldr1 cfoldl1 = F.foldl1 ctoList = F.toList cnull = F.null clength = F.length celem = F.elem cmaximum = F.maximum cminimum = F.minimum csum = F.sum cproduct = F.product instance CFoldable Semigroup.Max where # INLINE cfold # # INLINE cfoldMap # # INLINE cfoldr # # INLINE cfoldr ' # {-# INLINE cfoldl #-} {-# INLINE cfoldl' #-} # INLINE cfoldr1 # {-# INLINE cfoldl1 #-} {-# INLINE ctoList #-} # INLINE cnull # # INLINE clength # # INLINE celem # # INLINE cmaximum # # INLINE cminimum # {-# INLINE csum #-} # INLINE cproduct # cfold = F.fold cfoldMap = F.foldMap cfoldr = F.foldr cfoldr' = F.foldr' cfoldl = F.foldl cfoldl' = F.foldl' cfoldr1 = F.foldr1 cfoldl1 = F.foldl1 ctoList = F.toList cnull = F.null clength = F.length celem = F.elem cmaximum = F.maximum cminimum = F.minimum csum = F.sum cproduct = F.product instance CFoldable Semigroup.First where # INLINE cfold # # INLINE cfoldMap # # INLINE cfoldr # # INLINE cfoldr ' # {-# INLINE cfoldl #-} {-# INLINE cfoldl' #-} # INLINE cfoldr1 # {-# INLINE cfoldl1 #-} {-# INLINE ctoList #-} # INLINE cnull # # INLINE clength # # INLINE celem # # INLINE cmaximum # # INLINE cminimum # {-# INLINE csum #-} # INLINE cproduct # cfold = F.fold cfoldMap = F.foldMap cfoldr = F.foldr cfoldr' = F.foldr' cfoldl = F.foldl cfoldl' = F.foldl' cfoldr1 = F.foldr1 cfoldl1 = F.foldl1 ctoList = F.toList cnull = F.null clength = F.length celem = F.elem cmaximum = F.maximum cminimum = F.minimum csum = F.sum cproduct = F.product instance CFoldable Semigroup.Last where # INLINE cfold # # INLINE cfoldMap # # INLINE cfoldr # # INLINE cfoldr ' # {-# INLINE cfoldl #-} {-# INLINE cfoldl' #-} # INLINE cfoldr1 # {-# INLINE cfoldl1 #-} {-# INLINE ctoList #-} # INLINE cnull # # INLINE clength # # INLINE celem # # INLINE cmaximum # # INLINE cminimum # {-# INLINE csum #-} # INLINE cproduct # cfold = F.fold cfoldMap = F.foldMap cfoldr = F.foldr cfoldr' = F.foldr' cfoldl = F.foldl cfoldl' = F.foldl' cfoldr1 = F.foldr1 cfoldl1 = F.foldl1 ctoList = F.toList cnull = F.null clength = F.length celem = F.elem cmaximum = F.maximum cminimum = F.minimum csum = F.sum cproduct = F.product instance CFoldable Semigroup.Dual where # INLINE cfold # # INLINE cfoldMap # # INLINE cfoldr # # INLINE cfoldr ' # {-# INLINE cfoldl #-} {-# INLINE cfoldl' #-} # INLINE cfoldr1 # {-# INLINE cfoldl1 #-} {-# INLINE ctoList #-} # INLINE cnull # # INLINE clength # # INLINE celem # # INLINE cmaximum # # INLINE cminimum # {-# INLINE csum #-} # INLINE cproduct # cfold = F.fold cfoldMap = F.foldMap cfoldr = F.foldr cfoldr' = F.foldr' cfoldl = F.foldl cfoldl' = F.foldl' cfoldr1 = F.foldr1 cfoldl1 = F.foldl1 ctoList = F.toList cnull = F.null clength = F.length celem = F.elem cmaximum = F.maximum cminimum = F.minimum csum = F.sum cproduct = F.product instance CFoldable Semigroup.Sum where # INLINE cfold # # INLINE cfoldMap # # INLINE cfoldr # # INLINE cfoldr ' # {-# INLINE cfoldl #-} {-# INLINE cfoldl' #-} # INLINE cfoldr1 # {-# INLINE cfoldl1 #-} {-# INLINE ctoList #-} # INLINE cnull # # INLINE clength # # INLINE celem # # INLINE cmaximum # # INLINE cminimum # {-# INLINE csum #-} # INLINE cproduct # cfold = F.fold cfoldMap = F.foldMap cfoldr = F.foldr cfoldr' = F.foldr' cfoldl = F.foldl cfoldl' = F.foldl' cfoldr1 = F.foldr1 cfoldl1 = F.foldl1 ctoList = F.toList cnull = F.null clength = F.length celem = F.elem cmaximum = F.maximum cminimum = F.minimum csum = F.sum cproduct = F.product instance CFoldable Semigroup.Product where # INLINE cfold # # INLINE cfoldMap # # INLINE cfoldr # # INLINE cfoldr ' # {-# INLINE cfoldl #-} {-# INLINE cfoldl' #-} # INLINE cfoldr1 # {-# INLINE cfoldl1 #-} {-# INLINE ctoList #-} # INLINE cnull # # INLINE clength # # INLINE celem # # INLINE cmaximum # # INLINE cminimum # {-# INLINE csum #-} # INLINE cproduct # cfold = F.fold cfoldMap = F.foldMap cfoldr = F.foldr cfoldr' = F.foldr' cfoldl = F.foldl cfoldl' = F.foldl' cfoldr1 = F.foldr1 cfoldl1 = F.foldl1 ctoList = F.toList cnull = F.null clength = F.length celem = F.elem cmaximum = F.maximum cminimum = F.minimum csum = F.sum cproduct = F.product #if MIN_VERSION_base(4,12,0) instance CFoldable f => CFoldable (Monoid.Ap f) where # INLINE cfold # # INLINE cfoldMap # # INLINE cfoldr # # INLINE cfoldr ' # {-# INLINE cfoldl #-} {-# INLINE cfoldl' #-} # INLINE cfoldr1 # {-# INLINE cfoldl1 #-} {-# INLINE ctoList #-} # INLINE cnull # # INLINE clength # # INLINE celem # # INLINE cmaximum # # INLINE cminimum # {-# INLINE csum #-} # INLINE cproduct # cfold :: forall a. (Monoid a, Constraints (Monoid.Ap f) a) => Monoid.Ap f a -> a cfold = coerce (cfold :: f a -> a) cfoldMap :: forall a b. (Monoid b, Constraints (Monoid.Ap f) a) => (a -> b) -> Monoid.Ap f a -> b cfoldMap = coerce (cfoldMap :: (a -> b) -> f a -> b) cfoldr :: forall a b. Constraints (Monoid.Ap f) a => (a -> b -> b) -> b -> Monoid.Ap f a -> b cfoldr = coerce (cfoldr :: (a -> b -> b) -> b -> f a -> b) cfoldr' :: forall a b. Constraints (Monoid.Ap f) a => (a -> b -> b) -> b -> Monoid.Ap f a -> b cfoldr' = coerce (cfoldr' :: (a -> b -> b) -> b -> f a -> b) cfoldl :: forall a b. Constraints (Monoid.Ap f) a => (b -> a -> b) -> b -> Monoid.Ap f a -> b cfoldl = coerce (cfoldl :: (b -> a -> b) -> b -> f a -> b) cfoldl' :: forall a b. Constraints (Monoid.Ap f) a => (b -> a -> b) -> b -> Monoid.Ap f a -> b cfoldl' = coerce (cfoldl' :: (b -> a -> b) -> b -> f a -> b) cfoldr1 :: forall a. Constraints (Monoid.Ap f) a => (a -> a -> a) -> Monoid.Ap f a -> a cfoldr1 = coerce (cfoldr1 :: (a -> a -> a) -> f a -> a) cfoldl1 :: forall a. Constraints (Monoid.Ap f) a => (a -> a -> a) -> Monoid.Ap f a -> a cfoldl1 = coerce (cfoldl1 :: (a -> a -> a) -> f a -> a) ctoList :: forall a. Constraints (Monoid.Ap f) a => Monoid.Ap f a -> [a] ctoList = coerce (ctoList :: f a -> [a]) cnull :: forall a. Constraints (Monoid.Ap f) a => Monoid.Ap f a -> Bool cnull = coerce (cnull :: f a -> Bool) clength :: forall a. Constraints (Monoid.Ap f) a => Monoid.Ap f a -> Int clength = coerce (clength :: f a -> Int) celem :: forall a. (Eq a, Constraints (Monoid.Ap f) a) => a -> Monoid.Ap f a -> Bool celem = coerce (celem :: a -> f a -> Bool) cmaximum :: forall a. (Ord a, Constraints (Monoid.Ap f) a) => Monoid.Ap f a -> a cmaximum = coerce (cmaximum :: f a -> a) cminimum :: forall a. (Ord a, Constraints (Monoid.Ap f) a) => Monoid.Ap f a -> a cminimum = coerce (cminimum :: f a -> a) csum :: forall a. (Num a, Constraints (Monoid.Ap f) a) => Monoid.Ap f a -> a csum = coerce (csum :: f a -> a) cproduct :: forall a. (Num a, Constraints (Monoid.Ap f) a) => Monoid.Ap f a -> a cproduct = coerce (cproduct :: f a -> a) #endif instance CFoldable f => CFoldable (Monoid.Alt f) where # INLINE cfold # # INLINE cfoldMap # # INLINE cfoldr # # INLINE cfoldr ' # {-# INLINE cfoldl #-} {-# INLINE cfoldl' #-} # INLINE cfoldr1 # {-# INLINE cfoldl1 #-} {-# INLINE ctoList #-} # INLINE cnull # # INLINE clength # # INLINE celem # # INLINE cmaximum # # INLINE cminimum # {-# INLINE csum #-} # INLINE cproduct # cfold :: forall a. (Monoid a, Constraints (Monoid.Alt f) a) => Monoid.Alt f a -> a cfold = coerce (cfold :: f a -> a) cfoldMap :: forall a b. (Monoid b, Constraints (Monoid.Alt f) a) => (a -> b) -> Monoid.Alt f a -> b cfoldMap = coerce (cfoldMap :: (a -> b) -> f a -> b) cfoldr :: forall a b. Constraints (Monoid.Alt f) a => (a -> b -> b) -> b -> Monoid.Alt f a -> b cfoldr = coerce (cfoldr :: (a -> b -> b) -> b -> f a -> b) cfoldr' :: forall a b. Constraints (Monoid.Alt f) a => (a -> b -> b) -> b -> Monoid.Alt f a -> b cfoldr' = coerce (cfoldr' :: (a -> b -> b) -> b -> f a -> b) cfoldl :: forall a b. Constraints (Monoid.Alt f) a => (b -> a -> b) -> b -> Monoid.Alt f a -> b cfoldl = coerce (cfoldl :: (b -> a -> b) -> b -> f a -> b) cfoldl' :: forall a b. Constraints (Monoid.Alt f) a => (b -> a -> b) -> b -> Monoid.Alt f a -> b cfoldl' = coerce (cfoldl' :: (b -> a -> b) -> b -> f a -> b) cfoldr1 :: forall a. Constraints (Monoid.Alt f) a => (a -> a -> a) -> Monoid.Alt f a -> a cfoldr1 = coerce (cfoldr1 :: (a -> a -> a) -> f a -> a) cfoldl1 :: forall a. Constraints (Monoid.Alt f) a => (a -> a -> a) -> Monoid.Alt f a -> a cfoldl1 = coerce (cfoldl1 :: (a -> a -> a) -> f a -> a) ctoList :: forall a. Constraints (Monoid.Alt f) a => Monoid.Alt f a -> [a] ctoList = coerce (ctoList :: f a -> [a]) cnull :: forall a. Constraints (Monoid.Alt f) a => Monoid.Alt f a -> Bool cnull = coerce (cnull :: f a -> Bool) clength :: forall a. Constraints (Monoid.Alt f) a => Monoid.Alt f a -> Int clength = coerce (clength :: f a -> Int) celem :: forall a. (Eq a, Constraints (Monoid.Alt f) a) => a -> Monoid.Alt f a -> Bool celem = coerce (celem :: a -> f a -> Bool) cmaximum :: forall a. (Ord a, Constraints (Monoid.Alt f) a) => Monoid.Alt f a -> a cmaximum = coerce (cmaximum :: f a -> a) cminimum :: forall a. (Ord a, Constraints (Monoid.Alt f) a) => Monoid.Alt f a -> a cminimum = coerce (cminimum :: f a -> a) csum :: forall a. (Num a, Constraints (Monoid.Alt f) a) => Monoid.Alt f a -> a csum = coerce (csum :: f a -> a) cproduct :: forall a. (Num a, Constraints (Monoid.Alt f) a) => Monoid.Alt f a -> a cproduct = coerce (cproduct :: f a -> a) instance (CFoldable f, CFoldable g) => CFoldable (Compose f g) where # INLINABLE cfold # # INLINABLE cfoldMap # # INLINABLE cfoldr # cfold = cfoldMap cfold . getCompose cfoldMap f = cfoldMap (cfoldMap f) . getCompose cfoldr f z = cfoldr (\ga acc -> cfoldr f acc ga) z . getCompose instance (CFoldable f, CFoldable g) => CFoldable (Product.Product f g) where # INLINABLE cfold # # INLINABLE cfoldMap # # INLINABLE cfoldr # # INLINABLE cfoldr ' # # INLINABLE cfoldl # # INLINABLE cfoldl ' # {-# INLINABLE cfoldr1 #-} {-# INLINABLE cfoldl1 #-} cfold (Pair x y) = cfold x <> cfold y cfoldMap f (Pair x y) = cfoldMap f x <> cfoldMap f y cfoldr f z (Pair x y) = cfoldr f (cfoldr f z y) x cfoldr' f z (Pair x y) = cfoldr' f y' x where !y' = cfoldr' f z y cfoldl f z (Pair x y) = cfoldl f (cfoldl f z y) x cfoldl' f z (Pair x y) = cfoldl' f x' x where !x' = cfoldl' f z y cfoldr1 f (Pair x y) = cfoldl1 f x `f` cfoldl1 f y cfoldl1 f (Pair x y) = cfoldr1 f y `f` cfoldr1 f x instance (CFoldable f, CFoldable g) => CFoldable (Sum.Sum f g) where # INLINE cfold # # INLINE cfoldMap # # INLINE cfoldr # # INLINE cfoldr ' # {-# INLINE cfoldl #-} {-# INLINE cfoldl' #-} # INLINE cfoldr1 # {-# INLINE cfoldl1 #-} cfold (InL x) = cfold x cfold (InR y) = cfold y cfoldMap f (InL x) = cfoldMap f x cfoldMap f (InR y) = cfoldMap f y cfoldr f z (InL x) = cfoldr f z x cfoldr f z (InR y) = cfoldr f z y cfoldr' f z (InL x) = cfoldr' f z x cfoldr' f z (InR y) = cfoldr' f z y cfoldl f z (InL x) = cfoldl f z x cfoldl f z (InR y) = cfoldl f z y cfoldl' f z (InL x) = cfoldl' f z x cfoldl' f z (InR y) = cfoldl' f z y cfoldr1 f (InL x) = cfoldr1 f x cfoldr1 f (InR y) = cfoldr1 f y cfoldl1 f (InL x) = cfoldl1 f x cfoldl1 f (InR y) = cfoldl1 f y
null
https://raw.githubusercontent.com/sergv/constrained/7a07b686e0f5fc039dd75f7358584487372ab3e2/constrained/src/Data/Foldable/Constrained.hs
haskell
-------------------------------------------------------------------------- | Module : Data.Foldable.Constrained Maintainer : sergey@debian -------------------------------------------------------------------------- # LANGUAGE BangPatterns # | Like 'Data.Foldable.Foldable' but allows elements to have constraints on them. Laws are the same. | Combine the elements of a structure using a monoid. | Map each element of the structure to a monoid, and combine the results. | Right-associative fold of a structure. starting value (typically the right-identity of the operator), and a list, reduces the list using the binary operator, from right to left: > cfoldr f z [x1, x2, ..., xn] == x1 `f` (x2 `f` ... (xn `f` z)...) Note that, since the head of the resulting expression is produced by 'cfoldr' can produce a terminating expression from an infinite list. For a general 'CFoldable' structure this should be semantically identical to, | Right-associative fold of a structure, but with strict application of the operator. | Left-associative fold of a structure. In the case of lists, 'cfoldl', when applied to a binary operator, a starting value (typically the left-identity of the operator), and a list, reduces the list using the binary operator, from left to right: Note that to produce the outermost application of the operator the entire input list must be traversed. This means that 'cfoldl'' will diverge if given an infinite list. Also note that if you want an efficient left-fold, you probably want to use 'cfoldl'' instead of 'cfoldl'. The reason for this is that latter does before applying them to the operator (e.g. to @(`f` x2)@). This results in a thunk chain @O(n)@ elements long, which then must be evaluated from the outside-in. For a general 'CFoldable' structure this should be semantically identical to, There's no point mucking around with coercions here, because flip forces us to build a new function anyway. | Left-associative fold of a structure but with strict application of the operator. This ensures that each step of the fold is forced to weak head normal form before being applied, avoiding the collection of thunks that would otherwise occur. This is often what you want to strictly reduce a finite For a general 'CFoldable' structure this should be semantically identical to, | A variant of 'cfoldr' that has no base case, and thus may only be applied to non-empty structures. | A variant of 'cfoldl' that has no base case, and thus may only be applied to non-empty structures. @'cfoldl1' f = 'List.foldl1' f . 'ctoList'@ | List of elements of a structure, from left to right. | Test whether the structure is empty. The default implementation is optimized for structures that are similar to cons-lists, because there is no general way to do better. | Returns the size/length of a finite structure as an 'Int'. The default implementation is optimized for structures that are similar to cons-lists, because there is no general way to do better. | Does the element occur in the structure? | The largest element of a non-empty structure. | The least element of a non-empty structure. | The 'csum' function computes the sum of the numbers of a structure. | The 'cproduct' function computes the product of the numbers of a structure. | Monadic fold over the elements of a structure, associating to the right, i.e. from right to left. | Monadic fold over the elements of a structure, associating to the left, i.e. from left to right. | Map each element of a structure to an action, evaluate these actions from left to right, and ignore the results. For a version that doesn't ignore the results see 'Data.Traversable.Constrained.cfor'. # INLINE cfor_ # | Map each element of a structure to a monadic action, evaluate these actions from left to right, and ignore the results. For a version that doesn't ignore the results see 'Data.Traversable.mapM'. | 'cforM_' is 'cmapM_' with its arguments flipped. For a version that doesn't ignore the results see 'Data.Traversable.forM'. # INLINE cforM_ # | Evaluate each action in the structure from left to right, and ignore the results. For a version that doesn't ignore the results see 'Data.Traversable.sequenceA'. | Evaluate each monadic action in the structure from left to right, and ignore the results. For a version that doesn't ignore the Just "Hello" | The concatenation of all the elements of a container of lists. | Map a function over all the elements of a container and concatenate the resulting lists. These use foldr rather than cfoldMap to avoid repeated concatenation. result to be 'True', the container must be finite; 'False', however, results from a 'False' value finitely far from the left end. result to be 'False', the container must be finite; 'True', however, results from a 'True' value finitely far from the left end. | Determines whether any element of the structure satisfies the predicate. | Determines whether all elements of the structure satisfy the predicate. | The largest element of a non-empty structure with respect to the given comparison function. | The least element of a non-empty structure with respect to the given comparison function. | 'cnotElem' is the negation of 'celem'. | The 'cfind' function takes a predicate and a structure and returns the leftmost element of the structure matching the predicate, or 'Nothing' if there is no such element. # INLINE cfoldl # # INLINE cfoldl' # # INLINE cfoldl1 # # INLINE ctoList # # INLINE csum # # INLINE cfoldl # # INLINE cfoldl' # # INLINE cfoldl1 # # INLINE ctoList # # INLINE csum # # INLINE cfoldl # # INLINE cfoldl' # # INLINE cfoldl1 # # INLINE ctoList # # INLINE csum # # INLINE cfoldl # # INLINE cfoldl' # # INLINE cfoldl1 # # INLINE ctoList # # INLINE csum # # INLINE cfoldl # # INLINE cfoldl' # # INLINE cfoldl1 # # INLINE ctoList # # INLINE csum # # INLINE cfoldl # # INLINE cfoldl' # # INLINE cfoldl1 # # INLINE ctoList # # INLINE csum # # INLINE cfoldl # # INLINE cfoldl' # # INLINE cfoldl1 # # INLINE ctoList # # INLINE csum # # INLINE cfoldl # # INLINE cfoldl' # # INLINE cfoldl1 # # INLINE ctoList # # INLINE csum # # INLINE cfoldl # # INLINE cfoldl' # # INLINE cfoldl1 # # INLINE ctoList # # INLINE csum # # INLINE cfoldl # # INLINE cfoldl' # # INLINE cfoldl1 # # INLINE ctoList # # INLINE csum # # INLINE cfoldl # # INLINE cfoldl' # # INLINE cfoldl1 # # INLINE ctoList # # INLINE csum # # INLINE cfoldl # # INLINE cfoldl' # # INLINE cfoldl1 # # INLINE ctoList # # INLINE csum # # INLINE cfoldl # # INLINE cfoldl' # # INLINE cfoldl1 # # INLINE ctoList # # INLINE csum # # INLINE cfoldl # # INLINE cfoldl' # # INLINE cfoldl1 # # INLINE ctoList # # INLINE csum # # INLINE cfoldl # # INLINE cfoldl' # # INLINE cfoldl1 # # INLINE ctoList # # INLINE csum # # INLINE cfoldl # # INLINE cfoldl' # # INLINE cfoldl1 # # INLINE ctoList # # INLINE csum # # INLINE cfoldl # # INLINE cfoldl' # # INLINE cfoldl1 # # INLINE ctoList # # INLINE csum # # INLINABLE cfoldr1 # # INLINABLE cfoldl1 # # INLINE cfoldl # # INLINE cfoldl' # # INLINE cfoldl1 #
Copyright : ( c ) 2019 License : BSD-2 ( see LICENSE ) # LANGUAGE CPP # # LANGUAGE InstanceSigs # # LANGUAGE ScopedTypeVariables # # LANGUAGE ScopedTypeVariables # # LANGUAGE TypeFamilies # module Data.Foldable.Constrained ( CFoldable(..) , cfoldrM , cfoldlM , ctraverse_ , cfor_ , cmapM_ , cforM_ , csequenceA_ , csequence_ , casum , cmsum , cconcat , cconcatMap , cand , cor , cany , call , cmaximumBy , cminimumBy , cnotElem , cfind , module Data.Constrained ) where import Prelude (Bool(..), id, (.), Int, Eq(..), Num(..), ($), ($!), flip, errorWithoutStackTrace, not) import Control.Applicative import Control.Monad hiding (mapM_) import Data.Coerce import Data.Either import qualified Data.Foldable as F import Data.Functor.Compose (Compose(..)) import Data.Functor.Identity (Identity(..)) import Data.Functor.Product as Product import Data.Functor.Sum as Sum import Data.List.NonEmpty (NonEmpty(..)) import Data.Maybe import Data.Monoid import qualified Data.Monoid as Monoid import Data.Ord import Data.Semigroup (Max(..), Min(..), Option(..)) import qualified Data.Semigroup as Semigroup import GHC.Base (build) import Data.Constrained (Constrained(..)) class Constrained f => CFoldable f where # MINIMAL cfoldMap | cfoldr # cfold :: (Monoid m, Constraints f m) => f m -> m cfold = cfoldMap id # INLINABLE cfold # cfoldMap :: (Monoid m, Constraints f a) => (a -> m) -> f a -> m cfoldMap f = cfoldr (mappend . f) mempty This INLINE allows more list functions to fuse . See Trac # 9848 . # INLINE cfoldMap # In the case of lists , ' cfoldr ' , when applied to a binary operator , a an application of the operator to the first element of the list , @cfoldr f z = ' List.foldr ' f z . ' ctoList'@ cfoldr :: Constraints f a => (a -> b -> b) -> b -> f a -> b cfoldr f z t = appEndo (cfoldMap (Endo . f) t) z cfoldr' :: Constraints f a => (a -> b -> b) -> b -> f a -> b cfoldr' f z0 xs = cfoldl f' id xs z0 where f' k x z = k $! f x z > cfoldl f z [ x1 , x2 , ... , xn ] = = ( ... ( ( z ` f ` x1 ) ` f ` x2 ) ` f ` ... ) ` f ` xn not force the " inner " results ( e.g. ` f ` x1@ in the above example ) @cfoldl f z = ' List.foldl ' f z . ' ctoList'@ cfoldl :: Constraints f a => (b -> a -> b) -> b -> f a -> b cfoldl f z t = appEndo (getDual (cfoldMap (Dual . Endo . flip f) t)) z list to a single , monolithic result ( e.g. ' clength ' ) . @cfoldl f z = ' List.foldl '' f z . ' ctoList'@ cfoldl' :: Constraints f a => (b -> a -> b) -> b -> f a -> b cfoldl' f z0 xs = cfoldr f' id xs z0 where f' x k z = k $! f z x @'cfoldr1 ' f = f . ' ctoList'@ cfoldr1 :: Constraints f a => (a -> a -> a) -> f a -> a cfoldr1 f xs = fromMaybe (errorWithoutStackTrace "foldr1: empty structure") (cfoldr mf Nothing xs) where mf x m = Just $ case m of Nothing -> x Just y -> f x y cfoldl1 :: Constraints f a => (a -> a -> a) -> f a -> a cfoldl1 f xs = fromMaybe (errorWithoutStackTrace "foldl1: empty structure") (cfoldl mf Nothing xs) where mf m y = Just $ case m of Nothing -> y Just x -> f x y ctoList :: Constraints f a => f a -> [a] ctoList t = build (\ c n -> cfoldr c n t) # INLINE ctoList # cnull :: Constraints f a => f a -> Bool cnull = cfoldr (\_ _ -> False) True # INLINE cnull # clength :: Constraints f a => f a -> Int clength = cfoldl' (\c _ -> c + 1) 0 celem :: (Eq a, Constraints f a) => a -> f a -> Bool celem = cany . (==) # INLINE celem # cmaximum :: forall a. (Ord a, Constraints f a) => f a -> a cmaximum = maybe (errorWithoutStackTrace "maximum: empty structure") getMax . getOption . cfoldMap (Option . Just . Max) # INLINABLE cmaximum # cminimum :: forall a. (Ord a, Constraints f a) => f a -> a cminimum = maybe (errorWithoutStackTrace "maximum: empty structure") getMin . getOption . cfoldMap (Option . Just . Min) # INLINABLE cminimum # csum :: (Num a, Constraints f a) => f a -> a csum = getSum . cfoldMap Sum # INLINABLE csum # cproduct :: (Num a, Constraints f a) => f a -> a cproduct = getProduct . cfoldMap Product # INLINABLE cproduct # cfoldrM :: (CFoldable f, Monad m, Constraints f a) => (a -> b -> m b) -> b -> f a -> m b cfoldrM f z0 xs = cfoldl f' return xs z0 where f' k x z = f x z >>= k cfoldlM :: (CFoldable f, Monad m, Constraints f a) => (b -> a -> m b) -> b -> f a -> m b cfoldlM f z0 xs = cfoldr f' return xs z0 where f' x k z = f z x >>= k that does n't ignore the results see ' ' . ctraverse_ :: (CFoldable f, Applicative f, Constraints f a) => (a -> f b) -> f a -> f () ctraverse_ f = cfoldr ((*>) . f) (pure ()) | ' cfor _ ' is ' _ ' with its arguments flipped . For a version > > > for _ [ 1 .. 4 ] print 1 2 3 4 cfor_ :: (CFoldable f, Applicative f, Constraints f a) => f a -> (a -> f b) -> f () cfor_ = flip ctraverse_ cmapM_ :: (CFoldable f, Monad m, Constraints f a) => (a -> m b) -> f a -> m () cmapM_ f = cfoldr ((>>) . f) (return ()) cforM_ :: (CFoldable f, Monad m, Constraints f a) => f a -> (a -> m b) -> m () cforM_ = flip cmapM_ csequenceA_ :: (CFoldable f, Applicative m, Constraints f (m a)) => f (m a) -> m () csequenceA_ = cfoldr (*>) (pure ()) results see ' ' . csequence_ :: (CFoldable f, Monad m, Constraints f a, Constraints f (m a)) => f (m a) -> m () csequence_ = cfoldr (>>) (return ()) | The sum of a collection of actions , generalizing ' Data.Foldable.concat ' . asum [ Just " Hello " , Nothing , Just " World " ] casum :: (CFoldable f, Alternative m, Constraints f (m a)) => f (m a) -> m a # INLINE casum # casum = cfoldr (<|>) empty | The sum of a collection of actions , generalizing ' Data.Foldable.concat ' . cmsum :: (CFoldable f, MonadPlus m, Constraints f (m a)) => f (m a) -> m a # INLINE cmsum # cmsum = casum cconcat :: (CFoldable f, Constraints f [a]) => f [a] -> [a] cconcat xs = build (\c n -> cfoldr (\x y -> cfoldr c y x) n xs) # INLINE cconcat # cconcatMap :: (CFoldable f, Constraints f a) => (a -> [b]) -> f a -> [b] cconcatMap f xs = build (\c n -> cfoldr (\x b -> cfoldr c b (f x)) n xs) # INLINE cconcatMap # | ' cand ' returns the conjunction of a container of Bools . For the cand :: (CFoldable f, Constraints f Bool) => f Bool -> Bool cand = getAll . cfoldMap All | ' cor ' returns the disjunction of a container of Bools . For the cor :: (CFoldable f, Constraints f Bool) => f Bool -> Bool cor = getAny . cfoldMap Any cany :: (CFoldable f, Constraints f a) => (a -> Bool) -> f a -> Bool cany p = getAny . cfoldMap (Any . p) call :: (CFoldable f, Constraints f a) => (a -> Bool) -> f a -> Bool call p = getAll . cfoldMap (All . p) See Note [ / minimumBy space usage ] cmaximumBy :: (CFoldable f, Constraints f a) => (a -> a -> Ordering) -> f a -> a cmaximumBy cmp = cfoldl1 max' where max' x y = case cmp x y of GT -> x _ -> y See Note [ / minimumBy space usage ] cminimumBy :: (CFoldable f, Constraints f a) => (a -> a -> Ordering) -> f a -> a cminimumBy cmp = cfoldl1 min' where min' x y = case cmp x y of GT -> y _ -> x cnotElem :: (CFoldable f, Eq a, Constraints f a) => a -> f a -> Bool cnotElem x = not . celem x cfind :: (CFoldable f, Constraints f a) => (a -> Bool) -> f a -> Maybe a cfind p = getFirst . cfoldMap (\ x -> First (if p x then Just x else Nothing)) Note [ / minimumBy space usage ] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When the type signatures of and minimumBy were generalized to work over any Foldable instance ( instead of just lists ) , they were defined using foldr1 . This was problematic for space usage , as the semantics of and minimumBy essentially require that they examine every element of the data structure . Using to examine every element results in space usage proportional to the size of the data structure . For the common case of lists , this could be particularly bad ( see Trac # 10830 ) . For the common case of lists , switching the implementations of and minimumBy to foldl1 solves the issue , as GHC 's strictness analysis can then make these functions only use O(1 ) stack space . It is perhaps not the optimal way to fix this problem , as there are other conceivable data structures ( besides lists ) which might benefit from specialized implementations for and minimumBy ( see #comment:26 for a further discussion ) . But using foldl1 is at least always better than using , so GHC has chosen to adopt that approach for now . Note [maximumBy/minimumBy space usage] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When the type signatures of maximumBy and minimumBy were generalized to work over any Foldable instance (instead of just lists), they were defined using foldr1. This was problematic for space usage, as the semantics of maximumBy and minimumBy essentially require that they examine every element of the data structure. Using foldr1 to examine every element results in space usage proportional to the size of the data structure. For the common case of lists, this could be particularly bad (see Trac #10830). For the common case of lists, switching the implementations of maximumBy and minimumBy to foldl1 solves the issue, as GHC's strictness analysis can then make these functions only use O(1) stack space. It is perhaps not the optimal way to fix this problem, as there are other conceivable data structures (besides lists) which might benefit from specialized implementations for maximumBy and minimumBy (see #comment:26 for a further discussion). But using foldl1 is at least always better than using foldr1, so GHC has chosen to adopt that approach for now. -} instance CFoldable [] where # INLINE cfold # # INLINE cfoldMap # # INLINE cfoldr # # INLINE cfoldr ' # # INLINE cfoldr1 # # INLINE cnull # # INLINE clength # # INLINE celem # # INLINE cmaximum # # INLINE cminimum # # INLINE cproduct # cfold = F.fold cfoldMap = F.foldMap cfoldr = F.foldr cfoldr' = F.foldr' cfoldl = F.foldl cfoldl' = F.foldl' cfoldr1 = F.foldr1 cfoldl1 = F.foldl1 ctoList = F.toList cnull = F.null clength = F.length celem = F.elem cmaximum = F.maximum cminimum = F.minimum csum = F.sum cproduct = F.product instance CFoldable NonEmpty where # INLINE cfold # # INLINE cfoldMap # # INLINE cfoldr # # INLINE cfoldr ' # # INLINE cfoldr1 # # INLINE cnull # # INLINE clength # # INLINE celem # # INLINE cmaximum # # INLINE cminimum # # INLINE cproduct # cfold = F.fold cfoldMap = F.foldMap cfoldr = F.foldr cfoldr' = F.foldr' cfoldl = F.foldl cfoldl' = F.foldl' cfoldr1 = F.foldr1 cfoldl1 = F.foldl1 ctoList = F.toList cnull = F.null clength = F.length celem = F.elem cmaximum = F.maximum cminimum = F.minimum csum = F.sum cproduct = F.product instance CFoldable Identity where # INLINE cfold # # INLINE cfoldMap # # INLINE cfoldr # # INLINE cfoldr ' # # INLINE cfoldr1 # # INLINE cnull # # INLINE clength # # INLINE celem # # INLINE cmaximum # # INLINE cminimum # # INLINE cproduct # cfold = F.fold cfoldMap = F.foldMap cfoldr = F.foldr cfoldr' = F.foldr' cfoldl = F.foldl cfoldl' = F.foldl' cfoldr1 = F.foldr1 cfoldl1 = F.foldl1 ctoList = F.toList cnull = F.null clength = F.length celem = F.elem cmaximum = F.maximum cminimum = F.minimum csum = F.sum cproduct = F.product instance CFoldable ((,) a) where # INLINE cfold # # INLINE cfoldMap # # INLINE cfoldr # # INLINE cfoldr ' # # INLINE cfoldr1 # # INLINE cnull # # INLINE clength # # INLINE celem # # INLINE cmaximum # # INLINE cminimum # # INLINE cproduct # cfold = F.fold cfoldMap = F.foldMap cfoldr = F.foldr cfoldr' = F.foldr' cfoldl = F.foldl cfoldl' = F.foldl' cfoldr1 = F.foldr1 cfoldl1 = F.foldl1 ctoList = F.toList cnull = F.null clength = F.length celem = F.elem cmaximum = F.maximum cminimum = F.minimum csum = F.sum cproduct = F.product instance CFoldable Maybe where # INLINE cfold # # INLINE cfoldMap # # INLINE cfoldr # # INLINE cfoldr ' # # INLINE cfoldr1 # # INLINE cnull # # INLINE clength # # INLINE celem # # INLINE cmaximum # # INLINE cminimum # # INLINE cproduct # cfold = F.fold cfoldMap = F.foldMap cfoldr = F.foldr cfoldr' = F.foldr' cfoldl = F.foldl cfoldl' = F.foldl' cfoldr1 = F.foldr1 cfoldl1 = F.foldl1 ctoList = F.toList cnull = F.null clength = F.length celem = F.elem cmaximum = F.maximum cminimum = F.minimum csum = F.sum cproduct = F.product instance CFoldable (Either a) where # INLINE cfold # # INLINE cfoldMap # # INLINE cfoldr # # INLINE cfoldr ' # # INLINE cfoldr1 # # INLINE cnull # # INLINE clength # # INLINE celem # # INLINE cmaximum # # INLINE cminimum # # INLINE cproduct # cfold = F.fold cfoldMap = F.foldMap cfoldr = F.foldr cfoldr' = F.foldr' cfoldl = F.foldl cfoldl' = F.foldl' cfoldr1 = F.foldr1 cfoldl1 = F.foldl1 ctoList = F.toList cnull = F.null clength = F.length celem = F.elem cmaximum = F.maximum cminimum = F.minimum csum = F.sum cproduct = F.product instance CFoldable (Const a) where # INLINE cfold # # INLINE cfoldMap # # INLINE cfoldr # # INLINE cfoldr ' # # INLINE cfoldr1 # # INLINE cnull # # INLINE clength # # INLINE celem # # INLINE cmaximum # # INLINE cminimum # # INLINE cproduct # cfold = F.fold cfoldMap = F.foldMap cfoldr = F.foldr cfoldr' = F.foldr' cfoldl = F.foldl cfoldl' = F.foldl' cfoldr1 = F.foldr1 cfoldl1 = F.foldl1 ctoList = F.toList cnull = F.null clength = F.length celem = F.elem cmaximum = F.maximum cminimum = F.minimum csum = F.sum cproduct = F.product instance CFoldable ZipList where # INLINE cfold # # INLINE cfoldMap # # INLINE cfoldr # # INLINE cfoldr ' # # INLINE cfoldr1 # # INLINE cnull # # INLINE clength # # INLINE celem # # INLINE cmaximum # # INLINE cminimum # # INLINE cproduct # cfold = F.fold cfoldMap = F.foldMap cfoldr = F.foldr cfoldr' = F.foldr' cfoldl = F.foldl cfoldl' = F.foldl' cfoldr1 = F.foldr1 cfoldl1 = F.foldl1 ctoList = F.toList cnull = F.null clength = F.length celem = F.elem cmaximum = F.maximum cminimum = F.minimum csum = F.sum cproduct = F.product instance CFoldable Semigroup.Min where # INLINE cfold # # INLINE cfoldMap # # INLINE cfoldr # # INLINE cfoldr ' # # INLINE cfoldr1 # # INLINE cnull # # INLINE clength # # INLINE celem # # INLINE cmaximum # # INLINE cminimum # # INLINE cproduct # cfold = F.fold cfoldMap = F.foldMap cfoldr = F.foldr cfoldr' = F.foldr' cfoldl = F.foldl cfoldl' = F.foldl' cfoldr1 = F.foldr1 cfoldl1 = F.foldl1 ctoList = F.toList cnull = F.null clength = F.length celem = F.elem cmaximum = F.maximum cminimum = F.minimum csum = F.sum cproduct = F.product instance CFoldable Semigroup.Max where # INLINE cfold # # INLINE cfoldMap # # INLINE cfoldr # # INLINE cfoldr ' # # INLINE cfoldr1 # # INLINE cnull # # INLINE clength # # INLINE celem # # INLINE cmaximum # # INLINE cminimum # # INLINE cproduct # cfold = F.fold cfoldMap = F.foldMap cfoldr = F.foldr cfoldr' = F.foldr' cfoldl = F.foldl cfoldl' = F.foldl' cfoldr1 = F.foldr1 cfoldl1 = F.foldl1 ctoList = F.toList cnull = F.null clength = F.length celem = F.elem cmaximum = F.maximum cminimum = F.minimum csum = F.sum cproduct = F.product instance CFoldable Semigroup.First where # INLINE cfold # # INLINE cfoldMap # # INLINE cfoldr # # INLINE cfoldr ' # # INLINE cfoldr1 # # INLINE cnull # # INLINE clength # # INLINE celem # # INLINE cmaximum # # INLINE cminimum # # INLINE cproduct # cfold = F.fold cfoldMap = F.foldMap cfoldr = F.foldr cfoldr' = F.foldr' cfoldl = F.foldl cfoldl' = F.foldl' cfoldr1 = F.foldr1 cfoldl1 = F.foldl1 ctoList = F.toList cnull = F.null clength = F.length celem = F.elem cmaximum = F.maximum cminimum = F.minimum csum = F.sum cproduct = F.product instance CFoldable Semigroup.Last where # INLINE cfold # # INLINE cfoldMap # # INLINE cfoldr # # INLINE cfoldr ' # # INLINE cfoldr1 # # INLINE cnull # # INLINE clength # # INLINE celem # # INLINE cmaximum # # INLINE cminimum # # INLINE cproduct # cfold = F.fold cfoldMap = F.foldMap cfoldr = F.foldr cfoldr' = F.foldr' cfoldl = F.foldl cfoldl' = F.foldl' cfoldr1 = F.foldr1 cfoldl1 = F.foldl1 ctoList = F.toList cnull = F.null clength = F.length celem = F.elem cmaximum = F.maximum cminimum = F.minimum csum = F.sum cproduct = F.product instance CFoldable Semigroup.Dual where # INLINE cfold # # INLINE cfoldMap # # INLINE cfoldr # # INLINE cfoldr ' # # INLINE cfoldr1 # # INLINE cnull # # INLINE clength # # INLINE celem # # INLINE cmaximum # # INLINE cminimum # # INLINE cproduct # cfold = F.fold cfoldMap = F.foldMap cfoldr = F.foldr cfoldr' = F.foldr' cfoldl = F.foldl cfoldl' = F.foldl' cfoldr1 = F.foldr1 cfoldl1 = F.foldl1 ctoList = F.toList cnull = F.null clength = F.length celem = F.elem cmaximum = F.maximum cminimum = F.minimum csum = F.sum cproduct = F.product instance CFoldable Semigroup.Sum where # INLINE cfold # # INLINE cfoldMap # # INLINE cfoldr # # INLINE cfoldr ' # # INLINE cfoldr1 # # INLINE cnull # # INLINE clength # # INLINE celem # # INLINE cmaximum # # INLINE cminimum # # INLINE cproduct # cfold = F.fold cfoldMap = F.foldMap cfoldr = F.foldr cfoldr' = F.foldr' cfoldl = F.foldl cfoldl' = F.foldl' cfoldr1 = F.foldr1 cfoldl1 = F.foldl1 ctoList = F.toList cnull = F.null clength = F.length celem = F.elem cmaximum = F.maximum cminimum = F.minimum csum = F.sum cproduct = F.product instance CFoldable Semigroup.Product where # INLINE cfold # # INLINE cfoldMap # # INLINE cfoldr # # INLINE cfoldr ' # # INLINE cfoldr1 # # INLINE cnull # # INLINE clength # # INLINE celem # # INLINE cmaximum # # INLINE cminimum # # INLINE cproduct # cfold = F.fold cfoldMap = F.foldMap cfoldr = F.foldr cfoldr' = F.foldr' cfoldl = F.foldl cfoldl' = F.foldl' cfoldr1 = F.foldr1 cfoldl1 = F.foldl1 ctoList = F.toList cnull = F.null clength = F.length celem = F.elem cmaximum = F.maximum cminimum = F.minimum csum = F.sum cproduct = F.product #if MIN_VERSION_base(4,12,0) instance CFoldable f => CFoldable (Monoid.Ap f) where # INLINE cfold # # INLINE cfoldMap # # INLINE cfoldr # # INLINE cfoldr ' # # INLINE cfoldr1 # # INLINE cnull # # INLINE clength # # INLINE celem # # INLINE cmaximum # # INLINE cminimum # # INLINE cproduct # cfold :: forall a. (Monoid a, Constraints (Monoid.Ap f) a) => Monoid.Ap f a -> a cfold = coerce (cfold :: f a -> a) cfoldMap :: forall a b. (Monoid b, Constraints (Monoid.Ap f) a) => (a -> b) -> Monoid.Ap f a -> b cfoldMap = coerce (cfoldMap :: (a -> b) -> f a -> b) cfoldr :: forall a b. Constraints (Monoid.Ap f) a => (a -> b -> b) -> b -> Monoid.Ap f a -> b cfoldr = coerce (cfoldr :: (a -> b -> b) -> b -> f a -> b) cfoldr' :: forall a b. Constraints (Monoid.Ap f) a => (a -> b -> b) -> b -> Monoid.Ap f a -> b cfoldr' = coerce (cfoldr' :: (a -> b -> b) -> b -> f a -> b) cfoldl :: forall a b. Constraints (Monoid.Ap f) a => (b -> a -> b) -> b -> Monoid.Ap f a -> b cfoldl = coerce (cfoldl :: (b -> a -> b) -> b -> f a -> b) cfoldl' :: forall a b. Constraints (Monoid.Ap f) a => (b -> a -> b) -> b -> Monoid.Ap f a -> b cfoldl' = coerce (cfoldl' :: (b -> a -> b) -> b -> f a -> b) cfoldr1 :: forall a. Constraints (Monoid.Ap f) a => (a -> a -> a) -> Monoid.Ap f a -> a cfoldr1 = coerce (cfoldr1 :: (a -> a -> a) -> f a -> a) cfoldl1 :: forall a. Constraints (Monoid.Ap f) a => (a -> a -> a) -> Monoid.Ap f a -> a cfoldl1 = coerce (cfoldl1 :: (a -> a -> a) -> f a -> a) ctoList :: forall a. Constraints (Monoid.Ap f) a => Monoid.Ap f a -> [a] ctoList = coerce (ctoList :: f a -> [a]) cnull :: forall a. Constraints (Monoid.Ap f) a => Monoid.Ap f a -> Bool cnull = coerce (cnull :: f a -> Bool) clength :: forall a. Constraints (Monoid.Ap f) a => Monoid.Ap f a -> Int clength = coerce (clength :: f a -> Int) celem :: forall a. (Eq a, Constraints (Monoid.Ap f) a) => a -> Monoid.Ap f a -> Bool celem = coerce (celem :: a -> f a -> Bool) cmaximum :: forall a. (Ord a, Constraints (Monoid.Ap f) a) => Monoid.Ap f a -> a cmaximum = coerce (cmaximum :: f a -> a) cminimum :: forall a. (Ord a, Constraints (Monoid.Ap f) a) => Monoid.Ap f a -> a cminimum = coerce (cminimum :: f a -> a) csum :: forall a. (Num a, Constraints (Monoid.Ap f) a) => Monoid.Ap f a -> a csum = coerce (csum :: f a -> a) cproduct :: forall a. (Num a, Constraints (Monoid.Ap f) a) => Monoid.Ap f a -> a cproduct = coerce (cproduct :: f a -> a) #endif instance CFoldable f => CFoldable (Monoid.Alt f) where # INLINE cfold # # INLINE cfoldMap # # INLINE cfoldr # # INLINE cfoldr ' # # INLINE cfoldr1 # # INLINE cnull # # INLINE clength # # INLINE celem # # INLINE cmaximum # # INLINE cminimum # # INLINE cproduct # cfold :: forall a. (Monoid a, Constraints (Monoid.Alt f) a) => Monoid.Alt f a -> a cfold = coerce (cfold :: f a -> a) cfoldMap :: forall a b. (Monoid b, Constraints (Monoid.Alt f) a) => (a -> b) -> Monoid.Alt f a -> b cfoldMap = coerce (cfoldMap :: (a -> b) -> f a -> b) cfoldr :: forall a b. Constraints (Monoid.Alt f) a => (a -> b -> b) -> b -> Monoid.Alt f a -> b cfoldr = coerce (cfoldr :: (a -> b -> b) -> b -> f a -> b) cfoldr' :: forall a b. Constraints (Monoid.Alt f) a => (a -> b -> b) -> b -> Monoid.Alt f a -> b cfoldr' = coerce (cfoldr' :: (a -> b -> b) -> b -> f a -> b) cfoldl :: forall a b. Constraints (Monoid.Alt f) a => (b -> a -> b) -> b -> Monoid.Alt f a -> b cfoldl = coerce (cfoldl :: (b -> a -> b) -> b -> f a -> b) cfoldl' :: forall a b. Constraints (Monoid.Alt f) a => (b -> a -> b) -> b -> Monoid.Alt f a -> b cfoldl' = coerce (cfoldl' :: (b -> a -> b) -> b -> f a -> b) cfoldr1 :: forall a. Constraints (Monoid.Alt f) a => (a -> a -> a) -> Monoid.Alt f a -> a cfoldr1 = coerce (cfoldr1 :: (a -> a -> a) -> f a -> a) cfoldl1 :: forall a. Constraints (Monoid.Alt f) a => (a -> a -> a) -> Monoid.Alt f a -> a cfoldl1 = coerce (cfoldl1 :: (a -> a -> a) -> f a -> a) ctoList :: forall a. Constraints (Monoid.Alt f) a => Monoid.Alt f a -> [a] ctoList = coerce (ctoList :: f a -> [a]) cnull :: forall a. Constraints (Monoid.Alt f) a => Monoid.Alt f a -> Bool cnull = coerce (cnull :: f a -> Bool) clength :: forall a. Constraints (Monoid.Alt f) a => Monoid.Alt f a -> Int clength = coerce (clength :: f a -> Int) celem :: forall a. (Eq a, Constraints (Monoid.Alt f) a) => a -> Monoid.Alt f a -> Bool celem = coerce (celem :: a -> f a -> Bool) cmaximum :: forall a. (Ord a, Constraints (Monoid.Alt f) a) => Monoid.Alt f a -> a cmaximum = coerce (cmaximum :: f a -> a) cminimum :: forall a. (Ord a, Constraints (Monoid.Alt f) a) => Monoid.Alt f a -> a cminimum = coerce (cminimum :: f a -> a) csum :: forall a. (Num a, Constraints (Monoid.Alt f) a) => Monoid.Alt f a -> a csum = coerce (csum :: f a -> a) cproduct :: forall a. (Num a, Constraints (Monoid.Alt f) a) => Monoid.Alt f a -> a cproduct = coerce (cproduct :: f a -> a) instance (CFoldable f, CFoldable g) => CFoldable (Compose f g) where # INLINABLE cfold # # INLINABLE cfoldMap # # INLINABLE cfoldr # cfold = cfoldMap cfold . getCompose cfoldMap f = cfoldMap (cfoldMap f) . getCompose cfoldr f z = cfoldr (\ga acc -> cfoldr f acc ga) z . getCompose instance (CFoldable f, CFoldable g) => CFoldable (Product.Product f g) where # INLINABLE cfold # # INLINABLE cfoldMap # # INLINABLE cfoldr # # INLINABLE cfoldr ' # # INLINABLE cfoldl # # INLINABLE cfoldl ' # cfold (Pair x y) = cfold x <> cfold y cfoldMap f (Pair x y) = cfoldMap f x <> cfoldMap f y cfoldr f z (Pair x y) = cfoldr f (cfoldr f z y) x cfoldr' f z (Pair x y) = cfoldr' f y' x where !y' = cfoldr' f z y cfoldl f z (Pair x y) = cfoldl f (cfoldl f z y) x cfoldl' f z (Pair x y) = cfoldl' f x' x where !x' = cfoldl' f z y cfoldr1 f (Pair x y) = cfoldl1 f x `f` cfoldl1 f y cfoldl1 f (Pair x y) = cfoldr1 f y `f` cfoldr1 f x instance (CFoldable f, CFoldable g) => CFoldable (Sum.Sum f g) where # INLINE cfold # # INLINE cfoldMap # # INLINE cfoldr # # INLINE cfoldr ' # # INLINE cfoldr1 # cfold (InL x) = cfold x cfold (InR y) = cfold y cfoldMap f (InL x) = cfoldMap f x cfoldMap f (InR y) = cfoldMap f y cfoldr f z (InL x) = cfoldr f z x cfoldr f z (InR y) = cfoldr f z y cfoldr' f z (InL x) = cfoldr' f z x cfoldr' f z (InR y) = cfoldr' f z y cfoldl f z (InL x) = cfoldl f z x cfoldl f z (InR y) = cfoldl f z y cfoldl' f z (InL x) = cfoldl' f z x cfoldl' f z (InR y) = cfoldl' f z y cfoldr1 f (InL x) = cfoldr1 f x cfoldr1 f (InR y) = cfoldr1 f y cfoldl1 f (InL x) = cfoldl1 f x cfoldl1 f (InR y) = cfoldl1 f y
cfcb69931d14e6793354485dea947c86324130eacb05589a36967db0a3369631
Ericson2314/lighthouse
PixelRectangles.hs
-------------------------------------------------------------------------------- -- | -- Module : Graphics.Rendering.OpenGL.GL.PixelRectangles Copyright : ( c ) 2002 - 2006 -- License : BSD-style (see the file libraries/OpenGL/LICENSE) -- -- Maintainer : -- Stability : stable -- Portability : portable -- This module corresponds to section 3.6 ( Pixel Rectangles ) of the OpenGL 2.1 -- specs. -- -------------------------------------------------------------------------------- module Graphics.Rendering.OpenGL.GL.PixelRectangles ( module Graphics.Rendering.OpenGL.GL.PixelRectangles.PixelStorage, module Graphics.Rendering.OpenGL.GL.PixelRectangles.PixelTransfer, module Graphics.Rendering.OpenGL.GL.PixelRectangles.PixelMap, module Graphics.Rendering.OpenGL.GL.PixelRectangles.ColorTable, module Graphics.Rendering.OpenGL.GL.PixelRectangles.Convolution, module Graphics.Rendering.OpenGL.GL.PixelRectangles.Histogram, module Graphics.Rendering.OpenGL.GL.PixelRectangles.Minmax, module Graphics.Rendering.OpenGL.GL.PixelRectangles.Rasterization ) where import Graphics.Rendering.OpenGL.GL.PixelRectangles.PixelStorage import Graphics.Rendering.OpenGL.GL.PixelRectangles.PixelTransfer import Graphics.Rendering.OpenGL.GL.PixelRectangles.PixelMap import Graphics.Rendering.OpenGL.GL.PixelRectangles.ColorTable import Graphics.Rendering.OpenGL.GL.PixelRectangles.Convolution import Graphics.Rendering.OpenGL.GL.PixelRectangles.Histogram import Graphics.Rendering.OpenGL.GL.PixelRectangles.Minmax import Graphics.Rendering.OpenGL.GL.PixelRectangles.Rasterization
null
https://raw.githubusercontent.com/Ericson2314/lighthouse/210078b846ebd6c43b89b5f0f735362a01a9af02/ghc-6.8.2/libraries/OpenGL/Graphics/Rendering/OpenGL/GL/PixelRectangles.hs
haskell
------------------------------------------------------------------------------ | Module : Graphics.Rendering.OpenGL.GL.PixelRectangles License : BSD-style (see the file libraries/OpenGL/LICENSE) Maintainer : Stability : stable Portability : portable specs. ------------------------------------------------------------------------------
Copyright : ( c ) 2002 - 2006 This module corresponds to section 3.6 ( Pixel Rectangles ) of the OpenGL 2.1 module Graphics.Rendering.OpenGL.GL.PixelRectangles ( module Graphics.Rendering.OpenGL.GL.PixelRectangles.PixelStorage, module Graphics.Rendering.OpenGL.GL.PixelRectangles.PixelTransfer, module Graphics.Rendering.OpenGL.GL.PixelRectangles.PixelMap, module Graphics.Rendering.OpenGL.GL.PixelRectangles.ColorTable, module Graphics.Rendering.OpenGL.GL.PixelRectangles.Convolution, module Graphics.Rendering.OpenGL.GL.PixelRectangles.Histogram, module Graphics.Rendering.OpenGL.GL.PixelRectangles.Minmax, module Graphics.Rendering.OpenGL.GL.PixelRectangles.Rasterization ) where import Graphics.Rendering.OpenGL.GL.PixelRectangles.PixelStorage import Graphics.Rendering.OpenGL.GL.PixelRectangles.PixelTransfer import Graphics.Rendering.OpenGL.GL.PixelRectangles.PixelMap import Graphics.Rendering.OpenGL.GL.PixelRectangles.ColorTable import Graphics.Rendering.OpenGL.GL.PixelRectangles.Convolution import Graphics.Rendering.OpenGL.GL.PixelRectangles.Histogram import Graphics.Rendering.OpenGL.GL.PixelRectangles.Minmax import Graphics.Rendering.OpenGL.GL.PixelRectangles.Rasterization
c26be06e8603ef11833559ba6490f29de84f915e263c552cf77792d685a09c6e
votinginfoproject/data-processor
district_type.clj
(ns vip.data-processor.validation.v5.district-type (:require [vip.data-processor.validation.v5.util :as util])) (def validate "Validates all DistrictType elements' formats." (util/validate-enum-elements :district-type :errors))
null
https://raw.githubusercontent.com/votinginfoproject/data-processor/b4baf334b3a6219d12125af8e8c1e3de93ba1dc9/src/vip/data_processor/validation/v5/district_type.clj
clojure
(ns vip.data-processor.validation.v5.district-type (:require [vip.data-processor.validation.v5.util :as util])) (def validate "Validates all DistrictType elements' formats." (util/validate-enum-elements :district-type :errors))
1ef1d8e70017e34ef9a49217467c0164ebcc548584842da127c788d31d5719b2
dmitryvk/sbcl-win32-threads
late-deftypes-for-target.lisp
(in-package "SB!KERNEL") (sb!xc:deftype compiled-function () '(and function #!+sb-eval (not sb!eval:interpreted-function)))
null
https://raw.githubusercontent.com/dmitryvk/sbcl-win32-threads/5abfd64b00a0937ba2df2919f177697d1d91bde4/src/code/late-deftypes-for-target.lisp
lisp
(in-package "SB!KERNEL") (sb!xc:deftype compiled-function () '(and function #!+sb-eval (not sb!eval:interpreted-function)))
09e1c4b00f3201f44519be7a5357040f9ca70d86160c9781d198d51460a0afda
t-sin/inquisitor
inquisitor.lisp
(in-package :cl-user) (defpackage inquisitor-test (:use :cl :inquisitor :prove) (:import-from :babel :string-to-octets)) (in-package :inquisitor-test) ;; NOTE: To run this test file, execute `(asdf:test-system :inquisitor)' in your Lisp. (plan 5) (subtest "detect-encoding" (subtest "for vector" (with-open-file (in (asdf:system-relative-pathname :inquisitor "t/data/ascii/ascii-lf.txt") :direction :input :element-type '(unsigned-byte 8)) (let ((buffer (make-array (file-length in) :element-type '(unsigned-byte 8)))) (read-sequence buffer in) (is (detect-encoding buffer :jp) :utf-8)))) (subtest "for stream" (with-open-file (in (asdf:system-relative-pathname :inquisitor "t/data/ascii/ascii-lf.txt") :direction :input) (is-error (detect-encoding in :jp) 'error)) (with-open-file (in (asdf:system-relative-pathname :inquisitor "t/data/unicode/utf-8.txt") :direction :input :element-type '(unsigned-byte 8)) (is (detect-encoding in :jp) :utf-8) (is (file-position in) (file-length in)))) (subtest "for pathname" (is (detect-encoding (asdf:system-relative-pathname :inquisitor "t/data/ascii/ascii-lf.txt") :jp) :utf-8))) (subtest "detect-end-of-line" (subtest "for vector" (with-open-file (in (asdf:system-relative-pathname :inquisitor "t/data/ascii/ascii-lf.txt") :direction :input :element-type '(unsigned-byte 8)) (let ((buffer (make-array (file-length in) :element-type '(unsigned-byte 8)))) (read-sequence buffer in) (is (detect-end-of-line buffer) :lf)))) (subtest "for stream" (with-open-file (in (asdf:system-relative-pathname :inquisitor "t/data/ascii/ascii-lf.txt") :direction :input) (is-error (detect-end-of-line in) 'error)) (with-open-file (in (asdf:system-relative-pathname :inquisitor "t/data/unicode/utf-8.txt") :direction :input :element-type '(unsigned-byte 8)) (is (detect-end-of-line in) :lf) (diag "is this check valid?") (is (file-position in) (file-length in)))) (subtest "for pathname" (is (detect-end-of-line (asdf:system-relative-pathname :inquisitor "t/data/ascii/ascii-lf.txt")) :lf))) (subtest "detect external-format --- from vector" (diag "when not byte-array") (is-error (detect-external-format "string" :jp) 'error) (diag "when cannot treat the encodings (how do I cause it...?)") (is-error (detect-external-format "" :jp) 'error) (let ((str (string-to-octets "string"))) (is (detect-external-format str :jp) (make-external-format :utf-8 :lf)))) (subtest "detect external-format --- from stream" (with-output-to-string (out) (is-error (detect-external-format out :jp) 'error)) (with-input-from-string (in "string") (is-error (detect-external-format in :jp) 'error)) (with-open-file (in (asdf:system-relative-pathname :inquisitor "t/data/ascii/ascii-lf.txt") :direction :input :element-type '(unsigned-byte 8)) (is (detect-external-format in :jp) (make-external-format :utf-8 :lf)))) (subtest "detect external-format --- from pathname" (is-error (detect-external-format "t/data/ascii/ascii-lf.txt" :jp) 'error) (is (detect-external-format (asdf:system-relative-pathname :inquisitor "t/data/ascii/ascii-lf.txt") :jp) (make-external-format :utf-8 :lf))) (finalize)
null
https://raw.githubusercontent.com/t-sin/inquisitor/423fa9bdd4a68a6ae517b18406d81491409ccae8/t/inquisitor.lisp
lisp
NOTE: To run this test file, execute `(asdf:test-system :inquisitor)' in your Lisp.
(in-package :cl-user) (defpackage inquisitor-test (:use :cl :inquisitor :prove) (:import-from :babel :string-to-octets)) (in-package :inquisitor-test) (plan 5) (subtest "detect-encoding" (subtest "for vector" (with-open-file (in (asdf:system-relative-pathname :inquisitor "t/data/ascii/ascii-lf.txt") :direction :input :element-type '(unsigned-byte 8)) (let ((buffer (make-array (file-length in) :element-type '(unsigned-byte 8)))) (read-sequence buffer in) (is (detect-encoding buffer :jp) :utf-8)))) (subtest "for stream" (with-open-file (in (asdf:system-relative-pathname :inquisitor "t/data/ascii/ascii-lf.txt") :direction :input) (is-error (detect-encoding in :jp) 'error)) (with-open-file (in (asdf:system-relative-pathname :inquisitor "t/data/unicode/utf-8.txt") :direction :input :element-type '(unsigned-byte 8)) (is (detect-encoding in :jp) :utf-8) (is (file-position in) (file-length in)))) (subtest "for pathname" (is (detect-encoding (asdf:system-relative-pathname :inquisitor "t/data/ascii/ascii-lf.txt") :jp) :utf-8))) (subtest "detect-end-of-line" (subtest "for vector" (with-open-file (in (asdf:system-relative-pathname :inquisitor "t/data/ascii/ascii-lf.txt") :direction :input :element-type '(unsigned-byte 8)) (let ((buffer (make-array (file-length in) :element-type '(unsigned-byte 8)))) (read-sequence buffer in) (is (detect-end-of-line buffer) :lf)))) (subtest "for stream" (with-open-file (in (asdf:system-relative-pathname :inquisitor "t/data/ascii/ascii-lf.txt") :direction :input) (is-error (detect-end-of-line in) 'error)) (with-open-file (in (asdf:system-relative-pathname :inquisitor "t/data/unicode/utf-8.txt") :direction :input :element-type '(unsigned-byte 8)) (is (detect-end-of-line in) :lf) (diag "is this check valid?") (is (file-position in) (file-length in)))) (subtest "for pathname" (is (detect-end-of-line (asdf:system-relative-pathname :inquisitor "t/data/ascii/ascii-lf.txt")) :lf))) (subtest "detect external-format --- from vector" (diag "when not byte-array") (is-error (detect-external-format "string" :jp) 'error) (diag "when cannot treat the encodings (how do I cause it...?)") (is-error (detect-external-format "" :jp) 'error) (let ((str (string-to-octets "string"))) (is (detect-external-format str :jp) (make-external-format :utf-8 :lf)))) (subtest "detect external-format --- from stream" (with-output-to-string (out) (is-error (detect-external-format out :jp) 'error)) (with-input-from-string (in "string") (is-error (detect-external-format in :jp) 'error)) (with-open-file (in (asdf:system-relative-pathname :inquisitor "t/data/ascii/ascii-lf.txt") :direction :input :element-type '(unsigned-byte 8)) (is (detect-external-format in :jp) (make-external-format :utf-8 :lf)))) (subtest "detect external-format --- from pathname" (is-error (detect-external-format "t/data/ascii/ascii-lf.txt" :jp) 'error) (is (detect-external-format (asdf:system-relative-pathname :inquisitor "t/data/ascii/ascii-lf.txt") :jp) (make-external-format :utf-8 :lf))) (finalize)
b223a073b816eb8b9e82c9e81d50e384704e8e6cbce08a59c8add0afa9e23d87
willemdj/erlsom
erlsom_sax_utf16le.erl
Copyright ( C ) 2006 - 2008 %%% This file is part of Erlsom . %%% Erlsom is free software : you can redistribute it and/or modify %%% it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation , either version 3 of the License , or ( at your option ) any later version . %%% Erlsom is distributed in the hope that it will be useful , %%% but WITHOUT ANY WARRANTY; without even the implied warranty of %%% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details . %%% You should have received a copy of the GNU Lesser General Public License along with Erlsom . If not , see %%% </>. %%% %%% Author contact: %%% ==================================================================== An XML parser , using the SAX model . %%% ==================================================================== %% this file exists several times, but with different names: %% erlsom_sax_utf8, erlsom_sax_latin1 etc. The only difference to the content of these 2 files is the definition below : it can be UTF8 , LAT1 , LAT9 , U16B or U16L. ( The names have been chosen so that the %% number of bytes in the file will be the same in either case, so that it is %% easy to see whether the files are the same, although this check is obviously %% rather primitive.) -define(U16L, true). -ifdef(UTF8). -module(erlsom_sax_utf8). -define(BINARY, true). -define(STR1(X), <<X>>). -define(STR2(X1, X2), <<X1, X2>>). -define(STR3(X1, X2, X3), <<X1, X2, X3>>). -define(STR4(X1, X2, X3, X4), <<X1, X2, X3, X4>>). -define(STR5(X1, X2, X3, X4, X5), <<X1, X2, X3, X4, X5>>). -define(STR6(X1, X2, X3, X4, X5, X6), <<X1, X2, X3, X4, X5, X6>>). -define(STR7(X1, X2, X3, X4, X5, X6, X7), <<X1, X2, X3, X4, X5, X6, X7>>). -define(STR8(X1, X2, X3, X4, X5, X6, X7, X8), <<X1, X2, X3, X4, X5, X6, X7, X8>>). -define(DONTCARE_T(Y), <<_, Y/binary>>). -define(STR1_T(X, Y), <<X, Y/binary>>). -define(STR2_T(X1, X2, Y), <<X1, X2, Y/binary>>). -define(STR3_T(X1, X2, X3, Y), <<X1, X2, X3, Y/binary>>). -define(STR4_T(X1, X2, X3, X4, Y), <<X1, X2, X3, X4, Y/binary>>). -define(STR7_T(X1, X2, X3, X4, X5, X6, X7, Y), <<X1, X2, X3, X4, X5, X6, X7, Y/binary>>). -define(STR8_T(X1, X2, X3, X4, X5, X6, X7, X8, Y), <<X1, X2, X3, X4, X5, X6, X7, X8, Y/binary>>). -define(STR9_T(X1, X2, X3, X4, X5, X6, X7, X8, X9, Y), <<X1, X2, X3, X4, X5, X6, X7, X8, X9, Y/binary>>). -define(BOM1(X), <<16#EF, 16#BB, 16#BF, X/binary>>). -define(BOM2, <<16#EF, 16#BB>>). -define(BOM3, <<16#EF>>). -endif. -ifdef(U16B). -module(erlsom_sax_utf16be). -define(BINARY, true). -define(STR1(X), <<0, X>>). -define(STR2(X1, X2), <<0, X1, 0, X2>>). -define(STR3(X1, X2, X3), <<0, X1, 0, X2, 0, X3>>). -define(STR4(X1, X2, X3, X4), <<0, X1, 0, X2, 0, X3, 0, X4>>). -define(STR5(X1, X2, X3, X4, X5), <<0, X1, 0, X2, 0, X3, 0, X4, 0, X5>>). -define(STR6(X1, X2, X3, X4, X5, X6), <<0, X1, 0, X2, 0, X3, 0, X4, 0, X5, 0, X6>>). -define(STR7(X1, X2, X3, X4, X5, X6, X7), <<0, X1, 0, X2, 0, X3, 0, X4, 0, X5, 0, X6, 0, X7>>). -define(STR8(X1, X2, X3, X4, X5, X6, X7, X8), <<0, X1, 0, X2, 0, X3, 0, X4, 0, X5, 0, X6, 0, X7, 0, X8>>). -define(DONTCARE_T(Y), <<_, _, Y/binary>>). -define(STR1_T(X, Y), <<0, X, Y/binary>>). -define(STR2_T(X1, X2, Y), <<0, X1, 0, X2, Y/binary>>). -define(STR3_T(X1, X2, X3, Y), <<0, X1, 0, X2, 0, X3, Y/binary>>). -define(STR4_T(X1, X2, X3, X4, Y), <<0, X1, 0, X2, 0, X3, 0, X4, Y/binary>>). -define(STR7_T(X1, X2, X3, X4, X5, X6, X7, Y), <<0, X1, 0, X2, 0, X3, 0, X4, 0, X5, 0, X6, 0, X7, Y/binary>>). -define(STR8_T(X1, X2, X3, X4, X5, X6, X7, X8, Y), <<0, X1, 0, X2, 0, X3, 0, X4, 0, X5, 0, X6, 0, X7, 0, X8, Y/binary>>). -define(STR9_T(X1, X2, X3, X4, X5, X6, X7, X8, X9, Y), <<0, X1, 0, X2, 0, X3, 0, X4, 0, X5, 0, X6, 0, X7, 0, X8, 0, X9, Y/binary>>). -define(BOM1(X), <<16#FE, 16#FF, X/binary>>). -define(BOM2, <<16#FE>>). -define(BOM3, no_match). -endif. -ifdef(U16L). -module(erlsom_sax_utf16le). -define(BINARY, true). -define(STR1(X), <<X, 0>>). -define(STR2(X1, X2), <<X1, 0, X2, 0>>). -define(STR3(X1, X2, X3), <<X1, 0, X2, 0, X3, 0>>). -define(STR4(X1, X2, X3, X4), <<X1, 0, X2, 0, X3, 0, X4, 0>>). -define(STR5(X1, X2, X3, X4, X5), <<X1, 0, X2, 0, X3, 0, X4, 0, X5, 0>>). -define(STR6(X1, X2, X3, X4, X5, X6), <<X1, 0, X2, 0, X3, 0, X4, 0, X5, 0, X6, 0>>). -define(STR7(X1, X2, X3, X4, X5, X6, X7), <<X1, 0, X2, 0, X3, 0, X4, 0, X5, 0, X6, 0, X7, 0>>). -define(STR8(X1, X2, X3, X4, X5, X6, X7, X8), <<X1, 0, X2, 0, X3, 0, X4, 0, X5, 0, X6, 0, X7, 0, X8, 0>>). -define(DONTCARE_T(Y), <<_, _, Y/binary>>). -define(STR1_T(X, Y), <<X, 0, Y/binary>>). -define(STR2_T(X1, X2, Y), <<X1, 0, X2, 0, Y/binary>>). -define(STR3_T(X1, X2, X3, Y), <<X1, 0, X2, 0, X3, 0, Y/binary>>). -define(STR4_T(X1, X2, X3, X4, Y), <<X1, 0, X2, 0, X3, 0, X4, 0, Y/binary>>). -define(STR7_T(X1, X2, X3, X4, X5, X6, X7, Y), <<X1, 0, X2, 0, X3, 0, X4, 0, X5, 0, X6, 0, X7, 0, Y/binary>>). -define(STR8_T(X1, X2, X3, X4, X5, X6, X7, X8, Y), <<X1, 0, X2, 0, X3, 0, X4, 0, X5, 0, X6, 0, X7, 0, X8, 0, Y/binary>>). -define(STR9_T(X1, X2, X3, X4, X5, X6, X7, X8, X9, Y), <<X1, 0, X2, 0, X3, 0, X4, 0, X5, 0, X6, 0, X7, 0, X8, 0, X9, 0, Y/binary>>). -define(BOM1(X), <<16#FF, 16#FE, X/binary>>). -define(BOM2, <<16#FF>>). -define(BOM3, no_match). -endif. -ifdef(LAT1). -module(erlsom_sax_latin1). -define(BINARY, true). -define(STR1(X), <<X>>). -define(STR2(X1, X2), <<X1, X2>>). -define(STR3(X1, X2, X3), <<X1, X2, X3>>). -define(STR4(X1, X2, X3, X4), <<X1, X2, X3, X4>>). -define(STR5(X1, X2, X3, X4, X5), <<X1, X2, X3, X4, X5>>). -define(STR6(X1, X2, X3, X4, X5, X6), <<X1, X2, X3, X4, X5, X6>>). -define(STR7(X1, X2, X3, X4, X5, X6, X7), <<X1, X2, X3, X4, X5, X6, X7>>). -define(STR8(X1, X2, X3, X4, X5, X6, X7, X8), <<X1, X2, X3, X4, X5, X6, X7, X8>>). -define(DONTCARE_T(Y), <<_, Y/binary>>). -define(STR1_T(X, Y), <<X, Y/binary>>). -define(STR2_T(X1, X2, Y), <<X1, X2, Y/binary>>). -define(STR3_T(X1, X2, X3, Y), <<X1, X2, X3, Y/binary>>). -define(STR4_T(X1, X2, X3, X4, Y), <<X1, X2, X3, X4, Y/binary>>). -define(STR7_T(X1, X2, X3, X4, X5, X6, X7, Y), <<X1, X2, X3, X4, X5, X6, X7, Y/binary>>). -define(STR8_T(X1, X2, X3, X4, X5, X6, X7, X8, Y), <<X1, X2, X3, X4, X5, X6, X7, X8, Y/binary>>). -define(STR9_T(X1, X2, X3, X4, X5, X6, X7, X8, X9, Y), <<X1, X2, X3, X4, X5, X6, X7, X8, X9, Y/binary>>). -define(BOM1(X), [no_match | X]). -define(BOM2, no_match). -define(BOM3, no_match2). -endif. -ifdef(LAT9). -module(erlsom_sax_latin9). -define(BINARY, true). -define(STR1(X), <<X>>). -define(STR2(X1, X2), <<X1, X2>>). -define(STR3(X1, X2, X3), <<X1, X2, X3>>). -define(STR4(X1, X2, X3, X4), <<X1, X2, X3, X4>>). -define(STR5(X1, X2, X3, X4, X5), <<X1, X2, X3, X4, X5>>). -define(STR6(X1, X2, X3, X4, X5, X6), <<X1, X2, X3, X4, X5, X6>>). -define(STR7(X1, X2, X3, X4, X5, X6, X7), <<X1, X2, X3, X4, X5, X6, X7>>). -define(STR8(X1, X2, X3, X4, X5, X6, X7, X8), <<X1, X2, X3, X4, X5, X6, X7, X8>>). -define(DONTCARE_T(Y), <<_, Y/binary>>). -define(STR1_T(X, Y), <<X, Y/binary>>). -define(STR2_T(X1, X2, Y), <<X1, X2, Y/binary>>). -define(STR3_T(X1, X2, X3, Y), <<X1, X2, X3, Y/binary>>). -define(STR4_T(X1, X2, X3, X4, Y), <<X1, X2, X3, X4, Y/binary>>). -define(STR7_T(X1, X2, X3, X4, X5, X6, X7, Y), <<X1, X2, X3, X4, X5, X6, X7, Y/binary>>). -define(STR8_T(X1, X2, X3, X4, X5, X6, X7, X8, Y), <<X1, X2, X3, X4, X5, X6, X7, X8, Y/binary>>). -define(STR9_T(X1, X2, X3, X4, X5, X6, X7, X8, X9, Y), <<X1, X2, X3, X4, X5, X6, X7, X8, X9, Y/binary>>). -define(BOM1(X), [no_match | X]). -define(BOM2, no_match). -define(BOM3, no_match2). -endif. -ifdef(LIST). -module(erlsom_sax_list). -define(EMPTY, []). -define(STR1(X), [X]). -define(STR2(X1, X2), [X1, X2]). -define(STR3(X1, X2, X3), [X1, X2, X3]). -define(STR4(X1, X2, X3, X4), [X1, X2, X3, X4]). -define(STR5(X1, X2, X3, X4, X5), [X1, X2, X3, X4, X5]). -define(STR6(X1, X2, X3, X4, X5, X6), [X1, X2, X3, X4, X5, X6]). -define(STR7(X1, X2, X3, X4, X5, X6, X7), [X1, X2, X3, X4, X5, X6, X7]). -define(STR8(X1, X2, X3, X4, X5, X6, X7, X8), [X1, X2, X3, X4, X5, X6, X7, X8]). -define(DONTCARE_T(Y), [_ | Y]). -define(STR1_T(X, Y), [X | Y]). -define(STR2_T(X1, X2, Y), [X1, X2 | Y]). -define(STR3_T(X1, X2, X3, Y), [X1, X2, X3 | Y]). -define(STR4_T(X1, X2, X3, X4, Y), [X1, X2, X3, X4 | Y]). -define(STR7_T(X1, X2, X3, X4, X5, X6, X7, Y), [X1, X2, X3, X4, X5, X6, X7 |Y]). -define(STR8_T(X1, X2, X3, X4, X5, X6, X7, X8, Y), [X1, X2, X3, X4, X5, X6, X7, X8 | Y]). -define(BOM1(X), [65279 | X]). -define(BOM2, no_match). -define(BOM3, no_match2). -endif. -ifdef(BINARY). -define(EMPTY, <<>>). -endif. %% these are only here to save some typing -define(CF3(A, B, C), erlsom_sax_lib:continueFun(A, B, C)). -define(CF4(A, B, C, D), erlsom_sax_lib:continueFun(A, B, C, D)). -define(CF4_2(A, B, C, D), erlsom_sax_lib:continueFun2(A, B, C, D)). -define(CF5(A, B, C, D, E), erlsom_sax_lib:continueFun(A, B, C, D, E)). -define(CF6(A, B, C, D, E, F), erlsom_sax_lib:continueFun(A, B, C, D, E, F)). -define(CF6_2(A, B, C, D, E, F), erlsom_sax_lib:continueFun2(A, B, C, D, E, F)). -include("erlsom_sax.hrl"). -export([parse/2]). parse(Xml, State) -> State2 = wrapCallback(startDocument, State), {State3, Tail} = parseProlog(Xml, State2), State4 = wrapCallback(endDocument, State3), {ok, State4#erlsom_sax_state.user_state, Tail}. returns { State , Tail } parseProlog(?EMPTY, State) -> ?CF3(?EMPTY, State, fun parseProlog/2); parseProlog(?STR1($<), State) -> ?CF3(?STR1($<), State, fun parseProlog/2); parseProlog(?STR2_T($<, $?, Tail), State) -> {processinginstruction, Target, Data, Tail2, State2} = parseProcessingInstruction(Tail, State), State3 = wrapCallback({processingInstruction, Target, lists:reverse(Data)}, State2), parseProlog(Tail2, State3); parseProlog(?STR2_T($<, $!, Tail) = T, State) -> case Tail of ?STR2_T($-, $-, Tail2) -> {comment, Tail3, State2} = parseComment(Tail2, State), parseProlog(Tail3, State2); ?STR7_T($D, $O, $C, $T, $Y, $P, $E, Tail2) -> {dtd, Tail3, State2} = parseDTD(Tail2, State), parseProlog(Tail3, State2); ?STR6($D, $O, $C, $T, $Y, $P) -> ?CF3(T, State, fun parseProlog/2); ?STR5($D, $O, $C, $T, $Y) -> ?CF3(T, State, fun parseProlog/2); ?STR4($D, $O, $C, $T) -> ?CF3(T, State, fun parseProlog/2); ?STR3($D, $O, $C) -> ?CF3(T, State, fun parseProlog/2); ?STR2($D, $O) -> ?CF3(T, State, fun parseProlog/2); ?STR1($D) -> ?CF3(T, State, fun parseProlog/2); ?STR1($-) -> ?CF3(T, State, fun parseProlog/2); ?EMPTY -> ?CF3(T, State, fun parseProlog/2); _ -> throw({error, "Malformed: Illegal character in prolog"}) end; parseProlog(?STR1_T($<, Tail), State) -> parseContentLT(Tail, State); %% whitespace in the prolog is ignored parseProlog(?STR1_T(NextChar, Tail), State) when ?is_whitespace(NextChar) -> parseProlog(Tail, State); %% non-breaking space, used as byte order mark parseProlog(?BOM1(Tail), State) -> parseProlog(Tail, State); parseProlog(?BOM2, State) -> ?CF3(?BOM2, State, fun parseProlog/2); parseProlog(?BOM3, State) -> ?CF3(?BOM3, State, fun parseProlog/2); parseProlog(_Tail, _) -> throw({error, "Malformed: Illegal character in prolog"}). -ifdef(UTF8). %% Decode the next character Tail = the rest of the XML returns , Tail2 , State2 } decodeChar(Tail, State) -> case Tail of ?EMPTY -> ?CF3(?EMPTY, State, fun decodeChar/2); <<C1, Tail2/binary>> when C1 < 16#80 -> {C1, Tail2, State}; <<C1, C2, Tail2/binary>> when C1 band 16#E0 =:= 16#C0, C2 band 16#C0 =:= 16#80 -> {decode2(C1, C2), Tail2, State}; <<C1>> when C1 band 16#E0 =:= 16#C0 -> ?CF3(<<C1>>, State, fun decodeChar/2); <<C1, C2, C3, Tail2/binary>> when C1 band 16#F0 =:= 16#E0, C2 band 16#C0 =:= 16#80, C3 band 16#C0 =:= 16#80 -> {decode3(C1, C2, C3), Tail2, State}; <<C1, C2>> when C1 band 16#F0 =:= 16#E0, C2 band 16#C0 =:= 16#80 -> ?CF3(<<C1, C2>>, State, fun decodeChar/2); <<C1>> when C1 band 16#F0 =:= 16#E0 -> ?CF3(<<C1>>, State, fun decodeChar/2); <<C1,C2,C3,C4, Tail2/binary>> when C1 band 16#F8 =:= 16#F0, C2 band 16#C0 =:= 16#80, C3 band 16#C0 =:= 16#80, C4 band 16#C0 =:= 16#80 -> {decode4(C1, C2, C3, C4), Tail2, State}; <<C1,C2,C3>> when C1 band 16#F8 =:= 16#F0, C2 band 16#C0 =:= 16#80, C3 band 16#C0 =:= 16#80 -> ?CF3(<<C1, C2, C3>>, State, fun decodeChar/2); <<C1,C2>> when C1 band 16#F8 =:= 16#F0, C2 band 16#C0 =:= 16#80 -> ?CF3(<<C1, C2>>, State, fun decodeChar/2); <<C1>> when C1 band 16#F8 =:= 16#F0 -> ?CF3(<<C1>>, State, fun decodeChar/2); <<_C1, _C2>> -> throw({error, "Decoding error: illegal UTF-8 encoding"}) end. decodes an UTF-8 encoded character that consists of 2 bytes . decode2(C1, C2) -> case ((C1 band 16#1F) bsl 6) bor (C2 band 16#3F) of C when 16#80 =< C -> C; _ -> %% Bad range. throw({error, "Decoding error: illegal UTF-8 encoding"}) end. decode3(C1, C2, C3) -> case ((((C1 band 16#0F) bsl 6) bor (C2 band 16#3F)) bsl 6) bor (C3 band 16#3F) of C when 16#800 =< C -> C; _ -> %% Bad range. throw({error, "Decoding error: illegal UTF-8 encoding"}) end. decode4(C1, C2, C3, C4) -> case ((((((C1 band 16#0F) bsl 6) bor (C2 band 16#3F)) bsl 6) bor (C3 band 16#3F)) bsl 6) bor (C4 band 16#3F) of C when 16#10000 =< C -> C; _ -> %% Bad range. throw({error, "Decoding error: illegal UTF-8 encoding"}) end. -endif. -ifdef(U16B). decodeChar(Tail, State) -> case Tail of ?EMPTY -> ?CF3(Tail, State, fun decodeChar/2); <<_>> -> %% incomplete ?CF3(Tail, State, fun decodeChar/2); <<C1, C2, Tail2/binary>> when C1 < 16#D8; C1 > 16#DF -> {C1 * 256 + C2, Tail2, State}; <<_Hi1, _Hi2, _Lo1>> -> %% incomplete ?CF3(Tail, State, fun decodeChar/2); <<Hi1, Hi2, Lo1, Lo2, Tail2/binary>> when Hi1 >= 16#D8, Hi1 < 16#DC, Lo1 >= 16#DC, Lo1 < 16#E0 -> %% Surrogate pair Hi = Hi1 * 256 + Hi2, Lo = Lo1 * 256 + Lo2, Ch = ((Hi band 16#3FF) bsl 10) + (Lo band 16#3FF) + 16#10000, {Ch, Tail2, State}; <<Hi1, _Hi2>> when Hi1 >= 16#D8, Hi1 < 16#DC -> %% Surrogate pair, incomplete ?CF3(Tail, State, fun decodeChar/2); _ -> {error,not_utf16be} end. -endif. -ifdef(U16L). decodeChar(Tail, State) -> case Tail of ?EMPTY -> ?CF3(Tail, State, fun decodeChar/2); <<_>> -> %% incomplete ?CF3(Tail, State, fun decodeChar/2); <<C1, C2, Tail2/binary>> when C2 < 16#D8; C2 > 16#DF -> {C2 * 256 + C1, Tail2, State}; <<_Hi1, _Hi2, _Lo1>> -> %% incomplete ?CF3(Tail, State, fun decodeChar/2); <<Hi1, Hi2, Lo1, Lo2, Tail2/binary>> when Hi2 >= 16#D8, Hi2 < 16#DC, Lo2 >= 16#DC, Lo2 < 16#E0 -> %% Surrogate pair Hi = Hi2 * 256 + Hi1, Lo = Lo2 * 256 + Lo1, Ch = ((Hi band 16#3FF) bsl 10) + (Lo band 16#3FF) + 16#10000, {Ch, Tail2, State}; <<_Hi1, Hi2>> when Hi2 >= 16#D8, Hi2 < 16#DC -> %% Surrogate pair, incomplete ?CF3(Tail, State, fun decodeChar/2); _ -> {error,not_utf16le} end. -endif. -ifdef(LAT1). decodeChar(Tail, State) -> case Tail of ?EMPTY -> ?CF3(Tail, State, fun decodeChar/2); ?STR1_T(C, T) -> {C, T, State} end. -endif. -ifdef(LAT9). decodeChar(Tail, State) -> case Tail of ?EMPTY -> ?CF3(Tail, State, fun decodeChar/2); ?STR1_T(C, T) -> {latin9toUnicode(C), T, State} end. latin9toUnicode(16#A4) -> % EURO SIGN 16#20AC; latin9toUnicode(16#A6) -> % LATIN CAPITAL LETTER S WITH CARON 16#0160; latin9toUnicode(16#A8) -> % LATIN SMALL LETTER S WITH CARON 16#0161; latin9toUnicode(16#B4) -> % LATIN CAPITAL LETTER Z WITH CARON 16#017D; latin9toUnicode(16#B8) -> % LATIN SMALL LETTER Z WITH CARON 16#017E; latin9toUnicode(16#BC) -> % LATIN CAPITAL LIGATURE OE 16#0152; latin9toUnicode(16#BD) -> % LATIN SMALL LIGATURE OE 16#0153; LATIN CAPITAL LETTER Y WITH 16#0178; latin9toUnicode(Char) -> Char. -endif. -ifdef(LIST). decodeChar(Tail, State) -> case Tail of ?EMPTY -> ?CF3(Tail, State, fun decodeChar/2); ?STR1_T(C, T) -> {C, T, State} end. -endif. returns , CData , Tail } parseCDATA(Head, Tail0, State) -> case Tail0 of ?STR3_T($], $], $>, Tail) -> {cdata, lists:reverse(Head), Tail, State}; ?STR2($], $]) -> ?CF4(Head, ?STR2($], $]), State, fun parseCDATA/3); ?STR1($]) -> ?CF4(Head, ?STR1($]), State, fun parseCDATA/3); ?STR1_T(NextChar, Tail) when NextChar < 16#80 -> parseCDATA([NextChar | Head], Tail, State); ?EMPTY -> ?CF4(Head, ?EMPTY, State, fun parseCDATA/3); _ -> {Char, Tail2, State2} = decodeChar(Tail0, State), parseCDATA([Char | Head], Tail2, State2) end. %% returns {dtd, Tail} parseDTD(?STR1_T($[, Tail), State) -> {intSubset, Tail2, State2} = parseIntSubset(Tail, State), parseDTD(Tail2, State2); parseDTD(?STR1_T($>, Tail), State) -> {dtd, Tail, State}; parseDTD(?DONTCARE_T(Tail), State) -> parseDTD(Tail, State); parseDTD(?EMPTY, State) -> ?CF3(?EMPTY, State, fun parseDTD/2). %% returns {intSubset, Tail} parseIntSubset(?STR1_T($], Tail), State) -> {intSubset, Tail, State}; parseIntSubset(?STR1_T(NextChar, Tail), State) when ?is_whitespace(NextChar) -> parseIntSubset(Tail, State); %% get rid of whitespace parseIntSubset(?STR8_T($<, $!, $E, $N, $T, $I, $T, $Y, Tail), State) -> case parseEntity(Tail, State) of {Tail2, State2} -> parseIntSubset(Tail2, State2); Other -> Other end; parseIntSubset(?STR7($<, $!, $E, $N, $T, $I, $T) = T, State) -> ?CF3(T, State, fun parseIntSubset/2); parseIntSubset(?STR6($<, $!, $E, $N, $T, $I) = T, State) -> ?CF3(T, State, fun parseIntSubset/2); parseIntSubset(?STR5($<, $!, $E, $N, $T) = T, State) -> ?CF3(T, State, fun parseIntSubset/2); parseIntSubset(?STR4($<, $!, $E, $N) = T, State) -> ?CF3(T, State, fun parseIntSubset/2); parseIntSubset(?STR3($<, $!, $E) = T, State) -> ?CF3(T, State, fun parseIntSubset/2); parseIntSubset(?STR2($<, $!) = T, State) -> ?CF3(T, State, fun parseIntSubset/2); parseIntSubset(?STR1($<) = T, State) -> ?CF3(T, State, fun parseIntSubset/2); %% comments (starting with <--) parseIntSubset(?STR4_T($<, $!, $-, $-, Tail), State) -> {comment, Tail2, State2} = parseComment(Tail, State), parseIntSubset(Tail2, State2); parseIntSubset(?STR3($<, $!, $-) = T, State) -> ?CF3(T, State, fun parseIntSubset/2); %% parameter entities (starting with %) , Tail ) , State ) - > % % {Head, Tail2, State2} = parseReference([], parameter, Tail, State), parseIntSubset(Head ++ Tail2, State2); %% all other things starting with < parseIntSubset(?STR1_T($<, Tail), State) -> parseMarkupDecl(Tail, State); parseIntSubset(?EMPTY, State) -> ?CF3(?EMPTY, State, fun parseIntSubset/2). parseMarkupDecl(?STR1_T($>, Tail), State) -> parseIntSubset(Tail, State); parseMarkupDecl(?STR1_T($", Tail), State) -> %" {value, _, Tail2, State2} = parseLiteralValue(Tail, $", [], definition, State), %" parseMarkupDecl(Tail2, State2); parseMarkupDecl(?STR1_T($', Tail), State) -> %' {value, _, Tail2, State2} = parseLiteralValue(Tail, $', [], definition, State), %' parseMarkupDecl(Tail2, State2); parseMarkupDecl(?STR1_T(_, Tail), State) -> parseMarkupDecl(Tail, State); parseMarkupDecl(?EMPTY, State) -> ?CF3(?EMPTY, State, fun parseMarkupDecl/2). %% returns: { Tail2 , State2 } , where the parsed entity has been added to the State parseEntity(?STR1_T(NextChar, Tail), State) when ?is_whitespace(NextChar) -> parseEntity(Tail, State); parseEntity(?STR1_T(NextChar, _) = Tail, State) when ?is_namestart_char(NextChar) -> parseEntityName(Tail, State); parseEntity(?EMPTY, State) -> ?CF3(?EMPTY, State, fun parseEntity/2); parseEntity(Tail, State) -> parseEntityName(Tail, State). { , _ Tail2 , State2 } = decodeChar(Tail , State ) , case of _ when ? is_namestart_char2(Char ) - > %% parseEntityName(Tail, State2); %% _ -> %% throw({error, "Malformed: Illegal character in entity name"}) %% end. parseEntityName(Tail, State = #erlsom_sax_state{max_entity_size = MaxSize, max_nr_of_entities = MaxNr, output = OutputEncoding, entities = EntitiesSoFar, par_entities = ParEntitiesSoFar}) -> CurrentEntity = State#erlsom_sax_state.current_entity, {Type, Tail2, State2} = getType(Tail, State), {Name, Tail3, State3} = parseNameNoNamespaces(Tail2, State2), {value, Value, Tail4, State4} = parseLiteral(definition, Tail3, State3#erlsom_sax_state{current_entity = Name}), if length(EntitiesSoFar) + length(ParEntitiesSoFar) >= MaxNr -> throw({error, "Too many entities defined"}); true -> ok end, %% this is a bit of a hack - parseliteral may return an encoded value, %% but that is not what we want here. ValueAsList = case OutputEncoding of 'utf8' -> erlsom_ucs:decode_utf8(Value); _ -> Value end, if length(ValueAsList) > MaxSize -> throw({error, "Entity too long"}); true -> ok end, {Tail5, State5} = parseEndHook(Tail4, State4), case Type of general -> State6 = State5#erlsom_sax_state{ if an entity is declared twice , the first definition should be used . %% Therefore, add new ones to the back of the list. entities = EntitiesSoFar ++ [{Name, ValueAsList}], current_entity = CurrentEntity}; parameter -> State6 = State5#erlsom_sax_state{ par_entities = ParEntitiesSoFar ++ [{Name, ValueAsList}]} end, {Tail5, State6}. getType(?STR1_T(NextChar, Tail), State) when ?is_whitespace(NextChar) -> getType(Tail, State); , NextChar , Tail ) , State ) when ?is_whitespace(NextChar) -> {parameter, Tail, State}; getType(?EMPTY, State) -> ?CF3(?EMPTY, State, fun getType/2); getType(Tail, State) -> {general, Tail, State}. %% returns {comment, Tail} parseComment(?STR1_T($-, Tail), State) -> case Tail of ?STR2_T($-, $>, Tail2) -> {comment, Tail2, State}; ?STR1($-) -> ?CF3(?STR2($-, $-), State, fun parseComment/2); ?EMPTY -> ?CF3(?STR1($-), State, fun parseComment/2); ?STR1_T($-, _) -> throw({error, "Malformed: -- not allowed in comment"}); _ -> parseComment(Tail, State) end; parseComment(?DONTCARE_T(Tail), State) -> parseComment(Tail, State); parseComment(?EMPTY, State) -> ?CF3(?EMPTY, State, fun parseComment/2). returns { processinginstruction , Target , Data , Tail } parseProcessingInstruction(Tail, State) -> {Target, Tail2, State2} = parseNameNoNamespaces(Tail, State), {Data, Tail3, State3} = parsePIData([], Tail2, State2), {processinginstruction, Target, Data, Tail3, State3}. %% returns {Data, Tail} parsePIData(Head, Tail, State) -> case Tail of ?STR2_T($?, $>, Tail2) -> {Head, Tail2, State}; ?STR1($?) -> ?CF4(Head, ?STR1($?), State, fun parsePIData/3); ?STR1_T(NextChar, Tail2) when NextChar < 16#80 -> parsePIData([NextChar | Head], Tail2, State); ?EMPTY -> ?CF4(Head, ?EMPTY, State, fun parsePIData/3); _ -> {Char, Tail2, State2} = decodeChar(Tail, State), parsePIData([Char | Head], Tail2, State2) end. %% function to call the Callback function for all elements in a list of 'new namespaces'. returns State mapStartPrefixMappingCallback([{Prefix, Uri} | Tail], State) -> mapStartPrefixMappingCallback(Tail, wrapCallback({startPrefixMapping, Prefix, Uri}, State)); mapStartPrefixMappingCallback([], State) -> State. %% function to call the Callback function for all elements in a list of 'new namespaces'. returns State mapEndPrefixMappingCallback([{Prefix, _Uri} | Tail], State) -> mapEndPrefixMappingCallback(Tail, wrapCallback({endPrefixMapping, Prefix}, State)); mapEndPrefixMappingCallback([], State) -> State. %% the '<' is already removed returns { starttag , , Attributes , Tail } or { emptyelement , , Attributes , Tail } %% where = { Prefix , LocalName , QualifiedName } %% parseStartTag(Tail, State) -> parseTagName(Tail, State). %% parseTagName %% returns {Name, Tail}, where %% Name = {Prefix, LocalName, QualifiedName} %% %% To do: introduce a parameter that indicates whether we are using %% namespaces. parseTagName(?STR1_T(Char, Tail), State) when ?is_namestart_char(Char) -> %% this should differentiate between 'with namespaces'and 'without' %% for the moment the assumption is 'with', therefore a name cannot %% start with a ':'. parseTagName([Char], Tail, State); parseTagName(?EMPTY, State) -> ?CF3(?EMPTY, State, fun parseTagName/2); parseTagName(Tail, State) -> {Char, Tail2, State2} = decodeChar(Tail, State), case Char of _ when ?is_namestart_char2(Char) -> parseTagName([Char], Tail2, State2); _ -> throw({error, "Malformed: Illegal character in tag"}) end. parseTagName(Head, ?STR1_T(NextChar, Tail), State) when ?is_name_char(NextChar) -> parseTagName([NextChar | Head], Tail, State); parseTagName(Head, ?STR1_T($:, Tail), State) -> parseTagName(Head, [], Tail, State); parseTagName(Head, ?STR1_T($>, Tail), State) -> LocalName = lists:reverse(Head), {starttag, {[], LocalName, LocalName}, [], Tail, State}; parseTagName(Head, ?STR2_T($/, $>, Tail), State) -> LocalName = lists:reverse(Head), {emptyelement, {[], LocalName, LocalName}, [], Tail, State}; parseTagName(Head, ?STR1_T(NextChar, Tail), State) when ?is_whitespace(NextChar) -> LocalName = lists:reverse(Head), parseAttributes({[], LocalName, LocalName}, [], Tail, State); parseTagName(Head, ?STR1($/), State) -> ?CF4(Head, ?STR1($/), State, fun parseTagName/3); parseTagName(Head, ?EMPTY, State) -> ?CF4(Head, ?EMPTY, State, fun parseTagName/3); parseTagName(Head, Tail, State) -> {Char, Tail2, State2} = decodeChar(Tail, State), if ?is_name_char2(Char) -> parseTagName([Char | Head], Tail2, State2); true -> throw({error, "Malformed: Illegal character in tag"}) end. should there be another check on the first character of the local name ? parseTagName(Prefix, Head, ?STR1_T(NextChar, Tail), State) when ?is_name_char(NextChar) -> parseTagName(Prefix, [NextChar | Head], Tail, State); parseTagName(Prefix, Head, ?STR1_T(NextChar, Tail), State) when ?is_whitespace(NextChar) -> Pf = lists:reverse(Prefix), Hd = lists:reverse(Head), parseAttributes({Pf, Hd, lists:append([Pf, ":", Hd])}, [], Tail, State); parseTagName(Prefix, Head, ?STR1_T($>, Tail), State) -> Pf = lists:reverse(Prefix), Hd = lists:reverse(Head), {starttag, {Pf, Hd, lists:append([Pf, ":", Hd])}, [], Tail, State}; parseTagName(Prefix, Head, ?STR2_T($/, $>, Tail), State) -> Pf = lists:reverse(Prefix), Hd = lists:reverse(Head), {emptyelement, {Pf, Hd, lists:append([Pf, ":", Hd])}, [], Tail, State}; parseTagName(Prefix, Head, ?EMPTY, State) -> ?CF5(Prefix, Head, ?EMPTY, State, fun parseTagName/4); parseTagName(Prefix, Head, ?STR1($/), State) -> ?CF5(Prefix, Head, ?STR1($/), State, fun parseTagName/4); parseTagName(Prefix, Head, Tail, State) -> {Char, Tail2, State2} = decodeChar(Tail, State), if ?is_name_char2(Char) -> parseTagName(Prefix, [Char | Head], Tail2, State2); true -> throw({error, "Malformed: Illegal character in tag"}) end. parseAttrName(Head, ?STR1_T($:, Tail), State) -> %% Head is the prefix parseAttrName(Head, [], Tail, State); parseAttrName(Head, ?STR1_T(NextChar, Tail), State) when ?is_name_char(NextChar) -> parseAttrName([NextChar | Head], Tail, State); parseAttrName(Head, ?STR1_T($=, Tail), State) -> LocalName = lists:reverse(Head), {{[], LocalName, LocalName}, Tail, State}; parseAttrName(Head, ?STR1_T(NextChar, Tail), State) when ?is_whitespace(NextChar) -> LocalName = lists:reverse(Head), {Tail2, State2} = parseEqualSign(Tail, State), {{[], LocalName, LocalName}, Tail2, State2}; parseAttrName(Head, ?EMPTY, State) -> ?CF4(Head, ?EMPTY, State, fun parseAttrName/3); parseAttrName(Head, Tail, State) -> {Char, Tail2, State2} = decodeChar(Tail, State), if ?is_name_char2(Char) -> parseAttrName([Char | Head], Tail2, State2); true -> throw({error, "Malformed: Illegal character in attribute name"}) end. should there be another check on the first character of the local name ? parseAttrName(Prefix, Head, ?STR1_T(NextChar, Tail), State) when ?is_name_char(NextChar) -> parseAttrName(Prefix, [NextChar | Head], Tail, State); parseAttrName(Prefix, Head, ?STR1_T($=, Tail), State) -> Pf = lists:reverse(Prefix), Hd = lists:reverse(Head), {{Pf, Hd, lists:append([Pf, ":", Hd])}, Tail, State}; parseAttrName(Prefix, Head, ?STR1_T(NextChar, Tail), State) when ?is_whitespace(NextChar) -> Pf = lists:reverse(Prefix), Hd = lists:reverse(Head), {Tail2, State2} = parseEqualSign(Tail, State), {{Pf, Hd, lists:append([Pf, ":", Hd])}, Tail2, State2}; parseAttrName(Prefix, Head, ?EMPTY, State) -> ?CF5(Prefix, Head, ?EMPTY, State, fun parseAttrName/4); parseAttrName(Prefix, Head, Tail, State) -> {Char, Tail2, State2} = decodeChar(Tail, State), if ?is_name_char2(Char) -> parseAttrName(Prefix, [Char | Head], Tail2, State2); true -> throw({error, "Malformed: Illegal character in attribute name"}) end. %% returns {Name, Tail, State} parseNameNoNamespaces(?STR1_T(Char, Tail), State) when ?is_namestart_char(Char) -> parseNameNoNamespaces([Char], Tail, State); parseNameNoNamespaces(Tail, State) -> {Char, Tail2, State2} = decodeChar(Tail, State), if ?is_namestart_char2(Char) -> parseNameNoNamespaces([Char], Tail2, State2); true -> throw({error, "Malformed: Illegal character in name"}) end. parseNameNoNamespaces(Head, ?STR1_T(NextChar, Tail), State) when ?is_name_char(NextChar) -> parseNameNoNamespaces([NextChar | Head], Tail, State); parseNameNoNamespaces(Head, ?STR1_T($:, Tail), State) -> parseNameNoNamespaces([$: | Head], Tail, State); parseNameNoNamespaces(Head, T = ?STR1_T($>, _), State) -> {lists:reverse(Head), T, State}; parseNameNoNamespaces(Head, T = ?STR1_T($?, _), State) -> {lists:reverse(Head), T, State}; parseNameNoNamespaces(Head, T = ?STR1_T($=, _), State) -> {lists:reverse(Head), T, State}; parseNameNoNamespaces(Head, T = ?STR1_T(NextChar, _), State) when ?is_whitespace(NextChar) -> {lists:reverse(Head), T, State}; parseNameNoNamespaces(Head, ?EMPTY, State) -> ?CF4(Head, ?EMPTY, State, fun parseNameNoNamespaces/3); parseNameNoNamespaces(Head, Tail, State) -> {Char, Tail2, State2} = decodeChar(Tail, State), if ?is_name_char2(Char) -> parseNameNoNamespaces([Char | Head], Tail2, State2); true -> throw({error, "Malformed: Illegal character in name"}) end. %% returns: {attributes, Attributes, Tail}} %% Attributes = list of {Name, Value} tuples, and %% Name = {Prefix, LocalName, QualifiedName}. parseAttributes(StartTag, Attributes, ?STR1_T($>, Tail), State) -> {starttag, StartTag, Attributes, Tail, State}; parseAttributes(StartTag, Attributes, ?STR1($/), State) -> ?CF5(StartTag, Attributes, ?STR1($/), State, fun parseAttributes/4); parseAttributes(StartTag, Attributes, ?STR2_T($/, $>, Tail), State) -> {emptyelement, StartTag, Attributes, Tail, State}; parseAttributes(StartTag, Attributes, ?STR1_T(NextChar, Tail), State) when ?is_whitespace(NextChar) -> parseAttributes(StartTag, Attributes, Tail, State); parseAttributes(StartTag, Attributes, ?STR1_T(NextChar, Tail), State) when ?is_namestart_char(NextChar) -> {AttributeName, Tail2, State2} = parseAttrName([NextChar], Tail, State), { attribute , Attribute , Tail3 , State3 } = %% parseAttribute([NextChar], Tail, State), {value, Value, Tail3, State3} = parseLiteral(attribute, Tail2, State2), { attribute , { AttributeName , Value } , Tail2 , State2 } ; parseAttributeValue(AttributeName , Tail2 , State2 ) , parseAttributes(StartTag, [{AttributeName, Value} | Attributes], Tail3, State3); parseAttributes(StartTag, Attributes, ?EMPTY, State) -> ?CF5(StartTag, Attributes, ?EMPTY, State, fun parseAttributes/4); parseAttributes(StartTag, Attributes, Tail, State) -> {Char, Tail2, State2} = decodeChar(Tail, State), case Char of _ when ?is_namestart_char2(Char) -> {AttributeName, Tail3, State3} = parseAttrName([Char], Tail2, State2), {value, Value, Tail4, State4} = parseLiteral(attribute, Tail3, State3), { attribute , Attribute , Tail3 , State3 } = %% parseAttribute([Char], Tail2, State2), parseAttributes(StartTag, [{AttributeName, Value} | Attributes], Tail4, State4); _ -> throw({error, "Malformed: Illegal character in name"}) end. %% returns {value, Value, Tail, State} %% depending on the context (attribute or definition) the %% handling of entities is slightly different. parseLiteral(Context, ?STR1_T($", Tail), State) -> %" parseLiteralValue(Tail, $", Context, State); %" parseLiteral(Context, ?STR1_T($', Tail), State) -> %' parseLiteralValue(Tail, $', Context, State); %' parseLiteral(Context, ?STR1_T(NextChar, Tail), State) when ?is_whitespace(NextChar) -> parseLiteral(Context, Tail, State); parseLiteral(Context, ?EMPTY, State) -> ?CF4(Context, ?EMPTY, State, fun parseLiteral/3); parseLiteral(_C, _T, _) -> throw({error, "Malformed: Illegal character in literal value"}). %% TODO: this can be generalized, for example parsing up to the = sign %% in an attribute value is exactly the same. parseEndHook(?STR1_T($>, Tail), State) -> {Tail, State}; parseEndHook(?STR1_T(NextChar, Tail), State) when ?is_whitespace(NextChar) -> parseEndHook(Tail, State); parseEndHook(?EMPTY, State) -> ?CF3(?EMPTY, State, fun parseEndHook/2); parseEndHook(_Tail, _) -> throw({error, "Malformed: Illegal character in entity definition"}). parseEqualSign(?STR1_T($=, Tail), State) -> {Tail, State}; parseEqualSign(?STR1_T(NextChar, Tail), State) when ?is_whitespace(NextChar) -> parseEqualSign(Tail, State); parseEqualSign(?EMPTY, State) -> ?CF3(?EMPTY, State, fun parseEqualSign/2); parseEqualSign(_Tail, _) -> throw({error, "Malformed: Illegal character in attribute name"}). %% previous char was '<' parseContentLT(?STR1_T($!, Tail), State) -> case Tail of ?STR2_T($-, $-, Tail3) -> {comment, Tail4, State2} = parseComment(Tail3, State), parseContent(Tail4, State2); ?STR1($-) -> ?CF3(?STR2($!, $-), State, fun parseContentLT/2); ?EMPTY -> ?CF3(?STR1($!), State, fun parseContentLT/2); ?STR7_T($[, $C, $D, $A, $T, $A, $[, Tail3) -> {cdata, CData, Tail4, State2} = parseCDATA([], Tail3, State), %% call callback - If Cdata is preceded and/or followed by text there will be 2 or 3 %% events, but that is legal according to the sax doc. State3 = wrapCallback({characters, encodeOutput(CData, State)}, State2), parseContent(Tail4, State3); ?STR6($[, $C, $D, $A, $T, $A) -> ?CF3(?STR7($!, $[, $C, $D, $A, $T, $A), State, fun parseContentLT/2); ?STR5($[, $C, $D, $A, $T) -> ?CF3(?STR6($!, $[, $C, $D, $A, $T), State, fun parseContentLT/2); ?STR4($[, $C, $D, $A) -> ?CF3(?STR5($!, $[, $C, $D, $A), State, fun parseContentLT/2); ?STR3($[, $C, $D) -> ?CF3(?STR4($!, $[, $C, $D), State, fun parseContentLT/2); ?STR2($[, $C) -> ?CF3(?STR3($!, $[, $C), State, fun parseContentLT/2); ?STR1($[) -> ?CF3(?STR2($!, $[), State, fun parseContentLT/2) end; parseContentLT(?STR1_T($?, Tail), State) -> {processinginstruction, Target, Data, Tail3, State2} = parseProcessingInstruction(Tail, State), State3 = wrapCallback({processingInstruction, Target, lists:reverse(Data)}, State2), parseContent(Tail3, State3); parseContentLT(?STR1_T($/, Tail), State) -> %% this should be the endTag [{QName, Uri, LocalName, Prefix, OldNamespaces, NewNamespaces} | EndTags2] = State#erlsom_sax_state.endtags, case parseEndTag(Tail, QName, State) of {ok, Tail3, State2} -> %% Call the call back functions for the end tag State3 = wrapCallback({endElement, Uri, LocalName, Prefix}, State2), State4 = mapEndPrefixMappingCallback(NewNamespaces, State3), State5 = State4#erlsom_sax_state{namespaces = OldNamespaces, endtags = EndTags2}, parseContent(Tail3, State5); error -> throw({error, "Malformed: Tags don't match"}) end; parseContentLT(?EMPTY, State) -> ?CF3(?EMPTY, State, fun parseContentLT/2); parseContentLT(Tail, State) -> Namespaces = State#erlsom_sax_state.namespaces, case parseStartTag(Tail, State) of {emptyelement, {Prefix, _LocalName, _QName}=StartTag, Attributes, Tail2, State2} -> {{Uri, LocalName, QName}, Attributes2, NewNamespaces} = createStartTagEvent(StartTag, Namespaces, Attributes), %% Call the call back functions State3 = mapStartPrefixMappingCallback(NewNamespaces, State2), State4 = wrapCallback({startElement, Uri, LocalName, Prefix, Attributes2}, State3), State5 = wrapCallback({endElement, Uri, LocalName, QName}, State4), State6 = mapEndPrefixMappingCallback(NewNamespaces, State5), parseContent(Tail2, State6); {starttag, {Prefix, _LocalName, QName} = StartTag, Attributes, Tail2, State2} -> EndTags = State#erlsom_sax_state.endtags, {{Uri, LocalName, Prefix}, Attributes2, NewNamespaces} = createStartTagEvent(StartTag, Namespaces, Attributes), %% Call the call back function State3 = mapStartPrefixMappingCallback(NewNamespaces, State2), State4 = wrapCallback({startElement, Uri, LocalName, Prefix, Attributes2}, State3), State5 = State4#erlsom_sax_state{namespaces = NewNamespaces ++ Namespaces, endtags = [{QName, Uri, LocalName, Prefix, Namespaces, NewNamespaces} | EndTags]}, %% TODO: check the order of the namespaces parseContent(Tail2, State5) end. parseContent(?STR1_T($<, Tail), #erlsom_sax_state{endtags = EndTags} = State) when EndTags /= [] -> parseContentLT(Tail, State); parseContent(?EMPTY, #erlsom_sax_state{endtags = EndTags} = State) -> case EndTags of [] -> This is the return value . The second element is what follows the XML document , as a list . {State, []}; _ -> ?CF3(?EMPTY, State, fun parseContent/2) end; parseContent(T, #erlsom_sax_state{endtags = EndTags} = State) -> case EndTags of [] -> This is the return value . The second element is what follows the XML document , as a list . {State, decode(T)}; _ -> {Tail2, State2} = parseText(T, State), parseContentLT(Tail2, State2) end. parseText(Tail, #erlsom_sax_state{output = 'utf8'} = State) -> parseTextBinary(<<>>, Tail, State); parseText(Tail, State) -> parseText([], Tail, State). parseText(Head, ?STR1_T($<, Tail), State) -> State2 = wrapCallback({ignorableWhitespace, lists:reverse(Head)}, State), {Tail, State2}; parseText(Head, ?STR1_T(NextChar, Tail), State) when ?is_whitespace(NextChar) -> parseText([NextChar | Head], Tail, State); parseText(Head, ?EMPTY, State) -> ?CF4(Head, ?EMPTY, State, fun parseText/3); parseText(Head, Tail, State) -> parseTextNoIgnore(Head, Tail, State). parseTextNoIgnore(Head, ?STR1_T($<, Tail), State) -> State2 = wrapCallback({characters, lists:reverse(Head)}, State), {Tail, State2}; parseTextNoIgnore(Head, ?STR1_T($&, Tail), State) -> {Head2, Tail2, State2} = parseReference([], element, Tail, State), parseTextNoIgnore(Head2 ++ Head, Tail2, State2); parseTextNoIgnore(Head, ?STR1_T(NextChar, Tail), State) when NextChar < 16#80 -> parseTextNoIgnore([NextChar|Head], Tail, State); parseTextNoIgnore(Head, ?EMPTY, State) -> ?CF4(Head, ?EMPTY, State, fun parseTextNoIgnore/3); parseTextNoIgnore(Head, Tail, State) -> {Char, Tail2, State2} = decodeChar(Tail, State), parseTextNoIgnore([Char | Head], Tail2, State2). parseTextBinary(Head, ?STR1_T($<, Tail), State) -> State2 = wrapCallback({ignorableWhitespace, Head}, State), {Tail, State2}; parseTextBinary(Head, ?STR1_T(NextChar, Tail), State) when ?is_whitespace(NextChar) -> parseTextBinary(<<Head/binary, NextChar>>, Tail, State); parseTextBinary(Head, ?EMPTY, State) -> ?CF4(Head, ?EMPTY, State, fun parseTextBinary/3); parseTextBinary(Head, Tail, State) -> parseTextNoIgnoreBinary(Head, Tail, State). parseTextNoIgnoreBinary(Head, ?STR1_T($<, Tail), State) -> State2 = wrapCallback({characters, Head}, State), {Tail, State2}; parseTextNoIgnoreBinary(Head, ?STR1_T($&, Tail), State) -> {Head2, Tail2, State2} = parseReference([], element, Tail, State), %% parseReference returns a list Head2Binary = list_to_binary(erlsom_ucs:to_utf8(lists:reverse(Head2))), parseTextNoIgnoreBinary(<<Head/binary, Head2Binary/binary>>, Tail2, State2); parseTextNoIgnoreBinary(Head, ?STR1_T(NextChar, Tail), State) when NextChar < 16#80 -> parseTextNoIgnoreBinary(<<Head/binary, NextChar>>, Tail, State); parseTextNoIgnoreBinary(Head, ?EMPTY, State) -> ?CF4(Head, ?EMPTY, State, fun parseTextNoIgnoreBinary/3); parseTextNoIgnoreBinary(Head, Tail, State) -> {Char, Tail2, State2} = decodeChar(Tail, State), EncodedChar = erlsom_ucs:char_to_utf8(Char), parseTextNoIgnoreBinary(<<Head/binary, EncodedChar/binary>>, Tail2, State2). %% entity references in attribute values differ fundamentally from %% references in elements and in entity definitions %% Context can be: element, attribute, definition parseReference(Head, Context, ?STR1_T($;, Tail), State) -> translateReference(lists:reverse(Head), Context, Tail, State); parseReference(Head, Context, ?STR1_T(NextChar, Tail), State) when NextChar < 16#80 -> parseReference([NextChar | Head], Context, Tail, State); parseReference(Head, Context, ?EMPTY, State) -> ?CF5(Head, Context, ?EMPTY, State, fun parseReference/4); parseReference(Head, Context, Tail, State) -> {Char, Tail2, State2} = decodeChar(Tail, State), parseReference([Char | Head], Context, Tail2, State2). returns : { Head2 , Tail2 , State2 } %% Character entities are added to the 'head' (the bit that was parsed already), %% other entities are added to the tail (they still have to be parsed). %% The problem here is that we have to make sure that we don't get into an infinite %% loop. This solved as follows: %% We proceed by parsing only the entity (while registering in the state that we %% are parsing this particular entity). However, we replace the continuation function %% by something that simply returns (in stead of calling the function that it was %% working on recursively). We then proceed. %% Before starting to work on this entity, we need to check that we are not already %% parsing this entity (because that would mean an infinite loop). translateReference(Reference, Context, Tail, State) -> %% in the context of a definition, character references have to be replaced %% (and others not). case Reference of [$#, $x | Tail1] -> %% hex number of char's code point %% unfortunately this function accepts illegal values %% to do: replace by something that throws an error in case of %% an illegal value {[list_to_integer(Tail1, 16)], Tail, State}; [$# | Tail1] -> %% dec number of char's code point case catch list_to_integer(Tail1) of {'EXIT', _} -> throw({error, "Malformed: Illegal character in reference"}); %% to do: check on legal character. Other -> {[Other], Tail, State} end; _ -> translateReferenceNonCharacter(Reference, Context, Tail, State) end. translateReferenceNonCharacter(Reference, Context, Tail, State = #erlsom_sax_state{current_entity = CurrentEntity, max_entity_depth = MaxDepth, entity_relations = Relations, entity_size_acc = TotalSize, max_expanded_entity_size = MaxSize}) -> case Context of definition -> case MaxDepth of 0 -> throw({error, "Entities nested too deep"}); _ -> ok end, %% check on circular definition NewRelation = {CurrentEntity, Reference}, case lists:member(NewRelation, Relations) of true -> Relations2 = Relations; false -> Relations2 = [NewRelation | Relations], case erlsom_sax_lib:findCycle(Reference, CurrentEntity, Relations2, MaxDepth) of cycle -> throw({error, "Malformed: Cycle in entity definitions"}); max_depth -> throw({error, "Entities nested too deep"}); _ -> ok end end, %% don't replace {lists:reverse("&" ++ Reference ++ ";"), Tail, State#erlsom_sax_state{entity_relations = Relations2}}; _ -> {Translation, Type} = nowFinalyTranslate(Reference, Context, State), NewTotal = TotalSize + length(Translation), if NewTotal > MaxSize -> throw({error, "Too many characters in expanded entities"}); true -> ok end, case Context of attribute -> %% replace, add to the parsed text (head) {Translation, Tail, State#erlsom_sax_state{entity_size_acc = NewTotal}}; _ -> %% element or parameter case Type of user_defined -> %% replace, encode again and put back into the input stream (Tail) TEncoded = encode(Translation), {[], combine(TEncoded, Tail), State#erlsom_sax_state{entity_size_acc = NewTotal}}; _ -> {Translation, Tail, State#erlsom_sax_state{entity_size_acc = NewTotal}} end end end. nowFinalyTranslate(Reference, Context, State) -> case Reference of "amp" -> {[$&], other}; "lt" -> {[$<], other}; "gt" -> {[$>], other}; "apos" -> {[39], other}; %% apostrof "quot" -> {[34], other}; %% quote _ -> case State#erlsom_sax_state.expand_entities of true -> ListOfEntities = case Context of parameter -> State#erlsom_sax_state.par_entities; element -> State#erlsom_sax_state.entities end, case lists:keysearch(Reference, 1, ListOfEntities) of {value, {_, EntityText}} -> {EntityText, user_defined}; _ -> throw({error, "Malformed: unknown reference: " ++ Reference}) end; false -> throw({error, "Entity expansion disabled, found reference " ++ Reference}) end end. %% TODO: proper encoding -ifdef(BINARY). combine(Head, Tail) -> <<Head/binary, Tail/binary>>. -endif. -ifdef(UTF8). encode(List) -> list_to_binary(erlsom_ucs:to_utf8(List)). -endif. -ifdef(U16B). encode(List) -> list_to_binary(xmerl_ucs:to_utf16be(List)). -endif. -ifdef(U16L). encode(List) -> list_to_binary(xmerl_ucs:to_utf16le(List)). -endif. -ifdef(LAT1). encode(List) -> list_to_binary(List). -endif. -ifdef(LAT9). encode(List) -> list_to_binary(List). -endif. -ifdef(LIST). encode(List) -> List. combine(Head, Tail) -> Head ++ Tail. -endif. encodeOutput(List, #erlsom_sax_state{output = 'utf8'}) -> list_to_binary(erlsom_ucs:to_utf8(List)); encodeOutput(List, _) -> List. %%parseText(Tail, #erlsom_sax_state{output = 'utf8'} = State) -> %%parseTextBinary(?EMPTY, Tail, State); parseText(Tail , State ) - > %%parseText([], Tail, State). parseLiteralValue(Tail, Quote, Context, #erlsom_sax_state{output = 'utf8'} = State) -> parseLiteralValueBinary(Tail, Quote, <<>>, Context, State); parseLiteralValue(Tail, Quote, Context, State) -> parseLiteralValue(Tail, Quote, [], Context, State). parseLiteralValue(?STR1_T(Quote, Tail), Quote, Head, _Context, State) -> {value, lists:reverse(Head), Tail, State}; parseLiteralValue(?STR1_T($&, Tail), Quote, Head, Context, State) -> {Reference, Tail2, State2} = parseReference([], Context, Tail, State), parseLiteralValue(Tail2, Quote, Reference ++ Head, Context, State2); parseLiteralValue(?STR1_T($<, Tail), Quote, Head, Context, State) -> case Context of attribute -> throw({error, "Malformed: < not allowed in literal value"}); _ -> parseLiteralValue(Tail, Quote, [$< | Head], Context, State) end; parseLiteralValue(?STR1_T($%, Tail), Quote, Head, Context, State) -> %% case Context of definition -> this is weird , but it follows the implementation of MS %% Internet Explorer... %% Can't find this in the standard, but it is an unlikely thing %% to happen in a bonafide xml, and it avoids some problems with %% circular definitions throw({error, "Malformed: cannot use % in entity definition (?)"}); _ -> parseLiteralValue(Tail, Quote, [$% | Head], Context, State) end; parseLiteralValue(?STR1_T(NextChar, Tail), Quote, Head, Context, State) when NextChar < 16#80 -> parseLiteralValue(Tail, Quote, [NextChar | Head], Context, State); parseLiteralValue(?EMPTY, Quote, Head, Context, State) -> ?CF6_2(?EMPTY, Quote, Head, Context, State, fun parseLiteralValue/5); parseLiteralValue(Tail, Quote, Head, Context, State) -> {Char, Tail2, State2} = decodeChar(Tail, State), parseLiteralValue(Tail2, Quote, [Char | Head], Context, State2). parseLiteralValueBinary(?STR1_T(Quote, Tail), Quote, Head, _Context, State) -> {value, Head, Tail, State}; parseLiteralValueBinary(?STR1_T($&, Tail), Quote, Head, Context, State) -> {Head2, Tail2, State2} = parseReference([], element, Tail, State), %% parseReference returns a list (only 1 char long - in case of a %% user defined entity this will be put in front of tail!) Head2Binary = list_to_binary(erlsom_ucs:to_utf8(lists:reverse(Head2))), parseLiteralValueBinary(Tail2, Quote, <<Head/binary, Head2Binary/binary>>, Context, State2); parseLiteralValueBinary(?STR1_T($<, Tail), Quote, Head, Context, State) -> case Context of attribute -> throw({error, "Malformed: < not allowed in literal value"}); _ -> parseLiteralValueBinary(Tail, Quote, <<Head/binary, $<>>, Context, State) end; parseLiteralValueBinary(?STR1_T($%, Tail), Quote, Head, Context, State) -> %% case Context of definition -> throw({error, "Malformed: cannot use % in entity definition (?)"}); _ -> parseLiteralValueBinary(Tail, Quote, <<Head/binary, $%>>, Context, State) end; parseLiteralValueBinary(?STR1_T(NextChar, Tail), Quote, Head, Context, State) when NextChar < 16#80 -> parseLiteralValueBinary(Tail, Quote, <<Head/binary, NextChar>>, Context, State); parseLiteralValueBinary(?EMPTY, Quote, Head, Context, State) -> ?CF6_2(?EMPTY, Quote, Head, Context, State, fun parseLiteralValueBinary/5); parseLiteralValueBinary(Tail, Quote, Head, Context, State) -> {Char, Tail2, State2} = decodeChar(Tail, State), EncodedChar = erlsom_ucs:char_to_utf8(Char), parseLiteralValueBinary(Tail2, Quote, <<Head/binary, EncodedChar/binary>>, Context, State2). %% the start tag is decoded (it is a list of unicode code points) parseEndTag(?STR1_T(A, Tail1), [A | Tail2], State) when A < 16#80 -> parseEndTag(Tail1, Tail2, State); parseEndTag(?STR1_T($>, Tail), [], State) -> {ok, Tail, State}; parseEndTag(?STR1_T(NextChar, Tail), [], State) when ?is_whitespace(NextChar) -> {Tail2, State2} = removeWS(Tail, State), {ok, Tail2, State2}; parseEndTag(?EMPTY, StartTag, State) -> ?CF4_2(?EMPTY, StartTag, State, fun parseEndTag/3); parseEndTag(Tail, [B | StartTagTail], State) -> {Char, Tail2, State2} = decodeChar(Tail, State), if Char =:= B -> parseEndTag(Tail2, StartTagTail, State2); true -> error end; parseEndTag(_Tail, [], _State) -> error. removeWS(?STR1_T($>, T), State) -> {T, State}; removeWS(?STR1_T(C, T), State) when ?is_whitespace(C) -> removeWS(T, State); removeWS(?EMPTY, State) -> ?CF3(?EMPTY, State, fun removeWS/2); removeWS(_, _) -> throw({error, "Malformed: Unexpected character in end tag"}). = { Prefix , LocalName , QualifiedName } %% Attributes = list of Attribute %% Attribute = {{Prefix, LocalName} Value} %% %% returns: {Name, Attributes2, NewNamespaces} %% Name = {URI, LocalName, QualifiedName} Attributes2 = list of %% Attribute2 = #attribute NewNamespaces = list of { Prefix , URI } ( prefix can be [ ] ) . %% %% Namespaces are in such an order that namespace of the 'closest ancestors' %% are in front. That way the right element will be found, even if a prefix is %% used more than once in the document. %% createStartTagEvent(StartTag, Namespaces, Attributes) -> %% find the namespace definitions in the attributes {NewNamespaces, OtherAttributes} = lookForNamespaces([], [], Attributes), AllNamespaces = NewNamespaces ++ Namespaces, add the to the tag name ( if applicable ) Name = tagNameTuple(StartTag, AllNamespaces), %% add the URIs to the attribute names (if applicable) Attributes2 = attributeNameTuples([], OtherAttributes, AllNamespaces), {Name, Attributes2, NewNamespaces}. %% returns {Namespaces, OtherAttributes}, where %% Namespaces = a list of tuples {Prefix, URI} %% OtherAttributes = a list of tuples {Name, Value} %% lookForNamespaces(Namespaces, OtherAttributes, [Head | Tail]) -> {{Prefix, LocalName, _QName}, Value} = Head, if Prefix == "xmlns" -> lookForNamespaces([{LocalName, decodeIfRequired(Value)} | Namespaces], OtherAttributes, Tail); Prefix == [], LocalName == "xmlns" -> lookForNamespaces([{[], decodeIfRequired(Value)} | Namespaces], OtherAttributes, Tail); true -> lookForNamespaces(Namespaces, [Head | OtherAttributes], Tail) end; lookForNamespaces(Namespaces, OtherAttributes, []) -> {Namespaces, OtherAttributes}. decodeIfRequired(URI) when is_list(URI) -> URI; decodeIfRequired(URI) when is_binary(URI) -> {Value, _} = erlsom_ucs:from_utf8(URI), Value. = { Prefix , LocalName , QualifiedName } %% Namespaces = list of {Prefix, URI} (prefix can be []). %% Returns , LocalName , Prefix } %% %% TODO: error if not found? special treatment of 'xml:lang'? tagNameTuple(StartTag, Namespaces) -> {Prefix, LocalName, _QName} = StartTag, case lists:keysearch(Prefix, 1, Namespaces) of {value, {Prefix, Uri}} -> {Uri, LocalName, Prefix}; false -> {[], LocalName, Prefix} end. %% Attributes = list of Attribute %% Attribute = {{Prefix, LocalName} Value} %% Namespaces = list of {Prefix, URI} (prefix can be []). %% %% Returns a list of #attribute records attributeNameTuples(ProcessedAttributes, [{AttributeName, Value} | Attributes], Namespaces) -> {Uri, LocalName, Prefix} = attributeNameTuple(AttributeName, Namespaces), attributeNameTuples([#attribute{localName= LocalName, prefix = Prefix, uri = Uri, value = Value} | ProcessedAttributes], Attributes, Namespaces); attributeNameTuples(ProcessedAttributes, [], _) -> ProcessedAttributes. %% AttributeName = {Prefix, LocalName, QualifiedName} %% Namespaces = list of {Prefix, URI} (prefix can be []). %% Returns , LocalName , Prefix } . %% Difference with TagNameTuple: attributes without prefix do NOT belong %% to the default namespace. attributeNameTuple(AttributeName, Namespaces) -> {Prefix, LocalName, _} = AttributeName, if Prefix == [] -> {[], LocalName, []}; true -> case lists:keysearch(Prefix, 1, Namespaces) of {value, {Prefix, Uri}} -> {Uri, LocalName, Prefix}; false -> case Prefix of "xml" -> {"", LocalName, Prefix}; _ -> {[], LocalName, Prefix} end end end. wrapCallback(Event, #erlsom_sax_state{callback = Callback, user_state = UserState} = State) -> State#erlsom_sax_state{user_state = Callback(Event, UserState)}. -ifdef(UTF8). decode(Bin) -> {Value, _} = erlsom_ucs:from_utf8(Bin), Value. -endif. -ifdef(LAT1). decode(Bin) -> {Value, _} = erlsom_ucs:from_utf8(Bin), Value. -endif. -ifdef(LAT9). decode(Bin) -> [latin9toUnicode(Char) || Char <- binary_to_list(Bin)]. -endif. -ifdef(U16B). decode(Bin) -> {Value, _} = erlsom_ucs:from_utf16be(Bin), Value. -endif. -ifdef(U16L). decode(Bin) -> {Value, _} = erlsom_ucs:from_utf16le(Bin), Value. -endif. -ifdef(LIST). decode(List) -> List. -endif.
null
https://raw.githubusercontent.com/willemdj/erlsom/b8b25d9b9f8676e114548792e9c01debf207926d/src/erlsom_sax_utf16le.erl
erlang
it under the terms of the GNU Lesser General Public License as but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the </>. Author contact: ==================================================================== ==================================================================== this file exists several times, but with different names: erlsom_sax_utf8, erlsom_sax_latin1 etc. number of bytes in the file will be the same in either case, so that it is easy to see whether the files are the same, although this check is obviously rather primitive.) these are only here to save some typing whitespace in the prolog is ignored non-breaking space, used as byte order mark Decode the next character Bad range. Bad range. Bad range. incomplete incomplete Surrogate pair Surrogate pair, incomplete incomplete incomplete Surrogate pair Surrogate pair, incomplete EURO SIGN LATIN CAPITAL LETTER S WITH CARON LATIN SMALL LETTER S WITH CARON LATIN CAPITAL LETTER Z WITH CARON LATIN SMALL LETTER Z WITH CARON LATIN CAPITAL LIGATURE OE LATIN SMALL LIGATURE OE returns {dtd, Tail} returns {intSubset, Tail} get rid of whitespace comments (starting with <--) parameter entities (starting with %) % all other things starting with < ' ' returns: parseEntityName(Tail, State2); _ -> throw({error, "Malformed: Illegal character in entity name"}) end. this is a bit of a hack - parseliteral may return an encoded value, but that is not what we want here. Therefore, add new ones to the back of the list. returns {comment, Tail} returns {Data, Tail} function to call the Callback function for all elements in a list of 'new namespaces'. function to call the Callback function for all elements in a list of 'new namespaces'. the '<' is already removed parseTagName returns {Name, Tail}, where Name = {Prefix, LocalName, QualifiedName} To do: introduce a parameter that indicates whether we are using namespaces. this should differentiate between 'with namespaces'and 'without' for the moment the assumption is 'with', therefore a name cannot start with a ':'. Head is the prefix returns {Name, Tail, State} returns: {attributes, Attributes, Tail}} Attributes = list of {Name, Value} tuples, and Name = {Prefix, LocalName, QualifiedName}. parseAttribute([NextChar], Tail, State), parseAttribute([Char], Tail2, State2), returns {value, Value, Tail, State} depending on the context (attribute or definition) the handling of entities is slightly different. ' ' TODO: this can be generalized, for example parsing up to the = sign in an attribute value is exactly the same. previous char was '<' call callback - events, but that is legal according to the sax doc. this should be the endTag Call the call back functions for the end tag Call the call back functions Call the call back function TODO: check the order of the namespaces parseReference returns a list entity references in attribute values differ fundamentally from references in elements and in entity definitions Context can be: element, attribute, definition Character entities are added to the 'head' (the bit that was parsed already), other entities are added to the tail (they still have to be parsed). The problem here is that we have to make sure that we don't get into an infinite loop. This solved as follows: We proceed by parsing only the entity (while registering in the state that we are parsing this particular entity). However, we replace the continuation function by something that simply returns (in stead of calling the function that it was working on recursively). We then proceed. Before starting to work on this entity, we need to check that we are not already parsing this entity (because that would mean an infinite loop). in the context of a definition, character references have to be replaced (and others not). hex number of char's code point unfortunately this function accepts illegal values to do: replace by something that throws an error in case of an illegal value dec number of char's code point to do: check on legal character. check on circular definition don't replace replace, add to the parsed text (head) element or parameter replace, encode again and put back into the input stream (Tail) apostrof quote TODO: proper encoding parseText(Tail, #erlsom_sax_state{output = 'utf8'} = State) -> parseTextBinary(?EMPTY, Tail, State); parseText([], Tail, State). , Tail), Quote, Head, Context, State) -> %% Internet Explorer... Can't find this in the standard, but it is an unlikely thing to happen in a bonafide xml, and it avoids some problems with circular definitions | Head], Context, State) parseReference returns a list (only 1 char long - in case of a user defined entity this will be put in front of tail!) , Tail), Quote, Head, Context, State) -> %% >>, Context, State) the start tag is decoded (it is a list of unicode code points) Attributes = list of Attribute Attribute = {{Prefix, LocalName} Value} returns: {Name, Attributes2, NewNamespaces} Name = {URI, LocalName, QualifiedName} Attribute2 = #attribute Namespaces are in such an order that namespace of the 'closest ancestors' are in front. That way the right element will be found, even if a prefix is used more than once in the document. find the namespace definitions in the attributes add the URIs to the attribute names (if applicable) returns {Namespaces, OtherAttributes}, where Namespaces = a list of tuples {Prefix, URI} OtherAttributes = a list of tuples {Name, Value} Namespaces = list of {Prefix, URI} (prefix can be []). TODO: error if not found? special treatment of 'xml:lang'? Attributes = list of Attribute Attribute = {{Prefix, LocalName} Value} Namespaces = list of {Prefix, URI} (prefix can be []). Returns a list of #attribute records AttributeName = {Prefix, LocalName, QualifiedName} Namespaces = list of {Prefix, URI} (prefix can be []). Difference with TagNameTuple: attributes without prefix do NOT belong to the default namespace.
Copyright ( C ) 2006 - 2008 This file is part of Erlsom . Erlsom is free software : you can redistribute it and/or modify published by the Free Software Foundation , either version 3 of the License , or ( at your option ) any later version . Erlsom is distributed in the hope that it will be useful , GNU Lesser General Public License for more details . You should have received a copy of the GNU Lesser General Public License along with Erlsom . If not , see An XML parser , using the SAX model . The only difference to the content of these 2 files is the definition below : it can be UTF8 , LAT1 , LAT9 , U16B or U16L. ( The names have been chosen so that the -define(U16L, true). -ifdef(UTF8). -module(erlsom_sax_utf8). -define(BINARY, true). -define(STR1(X), <<X>>). -define(STR2(X1, X2), <<X1, X2>>). -define(STR3(X1, X2, X3), <<X1, X2, X3>>). -define(STR4(X1, X2, X3, X4), <<X1, X2, X3, X4>>). -define(STR5(X1, X2, X3, X4, X5), <<X1, X2, X3, X4, X5>>). -define(STR6(X1, X2, X3, X4, X5, X6), <<X1, X2, X3, X4, X5, X6>>). -define(STR7(X1, X2, X3, X4, X5, X6, X7), <<X1, X2, X3, X4, X5, X6, X7>>). -define(STR8(X1, X2, X3, X4, X5, X6, X7, X8), <<X1, X2, X3, X4, X5, X6, X7, X8>>). -define(DONTCARE_T(Y), <<_, Y/binary>>). -define(STR1_T(X, Y), <<X, Y/binary>>). -define(STR2_T(X1, X2, Y), <<X1, X2, Y/binary>>). -define(STR3_T(X1, X2, X3, Y), <<X1, X2, X3, Y/binary>>). -define(STR4_T(X1, X2, X3, X4, Y), <<X1, X2, X3, X4, Y/binary>>). -define(STR7_T(X1, X2, X3, X4, X5, X6, X7, Y), <<X1, X2, X3, X4, X5, X6, X7, Y/binary>>). -define(STR8_T(X1, X2, X3, X4, X5, X6, X7, X8, Y), <<X1, X2, X3, X4, X5, X6, X7, X8, Y/binary>>). -define(STR9_T(X1, X2, X3, X4, X5, X6, X7, X8, X9, Y), <<X1, X2, X3, X4, X5, X6, X7, X8, X9, Y/binary>>). -define(BOM1(X), <<16#EF, 16#BB, 16#BF, X/binary>>). -define(BOM2, <<16#EF, 16#BB>>). -define(BOM3, <<16#EF>>). -endif. -ifdef(U16B). -module(erlsom_sax_utf16be). -define(BINARY, true). -define(STR1(X), <<0, X>>). -define(STR2(X1, X2), <<0, X1, 0, X2>>). -define(STR3(X1, X2, X3), <<0, X1, 0, X2, 0, X3>>). -define(STR4(X1, X2, X3, X4), <<0, X1, 0, X2, 0, X3, 0, X4>>). -define(STR5(X1, X2, X3, X4, X5), <<0, X1, 0, X2, 0, X3, 0, X4, 0, X5>>). -define(STR6(X1, X2, X3, X4, X5, X6), <<0, X1, 0, X2, 0, X3, 0, X4, 0, X5, 0, X6>>). -define(STR7(X1, X2, X3, X4, X5, X6, X7), <<0, X1, 0, X2, 0, X3, 0, X4, 0, X5, 0, X6, 0, X7>>). -define(STR8(X1, X2, X3, X4, X5, X6, X7, X8), <<0, X1, 0, X2, 0, X3, 0, X4, 0, X5, 0, X6, 0, X7, 0, X8>>). -define(DONTCARE_T(Y), <<_, _, Y/binary>>). -define(STR1_T(X, Y), <<0, X, Y/binary>>). -define(STR2_T(X1, X2, Y), <<0, X1, 0, X2, Y/binary>>). -define(STR3_T(X1, X2, X3, Y), <<0, X1, 0, X2, 0, X3, Y/binary>>). -define(STR4_T(X1, X2, X3, X4, Y), <<0, X1, 0, X2, 0, X3, 0, X4, Y/binary>>). -define(STR7_T(X1, X2, X3, X4, X5, X6, X7, Y), <<0, X1, 0, X2, 0, X3, 0, X4, 0, X5, 0, X6, 0, X7, Y/binary>>). -define(STR8_T(X1, X2, X3, X4, X5, X6, X7, X8, Y), <<0, X1, 0, X2, 0, X3, 0, X4, 0, X5, 0, X6, 0, X7, 0, X8, Y/binary>>). -define(STR9_T(X1, X2, X3, X4, X5, X6, X7, X8, X9, Y), <<0, X1, 0, X2, 0, X3, 0, X4, 0, X5, 0, X6, 0, X7, 0, X8, 0, X9, Y/binary>>). -define(BOM1(X), <<16#FE, 16#FF, X/binary>>). -define(BOM2, <<16#FE>>). -define(BOM3, no_match). -endif. -ifdef(U16L). -module(erlsom_sax_utf16le). -define(BINARY, true). -define(STR1(X), <<X, 0>>). -define(STR2(X1, X2), <<X1, 0, X2, 0>>). -define(STR3(X1, X2, X3), <<X1, 0, X2, 0, X3, 0>>). -define(STR4(X1, X2, X3, X4), <<X1, 0, X2, 0, X3, 0, X4, 0>>). -define(STR5(X1, X2, X3, X4, X5), <<X1, 0, X2, 0, X3, 0, X4, 0, X5, 0>>). -define(STR6(X1, X2, X3, X4, X5, X6), <<X1, 0, X2, 0, X3, 0, X4, 0, X5, 0, X6, 0>>). -define(STR7(X1, X2, X3, X4, X5, X6, X7), <<X1, 0, X2, 0, X3, 0, X4, 0, X5, 0, X6, 0, X7, 0>>). -define(STR8(X1, X2, X3, X4, X5, X6, X7, X8), <<X1, 0, X2, 0, X3, 0, X4, 0, X5, 0, X6, 0, X7, 0, X8, 0>>). -define(DONTCARE_T(Y), <<_, _, Y/binary>>). -define(STR1_T(X, Y), <<X, 0, Y/binary>>). -define(STR2_T(X1, X2, Y), <<X1, 0, X2, 0, Y/binary>>). -define(STR3_T(X1, X2, X3, Y), <<X1, 0, X2, 0, X3, 0, Y/binary>>). -define(STR4_T(X1, X2, X3, X4, Y), <<X1, 0, X2, 0, X3, 0, X4, 0, Y/binary>>). -define(STR7_T(X1, X2, X3, X4, X5, X6, X7, Y), <<X1, 0, X2, 0, X3, 0, X4, 0, X5, 0, X6, 0, X7, 0, Y/binary>>). -define(STR8_T(X1, X2, X3, X4, X5, X6, X7, X8, Y), <<X1, 0, X2, 0, X3, 0, X4, 0, X5, 0, X6, 0, X7, 0, X8, 0, Y/binary>>). -define(STR9_T(X1, X2, X3, X4, X5, X6, X7, X8, X9, Y), <<X1, 0, X2, 0, X3, 0, X4, 0, X5, 0, X6, 0, X7, 0, X8, 0, X9, 0, Y/binary>>). -define(BOM1(X), <<16#FF, 16#FE, X/binary>>). -define(BOM2, <<16#FF>>). -define(BOM3, no_match). -endif. -ifdef(LAT1). -module(erlsom_sax_latin1). -define(BINARY, true). -define(STR1(X), <<X>>). -define(STR2(X1, X2), <<X1, X2>>). -define(STR3(X1, X2, X3), <<X1, X2, X3>>). -define(STR4(X1, X2, X3, X4), <<X1, X2, X3, X4>>). -define(STR5(X1, X2, X3, X4, X5), <<X1, X2, X3, X4, X5>>). -define(STR6(X1, X2, X3, X4, X5, X6), <<X1, X2, X3, X4, X5, X6>>). -define(STR7(X1, X2, X3, X4, X5, X6, X7), <<X1, X2, X3, X4, X5, X6, X7>>). -define(STR8(X1, X2, X3, X4, X5, X6, X7, X8), <<X1, X2, X3, X4, X5, X6, X7, X8>>). -define(DONTCARE_T(Y), <<_, Y/binary>>). -define(STR1_T(X, Y), <<X, Y/binary>>). -define(STR2_T(X1, X2, Y), <<X1, X2, Y/binary>>). -define(STR3_T(X1, X2, X3, Y), <<X1, X2, X3, Y/binary>>). -define(STR4_T(X1, X2, X3, X4, Y), <<X1, X2, X3, X4, Y/binary>>). -define(STR7_T(X1, X2, X3, X4, X5, X6, X7, Y), <<X1, X2, X3, X4, X5, X6, X7, Y/binary>>). -define(STR8_T(X1, X2, X3, X4, X5, X6, X7, X8, Y), <<X1, X2, X3, X4, X5, X6, X7, X8, Y/binary>>). -define(STR9_T(X1, X2, X3, X4, X5, X6, X7, X8, X9, Y), <<X1, X2, X3, X4, X5, X6, X7, X8, X9, Y/binary>>). -define(BOM1(X), [no_match | X]). -define(BOM2, no_match). -define(BOM3, no_match2). -endif. -ifdef(LAT9). -module(erlsom_sax_latin9). -define(BINARY, true). -define(STR1(X), <<X>>). -define(STR2(X1, X2), <<X1, X2>>). -define(STR3(X1, X2, X3), <<X1, X2, X3>>). -define(STR4(X1, X2, X3, X4), <<X1, X2, X3, X4>>). -define(STR5(X1, X2, X3, X4, X5), <<X1, X2, X3, X4, X5>>). -define(STR6(X1, X2, X3, X4, X5, X6), <<X1, X2, X3, X4, X5, X6>>). -define(STR7(X1, X2, X3, X4, X5, X6, X7), <<X1, X2, X3, X4, X5, X6, X7>>). -define(STR8(X1, X2, X3, X4, X5, X6, X7, X8), <<X1, X2, X3, X4, X5, X6, X7, X8>>). -define(DONTCARE_T(Y), <<_, Y/binary>>). -define(STR1_T(X, Y), <<X, Y/binary>>). -define(STR2_T(X1, X2, Y), <<X1, X2, Y/binary>>). -define(STR3_T(X1, X2, X3, Y), <<X1, X2, X3, Y/binary>>). -define(STR4_T(X1, X2, X3, X4, Y), <<X1, X2, X3, X4, Y/binary>>). -define(STR7_T(X1, X2, X3, X4, X5, X6, X7, Y), <<X1, X2, X3, X4, X5, X6, X7, Y/binary>>). -define(STR8_T(X1, X2, X3, X4, X5, X6, X7, X8, Y), <<X1, X2, X3, X4, X5, X6, X7, X8, Y/binary>>). -define(STR9_T(X1, X2, X3, X4, X5, X6, X7, X8, X9, Y), <<X1, X2, X3, X4, X5, X6, X7, X8, X9, Y/binary>>). -define(BOM1(X), [no_match | X]). -define(BOM2, no_match). -define(BOM3, no_match2). -endif. -ifdef(LIST). -module(erlsom_sax_list). -define(EMPTY, []). -define(STR1(X), [X]). -define(STR2(X1, X2), [X1, X2]). -define(STR3(X1, X2, X3), [X1, X2, X3]). -define(STR4(X1, X2, X3, X4), [X1, X2, X3, X4]). -define(STR5(X1, X2, X3, X4, X5), [X1, X2, X3, X4, X5]). -define(STR6(X1, X2, X3, X4, X5, X6), [X1, X2, X3, X4, X5, X6]). -define(STR7(X1, X2, X3, X4, X5, X6, X7), [X1, X2, X3, X4, X5, X6, X7]). -define(STR8(X1, X2, X3, X4, X5, X6, X7, X8), [X1, X2, X3, X4, X5, X6, X7, X8]). -define(DONTCARE_T(Y), [_ | Y]). -define(STR1_T(X, Y), [X | Y]). -define(STR2_T(X1, X2, Y), [X1, X2 | Y]). -define(STR3_T(X1, X2, X3, Y), [X1, X2, X3 | Y]). -define(STR4_T(X1, X2, X3, X4, Y), [X1, X2, X3, X4 | Y]). -define(STR7_T(X1, X2, X3, X4, X5, X6, X7, Y), [X1, X2, X3, X4, X5, X6, X7 |Y]). -define(STR8_T(X1, X2, X3, X4, X5, X6, X7, X8, Y), [X1, X2, X3, X4, X5, X6, X7, X8 | Y]). -define(BOM1(X), [65279 | X]). -define(BOM2, no_match). -define(BOM3, no_match2). -endif. -ifdef(BINARY). -define(EMPTY, <<>>). -endif. -define(CF3(A, B, C), erlsom_sax_lib:continueFun(A, B, C)). -define(CF4(A, B, C, D), erlsom_sax_lib:continueFun(A, B, C, D)). -define(CF4_2(A, B, C, D), erlsom_sax_lib:continueFun2(A, B, C, D)). -define(CF5(A, B, C, D, E), erlsom_sax_lib:continueFun(A, B, C, D, E)). -define(CF6(A, B, C, D, E, F), erlsom_sax_lib:continueFun(A, B, C, D, E, F)). -define(CF6_2(A, B, C, D, E, F), erlsom_sax_lib:continueFun2(A, B, C, D, E, F)). -include("erlsom_sax.hrl"). -export([parse/2]). parse(Xml, State) -> State2 = wrapCallback(startDocument, State), {State3, Tail} = parseProlog(Xml, State2), State4 = wrapCallback(endDocument, State3), {ok, State4#erlsom_sax_state.user_state, Tail}. returns { State , Tail } parseProlog(?EMPTY, State) -> ?CF3(?EMPTY, State, fun parseProlog/2); parseProlog(?STR1($<), State) -> ?CF3(?STR1($<), State, fun parseProlog/2); parseProlog(?STR2_T($<, $?, Tail), State) -> {processinginstruction, Target, Data, Tail2, State2} = parseProcessingInstruction(Tail, State), State3 = wrapCallback({processingInstruction, Target, lists:reverse(Data)}, State2), parseProlog(Tail2, State3); parseProlog(?STR2_T($<, $!, Tail) = T, State) -> case Tail of ?STR2_T($-, $-, Tail2) -> {comment, Tail3, State2} = parseComment(Tail2, State), parseProlog(Tail3, State2); ?STR7_T($D, $O, $C, $T, $Y, $P, $E, Tail2) -> {dtd, Tail3, State2} = parseDTD(Tail2, State), parseProlog(Tail3, State2); ?STR6($D, $O, $C, $T, $Y, $P) -> ?CF3(T, State, fun parseProlog/2); ?STR5($D, $O, $C, $T, $Y) -> ?CF3(T, State, fun parseProlog/2); ?STR4($D, $O, $C, $T) -> ?CF3(T, State, fun parseProlog/2); ?STR3($D, $O, $C) -> ?CF3(T, State, fun parseProlog/2); ?STR2($D, $O) -> ?CF3(T, State, fun parseProlog/2); ?STR1($D) -> ?CF3(T, State, fun parseProlog/2); ?STR1($-) -> ?CF3(T, State, fun parseProlog/2); ?EMPTY -> ?CF3(T, State, fun parseProlog/2); _ -> throw({error, "Malformed: Illegal character in prolog"}) end; parseProlog(?STR1_T($<, Tail), State) -> parseContentLT(Tail, State); parseProlog(?STR1_T(NextChar, Tail), State) when ?is_whitespace(NextChar) -> parseProlog(Tail, State); parseProlog(?BOM1(Tail), State) -> parseProlog(Tail, State); parseProlog(?BOM2, State) -> ?CF3(?BOM2, State, fun parseProlog/2); parseProlog(?BOM3, State) -> ?CF3(?BOM3, State, fun parseProlog/2); parseProlog(_Tail, _) -> throw({error, "Malformed: Illegal character in prolog"}). -ifdef(UTF8). Tail = the rest of the XML returns , Tail2 , State2 } decodeChar(Tail, State) -> case Tail of ?EMPTY -> ?CF3(?EMPTY, State, fun decodeChar/2); <<C1, Tail2/binary>> when C1 < 16#80 -> {C1, Tail2, State}; <<C1, C2, Tail2/binary>> when C1 band 16#E0 =:= 16#C0, C2 band 16#C0 =:= 16#80 -> {decode2(C1, C2), Tail2, State}; <<C1>> when C1 band 16#E0 =:= 16#C0 -> ?CF3(<<C1>>, State, fun decodeChar/2); <<C1, C2, C3, Tail2/binary>> when C1 band 16#F0 =:= 16#E0, C2 band 16#C0 =:= 16#80, C3 band 16#C0 =:= 16#80 -> {decode3(C1, C2, C3), Tail2, State}; <<C1, C2>> when C1 band 16#F0 =:= 16#E0, C2 band 16#C0 =:= 16#80 -> ?CF3(<<C1, C2>>, State, fun decodeChar/2); <<C1>> when C1 band 16#F0 =:= 16#E0 -> ?CF3(<<C1>>, State, fun decodeChar/2); <<C1,C2,C3,C4, Tail2/binary>> when C1 band 16#F8 =:= 16#F0, C2 band 16#C0 =:= 16#80, C3 band 16#C0 =:= 16#80, C4 band 16#C0 =:= 16#80 -> {decode4(C1, C2, C3, C4), Tail2, State}; <<C1,C2,C3>> when C1 band 16#F8 =:= 16#F0, C2 band 16#C0 =:= 16#80, C3 band 16#C0 =:= 16#80 -> ?CF3(<<C1, C2, C3>>, State, fun decodeChar/2); <<C1,C2>> when C1 band 16#F8 =:= 16#F0, C2 band 16#C0 =:= 16#80 -> ?CF3(<<C1, C2>>, State, fun decodeChar/2); <<C1>> when C1 band 16#F8 =:= 16#F0 -> ?CF3(<<C1>>, State, fun decodeChar/2); <<_C1, _C2>> -> throw({error, "Decoding error: illegal UTF-8 encoding"}) end. decodes an UTF-8 encoded character that consists of 2 bytes . decode2(C1, C2) -> case ((C1 band 16#1F) bsl 6) bor (C2 band 16#3F) of C when 16#80 =< C -> C; _ -> throw({error, "Decoding error: illegal UTF-8 encoding"}) end. decode3(C1, C2, C3) -> case ((((C1 band 16#0F) bsl 6) bor (C2 band 16#3F)) bsl 6) bor (C3 band 16#3F) of C when 16#800 =< C -> C; _ -> throw({error, "Decoding error: illegal UTF-8 encoding"}) end. decode4(C1, C2, C3, C4) -> case ((((((C1 band 16#0F) bsl 6) bor (C2 band 16#3F)) bsl 6) bor (C3 band 16#3F)) bsl 6) bor (C4 band 16#3F) of C when 16#10000 =< C -> C; _ -> throw({error, "Decoding error: illegal UTF-8 encoding"}) end. -endif. -ifdef(U16B). decodeChar(Tail, State) -> case Tail of ?EMPTY -> ?CF3(Tail, State, fun decodeChar/2); <<_>> -> ?CF3(Tail, State, fun decodeChar/2); <<C1, C2, Tail2/binary>> when C1 < 16#D8; C1 > 16#DF -> {C1 * 256 + C2, Tail2, State}; <<_Hi1, _Hi2, _Lo1>> -> ?CF3(Tail, State, fun decodeChar/2); <<Hi1, Hi2, Lo1, Lo2, Tail2/binary>> when Hi1 >= 16#D8, Hi1 < 16#DC, Lo1 >= 16#DC, Lo1 < 16#E0 -> Hi = Hi1 * 256 + Hi2, Lo = Lo1 * 256 + Lo2, Ch = ((Hi band 16#3FF) bsl 10) + (Lo band 16#3FF) + 16#10000, {Ch, Tail2, State}; <<Hi1, _Hi2>> when Hi1 >= 16#D8, Hi1 < 16#DC -> ?CF3(Tail, State, fun decodeChar/2); _ -> {error,not_utf16be} end. -endif. -ifdef(U16L). decodeChar(Tail, State) -> case Tail of ?EMPTY -> ?CF3(Tail, State, fun decodeChar/2); <<_>> -> ?CF3(Tail, State, fun decodeChar/2); <<C1, C2, Tail2/binary>> when C2 < 16#D8; C2 > 16#DF -> {C2 * 256 + C1, Tail2, State}; <<_Hi1, _Hi2, _Lo1>> -> ?CF3(Tail, State, fun decodeChar/2); <<Hi1, Hi2, Lo1, Lo2, Tail2/binary>> when Hi2 >= 16#D8, Hi2 < 16#DC, Lo2 >= 16#DC, Lo2 < 16#E0 -> Hi = Hi2 * 256 + Hi1, Lo = Lo2 * 256 + Lo1, Ch = ((Hi band 16#3FF) bsl 10) + (Lo band 16#3FF) + 16#10000, {Ch, Tail2, State}; <<_Hi1, Hi2>> when Hi2 >= 16#D8, Hi2 < 16#DC -> ?CF3(Tail, State, fun decodeChar/2); _ -> {error,not_utf16le} end. -endif. -ifdef(LAT1). decodeChar(Tail, State) -> case Tail of ?EMPTY -> ?CF3(Tail, State, fun decodeChar/2); ?STR1_T(C, T) -> {C, T, State} end. -endif. -ifdef(LAT9). decodeChar(Tail, State) -> case Tail of ?EMPTY -> ?CF3(Tail, State, fun decodeChar/2); ?STR1_T(C, T) -> {latin9toUnicode(C), T, State} end. 16#20AC; 16#0160; 16#0161; 16#017D; 16#017E; 16#0152; 16#0153; LATIN CAPITAL LETTER Y WITH 16#0178; latin9toUnicode(Char) -> Char. -endif. -ifdef(LIST). decodeChar(Tail, State) -> case Tail of ?EMPTY -> ?CF3(Tail, State, fun decodeChar/2); ?STR1_T(C, T) -> {C, T, State} end. -endif. returns , CData , Tail } parseCDATA(Head, Tail0, State) -> case Tail0 of ?STR3_T($], $], $>, Tail) -> {cdata, lists:reverse(Head), Tail, State}; ?STR2($], $]) -> ?CF4(Head, ?STR2($], $]), State, fun parseCDATA/3); ?STR1($]) -> ?CF4(Head, ?STR1($]), State, fun parseCDATA/3); ?STR1_T(NextChar, Tail) when NextChar < 16#80 -> parseCDATA([NextChar | Head], Tail, State); ?EMPTY -> ?CF4(Head, ?EMPTY, State, fun parseCDATA/3); _ -> {Char, Tail2, State2} = decodeChar(Tail0, State), parseCDATA([Char | Head], Tail2, State2) end. parseDTD(?STR1_T($[, Tail), State) -> {intSubset, Tail2, State2} = parseIntSubset(Tail, State), parseDTD(Tail2, State2); parseDTD(?STR1_T($>, Tail), State) -> {dtd, Tail, State}; parseDTD(?DONTCARE_T(Tail), State) -> parseDTD(Tail, State); parseDTD(?EMPTY, State) -> ?CF3(?EMPTY, State, fun parseDTD/2). parseIntSubset(?STR1_T($], Tail), State) -> {intSubset, Tail, State}; parseIntSubset(?STR1_T(NextChar, Tail), State) when ?is_whitespace(NextChar) -> parseIntSubset(Tail, State); parseIntSubset(?STR8_T($<, $!, $E, $N, $T, $I, $T, $Y, Tail), State) -> case parseEntity(Tail, State) of {Tail2, State2} -> parseIntSubset(Tail2, State2); Other -> Other end; parseIntSubset(?STR7($<, $!, $E, $N, $T, $I, $T) = T, State) -> ?CF3(T, State, fun parseIntSubset/2); parseIntSubset(?STR6($<, $!, $E, $N, $T, $I) = T, State) -> ?CF3(T, State, fun parseIntSubset/2); parseIntSubset(?STR5($<, $!, $E, $N, $T) = T, State) -> ?CF3(T, State, fun parseIntSubset/2); parseIntSubset(?STR4($<, $!, $E, $N) = T, State) -> ?CF3(T, State, fun parseIntSubset/2); parseIntSubset(?STR3($<, $!, $E) = T, State) -> ?CF3(T, State, fun parseIntSubset/2); parseIntSubset(?STR2($<, $!) = T, State) -> ?CF3(T, State, fun parseIntSubset/2); parseIntSubset(?STR1($<) = T, State) -> ?CF3(T, State, fun parseIntSubset/2); parseIntSubset(?STR4_T($<, $!, $-, $-, Tail), State) -> {comment, Tail2, State2} = parseComment(Tail, State), parseIntSubset(Tail2, State2); parseIntSubset(?STR3($<, $!, $-) = T, State) -> ?CF3(T, State, fun parseIntSubset/2); {Head, Tail2, State2} = parseReference([], parameter, Tail, State), parseIntSubset(Head ++ Tail2, State2); parseIntSubset(?STR1_T($<, Tail), State) -> parseMarkupDecl(Tail, State); parseIntSubset(?EMPTY, State) -> ?CF3(?EMPTY, State, fun parseIntSubset/2). parseMarkupDecl(?STR1_T($>, Tail), State) -> parseIntSubset(Tail, State); parseMarkupDecl(?STR1_T($", Tail), State) -> %" {value, _, Tail2, State2} = parseLiteralValue(Tail, $", [], definition, State), %" parseMarkupDecl(Tail2, State2); parseMarkupDecl(Tail2, State2); parseMarkupDecl(?STR1_T(_, Tail), State) -> parseMarkupDecl(Tail, State); parseMarkupDecl(?EMPTY, State) -> ?CF3(?EMPTY, State, fun parseMarkupDecl/2). { Tail2 , State2 } , where the parsed entity has been added to the State parseEntity(?STR1_T(NextChar, Tail), State) when ?is_whitespace(NextChar) -> parseEntity(Tail, State); parseEntity(?STR1_T(NextChar, _) = Tail, State) when ?is_namestart_char(NextChar) -> parseEntityName(Tail, State); parseEntity(?EMPTY, State) -> ?CF3(?EMPTY, State, fun parseEntity/2); parseEntity(Tail, State) -> parseEntityName(Tail, State). { , _ Tail2 , State2 } = decodeChar(Tail , State ) , case of _ when ? is_namestart_char2(Char ) - > parseEntityName(Tail, State = #erlsom_sax_state{max_entity_size = MaxSize, max_nr_of_entities = MaxNr, output = OutputEncoding, entities = EntitiesSoFar, par_entities = ParEntitiesSoFar}) -> CurrentEntity = State#erlsom_sax_state.current_entity, {Type, Tail2, State2} = getType(Tail, State), {Name, Tail3, State3} = parseNameNoNamespaces(Tail2, State2), {value, Value, Tail4, State4} = parseLiteral(definition, Tail3, State3#erlsom_sax_state{current_entity = Name}), if length(EntitiesSoFar) + length(ParEntitiesSoFar) >= MaxNr -> throw({error, "Too many entities defined"}); true -> ok end, ValueAsList = case OutputEncoding of 'utf8' -> erlsom_ucs:decode_utf8(Value); _ -> Value end, if length(ValueAsList) > MaxSize -> throw({error, "Entity too long"}); true -> ok end, {Tail5, State5} = parseEndHook(Tail4, State4), case Type of general -> State6 = State5#erlsom_sax_state{ if an entity is declared twice , the first definition should be used . entities = EntitiesSoFar ++ [{Name, ValueAsList}], current_entity = CurrentEntity}; parameter -> State6 = State5#erlsom_sax_state{ par_entities = ParEntitiesSoFar ++ [{Name, ValueAsList}]} end, {Tail5, State6}. getType(?STR1_T(NextChar, Tail), State) when ?is_whitespace(NextChar) -> getType(Tail, State); , NextChar , Tail ) , State ) when ?is_whitespace(NextChar) -> {parameter, Tail, State}; getType(?EMPTY, State) -> ?CF3(?EMPTY, State, fun getType/2); getType(Tail, State) -> {general, Tail, State}. parseComment(?STR1_T($-, Tail), State) -> case Tail of ?STR2_T($-, $>, Tail2) -> {comment, Tail2, State}; ?STR1($-) -> ?CF3(?STR2($-, $-), State, fun parseComment/2); ?EMPTY -> ?CF3(?STR1($-), State, fun parseComment/2); ?STR1_T($-, _) -> throw({error, "Malformed: -- not allowed in comment"}); _ -> parseComment(Tail, State) end; parseComment(?DONTCARE_T(Tail), State) -> parseComment(Tail, State); parseComment(?EMPTY, State) -> ?CF3(?EMPTY, State, fun parseComment/2). returns { processinginstruction , Target , Data , Tail } parseProcessingInstruction(Tail, State) -> {Target, Tail2, State2} = parseNameNoNamespaces(Tail, State), {Data, Tail3, State3} = parsePIData([], Tail2, State2), {processinginstruction, Target, Data, Tail3, State3}. parsePIData(Head, Tail, State) -> case Tail of ?STR2_T($?, $>, Tail2) -> {Head, Tail2, State}; ?STR1($?) -> ?CF4(Head, ?STR1($?), State, fun parsePIData/3); ?STR1_T(NextChar, Tail2) when NextChar < 16#80 -> parsePIData([NextChar | Head], Tail2, State); ?EMPTY -> ?CF4(Head, ?EMPTY, State, fun parsePIData/3); _ -> {Char, Tail2, State2} = decodeChar(Tail, State), parsePIData([Char | Head], Tail2, State2) end. returns State mapStartPrefixMappingCallback([{Prefix, Uri} | Tail], State) -> mapStartPrefixMappingCallback(Tail, wrapCallback({startPrefixMapping, Prefix, Uri}, State)); mapStartPrefixMappingCallback([], State) -> State. returns State mapEndPrefixMappingCallback([{Prefix, _Uri} | Tail], State) -> mapEndPrefixMappingCallback(Tail, wrapCallback({endPrefixMapping, Prefix}, State)); mapEndPrefixMappingCallback([], State) -> State. returns { starttag , , Attributes , Tail } or { emptyelement , , Attributes , Tail } where = { Prefix , LocalName , QualifiedName } parseStartTag(Tail, State) -> parseTagName(Tail, State). parseTagName(?STR1_T(Char, Tail), State) when ?is_namestart_char(Char) -> parseTagName([Char], Tail, State); parseTagName(?EMPTY, State) -> ?CF3(?EMPTY, State, fun parseTagName/2); parseTagName(Tail, State) -> {Char, Tail2, State2} = decodeChar(Tail, State), case Char of _ when ?is_namestart_char2(Char) -> parseTagName([Char], Tail2, State2); _ -> throw({error, "Malformed: Illegal character in tag"}) end. parseTagName(Head, ?STR1_T(NextChar, Tail), State) when ?is_name_char(NextChar) -> parseTagName([NextChar | Head], Tail, State); parseTagName(Head, ?STR1_T($:, Tail), State) -> parseTagName(Head, [], Tail, State); parseTagName(Head, ?STR1_T($>, Tail), State) -> LocalName = lists:reverse(Head), {starttag, {[], LocalName, LocalName}, [], Tail, State}; parseTagName(Head, ?STR2_T($/, $>, Tail), State) -> LocalName = lists:reverse(Head), {emptyelement, {[], LocalName, LocalName}, [], Tail, State}; parseTagName(Head, ?STR1_T(NextChar, Tail), State) when ?is_whitespace(NextChar) -> LocalName = lists:reverse(Head), parseAttributes({[], LocalName, LocalName}, [], Tail, State); parseTagName(Head, ?STR1($/), State) -> ?CF4(Head, ?STR1($/), State, fun parseTagName/3); parseTagName(Head, ?EMPTY, State) -> ?CF4(Head, ?EMPTY, State, fun parseTagName/3); parseTagName(Head, Tail, State) -> {Char, Tail2, State2} = decodeChar(Tail, State), if ?is_name_char2(Char) -> parseTagName([Char | Head], Tail2, State2); true -> throw({error, "Malformed: Illegal character in tag"}) end. should there be another check on the first character of the local name ? parseTagName(Prefix, Head, ?STR1_T(NextChar, Tail), State) when ?is_name_char(NextChar) -> parseTagName(Prefix, [NextChar | Head], Tail, State); parseTagName(Prefix, Head, ?STR1_T(NextChar, Tail), State) when ?is_whitespace(NextChar) -> Pf = lists:reverse(Prefix), Hd = lists:reverse(Head), parseAttributes({Pf, Hd, lists:append([Pf, ":", Hd])}, [], Tail, State); parseTagName(Prefix, Head, ?STR1_T($>, Tail), State) -> Pf = lists:reverse(Prefix), Hd = lists:reverse(Head), {starttag, {Pf, Hd, lists:append([Pf, ":", Hd])}, [], Tail, State}; parseTagName(Prefix, Head, ?STR2_T($/, $>, Tail), State) -> Pf = lists:reverse(Prefix), Hd = lists:reverse(Head), {emptyelement, {Pf, Hd, lists:append([Pf, ":", Hd])}, [], Tail, State}; parseTagName(Prefix, Head, ?EMPTY, State) -> ?CF5(Prefix, Head, ?EMPTY, State, fun parseTagName/4); parseTagName(Prefix, Head, ?STR1($/), State) -> ?CF5(Prefix, Head, ?STR1($/), State, fun parseTagName/4); parseTagName(Prefix, Head, Tail, State) -> {Char, Tail2, State2} = decodeChar(Tail, State), if ?is_name_char2(Char) -> parseTagName(Prefix, [Char | Head], Tail2, State2); true -> throw({error, "Malformed: Illegal character in tag"}) end. parseAttrName(Head, ?STR1_T($:, Tail), State) -> parseAttrName(Head, [], Tail, State); parseAttrName(Head, ?STR1_T(NextChar, Tail), State) when ?is_name_char(NextChar) -> parseAttrName([NextChar | Head], Tail, State); parseAttrName(Head, ?STR1_T($=, Tail), State) -> LocalName = lists:reverse(Head), {{[], LocalName, LocalName}, Tail, State}; parseAttrName(Head, ?STR1_T(NextChar, Tail), State) when ?is_whitespace(NextChar) -> LocalName = lists:reverse(Head), {Tail2, State2} = parseEqualSign(Tail, State), {{[], LocalName, LocalName}, Tail2, State2}; parseAttrName(Head, ?EMPTY, State) -> ?CF4(Head, ?EMPTY, State, fun parseAttrName/3); parseAttrName(Head, Tail, State) -> {Char, Tail2, State2} = decodeChar(Tail, State), if ?is_name_char2(Char) -> parseAttrName([Char | Head], Tail2, State2); true -> throw({error, "Malformed: Illegal character in attribute name"}) end. should there be another check on the first character of the local name ? parseAttrName(Prefix, Head, ?STR1_T(NextChar, Tail), State) when ?is_name_char(NextChar) -> parseAttrName(Prefix, [NextChar | Head], Tail, State); parseAttrName(Prefix, Head, ?STR1_T($=, Tail), State) -> Pf = lists:reverse(Prefix), Hd = lists:reverse(Head), {{Pf, Hd, lists:append([Pf, ":", Hd])}, Tail, State}; parseAttrName(Prefix, Head, ?STR1_T(NextChar, Tail), State) when ?is_whitespace(NextChar) -> Pf = lists:reverse(Prefix), Hd = lists:reverse(Head), {Tail2, State2} = parseEqualSign(Tail, State), {{Pf, Hd, lists:append([Pf, ":", Hd])}, Tail2, State2}; parseAttrName(Prefix, Head, ?EMPTY, State) -> ?CF5(Prefix, Head, ?EMPTY, State, fun parseAttrName/4); parseAttrName(Prefix, Head, Tail, State) -> {Char, Tail2, State2} = decodeChar(Tail, State), if ?is_name_char2(Char) -> parseAttrName(Prefix, [Char | Head], Tail2, State2); true -> throw({error, "Malformed: Illegal character in attribute name"}) end. parseNameNoNamespaces(?STR1_T(Char, Tail), State) when ?is_namestart_char(Char) -> parseNameNoNamespaces([Char], Tail, State); parseNameNoNamespaces(Tail, State) -> {Char, Tail2, State2} = decodeChar(Tail, State), if ?is_namestart_char2(Char) -> parseNameNoNamespaces([Char], Tail2, State2); true -> throw({error, "Malformed: Illegal character in name"}) end. parseNameNoNamespaces(Head, ?STR1_T(NextChar, Tail), State) when ?is_name_char(NextChar) -> parseNameNoNamespaces([NextChar | Head], Tail, State); parseNameNoNamespaces(Head, ?STR1_T($:, Tail), State) -> parseNameNoNamespaces([$: | Head], Tail, State); parseNameNoNamespaces(Head, T = ?STR1_T($>, _), State) -> {lists:reverse(Head), T, State}; parseNameNoNamespaces(Head, T = ?STR1_T($?, _), State) -> {lists:reverse(Head), T, State}; parseNameNoNamespaces(Head, T = ?STR1_T($=, _), State) -> {lists:reverse(Head), T, State}; parseNameNoNamespaces(Head, T = ?STR1_T(NextChar, _), State) when ?is_whitespace(NextChar) -> {lists:reverse(Head), T, State}; parseNameNoNamespaces(Head, ?EMPTY, State) -> ?CF4(Head, ?EMPTY, State, fun parseNameNoNamespaces/3); parseNameNoNamespaces(Head, Tail, State) -> {Char, Tail2, State2} = decodeChar(Tail, State), if ?is_name_char2(Char) -> parseNameNoNamespaces([Char | Head], Tail2, State2); true -> throw({error, "Malformed: Illegal character in name"}) end. parseAttributes(StartTag, Attributes, ?STR1_T($>, Tail), State) -> {starttag, StartTag, Attributes, Tail, State}; parseAttributes(StartTag, Attributes, ?STR1($/), State) -> ?CF5(StartTag, Attributes, ?STR1($/), State, fun parseAttributes/4); parseAttributes(StartTag, Attributes, ?STR2_T($/, $>, Tail), State) -> {emptyelement, StartTag, Attributes, Tail, State}; parseAttributes(StartTag, Attributes, ?STR1_T(NextChar, Tail), State) when ?is_whitespace(NextChar) -> parseAttributes(StartTag, Attributes, Tail, State); parseAttributes(StartTag, Attributes, ?STR1_T(NextChar, Tail), State) when ?is_namestart_char(NextChar) -> {AttributeName, Tail2, State2} = parseAttrName([NextChar], Tail, State), { attribute , Attribute , Tail3 , State3 } = {value, Value, Tail3, State3} = parseLiteral(attribute, Tail2, State2), { attribute , { AttributeName , Value } , Tail2 , State2 } ; parseAttributeValue(AttributeName , Tail2 , State2 ) , parseAttributes(StartTag, [{AttributeName, Value} | Attributes], Tail3, State3); parseAttributes(StartTag, Attributes, ?EMPTY, State) -> ?CF5(StartTag, Attributes, ?EMPTY, State, fun parseAttributes/4); parseAttributes(StartTag, Attributes, Tail, State) -> {Char, Tail2, State2} = decodeChar(Tail, State), case Char of _ when ?is_namestart_char2(Char) -> {AttributeName, Tail3, State3} = parseAttrName([Char], Tail2, State2), {value, Value, Tail4, State4} = parseLiteral(attribute, Tail3, State3), { attribute , Attribute , Tail3 , State3 } = parseAttributes(StartTag, [{AttributeName, Value} | Attributes], Tail4, State4); _ -> throw({error, "Malformed: Illegal character in name"}) end. parseLiteral(Context, ?STR1_T($", Tail), State) -> %" parseLiteralValue(Tail, $", Context, State); %" parseLiteral(Context, ?STR1_T(NextChar, Tail), State) when ?is_whitespace(NextChar) -> parseLiteral(Context, Tail, State); parseLiteral(Context, ?EMPTY, State) -> ?CF4(Context, ?EMPTY, State, fun parseLiteral/3); parseLiteral(_C, _T, _) -> throw({error, "Malformed: Illegal character in literal value"}). parseEndHook(?STR1_T($>, Tail), State) -> {Tail, State}; parseEndHook(?STR1_T(NextChar, Tail), State) when ?is_whitespace(NextChar) -> parseEndHook(Tail, State); parseEndHook(?EMPTY, State) -> ?CF3(?EMPTY, State, fun parseEndHook/2); parseEndHook(_Tail, _) -> throw({error, "Malformed: Illegal character in entity definition"}). parseEqualSign(?STR1_T($=, Tail), State) -> {Tail, State}; parseEqualSign(?STR1_T(NextChar, Tail), State) when ?is_whitespace(NextChar) -> parseEqualSign(Tail, State); parseEqualSign(?EMPTY, State) -> ?CF3(?EMPTY, State, fun parseEqualSign/2); parseEqualSign(_Tail, _) -> throw({error, "Malformed: Illegal character in attribute name"}). parseContentLT(?STR1_T($!, Tail), State) -> case Tail of ?STR2_T($-, $-, Tail3) -> {comment, Tail4, State2} = parseComment(Tail3, State), parseContent(Tail4, State2); ?STR1($-) -> ?CF3(?STR2($!, $-), State, fun parseContentLT/2); ?EMPTY -> ?CF3(?STR1($!), State, fun parseContentLT/2); ?STR7_T($[, $C, $D, $A, $T, $A, $[, Tail3) -> {cdata, CData, Tail4, State2} = parseCDATA([], Tail3, State), If Cdata is preceded and/or followed by text there will be 2 or 3 State3 = wrapCallback({characters, encodeOutput(CData, State)}, State2), parseContent(Tail4, State3); ?STR6($[, $C, $D, $A, $T, $A) -> ?CF3(?STR7($!, $[, $C, $D, $A, $T, $A), State, fun parseContentLT/2); ?STR5($[, $C, $D, $A, $T) -> ?CF3(?STR6($!, $[, $C, $D, $A, $T), State, fun parseContentLT/2); ?STR4($[, $C, $D, $A) -> ?CF3(?STR5($!, $[, $C, $D, $A), State, fun parseContentLT/2); ?STR3($[, $C, $D) -> ?CF3(?STR4($!, $[, $C, $D), State, fun parseContentLT/2); ?STR2($[, $C) -> ?CF3(?STR3($!, $[, $C), State, fun parseContentLT/2); ?STR1($[) -> ?CF3(?STR2($!, $[), State, fun parseContentLT/2) end; parseContentLT(?STR1_T($?, Tail), State) -> {processinginstruction, Target, Data, Tail3, State2} = parseProcessingInstruction(Tail, State), State3 = wrapCallback({processingInstruction, Target, lists:reverse(Data)}, State2), parseContent(Tail3, State3); parseContentLT(?STR1_T($/, Tail), State) -> [{QName, Uri, LocalName, Prefix, OldNamespaces, NewNamespaces} | EndTags2] = State#erlsom_sax_state.endtags, case parseEndTag(Tail, QName, State) of {ok, Tail3, State2} -> State3 = wrapCallback({endElement, Uri, LocalName, Prefix}, State2), State4 = mapEndPrefixMappingCallback(NewNamespaces, State3), State5 = State4#erlsom_sax_state{namespaces = OldNamespaces, endtags = EndTags2}, parseContent(Tail3, State5); error -> throw({error, "Malformed: Tags don't match"}) end; parseContentLT(?EMPTY, State) -> ?CF3(?EMPTY, State, fun parseContentLT/2); parseContentLT(Tail, State) -> Namespaces = State#erlsom_sax_state.namespaces, case parseStartTag(Tail, State) of {emptyelement, {Prefix, _LocalName, _QName}=StartTag, Attributes, Tail2, State2} -> {{Uri, LocalName, QName}, Attributes2, NewNamespaces} = createStartTagEvent(StartTag, Namespaces, Attributes), State3 = mapStartPrefixMappingCallback(NewNamespaces, State2), State4 = wrapCallback({startElement, Uri, LocalName, Prefix, Attributes2}, State3), State5 = wrapCallback({endElement, Uri, LocalName, QName}, State4), State6 = mapEndPrefixMappingCallback(NewNamespaces, State5), parseContent(Tail2, State6); {starttag, {Prefix, _LocalName, QName} = StartTag, Attributes, Tail2, State2} -> EndTags = State#erlsom_sax_state.endtags, {{Uri, LocalName, Prefix}, Attributes2, NewNamespaces} = createStartTagEvent(StartTag, Namespaces, Attributes), State3 = mapStartPrefixMappingCallback(NewNamespaces, State2), State4 = wrapCallback({startElement, Uri, LocalName, Prefix, Attributes2}, State3), State5 = State4#erlsom_sax_state{namespaces = NewNamespaces ++ Namespaces, endtags = [{QName, Uri, LocalName, Prefix, Namespaces, NewNamespaces} | EndTags]}, parseContent(Tail2, State5) end. parseContent(?STR1_T($<, Tail), #erlsom_sax_state{endtags = EndTags} = State) when EndTags /= [] -> parseContentLT(Tail, State); parseContent(?EMPTY, #erlsom_sax_state{endtags = EndTags} = State) -> case EndTags of [] -> This is the return value . The second element is what follows the XML document , as a list . {State, []}; _ -> ?CF3(?EMPTY, State, fun parseContent/2) end; parseContent(T, #erlsom_sax_state{endtags = EndTags} = State) -> case EndTags of [] -> This is the return value . The second element is what follows the XML document , as a list . {State, decode(T)}; _ -> {Tail2, State2} = parseText(T, State), parseContentLT(Tail2, State2) end. parseText(Tail, #erlsom_sax_state{output = 'utf8'} = State) -> parseTextBinary(<<>>, Tail, State); parseText(Tail, State) -> parseText([], Tail, State). parseText(Head, ?STR1_T($<, Tail), State) -> State2 = wrapCallback({ignorableWhitespace, lists:reverse(Head)}, State), {Tail, State2}; parseText(Head, ?STR1_T(NextChar, Tail), State) when ?is_whitespace(NextChar) -> parseText([NextChar | Head], Tail, State); parseText(Head, ?EMPTY, State) -> ?CF4(Head, ?EMPTY, State, fun parseText/3); parseText(Head, Tail, State) -> parseTextNoIgnore(Head, Tail, State). parseTextNoIgnore(Head, ?STR1_T($<, Tail), State) -> State2 = wrapCallback({characters, lists:reverse(Head)}, State), {Tail, State2}; parseTextNoIgnore(Head, ?STR1_T($&, Tail), State) -> {Head2, Tail2, State2} = parseReference([], element, Tail, State), parseTextNoIgnore(Head2 ++ Head, Tail2, State2); parseTextNoIgnore(Head, ?STR1_T(NextChar, Tail), State) when NextChar < 16#80 -> parseTextNoIgnore([NextChar|Head], Tail, State); parseTextNoIgnore(Head, ?EMPTY, State) -> ?CF4(Head, ?EMPTY, State, fun parseTextNoIgnore/3); parseTextNoIgnore(Head, Tail, State) -> {Char, Tail2, State2} = decodeChar(Tail, State), parseTextNoIgnore([Char | Head], Tail2, State2). parseTextBinary(Head, ?STR1_T($<, Tail), State) -> State2 = wrapCallback({ignorableWhitespace, Head}, State), {Tail, State2}; parseTextBinary(Head, ?STR1_T(NextChar, Tail), State) when ?is_whitespace(NextChar) -> parseTextBinary(<<Head/binary, NextChar>>, Tail, State); parseTextBinary(Head, ?EMPTY, State) -> ?CF4(Head, ?EMPTY, State, fun parseTextBinary/3); parseTextBinary(Head, Tail, State) -> parseTextNoIgnoreBinary(Head, Tail, State). parseTextNoIgnoreBinary(Head, ?STR1_T($<, Tail), State) -> State2 = wrapCallback({characters, Head}, State), {Tail, State2}; parseTextNoIgnoreBinary(Head, ?STR1_T($&, Tail), State) -> {Head2, Tail2, State2} = parseReference([], element, Tail, State), Head2Binary = list_to_binary(erlsom_ucs:to_utf8(lists:reverse(Head2))), parseTextNoIgnoreBinary(<<Head/binary, Head2Binary/binary>>, Tail2, State2); parseTextNoIgnoreBinary(Head, ?STR1_T(NextChar, Tail), State) when NextChar < 16#80 -> parseTextNoIgnoreBinary(<<Head/binary, NextChar>>, Tail, State); parseTextNoIgnoreBinary(Head, ?EMPTY, State) -> ?CF4(Head, ?EMPTY, State, fun parseTextNoIgnoreBinary/3); parseTextNoIgnoreBinary(Head, Tail, State) -> {Char, Tail2, State2} = decodeChar(Tail, State), EncodedChar = erlsom_ucs:char_to_utf8(Char), parseTextNoIgnoreBinary(<<Head/binary, EncodedChar/binary>>, Tail2, State2). parseReference(Head, Context, ?STR1_T($;, Tail), State) -> translateReference(lists:reverse(Head), Context, Tail, State); parseReference(Head, Context, ?STR1_T(NextChar, Tail), State) when NextChar < 16#80 -> parseReference([NextChar | Head], Context, Tail, State); parseReference(Head, Context, ?EMPTY, State) -> ?CF5(Head, Context, ?EMPTY, State, fun parseReference/4); parseReference(Head, Context, Tail, State) -> {Char, Tail2, State2} = decodeChar(Tail, State), parseReference([Char | Head], Context, Tail2, State2). returns : { Head2 , Tail2 , State2 } translateReference(Reference, Context, Tail, State) -> case Reference of {[list_to_integer(Tail1, 16)], Tail, State}; case catch list_to_integer(Tail1) of {'EXIT', _} -> throw({error, "Malformed: Illegal character in reference"}); Other -> {[Other], Tail, State} end; _ -> translateReferenceNonCharacter(Reference, Context, Tail, State) end. translateReferenceNonCharacter(Reference, Context, Tail, State = #erlsom_sax_state{current_entity = CurrentEntity, max_entity_depth = MaxDepth, entity_relations = Relations, entity_size_acc = TotalSize, max_expanded_entity_size = MaxSize}) -> case Context of definition -> case MaxDepth of 0 -> throw({error, "Entities nested too deep"}); _ -> ok end, NewRelation = {CurrentEntity, Reference}, case lists:member(NewRelation, Relations) of true -> Relations2 = Relations; false -> Relations2 = [NewRelation | Relations], case erlsom_sax_lib:findCycle(Reference, CurrentEntity, Relations2, MaxDepth) of cycle -> throw({error, "Malformed: Cycle in entity definitions"}); max_depth -> throw({error, "Entities nested too deep"}); _ -> ok end end, {lists:reverse("&" ++ Reference ++ ";"), Tail, State#erlsom_sax_state{entity_relations = Relations2}}; _ -> {Translation, Type} = nowFinalyTranslate(Reference, Context, State), NewTotal = TotalSize + length(Translation), if NewTotal > MaxSize -> throw({error, "Too many characters in expanded entities"}); true -> ok end, case Context of attribute -> {Translation, Tail, State#erlsom_sax_state{entity_size_acc = NewTotal}}; case Type of user_defined -> TEncoded = encode(Translation), {[], combine(TEncoded, Tail), State#erlsom_sax_state{entity_size_acc = NewTotal}}; _ -> {Translation, Tail, State#erlsom_sax_state{entity_size_acc = NewTotal}} end end end. nowFinalyTranslate(Reference, Context, State) -> case Reference of "amp" -> {[$&], other}; "lt" -> {[$<], other}; "gt" -> {[$>], other}; _ -> case State#erlsom_sax_state.expand_entities of true -> ListOfEntities = case Context of parameter -> State#erlsom_sax_state.par_entities; element -> State#erlsom_sax_state.entities end, case lists:keysearch(Reference, 1, ListOfEntities) of {value, {_, EntityText}} -> {EntityText, user_defined}; _ -> throw({error, "Malformed: unknown reference: " ++ Reference}) end; false -> throw({error, "Entity expansion disabled, found reference " ++ Reference}) end end. -ifdef(BINARY). combine(Head, Tail) -> <<Head/binary, Tail/binary>>. -endif. -ifdef(UTF8). encode(List) -> list_to_binary(erlsom_ucs:to_utf8(List)). -endif. -ifdef(U16B). encode(List) -> list_to_binary(xmerl_ucs:to_utf16be(List)). -endif. -ifdef(U16L). encode(List) -> list_to_binary(xmerl_ucs:to_utf16le(List)). -endif. -ifdef(LAT1). encode(List) -> list_to_binary(List). -endif. -ifdef(LAT9). encode(List) -> list_to_binary(List). -endif. -ifdef(LIST). encode(List) -> List. combine(Head, Tail) -> Head ++ Tail. -endif. encodeOutput(List, #erlsom_sax_state{output = 'utf8'}) -> list_to_binary(erlsom_ucs:to_utf8(List)); encodeOutput(List, _) -> List. parseText(Tail , State ) - > parseLiteralValue(Tail, Quote, Context, #erlsom_sax_state{output = 'utf8'} = State) -> parseLiteralValueBinary(Tail, Quote, <<>>, Context, State); parseLiteralValue(Tail, Quote, Context, State) -> parseLiteralValue(Tail, Quote, [], Context, State). parseLiteralValue(?STR1_T(Quote, Tail), Quote, Head, _Context, State) -> {value, lists:reverse(Head), Tail, State}; parseLiteralValue(?STR1_T($&, Tail), Quote, Head, Context, State) -> {Reference, Tail2, State2} = parseReference([], Context, Tail, State), parseLiteralValue(Tail2, Quote, Reference ++ Head, Context, State2); parseLiteralValue(?STR1_T($<, Tail), Quote, Head, Context, State) -> case Context of attribute -> throw({error, "Malformed: < not allowed in literal value"}); _ -> parseLiteralValue(Tail, Quote, [$< | Head], Context, State) end; case Context of definition -> this is weird , but it follows the implementation of MS throw({error, "Malformed: cannot use % in entity definition (?)"}); _ -> end; parseLiteralValue(?STR1_T(NextChar, Tail), Quote, Head, Context, State) when NextChar < 16#80 -> parseLiteralValue(Tail, Quote, [NextChar | Head], Context, State); parseLiteralValue(?EMPTY, Quote, Head, Context, State) -> ?CF6_2(?EMPTY, Quote, Head, Context, State, fun parseLiteralValue/5); parseLiteralValue(Tail, Quote, Head, Context, State) -> {Char, Tail2, State2} = decodeChar(Tail, State), parseLiteralValue(Tail2, Quote, [Char | Head], Context, State2). parseLiteralValueBinary(?STR1_T(Quote, Tail), Quote, Head, _Context, State) -> {value, Head, Tail, State}; parseLiteralValueBinary(?STR1_T($&, Tail), Quote, Head, Context, State) -> {Head2, Tail2, State2} = parseReference([], element, Tail, State), Head2Binary = list_to_binary(erlsom_ucs:to_utf8(lists:reverse(Head2))), parseLiteralValueBinary(Tail2, Quote, <<Head/binary, Head2Binary/binary>>, Context, State2); parseLiteralValueBinary(?STR1_T($<, Tail), Quote, Head, Context, State) -> case Context of attribute -> throw({error, "Malformed: < not allowed in literal value"}); _ -> parseLiteralValueBinary(Tail, Quote, <<Head/binary, $<>>, Context, State) end; case Context of definition -> throw({error, "Malformed: cannot use % in entity definition (?)"}); _ -> end; parseLiteralValueBinary(?STR1_T(NextChar, Tail), Quote, Head, Context, State) when NextChar < 16#80 -> parseLiteralValueBinary(Tail, Quote, <<Head/binary, NextChar>>, Context, State); parseLiteralValueBinary(?EMPTY, Quote, Head, Context, State) -> ?CF6_2(?EMPTY, Quote, Head, Context, State, fun parseLiteralValueBinary/5); parseLiteralValueBinary(Tail, Quote, Head, Context, State) -> {Char, Tail2, State2} = decodeChar(Tail, State), EncodedChar = erlsom_ucs:char_to_utf8(Char), parseLiteralValueBinary(Tail2, Quote, <<Head/binary, EncodedChar/binary>>, Context, State2). parseEndTag(?STR1_T(A, Tail1), [A | Tail2], State) when A < 16#80 -> parseEndTag(Tail1, Tail2, State); parseEndTag(?STR1_T($>, Tail), [], State) -> {ok, Tail, State}; parseEndTag(?STR1_T(NextChar, Tail), [], State) when ?is_whitespace(NextChar) -> {Tail2, State2} = removeWS(Tail, State), {ok, Tail2, State2}; parseEndTag(?EMPTY, StartTag, State) -> ?CF4_2(?EMPTY, StartTag, State, fun parseEndTag/3); parseEndTag(Tail, [B | StartTagTail], State) -> {Char, Tail2, State2} = decodeChar(Tail, State), if Char =:= B -> parseEndTag(Tail2, StartTagTail, State2); true -> error end; parseEndTag(_Tail, [], _State) -> error. removeWS(?STR1_T($>, T), State) -> {T, State}; removeWS(?STR1_T(C, T), State) when ?is_whitespace(C) -> removeWS(T, State); removeWS(?EMPTY, State) -> ?CF3(?EMPTY, State, fun removeWS/2); removeWS(_, _) -> throw({error, "Malformed: Unexpected character in end tag"}). = { Prefix , LocalName , QualifiedName } Attributes2 = list of NewNamespaces = list of { Prefix , URI } ( prefix can be [ ] ) . createStartTagEvent(StartTag, Namespaces, Attributes) -> {NewNamespaces, OtherAttributes} = lookForNamespaces([], [], Attributes), AllNamespaces = NewNamespaces ++ Namespaces, add the to the tag name ( if applicable ) Name = tagNameTuple(StartTag, AllNamespaces), Attributes2 = attributeNameTuples([], OtherAttributes, AllNamespaces), {Name, Attributes2, NewNamespaces}. lookForNamespaces(Namespaces, OtherAttributes, [Head | Tail]) -> {{Prefix, LocalName, _QName}, Value} = Head, if Prefix == "xmlns" -> lookForNamespaces([{LocalName, decodeIfRequired(Value)} | Namespaces], OtherAttributes, Tail); Prefix == [], LocalName == "xmlns" -> lookForNamespaces([{[], decodeIfRequired(Value)} | Namespaces], OtherAttributes, Tail); true -> lookForNamespaces(Namespaces, [Head | OtherAttributes], Tail) end; lookForNamespaces(Namespaces, OtherAttributes, []) -> {Namespaces, OtherAttributes}. decodeIfRequired(URI) when is_list(URI) -> URI; decodeIfRequired(URI) when is_binary(URI) -> {Value, _} = erlsom_ucs:from_utf8(URI), Value. = { Prefix , LocalName , QualifiedName } Returns , LocalName , Prefix } tagNameTuple(StartTag, Namespaces) -> {Prefix, LocalName, _QName} = StartTag, case lists:keysearch(Prefix, 1, Namespaces) of {value, {Prefix, Uri}} -> {Uri, LocalName, Prefix}; false -> {[], LocalName, Prefix} end. attributeNameTuples(ProcessedAttributes, [{AttributeName, Value} | Attributes], Namespaces) -> {Uri, LocalName, Prefix} = attributeNameTuple(AttributeName, Namespaces), attributeNameTuples([#attribute{localName= LocalName, prefix = Prefix, uri = Uri, value = Value} | ProcessedAttributes], Attributes, Namespaces); attributeNameTuples(ProcessedAttributes, [], _) -> ProcessedAttributes. Returns , LocalName , Prefix } . attributeNameTuple(AttributeName, Namespaces) -> {Prefix, LocalName, _} = AttributeName, if Prefix == [] -> {[], LocalName, []}; true -> case lists:keysearch(Prefix, 1, Namespaces) of {value, {Prefix, Uri}} -> {Uri, LocalName, Prefix}; false -> case Prefix of "xml" -> {"", LocalName, Prefix}; _ -> {[], LocalName, Prefix} end end end. wrapCallback(Event, #erlsom_sax_state{callback = Callback, user_state = UserState} = State) -> State#erlsom_sax_state{user_state = Callback(Event, UserState)}. -ifdef(UTF8). decode(Bin) -> {Value, _} = erlsom_ucs:from_utf8(Bin), Value. -endif. -ifdef(LAT1). decode(Bin) -> {Value, _} = erlsom_ucs:from_utf8(Bin), Value. -endif. -ifdef(LAT9). decode(Bin) -> [latin9toUnicode(Char) || Char <- binary_to_list(Bin)]. -endif. -ifdef(U16B). decode(Bin) -> {Value, _} = erlsom_ucs:from_utf16be(Bin), Value. -endif. -ifdef(U16L). decode(Bin) -> {Value, _} = erlsom_ucs:from_utf16le(Bin), Value. -endif. -ifdef(LIST). decode(List) -> List. -endif.
c1eb460487c45eb280206a6d24dde2044bf06b00ae3cfa5d12aaae5f6d72ba4d
ivanreese/diminished-fifth
orchestra.cljs
(ns app.orchestra (:require [app.drummer :as drummer] [app.history :as history] [app.math :as math] [app.phasor :as phasor] [app.player :as player] [app.span :as span] [app.state :refer [state]] [app.util :refer [snoop-logg]] [cljs.pprint :refer [pprint]])) (def key-change-steps 7) (def min-players 1) (def max-players 32) (def spawn-time (span/make 1 4)) ( span / make 60 600 ) ) (def min-sin (- 1 .03)) (def max-sin (+ 1 .03)) (def rescale-vel-min 0.5) (def rescale-vel-max 2) (def cycle-time 40) (def initial-vel .5) 50 % drummers at most ; VELOCITY ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn tick-velocity [state dt time] (let [accel (math/scale (math/pow (math/sin (/ time cycle-time)) 3) -1 1 min-sin max-sin) velocity (Math/max 0.0000001 (* (get-in state [:orchestra :velocity]) (Math/pow accel dt))) step 10] (history/add-history :orchestra :accel accel step) (history/add-history :orchestra :velocity velocity step) (assoc-in state [:orchestra :velocity] velocity))) RESCALE ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; (defn rescale-player [player factor] (case (:type player) :player (update player :scale * factor) :drummer (drummer/rescale player factor))) (defn rescale-players [players factor] (mapv #(rescale-player % factor) players)) (defn rescale [state factor] (-> state (update-in [:orchestra :velocity] / factor) (update :players rescale-players factor))) (defn tick-rescale [state] (let [velocity (get-in state [:orchestra :velocity])] (if (> velocity rescale-vel-max) (rescale state rescale-vel-max) (if (< velocity rescale-vel-min) (rescale state rescale-vel-min) state)))) ; PLAYERS ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (declare spawn) (defn ensure-min-players [state time] (if (> min-players (count (:players state))) (spawn state time) state)) (defn do-tick [player dt velocity transposition] (case (:type player) :player (player/tick player dt velocity transposition) :drummer (drummer/tick player dt velocity))) (defn update-players [players dt velocity transposition] (->> players (mapv #(do-tick % dt velocity transposition)) (filterv :alive))) (defn tick-players [state dt time] (-> state (update :players update-players dt (get-in state [:orchestra :velocity]) (get-in state [:orchestra :transposition])) (ensure-min-players time))) SPAWN ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; (defn next-key-change-time [time] (+ time (span/random key-change-time))) (defn next-spawn-time [time] (+ time (span/random spawn-time))) (defn update-transposition [transposition] (loop [t (* transposition (math/pow 2 (/ key-change-steps 12)))] (if (> t 1.5) (recur (/ t 2)) t))) (defn key-change [state time] (-> state (assoc-in [:orchestra :key-change-time] (next-key-change-time time)) (update-in [:orchestra :transposition] update-transposition))) (defn check-key-change [state time] (if (>= time (get-in state [:orchestra :key-change-time])) (key-change state time) state)) (defn get-sync-position [player] (case (:type player) :player (player/get-sync-position player) :drummer (drummer/get-sync-position player))) (defn spawn [state time] (let [players (:players state) nplayers (count players)] (if (>= nplayers max-players) state (let [drum-frac (Math/min min-drum-frac (/ (get-in state [:orchestra :velocity]) 4) ;; spawn fewer drummers at slower tempos spawn fewer drummers at first make-player (if (< (Math/random) drum-frac) drummer/make player/make) position (if (zero? nplayers) 0 (get-sync-position (last players))) new-player (make-player position (get-in state [:orchestra :next-player-index]) (get-in state [:orchestra :velocity]))] (-> state (update :players conj new-player) (update-in [:orchestra :next-player-index] inc) (assoc-in [:orchestra :spawn-time] (next-spawn-time time)) (assoc-in [:orchestra :drum-frac] drum-frac) (check-key-change time)))))) (defn tick-spawn [state time] (if (>= time (get-in state [:orchestra :spawn-time])) (spawn state time) state)) ; PUBLIC ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn init [state time] (history/init-history :orchestra :velocity) (history/init-history :orchestra :accel) (-> state (assoc :players []) (assoc :orchestra {:key-change-time (next-key-change-time time) ( int ( math / random 0 10000 ) ) :velocity initial-vel :drum-frac 0 :spawn-time (next-spawn-time time) :transposition 1}))) (defn tick [state dt time] (-> state (tick-velocity dt time) (tick-rescale) (tick-players dt time) (tick-spawn time)))
null
https://raw.githubusercontent.com/ivanreese/diminished-fifth/db7f7c781809b7b2733301cdc5241b17a6fee178/src/app/orchestra.cljs
clojure
VELOCITY ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; PLAYERS ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; spawn fewer drummers at slower tempos PUBLIC ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(ns app.orchestra (:require [app.drummer :as drummer] [app.history :as history] [app.math :as math] [app.phasor :as phasor] [app.player :as player] [app.span :as span] [app.state :refer [state]] [app.util :refer [snoop-logg]] [cljs.pprint :refer [pprint]])) (def key-change-steps 7) (def min-players 1) (def max-players 32) (def spawn-time (span/make 1 4)) ( span / make 60 600 ) ) (def min-sin (- 1 .03)) (def max-sin (+ 1 .03)) (def rescale-vel-min 0.5) (def rescale-vel-max 2) (def cycle-time 40) (def initial-vel .5) 50 % drummers at most (defn tick-velocity [state dt time] (let [accel (math/scale (math/pow (math/sin (/ time cycle-time)) 3) -1 1 min-sin max-sin) velocity (Math/max 0.0000001 (* (get-in state [:orchestra :velocity]) (Math/pow accel dt))) step 10] (history/add-history :orchestra :accel accel step) (history/add-history :orchestra :velocity velocity step) (assoc-in state [:orchestra :velocity] velocity))) (defn rescale-player [player factor] (case (:type player) :player (update player :scale * factor) :drummer (drummer/rescale player factor))) (defn rescale-players [players factor] (mapv #(rescale-player % factor) players)) (defn rescale [state factor] (-> state (update-in [:orchestra :velocity] / factor) (update :players rescale-players factor))) (defn tick-rescale [state] (let [velocity (get-in state [:orchestra :velocity])] (if (> velocity rescale-vel-max) (rescale state rescale-vel-max) (if (< velocity rescale-vel-min) (rescale state rescale-vel-min) state)))) (declare spawn) (defn ensure-min-players [state time] (if (> min-players (count (:players state))) (spawn state time) state)) (defn do-tick [player dt velocity transposition] (case (:type player) :player (player/tick player dt velocity transposition) :drummer (drummer/tick player dt velocity))) (defn update-players [players dt velocity transposition] (->> players (mapv #(do-tick % dt velocity transposition)) (filterv :alive))) (defn tick-players [state dt time] (-> state (update :players update-players dt (get-in state [:orchestra :velocity]) (get-in state [:orchestra :transposition])) (ensure-min-players time))) (defn next-key-change-time [time] (+ time (span/random key-change-time))) (defn next-spawn-time [time] (+ time (span/random spawn-time))) (defn update-transposition [transposition] (loop [t (* transposition (math/pow 2 (/ key-change-steps 12)))] (if (> t 1.5) (recur (/ t 2)) t))) (defn key-change [state time] (-> state (assoc-in [:orchestra :key-change-time] (next-key-change-time time)) (update-in [:orchestra :transposition] update-transposition))) (defn check-key-change [state time] (if (>= time (get-in state [:orchestra :key-change-time])) (key-change state time) state)) (defn get-sync-position [player] (case (:type player) :player (player/get-sync-position player) :drummer (drummer/get-sync-position player))) (defn spawn [state time] (let [players (:players state) nplayers (count players)] (if (>= nplayers max-players) state (let [drum-frac (Math/min min-drum-frac spawn fewer drummers at first make-player (if (< (Math/random) drum-frac) drummer/make player/make) position (if (zero? nplayers) 0 (get-sync-position (last players))) new-player (make-player position (get-in state [:orchestra :next-player-index]) (get-in state [:orchestra :velocity]))] (-> state (update :players conj new-player) (update-in [:orchestra :next-player-index] inc) (assoc-in [:orchestra :spawn-time] (next-spawn-time time)) (assoc-in [:orchestra :drum-frac] drum-frac) (check-key-change time)))))) (defn tick-spawn [state time] (if (>= time (get-in state [:orchestra :spawn-time])) (spawn state time) state)) (defn init [state time] (history/init-history :orchestra :velocity) (history/init-history :orchestra :accel) (-> state (assoc :players []) (assoc :orchestra {:key-change-time (next-key-change-time time) ( int ( math / random 0 10000 ) ) :velocity initial-vel :drum-frac 0 :spawn-time (next-spawn-time time) :transposition 1}))) (defn tick [state dt time] (-> state (tick-velocity dt time) (tick-rescale) (tick-players dt time) (tick-spawn time)))
a773b85d379776f9b24e20665e4089171ea6671e2640a3e092623bab2b695afe
drewolson/aoc-hs
Day22.hs
-- Solution liberally borrowed from module Aoc.Year2021.Day22 ( part1, part2, ) where import Aoc.Parser (Parser, runParser', signedIntP) import Control.Applicative ((<|>)) import Data.Foldable (Foldable (foldl')) import Text.Megaparsec (sepEndBy1) import Text.Megaparsec.Char (char, newline, space, string) data Action = On | Off deriving (Eq, Show) type Point = (Int, Int, Int) type Box = (Point, Point) data Step = Step { action :: Action, box :: Box } deriving (Eq, Show) data Cuboid = Cuboid { cbox :: Box, subs :: [Cuboid] } parseAction :: Parser Action parseAction = On <$ string "on" <|> Off <$ string "off" parseRange :: Parser (Int, Int) parseRange = (,) <$> signedIntP <*> (string ".." *> signedIntP) parseBox :: Parser Box parseBox = do (xmin, xmax) <- string "x=" *> parseRange <* char ',' (ymin, ymax) <- string "y=" *> parseRange <* char ',' (zmin, zmax) <- string "z=" *> parseRange pure ((xmin, ymin, zmin), (xmax, ymax, zmax)) parseStep :: Parser Step parseStep = Step <$> (parseAction <* space) <*> parseBox parseSteps :: Parser [Step] parseSteps = sepEndBy1 parseStep newline parseInput :: String -> [Step] parseInput = runParser' parseSteps intersect :: Box -> Box -> Maybe Box intersect ((xmin1, ymin1, zmin1), (xmax1, ymax1, zmax1)) ((xmin2, ymin2, zmin2), (xmax2, ymax2, zmax2)) = let ixmin = max xmin1 xmin2 iymin = max ymin1 ymin2 izmin = max zmin1 zmin2 ixmax = min xmax1 xmax2 iymax = min ymax1 ymax2 izmax = min zmax1 zmax2 in if ixmin <= ixmax && iymin <= iymax && izmin <= izmax then Just ((ixmin, iymin, izmin), (ixmax, iymax, izmax)) else Nothing subBox :: Box -> Cuboid -> Cuboid subBox box cube = case box `intersect` cbox cube of Nothing -> cube Just inter -> let subs' = subBox inter <$> subs cube iCube = Cuboid {cbox = inter, subs = []} in cube {subs = iCube : subs'} runSteps :: [Cuboid] -> Step -> [Cuboid] runSteps cubes Step {action, box} = let cubes' = fmap (subBox box) cubes in case action of Off -> cubes' On -> Cuboid {cbox = box, subs = []} : cubes' cuboidSize :: Cuboid -> Int cuboidSize Cuboid {cbox = ((xmin, ymin, zmin), (xmax, ymax, zmax)), subs} = let size = (xmax - xmin + 1) * (ymax - ymin + 1) * (zmax - zmin + 1) in size - sum (fmap cuboidSize subs) smallStep :: Step -> Bool smallStep Step {box = ((xmin, ymin, zmin), (xmax, ymax, zmax))} = all (>= -50) [xmin, ymin, zmin] && all (<= 50) [xmax, ymax, zmax] part1 :: String -> Int part1 = sum . fmap cuboidSize . foldl' runSteps [] . filter smallStep . parseInput part2 :: String -> Int part2 = sum . fmap cuboidSize . foldl' runSteps [] . parseInput
null
https://raw.githubusercontent.com/drewolson/aoc-hs/b0f06843e1f7d8c2af1da582e59a72d8f2bb73bf/aoc-year2021/src/Aoc/Year2021/Day22.hs
haskell
Solution liberally borrowed from
module Aoc.Year2021.Day22 ( part1, part2, ) where import Aoc.Parser (Parser, runParser', signedIntP) import Control.Applicative ((<|>)) import Data.Foldable (Foldable (foldl')) import Text.Megaparsec (sepEndBy1) import Text.Megaparsec.Char (char, newline, space, string) data Action = On | Off deriving (Eq, Show) type Point = (Int, Int, Int) type Box = (Point, Point) data Step = Step { action :: Action, box :: Box } deriving (Eq, Show) data Cuboid = Cuboid { cbox :: Box, subs :: [Cuboid] } parseAction :: Parser Action parseAction = On <$ string "on" <|> Off <$ string "off" parseRange :: Parser (Int, Int) parseRange = (,) <$> signedIntP <*> (string ".." *> signedIntP) parseBox :: Parser Box parseBox = do (xmin, xmax) <- string "x=" *> parseRange <* char ',' (ymin, ymax) <- string "y=" *> parseRange <* char ',' (zmin, zmax) <- string "z=" *> parseRange pure ((xmin, ymin, zmin), (xmax, ymax, zmax)) parseStep :: Parser Step parseStep = Step <$> (parseAction <* space) <*> parseBox parseSteps :: Parser [Step] parseSteps = sepEndBy1 parseStep newline parseInput :: String -> [Step] parseInput = runParser' parseSteps intersect :: Box -> Box -> Maybe Box intersect ((xmin1, ymin1, zmin1), (xmax1, ymax1, zmax1)) ((xmin2, ymin2, zmin2), (xmax2, ymax2, zmax2)) = let ixmin = max xmin1 xmin2 iymin = max ymin1 ymin2 izmin = max zmin1 zmin2 ixmax = min xmax1 xmax2 iymax = min ymax1 ymax2 izmax = min zmax1 zmax2 in if ixmin <= ixmax && iymin <= iymax && izmin <= izmax then Just ((ixmin, iymin, izmin), (ixmax, iymax, izmax)) else Nothing subBox :: Box -> Cuboid -> Cuboid subBox box cube = case box `intersect` cbox cube of Nothing -> cube Just inter -> let subs' = subBox inter <$> subs cube iCube = Cuboid {cbox = inter, subs = []} in cube {subs = iCube : subs'} runSteps :: [Cuboid] -> Step -> [Cuboid] runSteps cubes Step {action, box} = let cubes' = fmap (subBox box) cubes in case action of Off -> cubes' On -> Cuboid {cbox = box, subs = []} : cubes' cuboidSize :: Cuboid -> Int cuboidSize Cuboid {cbox = ((xmin, ymin, zmin), (xmax, ymax, zmax)), subs} = let size = (xmax - xmin + 1) * (ymax - ymin + 1) * (zmax - zmin + 1) in size - sum (fmap cuboidSize subs) smallStep :: Step -> Bool smallStep Step {box = ((xmin, ymin, zmin), (xmax, ymax, zmax))} = all (>= -50) [xmin, ymin, zmin] && all (<= 50) [xmax, ymax, zmax] part1 :: String -> Int part1 = sum . fmap cuboidSize . foldl' runSteps [] . filter smallStep . parseInput part2 :: String -> Int part2 = sum . fmap cuboidSize . foldl' runSteps [] . parseInput
9a933331c19169bf50735b5d02a3d427818dc75a0cdeab16715711fc0b262b15
DaMSL/K3
IO.hs
# LANGUAGE DeriveGeneric # # LANGUAGE ExistentialQuantification # module Language.K3.Interpreter.Builtins.IO where import Control.Monad.State import Language.K3.Core.Annotation import Language.K3.Core.Common import Language.K3.Core.Type import Language.K3.Interpreter.Data.Types import Language.K3.Interpreter.Data.Accessors import Language.K3.Utils.Pretty genIOBuiltin :: Identifier -> K3 Type -> Maybe (Interpretation Value) genIOBuiltin "error" _ = Just $ vfun $ \_ -> throwE $ RunTimeTypeError "Error encountered in program" -- Show values genIOBuiltin "show" _ = Just $ vfun $ \x -> do st <- get return $ VString $ showPC (getPrintConfig st) x -- Log to the screen genIOBuiltin "print" _ = Just $ vfun logString where logString (VString s) = do -- liftIO $ putStrLn s _notice_Function s return $ VTuple [] logString x = throwE $ RunTimeTypeError ("In 'print': Expected a string but received " ++ show x) genIOBuiltin _ _ = Nothing
null
https://raw.githubusercontent.com/DaMSL/K3/51749157844e76ae79dba619116fc5ad9d685643/src/Language/K3/Interpreter/Builtins/IO.hs
haskell
Show values Log to the screen liftIO $ putStrLn s
# LANGUAGE DeriveGeneric # # LANGUAGE ExistentialQuantification # module Language.K3.Interpreter.Builtins.IO where import Control.Monad.State import Language.K3.Core.Annotation import Language.K3.Core.Common import Language.K3.Core.Type import Language.K3.Interpreter.Data.Types import Language.K3.Interpreter.Data.Accessors import Language.K3.Utils.Pretty genIOBuiltin :: Identifier -> K3 Type -> Maybe (Interpretation Value) genIOBuiltin "error" _ = Just $ vfun $ \_ -> throwE $ RunTimeTypeError "Error encountered in program" genIOBuiltin "show" _ = Just $ vfun $ \x -> do st <- get return $ VString $ showPC (getPrintConfig st) x genIOBuiltin "print" _ = Just $ vfun logString where logString (VString s) = do _notice_Function s return $ VTuple [] logString x = throwE $ RunTimeTypeError ("In 'print': Expected a string but received " ++ show x) genIOBuiltin _ _ = Nothing
e4f0c47e19ed96c68bb4d776b28caf1c4dd7b98317fb88fcce8d8eb0290a6ebe
grimmelm/littleton
test.ml
open Core_kernel module P = Program.DerivativeProgram type test = { citation : string option ; caption : string option ; comment : string option ; expected : Sexp.t option ; program : string} [@@deriving sexp] type suite = { title : string ; reference : string option ; tests : test list } [@@deriving sexp] type tester = string -> test -> unit -> unit type mode = Parsing | Expected exception InvalidTestFile of string (** Utility functions for working with toml *) let program t = Util.TOML.( let (>>|) = Option.(>>|) in let citation = get_string' "citation" t in let caption = get_string' "caption" t in let comment = get_string' "comment" t in let expected = get_nonempty_string' "expected" t >>| Sexp.of_string in let program = get_string' "program" t |> function | Some p -> p | None -> raise (InvalidTestFile "No program in test") in { citation; caption; comment; expected; program }) (** Build a test suite from an input source *) let from_toml toml = let open Util.TOML in let title = get_string "title" toml in let reference = get_string' "reference" toml in let examples = get_table_array' "examples" toml in let ts = get_table_array' "tests" toml in let tests = (match examples, ts with | None, Some pgms | Some pgms, None -> List.map ~f:program pgms | _ -> [program toml] ) in { title; reference; tests } let from_filename (filename:string) : suite = match Util.TOML.from_filename' filename with | `Ok t -> from_toml t | `Error(s,l) -> let msg = sprintf "Error at line %d: %s\n%!" l.Toml.Parser.line s in raise (InvalidTestFile msg) (** Some useful test functions *) (* Check for successful parsing *) let parsing name test () = let open Alcotest in let result = match (P.parse' test.program) with | MParser.Success _ -> true | MParser.Failed(_,_) -> false in (check bool) name true result (* Compare the expected result with the computed result *) let expected name test () = let open Alcotest in let sexp = testable Sexp.pp Sexp.equal in let expect = Option.value test.expected ~default:(Sexp.Atom "") in let result = Result.(P.of_string test.program >>= P.run) in match result with | Ok trace -> let computed = (List.last_exn trace) |> P.testable in (check sexp) name expect computed | Error _ -> Alcotest.fail "There was an error" (** Apply functions to the test programs in a suite *) let test (s:suite) ~f = let open Alcotest in let test_set = List.mapi s.tests ~f:(fun i test -> let name = match test.caption, test.comment with | Some n, _ | None, Some n -> n | None, None -> sprintf "test %d" i in (name, `Quick, f name test)) in let argv = Array.of_list ["--verbose"] in run s.title ~argv [("Suite", test_set)] let map (s:suite) ~f = List.map s.tests ~f:(fun test -> test.program, f test.program ) let iter (s:suite) ~f = List.iter s.tests ~f:(fun test -> f test.program) let pick (s:suite) (i:int) ~f = match List.nth s.tests i with | Some t -> Some (f t.program) | None -> None
null
https://raw.githubusercontent.com/grimmelm/littleton/efa8c90ae13b3965c81876723f6622f6d0319e80/lib/test.ml
ocaml
* Utility functions for working with toml * Build a test suite from an input source * Some useful test functions Check for successful parsing Compare the expected result with the computed result * Apply functions to the test programs in a suite
open Core_kernel module P = Program.DerivativeProgram type test = { citation : string option ; caption : string option ; comment : string option ; expected : Sexp.t option ; program : string} [@@deriving sexp] type suite = { title : string ; reference : string option ; tests : test list } [@@deriving sexp] type tester = string -> test -> unit -> unit type mode = Parsing | Expected exception InvalidTestFile of string let program t = Util.TOML.( let (>>|) = Option.(>>|) in let citation = get_string' "citation" t in let caption = get_string' "caption" t in let comment = get_string' "comment" t in let expected = get_nonempty_string' "expected" t >>| Sexp.of_string in let program = get_string' "program" t |> function | Some p -> p | None -> raise (InvalidTestFile "No program in test") in { citation; caption; comment; expected; program }) let from_toml toml = let open Util.TOML in let title = get_string "title" toml in let reference = get_string' "reference" toml in let examples = get_table_array' "examples" toml in let ts = get_table_array' "tests" toml in let tests = (match examples, ts with | None, Some pgms | Some pgms, None -> List.map ~f:program pgms | _ -> [program toml] ) in { title; reference; tests } let from_filename (filename:string) : suite = match Util.TOML.from_filename' filename with | `Ok t -> from_toml t | `Error(s,l) -> let msg = sprintf "Error at line %d: %s\n%!" l.Toml.Parser.line s in raise (InvalidTestFile msg) let parsing name test () = let open Alcotest in let result = match (P.parse' test.program) with | MParser.Success _ -> true | MParser.Failed(_,_) -> false in (check bool) name true result let expected name test () = let open Alcotest in let sexp = testable Sexp.pp Sexp.equal in let expect = Option.value test.expected ~default:(Sexp.Atom "") in let result = Result.(P.of_string test.program >>= P.run) in match result with | Ok trace -> let computed = (List.last_exn trace) |> P.testable in (check sexp) name expect computed | Error _ -> Alcotest.fail "There was an error" let test (s:suite) ~f = let open Alcotest in let test_set = List.mapi s.tests ~f:(fun i test -> let name = match test.caption, test.comment with | Some n, _ | None, Some n -> n | None, None -> sprintf "test %d" i in (name, `Quick, f name test)) in let argv = Array.of_list ["--verbose"] in run s.title ~argv [("Suite", test_set)] let map (s:suite) ~f = List.map s.tests ~f:(fun test -> test.program, f test.program ) let iter (s:suite) ~f = List.iter s.tests ~f:(fun test -> f test.program) let pick (s:suite) (i:int) ~f = match List.nth s.tests i with | Some t -> Some (f t.program) | None -> None
1be4e90038273d51fc172eb5022244cc9bb7fb724b8b306bbd6dd460a5e6ad1e
dfinity/motoko
pretty.ml
include Mo_types.Type.MakePretty (Mo_types.Type.ElideStamps)
null
https://raw.githubusercontent.com/dfinity/motoko/dedaddffe633b07107e775e520700c1dbd18344f/src/languageServer/pretty.ml
ocaml
include Mo_types.Type.MakePretty (Mo_types.Type.ElideStamps)
228daf1c35a3b2138b084f75cc25c8d3cdb1d47449d42376668f5b4850962a29
soegaard/metapict
polygonal-numbers.rkt
#lang racket (require metapict) ;;; ;;; EXAMPLE ;;; Figure from Wikipedia article on polygonal numbers. ;;; (def (fig-polygonal-numbers) (let () (curve-pict-window (window -2.1 2.1 -2.1 2.1)) (set-curve-pict-size 400 400) (def A (pt 0 0)) (def B (pt 1 0)) space between pt centers ( 6 dots = > 5 spaces ) (def all-rings (append* (for/list ([j (in-range 1 6)]) (def bottom (for/list ([i j]) (shifted (* i Δ) 0 A))) (def ring (for/fold ([partial-ring '()]) ([i 6]) (append bottom (map (shifted (* j Δ) 0 (rotatedd 60)) partial-ring)))) ring))) (penwidth 10 (draw (draw* all-rings) (penscale 1.2 (color "red" (draw A))) (penscale 1.2 (color "blue" (draw B))))))) (fig-polygonal-numbers)
null
https://raw.githubusercontent.com/soegaard/metapict/47ae265f73cbb92ff3e7bdd61e49f4af17597fdf/metapict/examples/polygonal-numbers.rkt
racket
EXAMPLE Figure from Wikipedia article on polygonal numbers.
#lang racket (require metapict) (def (fig-polygonal-numbers) (let () (curve-pict-window (window -2.1 2.1 -2.1 2.1)) (set-curve-pict-size 400 400) (def A (pt 0 0)) (def B (pt 1 0)) space between pt centers ( 6 dots = > 5 spaces ) (def all-rings (append* (for/list ([j (in-range 1 6)]) (def bottom (for/list ([i j]) (shifted (* i Δ) 0 A))) (def ring (for/fold ([partial-ring '()]) ([i 6]) (append bottom (map (shifted (* j Δ) 0 (rotatedd 60)) partial-ring)))) ring))) (penwidth 10 (draw (draw* all-rings) (penscale 1.2 (color "red" (draw A))) (penscale 1.2 (color "blue" (draw B))))))) (fig-polygonal-numbers)
8e82d254d3102625b78c6e3e079a73f5545efa084a4f1c2f4305b4755f4995a8
kseo/systemf
Pretty.hs
-- | -- A collection of pretty printers for core data types: -- module Language.LambdaCalculus.Pretty (module P) where import Language.LambdaCalculus.Pretty.Term as P import Language.LambdaCalculus.Pretty.Types as P
null
https://raw.githubusercontent.com/kseo/systemf/ea73fd42567adf2ddcd7bb60f11a66e10eebc154/src/Language/LambdaCalculus/Pretty.hs
haskell
| A collection of pretty printers for core data types:
module Language.LambdaCalculus.Pretty (module P) where import Language.LambdaCalculus.Pretty.Term as P import Language.LambdaCalculus.Pretty.Types as P
df3a2fda60bd429fb86fc84256c1e91e0efc0bee3c7711ac7a8a7ade7b417758
plai-group/daphne
reverse_diff.clj
(ns daphne.reverse-diff "Reverse mode auto-diff." (:require [anglican.runtime :refer [observe* normal]] [daphne.gensym :refer [*my-gensym*]]) (:import [anglican.runtime normal-distribution])) ;; The following code so far follows ;; -bcl.cs.may.ie/~barak/papers/toplas-reverse.pdf and derivatives . 2008 . ;; Proposed roadmap 1 . generalization ;; + function composition (boundary type) + arbitrary Anglican style nested values ;; + external primitive functions + integrate into CPS trafo of Anglican ;; 2 . implement tape version through operator overloading ;; following diffsharp ;; 3 . linear algebra support ;; + extend to core.matrix ;; + support simple deep learning style composition ;; 4 . performance optimizations (set! *warn-on-reflection* true) (comment (set! *unchecked-math* :warn-on-boxed)) ;; some aliasing for formula sanity (def ** (fn [x p] (Math/pow x p))) (def sqrt (fn [x] (Math/sqrt x))) (def log (fn [x] (Math/log x))) (def exp (fn [x] (Math/exp x))) (def pow (fn [x p] (Math/pow x p))) (def sin (fn [x] (Math/sin x))) (def cos (fn [x] (Math/cos x))) (defn normpdf [x mu sigma] (let [x (double x) mu (double mu) sigma (double sigma)] (+ (- (/ (* (- x mu) (- x mu)) (* 2.0 (* sigma sigma)))) (* -0.5 (Math/log (* 2.0 (* 3.141592653589793 (* sigma sigma)))))))) (defn term? [exp] (or (number? exp) (symbol? exp))) (defn dispatch-exp [exp p] (assert (seq? exp) "All differentiation happens on arithmetic expressions.") (assert (zero? (count (filter seq? exp))) "Differentiation works on flat (not-nested) expressions only.") (keyword (name (first exp)))) ;; derivative definitions (defmulti partial-deriv dispatch-exp) (defmethod partial-deriv :+ [[_ & args] p] (seq (into '[+] (reduce (fn [nargs a] (if (= a p) (conj nargs 1) nargs)) [] args)))) (defmethod partial-deriv :- [[_ & args] p] (seq (into '[-] (reduce (fn [nargs a] (if (= a p) (conj nargs 1) (conj nargs 0))) [] args)))) (defmethod partial-deriv :* [[_ & args] p] (let [pn (count (filter #(= % p) args))] (seq (into ['* pn (list 'pow p (dec pn))] (filter #(not= % p) args))))) (defmethod partial-deriv :/ [[_ & [a b]] p] TODO support any arity (if (= a p) (if (= b p) 0 (list '/ 1 b)) (if (= b p) (list '- (list '* a (list 'pow b -2))) 0))) (defmethod partial-deriv :sin [[_ a] p] (if (= a p) (list 'cos a) 0)) (defmethod partial-deriv :cos [[_ a] p] (if (= a p) (list 'sin a) 0)) (defmethod partial-deriv :exp [[_ a] p] (if (= a p) (list 'exp a) 0)) (defmethod partial-deriv :log [[_ a] p] (if (= a p) (list '/ 1 a) 0)) (defmethod partial-deriv :pow [[_ & [base expo]] p] (if (= base p) (if (= expo p) TODO p^p only defined for p > 0 (list '* (list '+ 1 (list 'log p)) (list 'pow p p)) (list '* expo (list 'pow p (list 'dec expo)))) (if (= expo p) (list '* (list 'log base) (list 'pow base p)) 0))) (defmethod partial-deriv :normpdf [[_ x mu sigma] p] (cond (= x p) (list '* (list '- (list '/ 1 (list '* sigma sigma))) (list '- x mu)) (= mu p) (list '* (list '- (list '/ 1 (list '* sigma sigma))) (list '- mu x)) (= sigma p) (list '- (list '* (list '/ 1 (list '* sigma sigma sigma)) (list 'pow (list '- x mu) 2)) (list '/ 1 sigma)) :else 0)) (def empty-tape {:forward [] :backward []}) (defn adjoint-sym [sym] (symbol (str sym "_"))) (defn tape-expr "The tape returns flat variable assignments for forward and backward pass. It allows multiple assignments following Griewank p. 125 or chapter 3.2. Once lambdas are supported this should be A-normal form of code." [bound sym exp tape] (cond (and (seq? exp) (= (first exp) 'if)) (let [[_ condition then else] exp {:keys [forward backward]} tape then-s (*my-gensym* "then") else-s (*my-gensym* "else") {then-forward :forward then-backward :backward} (tape-expr bound then-s then empty-tape) {else-forward :forward else-backward :backward} (tape-expr bound else-s else empty-tape) if-forward (concat (map (fn [[s e]] [s (list 'if condition e 0)]) then-forward) (map (fn [[s e]] [s (list 'if-not condition e 0)]) else-forward)) if-backward (concat (map (fn [[s e]] [s (list 'if condition e s)]) then-backward) (map (fn [[s e]] [s (list 'if-not condition e s)]) else-backward))] {:forward (vec (concat forward if-forward [[sym (list 'if condition then-s else-s)]])) :backward (vec (concat backward if-backward [[(adjoint-sym then-s) (adjoint-sym sym)] [(adjoint-sym else-s) (adjoint-sym sym)]]))}) :else (let [[f & args] exp new-gensyms (atom []) nargs (map (fn [a] (if (term? a) a (let [ng (*my-gensym* "v")] (swap! new-gensyms conj ng) ng))) args) nexp (conj nargs f) {:keys [forward backward]} (reduce (fn [{:keys [forward backward] :as tape} [s a]] (if (term? a) tape (tape-expr bound s a tape))) tape (partition 2 (interleave nargs args))) bound (into bound (map first forward))] {:forward (conj forward [sym nexp]) :backward (vec (concat backward ;; reverse chain-rule (backpropagator) (for [a (distinct nargs) :when (bound a) ;; we only do backward on our vars :let [a-back (adjoint-sym a)]] [a-back (list '+ a-back (list '* (adjoint-sym sym) (partial-deriv nexp a)))]) ;; initialize new variables with 0 (map (fn [a] [(adjoint-sym a) 0]) @new-gensyms)))}))) (defn adjoints [args] (mapv (fn [a] (symbol (str (name a) "_"))) args)) (defn init-adjoints [args] (->> (interleave (adjoints args) (repeat 0)) (partition 2) (apply concat))) (defn reverse-diff* "Splice the tape " [args code] (let [{:keys [forward backward]} (tape-expr (into #{} args) (*my-gensym* "v") code {:forward [] :backward []}) ret (first (last forward))] (list 'fn args (list 'let (vec (apply concat forward)) [ret (list 'fn [(symbol (str ret "_"))] (list 'let (vec (concat (init-adjoints args) (apply concat (reverse backward)))) (adjoints args)))])))) ;; numeric gradient for checks (defmacro fnr [args code] `~(reverse-diff* args code)) (defn addd [exprl i d] (if (= i 0) (reduce conj [`(~'+ ~d ~(first exprl))] (subvec exprl 1)) (reduce conj (subvec exprl 0 i) (reduce conj [`(~'+ ~d ~(get exprl i))] (subvec exprl (+ i 1)))))) (defn finite-difference-expr [expr args i d] `(~'/ (~'- (~expr ~@(addd args i d)) (~expr ~@args)) ~d)) (defn finite-difference-grad [expr] (let [[op args body] expr d (*my-gensym*) fdes (mapv #(finite-difference-expr expr args % d) (range (count args))) argsyms (map (fn [x] `(~'quote ~x)) args)] `(~'fn [~@args] (~'let [~d 0.001] ~fdes #_~(zipmap argsyms fdes)))))
null
https://raw.githubusercontent.com/plai-group/daphne/b0f43fbb9c856116ec44419fea91c4011072dd74/src/daphne/reverse_diff.clj
clojure
The following code so far follows -bcl.cs.may.ie/~barak/papers/toplas-reverse.pdf Proposed roadmap + function composition (boundary type) + external primitive functions following diffsharp + extend to core.matrix + support simple deep learning style composition some aliasing for formula sanity derivative definitions reverse chain-rule (backpropagator) we only do backward on our vars initialize new variables with 0 numeric gradient for checks
(ns daphne.reverse-diff "Reverse mode auto-diff." (:require [anglican.runtime :refer [observe* normal]] [daphne.gensym :refer [*my-gensym*]]) (:import [anglican.runtime normal-distribution])) and derivatives . 2008 . 1 . generalization + arbitrary Anglican style nested values + integrate into CPS trafo of Anglican 2 . implement tape version through operator overloading 3 . linear algebra support 4 . performance optimizations (set! *warn-on-reflection* true) (comment (set! *unchecked-math* :warn-on-boxed)) (def ** (fn [x p] (Math/pow x p))) (def sqrt (fn [x] (Math/sqrt x))) (def log (fn [x] (Math/log x))) (def exp (fn [x] (Math/exp x))) (def pow (fn [x p] (Math/pow x p))) (def sin (fn [x] (Math/sin x))) (def cos (fn [x] (Math/cos x))) (defn normpdf [x mu sigma] (let [x (double x) mu (double mu) sigma (double sigma)] (+ (- (/ (* (- x mu) (- x mu)) (* 2.0 (* sigma sigma)))) (* -0.5 (Math/log (* 2.0 (* 3.141592653589793 (* sigma sigma)))))))) (defn term? [exp] (or (number? exp) (symbol? exp))) (defn dispatch-exp [exp p] (assert (seq? exp) "All differentiation happens on arithmetic expressions.") (assert (zero? (count (filter seq? exp))) "Differentiation works on flat (not-nested) expressions only.") (keyword (name (first exp)))) (defmulti partial-deriv dispatch-exp) (defmethod partial-deriv :+ [[_ & args] p] (seq (into '[+] (reduce (fn [nargs a] (if (= a p) (conj nargs 1) nargs)) [] args)))) (defmethod partial-deriv :- [[_ & args] p] (seq (into '[-] (reduce (fn [nargs a] (if (= a p) (conj nargs 1) (conj nargs 0))) [] args)))) (defmethod partial-deriv :* [[_ & args] p] (let [pn (count (filter #(= % p) args))] (seq (into ['* pn (list 'pow p (dec pn))] (filter #(not= % p) args))))) (defmethod partial-deriv :/ [[_ & [a b]] p] TODO support any arity (if (= a p) (if (= b p) 0 (list '/ 1 b)) (if (= b p) (list '- (list '* a (list 'pow b -2))) 0))) (defmethod partial-deriv :sin [[_ a] p] (if (= a p) (list 'cos a) 0)) (defmethod partial-deriv :cos [[_ a] p] (if (= a p) (list 'sin a) 0)) (defmethod partial-deriv :exp [[_ a] p] (if (= a p) (list 'exp a) 0)) (defmethod partial-deriv :log [[_ a] p] (if (= a p) (list '/ 1 a) 0)) (defmethod partial-deriv :pow [[_ & [base expo]] p] (if (= base p) (if (= expo p) TODO p^p only defined for p > 0 (list '* (list '+ 1 (list 'log p)) (list 'pow p p)) (list '* expo (list 'pow p (list 'dec expo)))) (if (= expo p) (list '* (list 'log base) (list 'pow base p)) 0))) (defmethod partial-deriv :normpdf [[_ x mu sigma] p] (cond (= x p) (list '* (list '- (list '/ 1 (list '* sigma sigma))) (list '- x mu)) (= mu p) (list '* (list '- (list '/ 1 (list '* sigma sigma))) (list '- mu x)) (= sigma p) (list '- (list '* (list '/ 1 (list '* sigma sigma sigma)) (list 'pow (list '- x mu) 2)) (list '/ 1 sigma)) :else 0)) (def empty-tape {:forward [] :backward []}) (defn adjoint-sym [sym] (symbol (str sym "_"))) (defn tape-expr "The tape returns flat variable assignments for forward and backward pass. It allows multiple assignments following Griewank p. 125 or chapter 3.2. Once lambdas are supported this should be A-normal form of code." [bound sym exp tape] (cond (and (seq? exp) (= (first exp) 'if)) (let [[_ condition then else] exp {:keys [forward backward]} tape then-s (*my-gensym* "then") else-s (*my-gensym* "else") {then-forward :forward then-backward :backward} (tape-expr bound then-s then empty-tape) {else-forward :forward else-backward :backward} (tape-expr bound else-s else empty-tape) if-forward (concat (map (fn [[s e]] [s (list 'if condition e 0)]) then-forward) (map (fn [[s e]] [s (list 'if-not condition e 0)]) else-forward)) if-backward (concat (map (fn [[s e]] [s (list 'if condition e s)]) then-backward) (map (fn [[s e]] [s (list 'if-not condition e s)]) else-backward))] {:forward (vec (concat forward if-forward [[sym (list 'if condition then-s else-s)]])) :backward (vec (concat backward if-backward [[(adjoint-sym then-s) (adjoint-sym sym)] [(adjoint-sym else-s) (adjoint-sym sym)]]))}) :else (let [[f & args] exp new-gensyms (atom []) nargs (map (fn [a] (if (term? a) a (let [ng (*my-gensym* "v")] (swap! new-gensyms conj ng) ng))) args) nexp (conj nargs f) {:keys [forward backward]} (reduce (fn [{:keys [forward backward] :as tape} [s a]] (if (term? a) tape (tape-expr bound s a tape))) tape (partition 2 (interleave nargs args))) bound (into bound (map first forward))] {:forward (conj forward [sym nexp]) :backward (vec (concat backward (for [a (distinct nargs) :let [a-back (adjoint-sym a)]] [a-back (list '+ a-back (list '* (adjoint-sym sym) (partial-deriv nexp a)))]) (map (fn [a] [(adjoint-sym a) 0]) @new-gensyms)))}))) (defn adjoints [args] (mapv (fn [a] (symbol (str (name a) "_"))) args)) (defn init-adjoints [args] (->> (interleave (adjoints args) (repeat 0)) (partition 2) (apply concat))) (defn reverse-diff* "Splice the tape " [args code] (let [{:keys [forward backward]} (tape-expr (into #{} args) (*my-gensym* "v") code {:forward [] :backward []}) ret (first (last forward))] (list 'fn args (list 'let (vec (apply concat forward)) [ret (list 'fn [(symbol (str ret "_"))] (list 'let (vec (concat (init-adjoints args) (apply concat (reverse backward)))) (adjoints args)))])))) (defmacro fnr [args code] `~(reverse-diff* args code)) (defn addd [exprl i d] (if (= i 0) (reduce conj [`(~'+ ~d ~(first exprl))] (subvec exprl 1)) (reduce conj (subvec exprl 0 i) (reduce conj [`(~'+ ~d ~(get exprl i))] (subvec exprl (+ i 1)))))) (defn finite-difference-expr [expr args i d] `(~'/ (~'- (~expr ~@(addd args i d)) (~expr ~@args)) ~d)) (defn finite-difference-grad [expr] (let [[op args body] expr d (*my-gensym*) fdes (mapv #(finite-difference-expr expr args % d) (range (count args))) argsyms (map (fn [x] `(~'quote ~x)) args)] `(~'fn [~@args] (~'let [~d 0.001] ~fdes #_~(zipmap argsyms fdes)))))
ee1e7f0a6c44b0432790d536310aab27b63316d88c64ee44ce6a6be6af742918
PEZ/rich4clojure
problem_128.clj
(ns rich4clojure.easy.problem-128 (:require [hyperfiddle.rcf :refer [tests]])) ;; = Recognize Playing Cards = ;; By 4Clojure user: amalloy ;; Difficulty: Easy ;; Tags: [strings game] ;; A standard American deck of playing cards has four ;; suits - spades, hearts, diamonds, and clubs - and thirteen cards in each suit . Two is the lowest rank , followed by other integers up to ten ; then the jack , ;; queen, king, and ace. ;; ;; ;; It's convenient for humans to represent these cards as suit / rank pairs , such as H5 or DQ : the heart five and ;; diamond queen respectively. But these forms are not ;; convenient for programmers, so to write a card game you ;; need some way to parse an input string into meaningful ;; components. For purposes of determining rank, we will define the cards to be valued from 0 ( the two ) to 12 ;; (the ace) ;; ;; ;; Write a function which converts (for example) the string " SJ " into a map of { : suit : spade , : rank 9 } . A ;; ten will always be represented with the single character " T " , rather than the two characters " 10 " . (def __ :tests-will-fail) (comment ) (tests {:suit :diamond :rank 10} := (__ "DQ") {:suit :heart :rank 3} := (__ "H5") {:suit :club :rank 12} := (__ "CA") (range 13) := (map (comp :rank __ str) '[S2 S3 S4 S5 S6 S7 S8 S9 ST SJ SQ SK SA])) ;; Share your solution, and/or check how others did it: ;;
null
https://raw.githubusercontent.com/PEZ/rich4clojure/2ccfac041840e9b1550f0a69b9becbdb03f9525b/src/rich4clojure/easy/problem_128.clj
clojure
= Recognize Playing Cards = By 4Clojure user: amalloy Difficulty: Easy Tags: [strings game] suits - spades, hearts, diamonds, and clubs - and then the jack , queen, king, and ace. It's convenient for humans to represent these cards as diamond queen respectively. But these forms are not convenient for programmers, so to write a card game you need some way to parse an input string into meaningful components. For purposes of determining rank, we will (the ace) Write a function which converts (for example) the ten will always be represented with the single Share your solution, and/or check how others did it:
(ns rich4clojure.easy.problem-128 (:require [hyperfiddle.rcf :refer [tests]])) A standard American deck of playing cards has four thirteen cards in each suit . Two is the lowest rank , suit / rank pairs , such as H5 or DQ : the heart five and define the cards to be valued from 0 ( the two ) to 12 string " SJ " into a map of { : suit : spade , : rank 9 } . A character " T " , rather than the two characters " 10 " . (def __ :tests-will-fail) (comment ) (tests {:suit :diamond :rank 10} := (__ "DQ") {:suit :heart :rank 3} := (__ "H5") {:suit :club :rank 12} := (__ "CA") (range 13) := (map (comp :rank __ str) '[S2 S3 S4 S5 S6 S7 S8 S9 ST SJ SQ SK SA]))
2ccc093398e50734174b431c14ecbdc76a5e936d177af8fe09315630d91434a0
aaronallen8455/inventory
T20.hs
# LANGUAGE PolyKinds # # LANGUAGE DataKinds # module HieSource.T20 where import Data.Proxy t20A :: Proxy (a :: [b] -> Bool -> Either b c) -> b -> c t20A = undefined t20B :: b -> Proxy (a :: Bool -> [b] -> Either b c) -> c t20B = undefined t20C :: b -> Proxy (a :: Bool -> [b] -> Either c b) -> c t20C = undefined t20D :: b -> Proxy (a :: Bool -> Either c b -> [b]) -> c t20D = undefined
null
https://raw.githubusercontent.com/aaronallen8455/inventory/e16244f2c3b920ec0caffc4b81d236219b78bd91/test/HieSource/T20.hs
haskell
# LANGUAGE PolyKinds # # LANGUAGE DataKinds # module HieSource.T20 where import Data.Proxy t20A :: Proxy (a :: [b] -> Bool -> Either b c) -> b -> c t20A = undefined t20B :: b -> Proxy (a :: Bool -> [b] -> Either b c) -> c t20B = undefined t20C :: b -> Proxy (a :: Bool -> [b] -> Either c b) -> c t20C = undefined t20D :: b -> Proxy (a :: Bool -> Either c b -> [b]) -> c t20D = undefined
c378257eab250de0743001ef407192c63d2f50d31e8e1139d2bdfc266dceaf09
jellelicht/guix
guile-wm.scm
;;; GNU Guix --- Functional package management for GNU Copyright © 2013 , 2014 < > ;;; ;;; This file is part of GNU Guix. ;;; GNU is free software ; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation ; either version 3 of the License , or ( at ;;; your option) any later version. ;;; ;;; GNU Guix is distributed in the hope that it will be useful, but ;;; WITHOUT ANY WARRANTY; without even the implied warranty of ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;;; GNU General Public License for more details. ;;; You should have received a copy of the GNU General Public License along with GNU . If not , see < / > . (define-module (gnu packages guile-wm) #:use-module (guix licenses) #:use-module (gnu packages) #:use-module (gnu packages xorg) #:use-module (gnu packages guile) #:use-module (gnu packages pkg-config) #:use-module (guix packages) #:use-module (guix download) #:use-module (guix build-system gnu)) (define-public guile-xcb (package (name "guile-xcb") (version "1.3") (source (origin (method url-fetch) (uri (string-append "-xcb-" version ".tar.gz")) (sha256 (base32 "04dvbqdrrs67490gn4gkq9zk8mqy3mkls2818ha4p0ckhh0pm149")))) (build-system gnu-build-system) Parallel builds fail . #:parallel-build? #f #:configure-flags (list (string-append "--with-guile-site-dir=" (assoc-ref %outputs "out") "/share/guile/site/2.0") (string-append "--with-guile-site-ccache-dir=" (assoc-ref %outputs "out") "/share/guile/site/2.0")))) (native-inputs `(("pkg-config" ,pkg-config))) (inputs `(("guile" ,guile-2.0) ("xcb" ,xcb-proto))) (home-page "-xcb/guile-xcb.html") (synopsis "XCB bindings for Guile") (description "Guile-XCB implements the XCB protocol and provides all the tools necessary to write X client code in Guile Scheme without any external dependencies.") (license gpl3+))) (define-public guile-wm (package (name "guile-wm") (version "1.0") (source (origin (method url-fetch) (uri (string-append "-wm-" version ".tar.gz")) (sha256 (base32 "1l9qcz236jxvryndimjy62cf8zxf8i3f8vg3zpqqjhw15j9mdk3r")))) (build-system gnu-build-system) (arguments '(;; The '.scm' files go to $(datadir), so set that to the ;; standard value. #:configure-flags (list (string-append "--datadir=" (assoc-ref %outputs "out") "/share/guile/site/2.0")) #:phases (alist-cons-before 'configure 'set-go-directory (lambda* (#:key outputs #:allow-other-keys) Install .go files to $ out / share / guile / site/2.0 . (let ((out (assoc-ref outputs "out"))) (substitute* "module/Makefile.in" (("^wmdir = .*$") (string-append "wmdir = " out "/share/guile/site/2.0\n"))))) (alist-cons-after 'install 'set-load-path (lambda* (#:key inputs outputs #:allow-other-keys) Put Guile - XCB 's and Guile - WM 's modules in the ;; search path of PROG. (let* ((out (assoc-ref outputs "out")) (prog (string-append out "/bin/guile-wm")) (mods (string-append out "/share/guile/site/2.0")) (xcb (string-append (assoc-ref inputs "guile-xcb") "/share/guile/site/2.0"))) (wrap-program prog `("GUILE_LOAD_PATH" ":" prefix (,mods ,xcb)) `("GUILE_LOAD_COMPILED_PATH" ":" prefix (,mods ,xcb))))) %standard-phases)))) (native-inputs `(("pkg-config" ,pkg-config))) (inputs `(("guile" ,guile-2.0) ("guile-xcb" ,guile-xcb))) (home-page "-xcb/guile-wm.html") (synopsis "X11 window manager toolkit in Scheme") (description "Guile-WM is a simple window manager that's completely customizable—you have total control of what it does by choosing which modules to include. Included with it are a few modules that provide basic TinyWM-like window management, some window record-keeping, multi-monitor support, and emacs-like keymaps and minibuffer. At this point, it's just enough to get you started.") (license gpl3+)))
null
https://raw.githubusercontent.com/jellelicht/guix/83cfc9414fca3ab57c949e18c1ceb375a179b59c/gnu/packages/guile-wm.scm
scheme
GNU Guix --- Functional package management for GNU This file is part of GNU Guix. you can redistribute it and/or modify it either version 3 of the License , or ( at your option) any later version. GNU Guix is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. The '.scm' files go to $(datadir), so set that to the standard value. search path of PROG.
Copyright © 2013 , 2014 < > under the terms of the GNU General Public License as published by You should have received a copy of the GNU General Public License along with GNU . If not , see < / > . (define-module (gnu packages guile-wm) #:use-module (guix licenses) #:use-module (gnu packages) #:use-module (gnu packages xorg) #:use-module (gnu packages guile) #:use-module (gnu packages pkg-config) #:use-module (guix packages) #:use-module (guix download) #:use-module (guix build-system gnu)) (define-public guile-xcb (package (name "guile-xcb") (version "1.3") (source (origin (method url-fetch) (uri (string-append "-xcb-" version ".tar.gz")) (sha256 (base32 "04dvbqdrrs67490gn4gkq9zk8mqy3mkls2818ha4p0ckhh0pm149")))) (build-system gnu-build-system) Parallel builds fail . #:parallel-build? #f #:configure-flags (list (string-append "--with-guile-site-dir=" (assoc-ref %outputs "out") "/share/guile/site/2.0") (string-append "--with-guile-site-ccache-dir=" (assoc-ref %outputs "out") "/share/guile/site/2.0")))) (native-inputs `(("pkg-config" ,pkg-config))) (inputs `(("guile" ,guile-2.0) ("xcb" ,xcb-proto))) (home-page "-xcb/guile-xcb.html") (synopsis "XCB bindings for Guile") (description "Guile-XCB implements the XCB protocol and provides all the tools necessary to write X client code in Guile Scheme without any external dependencies.") (license gpl3+))) (define-public guile-wm (package (name "guile-wm") (version "1.0") (source (origin (method url-fetch) (uri (string-append "-wm-" version ".tar.gz")) (sha256 (base32 "1l9qcz236jxvryndimjy62cf8zxf8i3f8vg3zpqqjhw15j9mdk3r")))) (build-system gnu-build-system) #:configure-flags (list (string-append "--datadir=" (assoc-ref %outputs "out") "/share/guile/site/2.0")) #:phases (alist-cons-before 'configure 'set-go-directory (lambda* (#:key outputs #:allow-other-keys) Install .go files to $ out / share / guile / site/2.0 . (let ((out (assoc-ref outputs "out"))) (substitute* "module/Makefile.in" (("^wmdir = .*$") (string-append "wmdir = " out "/share/guile/site/2.0\n"))))) (alist-cons-after 'install 'set-load-path (lambda* (#:key inputs outputs #:allow-other-keys) Put Guile - XCB 's and Guile - WM 's modules in the (let* ((out (assoc-ref outputs "out")) (prog (string-append out "/bin/guile-wm")) (mods (string-append out "/share/guile/site/2.0")) (xcb (string-append (assoc-ref inputs "guile-xcb") "/share/guile/site/2.0"))) (wrap-program prog `("GUILE_LOAD_PATH" ":" prefix (,mods ,xcb)) `("GUILE_LOAD_COMPILED_PATH" ":" prefix (,mods ,xcb))))) %standard-phases)))) (native-inputs `(("pkg-config" ,pkg-config))) (inputs `(("guile" ,guile-2.0) ("guile-xcb" ,guile-xcb))) (home-page "-xcb/guile-wm.html") (synopsis "X11 window manager toolkit in Scheme") (description "Guile-WM is a simple window manager that's completely customizable—you have total control of what it does by choosing which modules to include. Included with it are a few modules that provide basic TinyWM-like window management, some window record-keeping, multi-monitor support, and emacs-like keymaps and minibuffer. At this point, it's just enough to get you started.") (license gpl3+)))
59d077e3157e8fd5de963baa2d2eb0e7daaceefff8cb6143476e869ea827a110
SKS-Keyserver/sks-keyserver
ptree_consistency_test.ml
(***********************************************************************) (* ptree_consistency_test.ml - Test for verifying consistency of *) (* prefix tree data structure *) (* *) Copyright ( C ) 2002 , 2003 , 2004 , 2005 , 2006 , 2007 , 2008 , 2009 , 2010 , 2011 , 2012 , 2013 and Contributors (* *) This file is part of SKS . SKS 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. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA or see < / > . (***********************************************************************) open Common open StdLabels open MoreLabels module Set = PSet.Set open ReconPTreeDb let ident x = x let node_to_svalues node = node.PTree.svalues let check_svalues parent children = let parent = ZZp.zzarray_to_array parent in let children = List.map ~f:ZZp.zzarray_to_array children in match children with [] -> failwith "check_svalues: no children to check" | hd::tl -> parent = List.fold_left ~f:ZZp.array_mult ~init:hd tl let check_node ptree parent children = check_svalues parent.PTree.svalues (List.map ~f:node_to_svalues children) let check_leaf ptree node = let points = ptree.PTree.points in let svalues = PTree.create_svalues points in match node.PTree.children with | PTree.Children _ -> failwith "check_leaf called on non-leaf node" | PTree.Leaf children -> Set.iter children ~f:(fun zzs -> let zz = ZZp.of_bytes zzs in ZZp.add_el ~svalues ~points zz ); (ZZp.zzarray_to_array node.PTree.svalues = ZZp.zzarray_to_array svalues) let rec check_tree ptree node = let key = node.PTree.key in let keyrep = Bitstring.to_string key in if PTree.is_leaf node then let rval = check_leaf ptree node in if rval then perror "leaf passed: %s" keyrep else perror "leaf failed: %s" keyrep; rval else let childkeys = PTree.child_keys ptree key in let children = List.map ~f:(fun key -> PTree.get_node_key ptree key) childkeys in let node_passed = check_node ptree node children in if node_passed then perror "internal node passed: %s" keyrep else perror "internal node failed: %s" keyrep; let child_status = List.map ~f:(check_tree ptree) children in node_passed & List.for_all ~f:ident child_status let () = perror "Starting recursive check"; if check_tree !ptree (!ptree).PTree.root then perror "tree passed" else perror "tree FAILED"
null
https://raw.githubusercontent.com/SKS-Keyserver/sks-keyserver/a4e5267d817cddbdfee13d07a7fb38a9b94b3eee/ptree_consistency_test.ml
ocaml
********************************************************************* ptree_consistency_test.ml - Test for verifying consistency of prefix tree data structure redistribute it and/or modify it under the terms of the GNU General 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. *********************************************************************
Copyright ( C ) 2002 , 2003 , 2004 , 2005 , 2006 , 2007 , 2008 , 2009 , 2010 , 2011 , 2012 , 2013 and Contributors This file is part of SKS . SKS is free software ; you can Public License as published by the Free Software Foundation ; either version 2 of the License , or ( at your option ) any later version . 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 or see < / > . open Common open StdLabels open MoreLabels module Set = PSet.Set open ReconPTreeDb let ident x = x let node_to_svalues node = node.PTree.svalues let check_svalues parent children = let parent = ZZp.zzarray_to_array parent in let children = List.map ~f:ZZp.zzarray_to_array children in match children with [] -> failwith "check_svalues: no children to check" | hd::tl -> parent = List.fold_left ~f:ZZp.array_mult ~init:hd tl let check_node ptree parent children = check_svalues parent.PTree.svalues (List.map ~f:node_to_svalues children) let check_leaf ptree node = let points = ptree.PTree.points in let svalues = PTree.create_svalues points in match node.PTree.children with | PTree.Children _ -> failwith "check_leaf called on non-leaf node" | PTree.Leaf children -> Set.iter children ~f:(fun zzs -> let zz = ZZp.of_bytes zzs in ZZp.add_el ~svalues ~points zz ); (ZZp.zzarray_to_array node.PTree.svalues = ZZp.zzarray_to_array svalues) let rec check_tree ptree node = let key = node.PTree.key in let keyrep = Bitstring.to_string key in if PTree.is_leaf node then let rval = check_leaf ptree node in if rval then perror "leaf passed: %s" keyrep else perror "leaf failed: %s" keyrep; rval else let childkeys = PTree.child_keys ptree key in let children = List.map ~f:(fun key -> PTree.get_node_key ptree key) childkeys in let node_passed = check_node ptree node children in if node_passed then perror "internal node passed: %s" keyrep else perror "internal node failed: %s" keyrep; let child_status = List.map ~f:(check_tree ptree) children in node_passed & List.for_all ~f:ident child_status let () = perror "Starting recursive check"; if check_tree !ptree (!ptree).PTree.root then perror "tree passed" else perror "tree FAILED"
65fd8e90e3f9550a517b07f98b31f151cd2f6115629a5e3212b4b92144b1f8c0
maxhbr/LDBcollector
Rating.hs
# LANGUAGE DeriveGeneric # {-# LANGUAGE OverloadedStrings #-} module Model.LicenseProperties.Rating where import qualified Prelude as P import MyPrelude import qualified Data.Text as T import qualified Text.Pandoc as P import qualified Text.Pandoc.Builder as P data Rating = RGo -- can be used | RAttention -- needs more attention | RStop -- needs aproval | RNoGo -- can't be used | RUnknown [Rating] deriving (Generic, Eq) ratingMoreGeneralThan :: Rating -> Rating -> Bool ratingMoreGeneralThan widerRating (RUnknown rs) = all (widerRating `ratingMoreGeneralThan`) rs ratingMoreGeneralThan (RUnknown rs) smallerRating = any (`ratingMoreGeneralThan` smallerRating) rs ratingMoreGeneralThan widerRating smallerRating = widerRating == smallerRating instance Show Rating where show RGo = "Go" show RAttention = "Attention" show RStop = "Stop" show RNoGo = "No-Go" show (RUnknown []) = "Unknown, no option left" show (RUnknown [RGo, RAttention, RStop, RNoGo]) = "Unknown" show (RUnknown possibilities) = "Unknown, probably " ++ intercalate " or " (map show possibilities) instance ToJSON Rating instance Inlineable Rating where toInline = P.text . T.pack . show -- to keep track of current possibilities data RatingState = RatingState Bool Bool Bool Bool | FinalRating Rating deriving (Generic, Eq, Show) instance ToJSON RatingState rsGo :: RatingState -> Bool rsGo (RatingState b _ _ _) = b rsGo (FinalRating r) = r `ratingMoreGeneralThan` RGo rsAttention :: RatingState -> Bool rsAttention (RatingState _ b _ _) = b rsAttention (FinalRating r) = r `ratingMoreGeneralThan` RAttention rsStop :: RatingState -> Bool rsStop (RatingState _ _ b _) = b rsStop (FinalRating r) = r `ratingMoreGeneralThan` RStop rsNoGo :: RatingState -> Bool rsNoGo (RatingState _ _ _ b) = b rsNoGo (FinalRating r) = r `ratingMoreGeneralThan` RNoGo ratingFromRatingState :: RatingState -> Rating ratingFromRatingState s = let ratings = [(rsGo, RGo), (rsAttention, RAttention), (rsStop, RStop), (rsNoGo, RNoGo)] possibleRatings = catMaybes $ map (\(f,r) -> if f s then Just r else Nothing) ratings in case possibleRatings of [r] -> r rs -> RUnknown rs ratingIsPossibleInRatingState :: Rating -> RatingState -> Bool ratingIsPossibleInRatingState r rs = ratingFromRatingState rs `ratingMoreGeneralThan` r minimalImpliedRating :: Rating -> Rating minimalImpliedRating (RUnknown []) = RUnknown [] minimalImpliedRating (RUnknown rs) | RGo `elem` rs = RGo | RAttention `elem` rs = RAttention | RStop `elem` rs = RStop | RNoGo `elem` rs = RNoGo minimalImpliedRating r = r maximalImpliedRating :: Rating -> Rating maximalImpliedRating (RUnknown []) = RUnknown [] maximalImpliedRating (RUnknown rs) | RNoGo `elem` rs = RNoGo | RStop `elem` rs = RStop | RAttention `elem` rs = RAttention | RGo `elem` rs = RGo maximalImpliedRating r = r
null
https://raw.githubusercontent.com/maxhbr/LDBcollector/51d940f0af00b2acdd7de246b2be16fa30fc8a6b/src/Model/LicenseProperties/Rating.hs
haskell
# LANGUAGE OverloadedStrings # can be used needs more attention needs aproval can't be used to keep track of current possibilities
# LANGUAGE DeriveGeneric # module Model.LicenseProperties.Rating where import qualified Prelude as P import MyPrelude import qualified Data.Text as T import qualified Text.Pandoc as P import qualified Text.Pandoc.Builder as P data Rating | RUnknown [Rating] deriving (Generic, Eq) ratingMoreGeneralThan :: Rating -> Rating -> Bool ratingMoreGeneralThan widerRating (RUnknown rs) = all (widerRating `ratingMoreGeneralThan`) rs ratingMoreGeneralThan (RUnknown rs) smallerRating = any (`ratingMoreGeneralThan` smallerRating) rs ratingMoreGeneralThan widerRating smallerRating = widerRating == smallerRating instance Show Rating where show RGo = "Go" show RAttention = "Attention" show RStop = "Stop" show RNoGo = "No-Go" show (RUnknown []) = "Unknown, no option left" show (RUnknown [RGo, RAttention, RStop, RNoGo]) = "Unknown" show (RUnknown possibilities) = "Unknown, probably " ++ intercalate " or " (map show possibilities) instance ToJSON Rating instance Inlineable Rating where toInline = P.text . T.pack . show data RatingState = RatingState Bool Bool Bool Bool | FinalRating Rating deriving (Generic, Eq, Show) instance ToJSON RatingState rsGo :: RatingState -> Bool rsGo (RatingState b _ _ _) = b rsGo (FinalRating r) = r `ratingMoreGeneralThan` RGo rsAttention :: RatingState -> Bool rsAttention (RatingState _ b _ _) = b rsAttention (FinalRating r) = r `ratingMoreGeneralThan` RAttention rsStop :: RatingState -> Bool rsStop (RatingState _ _ b _) = b rsStop (FinalRating r) = r `ratingMoreGeneralThan` RStop rsNoGo :: RatingState -> Bool rsNoGo (RatingState _ _ _ b) = b rsNoGo (FinalRating r) = r `ratingMoreGeneralThan` RNoGo ratingFromRatingState :: RatingState -> Rating ratingFromRatingState s = let ratings = [(rsGo, RGo), (rsAttention, RAttention), (rsStop, RStop), (rsNoGo, RNoGo)] possibleRatings = catMaybes $ map (\(f,r) -> if f s then Just r else Nothing) ratings in case possibleRatings of [r] -> r rs -> RUnknown rs ratingIsPossibleInRatingState :: Rating -> RatingState -> Bool ratingIsPossibleInRatingState r rs = ratingFromRatingState rs `ratingMoreGeneralThan` r minimalImpliedRating :: Rating -> Rating minimalImpliedRating (RUnknown []) = RUnknown [] minimalImpliedRating (RUnknown rs) | RGo `elem` rs = RGo | RAttention `elem` rs = RAttention | RStop `elem` rs = RStop | RNoGo `elem` rs = RNoGo minimalImpliedRating r = r maximalImpliedRating :: Rating -> Rating maximalImpliedRating (RUnknown []) = RUnknown [] maximalImpliedRating (RUnknown rs) | RNoGo `elem` rs = RNoGo | RStop `elem` rs = RStop | RAttention `elem` rs = RAttention | RGo `elem` rs = RGo maximalImpliedRating r = r
139939613584f1da0b920f52876916e0d0aa282be3e6ce53b34fc121e9b84eba
tautologico/opfp
c03-registros.ml
OCaml : na Prática do do Capítulo 03 - Registros e variantes OCaml: Programação Funcional na Prática Andrei de A. Formiga - Casa do Código Exemplos do Capítulo 03 - Registros e variantes *) Os exemplos deste capítulo foram pensados para uso no REPL , digitando uma expressão de cada vez . usando um editor o REPL pode selecionar cada expressão neste arquivo e mandar para o REPL . termina cada expressão , e e colar cada uma no REPL , as expressões no arquivo terminam com ; ; , apesar em arquivos não precisar deste terminador . Os exemplos deste capítulo foram pensados para uso no REPL, digitando uma expressão de cada vez. Quem estiver usando um editor integrado com o REPL pode selecionar cada expressão neste arquivo e mandar para o REPL. Para deixar claro onde termina cada expressão, e para ficar mais fácil de copiar e colar cada uma no REPL, as expressões no arquivo terminam com ;;, apesar de código OCaml em arquivos não precisar deste terminador. *) * 3.1 Sinônimos de tipo type ponto2d = float * float;; let dist_origem (p : ponto2d) = sqrt ((fst p) ** 2.0 +. (snd p) ** 2.0);; let dist_origem p = sqrt ((fst p) ** 2.0 +. (snd p) ** 2.0);; type retangulo = float * float * float * float;; * 3.2 Registros type ponto2d = { x : float; y : float };; { x = 2.0; y = 3.0 };; let criar_ponto2d xp yp = { x = xp; y = yp };; let criar_ponto2d x y = { x = x; y = y };; let criar_ponto2d x y = { x; y };; let p = criar_ponto2d 1.2 3.6;; p.x;; p.y;; Nomes de campos let sum_xy p = p.x +. p.y;; type ponto3d = { x : float; y : float; z : float };; let mult_xy p = p.x *. p.y;; let mult_xy (p : ponto2d) = p.x *. p.y;; * 3.3 Variantes simples type mao = Pedra | Papel | Tesoura;; Pedra;; let m1 = Tesoura;; (* Pattern matching simples *) let vence_de m = if m = Pedra then Papel else if m = Papel then Tesoura m = Tesoura vence_de Tesoura;; let vence_de m = match m with Pedra -> Papel | Papel -> Tesoura | Tesoura -> Pedra;; let perde_de_errado1 m = if m = Pedra then Tesoura else Pedra (* m = Papel *);; perde_de_errado1 Tesoura;; let perde_de_errado2 m = match m with Pedra -> Tesoura | Papel -> Pedra;; (* O tipo determina o algoritmo *) * 3.4 Variantes com valores associados type figura = Retangulo of float * float | Circulo of float | Triangulo of float;; Circulo 5.0;; Retangulo (3.2, 1.2);; (* Pattern matching com valores *) let pi = 3.14159265359;; let perimetro f = match f with Retangulo (l, a) -> 2.0 *. l +. 2.0 *. a | Circulo r -> 2.0 *. pi *. r | Triangulo l -> 3.0 *. l;; let perimetro f = match f with Retangulo (largura, altura) -> 2.0 *. largura +. 2.0 *. altura | Circulo raio -> 2.0 *. pi *. raio | Triangulo lado -> 3.0 *. lado;; let redondo f = match f with Retangulo (l, a) -> false | Circulo r -> true | Triangulo l -> false;; let redondo f = match f with Retangulo (_, _) -> false | Circulo _ -> true | Triangulo _ -> false;; let redondo f = match f with Retangulo _ -> false | Circulo _ -> true | Triangulo _ -> false;; let redondo f = match f with | Circulo _ -> true | _ -> false;; redondo @@ Triangulo 5.23;; - : bool = false * 3.5 Tipos recursivos type lista_int = Nil | Cons of int * lista_int;; Nil;; let l1 = Cons (1, Nil);; let l2 = Cons (2, l1);; Pattern matching e a estrutura recursiva das listas let rec tamanho l = match l with Nil -> 0 | Cons (x, rl) -> 1 + tamanho rl;; tamanho Nil;; tamanho (Cons (1, Nil));; tamanho l2;; * 3.5 Árvores type arvore_int = Folha | No of arvore_int * int * arvore_int;; let a1 = No (Folha, 7, No (Folha, 9, Folha));; let a2 = No (No (Folha, 17, Folha), 21, No (Folha, 42, Folha));; let a3 = No (a1, 12, a2);; let rec soma_arvore a = match a with Folha -> 0 | No (a1, n, a2) -> soma_arvore a1 + n + soma_arvore a2;; soma_arvore a1;; soma_arvore a2;; soma_arvore a3;;
null
https://raw.githubusercontent.com/tautologico/opfp/74ef9ed97b0ab6b78c147c3edf7e0b69f2acf9d1/capitulos/c03-registros.ml
ocaml
Pattern matching simples m = Papel O tipo determina o algoritmo Pattern matching com valores
OCaml : na Prática do do Capítulo 03 - Registros e variantes OCaml: Programação Funcional na Prática Andrei de A. Formiga - Casa do Código Exemplos do Capítulo 03 - Registros e variantes *) Os exemplos deste capítulo foram pensados para uso no REPL , digitando uma expressão de cada vez . usando um editor o REPL pode selecionar cada expressão neste arquivo e mandar para o REPL . termina cada expressão , e e colar cada uma no REPL , as expressões no arquivo terminam com ; ; , apesar em arquivos não precisar deste terminador . Os exemplos deste capítulo foram pensados para uso no REPL, digitando uma expressão de cada vez. Quem estiver usando um editor integrado com o REPL pode selecionar cada expressão neste arquivo e mandar para o REPL. Para deixar claro onde termina cada expressão, e para ficar mais fácil de copiar e colar cada uma no REPL, as expressões no arquivo terminam com ;;, apesar de código OCaml em arquivos não precisar deste terminador. *) * 3.1 Sinônimos de tipo type ponto2d = float * float;; let dist_origem (p : ponto2d) = sqrt ((fst p) ** 2.0 +. (snd p) ** 2.0);; let dist_origem p = sqrt ((fst p) ** 2.0 +. (snd p) ** 2.0);; type retangulo = float * float * float * float;; * 3.2 Registros type ponto2d = { x : float; y : float };; { x = 2.0; y = 3.0 };; let criar_ponto2d xp yp = { x = xp; y = yp };; let criar_ponto2d x y = { x = x; y = y };; let criar_ponto2d x y = { x; y };; let p = criar_ponto2d 1.2 3.6;; p.x;; p.y;; Nomes de campos let sum_xy p = p.x +. p.y;; type ponto3d = { x : float; y : float; z : float };; let mult_xy p = p.x *. p.y;; let mult_xy (p : ponto2d) = p.x *. p.y;; * 3.3 Variantes simples type mao = Pedra | Papel | Tesoura;; Pedra;; let m1 = Tesoura;; let vence_de m = if m = Pedra then Papel else if m = Papel then Tesoura m = Tesoura vence_de Tesoura;; let vence_de m = match m with Pedra -> Papel | Papel -> Tesoura | Tesoura -> Pedra;; let perde_de_errado1 m = if m = Pedra then Tesoura perde_de_errado1 Tesoura;; let perde_de_errado2 m = match m with Pedra -> Tesoura | Papel -> Pedra;; * 3.4 Variantes com valores associados type figura = Retangulo of float * float | Circulo of float | Triangulo of float;; Circulo 5.0;; Retangulo (3.2, 1.2);; let pi = 3.14159265359;; let perimetro f = match f with Retangulo (l, a) -> 2.0 *. l +. 2.0 *. a | Circulo r -> 2.0 *. pi *. r | Triangulo l -> 3.0 *. l;; let perimetro f = match f with Retangulo (largura, altura) -> 2.0 *. largura +. 2.0 *. altura | Circulo raio -> 2.0 *. pi *. raio | Triangulo lado -> 3.0 *. lado;; let redondo f = match f with Retangulo (l, a) -> false | Circulo r -> true | Triangulo l -> false;; let redondo f = match f with Retangulo (_, _) -> false | Circulo _ -> true | Triangulo _ -> false;; let redondo f = match f with Retangulo _ -> false | Circulo _ -> true | Triangulo _ -> false;; let redondo f = match f with | Circulo _ -> true | _ -> false;; redondo @@ Triangulo 5.23;; - : bool = false * 3.5 Tipos recursivos type lista_int = Nil | Cons of int * lista_int;; Nil;; let l1 = Cons (1, Nil);; let l2 = Cons (2, l1);; Pattern matching e a estrutura recursiva das listas let rec tamanho l = match l with Nil -> 0 | Cons (x, rl) -> 1 + tamanho rl;; tamanho Nil;; tamanho (Cons (1, Nil));; tamanho l2;; * 3.5 Árvores type arvore_int = Folha | No of arvore_int * int * arvore_int;; let a1 = No (Folha, 7, No (Folha, 9, Folha));; let a2 = No (No (Folha, 17, Folha), 21, No (Folha, 42, Folha));; let a3 = No (a1, 12, a2);; let rec soma_arvore a = match a with Folha -> 0 | No (a1, n, a2) -> soma_arvore a1 + n + soma_arvore a2;; soma_arvore a1;; soma_arvore a2;; soma_arvore a3;;
c57c5bbc1c9f6fecfa8efa76152aa65d082645aeaff26b2f91a9475d7f230b0f
kit-ty-kate/visitors
expr15c.ml
open Expr15 open Expr15b let () = Printf.printf "%d\n" (size (EAdd (EConst 22, EConst 11)))
null
https://raw.githubusercontent.com/kit-ty-kate/visitors/fc53cc486178781e0b1e581eced98e07facb7d29/test/expr15c.ml
ocaml
open Expr15 open Expr15b let () = Printf.printf "%d\n" (size (EAdd (EConst 22, EConst 11)))
a9a887d003d5f9d6517d64395eed21aae7b6a2a89c33950c61fbb017966df7f7
thheller/shadow-cljsjs
fr_ca.cljs
(ns cljsjs.moment.locale.fr-ca (:require ["moment/locale/fr-ca"]))
null
https://raw.githubusercontent.com/thheller/shadow-cljsjs/eaf350d29d45adb85c0753dff77e276e7925a744/src/main/cljsjs/moment/locale/fr_ca.cljs
clojure
(ns cljsjs.moment.locale.fr-ca (:require ["moment/locale/fr-ca"]))
94a0d44b90820b317a94e1d656c8e8168422b92f8efee4a859bd2537532bafa3
rowangithub/DOrder
ident.mli
(***********************************************************************) (* *) (* Objective Caml *) (* *) , projet Cristal , INRIA Rocquencourt (* *) Copyright 1996 Institut National de Recherche en Informatique et en Automatique . All rights reserved . This file is distributed under the terms of the Q Public License version 1.0 . (* *) (***********************************************************************) $ I d : ident.mli 9547 2010 - 01 - 22 12:48:24Z doligez $ (* Identifiers (unique names) *) type t val create: string -> t val create_persistent: string -> t val create_predef_exn: string -> t This is a very dangerous extension for the internal use of Asolve only . He committed this code ( use before careful consideration please ) val create_with_stamp: string -> int -> t val rename: t -> t val name: t -> string val unique_name: t -> string val unique_toplevel_name: t -> string val persistent: t -> bool val equal: t -> t -> bool (* Compare identifiers by name. *) val same: t -> t -> bool Compare identifiers by binding location . Two identifiers are the same either if they are both non - persistent and have been created by the same call to [ new ] , or if they are both persistent and have the same name . Two identifiers are the same either if they are both non-persistent and have been created by the same call to [new], or if they are both persistent and have the same name. *) val hide: t -> t (* Return an identifier with same name as the given identifier, but stamp different from any stamp returned by new. When put in a 'a tbl, this identifier can only be looked up by name. *) val make_global: t -> unit val global: t -> bool val is_predef_exn: t -> bool val binding_time: t -> int val current_time: unit -> int val set_current_time: int -> unit val reinit: unit -> unit val print: Format.formatter -> t -> unit type 'a tbl (* Association tables from identifiers to type 'a. *) val empty: 'a tbl val add: t -> 'a -> 'a tbl -> 'a tbl val find_same: t -> 'a tbl -> 'a val find_name: string -> 'a tbl -> 'a val keys: 'a tbl -> t list This is a very dangerous extension for the internal use of Asolve only . He committed this code ( use before careful consideration please ) val stamp: t -> int
null
https://raw.githubusercontent.com/rowangithub/DOrder/e0d5efeb8853d2a51cc4796d7db0f8be3185d7df/typing/ident.mli
ocaml
********************************************************************* Objective Caml ********************************************************************* Identifiers (unique names) Compare identifiers by name. Return an identifier with same name as the given identifier, but stamp different from any stamp returned by new. When put in a 'a tbl, this identifier can only be looked up by name. Association tables from identifiers to type 'a.
, projet Cristal , INRIA Rocquencourt Copyright 1996 Institut National de Recherche en Informatique et en Automatique . All rights reserved . This file is distributed under the terms of the Q Public License version 1.0 . $ I d : ident.mli 9547 2010 - 01 - 22 12:48:24Z doligez $ type t val create: string -> t val create_persistent: string -> t val create_predef_exn: string -> t This is a very dangerous extension for the internal use of Asolve only . He committed this code ( use before careful consideration please ) val create_with_stamp: string -> int -> t val rename: t -> t val name: t -> string val unique_name: t -> string val unique_toplevel_name: t -> string val persistent: t -> bool val equal: t -> t -> bool val same: t -> t -> bool Compare identifiers by binding location . Two identifiers are the same either if they are both non - persistent and have been created by the same call to [ new ] , or if they are both persistent and have the same name . Two identifiers are the same either if they are both non-persistent and have been created by the same call to [new], or if they are both persistent and have the same name. *) val hide: t -> t val make_global: t -> unit val global: t -> bool val is_predef_exn: t -> bool val binding_time: t -> int val current_time: unit -> int val set_current_time: int -> unit val reinit: unit -> unit val print: Format.formatter -> t -> unit type 'a tbl val empty: 'a tbl val add: t -> 'a -> 'a tbl -> 'a tbl val find_same: t -> 'a tbl -> 'a val find_name: string -> 'a tbl -> 'a val keys: 'a tbl -> t list This is a very dangerous extension for the internal use of Asolve only . He committed this code ( use before careful consideration please ) val stamp: t -> int
e951ac1b64e824f5972b096096aa583263d7f0bbf32fe65af5a7812737be2a5b
wireapp/wire-server
Cookie_20_28_29_user.hs
-- This file is part of the Wire Server implementation. -- Copyright ( C ) 2022 Wire Swiss GmbH < > -- -- This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation , either version 3 of the License , or ( at your option ) any -- later version. -- -- This program is distributed in the hope that it will be useful, but WITHOUT -- ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -- FOR A PARTICULAR PURPOSE. See the GNU 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 </>. module Test.Wire.API.Golden.Generated.Cookie_20_28_29_user where import Imports (Maybe (Just, Nothing), read) import Wire.API.User.Auth ( Cookie (Cookie), CookieId (CookieId, cookieIdNum), CookieLabel (CookieLabel, cookieLabelText), CookieType (PersistentCookie, SessionCookie), ) testObject_Cookie_20_28_29_user_1 :: Cookie () testObject_Cookie_20_28_29_user_1 = Cookie (CookieId {cookieIdNum = 4}) SessionCookie (read "1864-05-13 05:47:44.953325209615 UTC") (read "1864-05-05 23:11:41.080048429153 UTC") Nothing Nothing () testObject_Cookie_20_28_29_user_2 :: Cookie () testObject_Cookie_20_28_29_user_2 = Cookie (CookieId {cookieIdNum = 4}) SessionCookie (read "1864-05-11 05:25:35.472438946148 UTC") (read "1864-05-13 13:29:31.539239953694 UTC") Nothing (Just (CookieId {cookieIdNum = 1})) () testObject_Cookie_20_28_29_user_3 :: Cookie () testObject_Cookie_20_28_29_user_3 = Cookie (CookieId {cookieIdNum = 0}) PersistentCookie (read "1864-05-09 06:32:09.653354599176 UTC") (read "1864-05-07 07:38:14.515001504525 UTC") (Just (CookieLabel {cookieLabelText = "\"\ETB\ETX"})) (Just (CookieId {cookieIdNum = 1})) () testObject_Cookie_20_28_29_user_4 :: Cookie () testObject_Cookie_20_28_29_user_4 = Cookie (CookieId {cookieIdNum = 3}) SessionCookie (read "1864-05-12 17:39:22.647800906939 UTC") (read "1864-05-08 21:05:44.689352987872 UTC") (Just (CookieLabel {cookieLabelText = "\SOH\STX"})) (Just (CookieId {cookieIdNum = 0})) () testObject_Cookie_20_28_29_user_5 :: Cookie () testObject_Cookie_20_28_29_user_5 = Cookie (CookieId {cookieIdNum = 1}) PersistentCookie (read "1864-05-05 18:31:27.854562456661 UTC") (read "1864-05-07 20:47:39.585530890253 UTC") Nothing (Just (CookieId {cookieIdNum = 1})) () testObject_Cookie_20_28_29_user_6 :: Cookie () testObject_Cookie_20_28_29_user_6 = Cookie (CookieId {cookieIdNum = 3}) SessionCookie (read "1864-05-09 21:11:41.006743014266 UTC") (read "1864-05-11 13:07:04.231169675877 UTC") (Just (CookieLabel {cookieLabelText = "x"})) (Just (CookieId {cookieIdNum = 0})) () testObject_Cookie_20_28_29_user_7 :: Cookie () testObject_Cookie_20_28_29_user_7 = Cookie (CookieId {cookieIdNum = 3}) SessionCookie (read "1864-05-10 10:07:45.191235538251 UTC") (read "1864-05-08 11:48:36.288367238761 UTC") Nothing (Just (CookieId {cookieIdNum = 3})) () testObject_Cookie_20_28_29_user_8 :: Cookie () testObject_Cookie_20_28_29_user_8 = Cookie (CookieId {cookieIdNum = 2}) PersistentCookie (read "1864-05-13 23:20:18.620984948327 UTC") (read "1864-05-10 17:19:51.999573387671 UTC") (Just (CookieLabel {cookieLabelText = "W\1095116"})) Nothing () testObject_Cookie_20_28_29_user_9 :: Cookie () testObject_Cookie_20_28_29_user_9 = Cookie (CookieId {cookieIdNum = 0}) PersistentCookie (read "1864-05-10 21:07:17.237535753229 UTC") (read "1864-05-07 13:26:23.632337100061 UTC") (Just (CookieLabel {cookieLabelText = "_"})) (Just (CookieId {cookieIdNum = 3})) () testObject_Cookie_20_28_29_user_10 :: Cookie () testObject_Cookie_20_28_29_user_10 = Cookie (CookieId {cookieIdNum = 0}) PersistentCookie (read "1864-05-05 13:10:26.655350748893 UTC") (read "1864-05-11 07:40:26.20362225993 UTC") (Just (CookieLabel {cookieLabelText = "@\129045f"})) (Just (CookieId {cookieIdNum = 2})) () testObject_Cookie_20_28_29_user_11 :: Cookie () testObject_Cookie_20_28_29_user_11 = Cookie (CookieId {cookieIdNum = 1}) SessionCookie (read "1864-05-05 18:46:43.751100514127 UTC") (read "1864-05-05 20:09:58.51051779151 UTC") (Just (CookieLabel {cookieLabelText = ""})) (Just (CookieId {cookieIdNum = 2})) () testObject_Cookie_20_28_29_user_12 :: Cookie () testObject_Cookie_20_28_29_user_12 = Cookie (CookieId {cookieIdNum = 3}) PersistentCookie (read "1864-05-08 10:13:20.99278185582 UTC") (read "1864-05-13 09:17:06.972542913972 UTC") (Just (CookieLabel {cookieLabelText = "0i"})) (Just (CookieId {cookieIdNum = 1})) () testObject_Cookie_20_28_29_user_13 :: Cookie () testObject_Cookie_20_28_29_user_13 = Cookie (CookieId {cookieIdNum = 0}) PersistentCookie (read "1864-05-08 13:32:34.77859094095 UTC") (read "1864-05-11 23:26:06.481608900736 UTC") (Just (CookieLabel {cookieLabelText = "\SI"})) (Just (CookieId {cookieIdNum = 2})) () testObject_Cookie_20_28_29_user_14 :: Cookie () testObject_Cookie_20_28_29_user_14 = Cookie (CookieId {cookieIdNum = 3}) SessionCookie (read "1864-05-13 05:03:36.689760525241 UTC") (read "1864-05-13 09:20:52.214909900547 UTC") (Just (CookieLabel {cookieLabelText = "\a5"})) (Just (CookieId {cookieIdNum = 2})) () testObject_Cookie_20_28_29_user_15 :: Cookie () testObject_Cookie_20_28_29_user_15 = Cookie (CookieId {cookieIdNum = 4}) SessionCookie (read "1864-05-13 15:06:06.162467079651 UTC") (read "1864-05-07 20:56:24.910663768998 UTC") Nothing Nothing () testObject_Cookie_20_28_29_user_16 :: Cookie () testObject_Cookie_20_28_29_user_16 = Cookie (CookieId {cookieIdNum = 1}) PersistentCookie (read "1864-05-11 01:41:37.159116274364 UTC") (read "1864-05-08 08:29:26.712811058187 UTC") Nothing Nothing () testObject_Cookie_20_28_29_user_17 :: Cookie () testObject_Cookie_20_28_29_user_17 = Cookie (CookieId {cookieIdNum = 3}) SessionCookie (read "1864-05-12 11:59:56.901830591377 UTC") (read "1864-05-10 21:32:23.833192157326 UTC") (Just (CookieLabel {cookieLabelText = "\13875"})) Nothing () testObject_Cookie_20_28_29_user_18 :: Cookie () testObject_Cookie_20_28_29_user_18 = Cookie (CookieId {cookieIdNum = 0}) PersistentCookie (read "1864-05-13 18:38:28.752407147796 UTC") (read "1864-05-12 15:17:29.299354245486 UTC") (Just (CookieLabel {cookieLabelText = "\1070053"})) (Just (CookieId {cookieIdNum = 0})) () testObject_Cookie_20_28_29_user_19 :: Cookie () testObject_Cookie_20_28_29_user_19 = Cookie (CookieId {cookieIdNum = 4}) SessionCookie (read "1864-05-13 07:03:36.619050229877 UTC") (read "1864-05-10 10:06:17.906037443659 UTC") Nothing (Just (CookieId {cookieIdNum = 3})) () testObject_Cookie_20_28_29_user_20 :: Cookie () testObject_Cookie_20_28_29_user_20 = Cookie (CookieId {cookieIdNum = 2}) PersistentCookie (read "1864-05-13 12:22:12.980555635796 UTC") (read "1864-05-06 11:24:34.525397249315 UTC") (Just (CookieLabel {cookieLabelText = "\1081398\&0\DC4W"})) (Just (CookieId {cookieIdNum = 0})) ()
null
https://raw.githubusercontent.com/wireapp/wire-server/c428355b7683b7b7722ea544eba314fc843ad8fa/libs/wire-api/test/golden/Test/Wire/API/Golden/Generated/Cookie_20_28_29_user.hs
haskell
This file is part of the Wire Server implementation. This program is free software: you can redistribute it and/or modify it under 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 Affero General Public License for more details. with this program. If not, see </>.
Copyright ( C ) 2022 Wire Swiss GmbH < > the terms of the GNU Affero General Public License as published by the Free Software Foundation , either version 3 of the License , or ( at your option ) any You should have received a copy of the GNU Affero General Public License along module Test.Wire.API.Golden.Generated.Cookie_20_28_29_user where import Imports (Maybe (Just, Nothing), read) import Wire.API.User.Auth ( Cookie (Cookie), CookieId (CookieId, cookieIdNum), CookieLabel (CookieLabel, cookieLabelText), CookieType (PersistentCookie, SessionCookie), ) testObject_Cookie_20_28_29_user_1 :: Cookie () testObject_Cookie_20_28_29_user_1 = Cookie (CookieId {cookieIdNum = 4}) SessionCookie (read "1864-05-13 05:47:44.953325209615 UTC") (read "1864-05-05 23:11:41.080048429153 UTC") Nothing Nothing () testObject_Cookie_20_28_29_user_2 :: Cookie () testObject_Cookie_20_28_29_user_2 = Cookie (CookieId {cookieIdNum = 4}) SessionCookie (read "1864-05-11 05:25:35.472438946148 UTC") (read "1864-05-13 13:29:31.539239953694 UTC") Nothing (Just (CookieId {cookieIdNum = 1})) () testObject_Cookie_20_28_29_user_3 :: Cookie () testObject_Cookie_20_28_29_user_3 = Cookie (CookieId {cookieIdNum = 0}) PersistentCookie (read "1864-05-09 06:32:09.653354599176 UTC") (read "1864-05-07 07:38:14.515001504525 UTC") (Just (CookieLabel {cookieLabelText = "\"\ETB\ETX"})) (Just (CookieId {cookieIdNum = 1})) () testObject_Cookie_20_28_29_user_4 :: Cookie () testObject_Cookie_20_28_29_user_4 = Cookie (CookieId {cookieIdNum = 3}) SessionCookie (read "1864-05-12 17:39:22.647800906939 UTC") (read "1864-05-08 21:05:44.689352987872 UTC") (Just (CookieLabel {cookieLabelText = "\SOH\STX"})) (Just (CookieId {cookieIdNum = 0})) () testObject_Cookie_20_28_29_user_5 :: Cookie () testObject_Cookie_20_28_29_user_5 = Cookie (CookieId {cookieIdNum = 1}) PersistentCookie (read "1864-05-05 18:31:27.854562456661 UTC") (read "1864-05-07 20:47:39.585530890253 UTC") Nothing (Just (CookieId {cookieIdNum = 1})) () testObject_Cookie_20_28_29_user_6 :: Cookie () testObject_Cookie_20_28_29_user_6 = Cookie (CookieId {cookieIdNum = 3}) SessionCookie (read "1864-05-09 21:11:41.006743014266 UTC") (read "1864-05-11 13:07:04.231169675877 UTC") (Just (CookieLabel {cookieLabelText = "x"})) (Just (CookieId {cookieIdNum = 0})) () testObject_Cookie_20_28_29_user_7 :: Cookie () testObject_Cookie_20_28_29_user_7 = Cookie (CookieId {cookieIdNum = 3}) SessionCookie (read "1864-05-10 10:07:45.191235538251 UTC") (read "1864-05-08 11:48:36.288367238761 UTC") Nothing (Just (CookieId {cookieIdNum = 3})) () testObject_Cookie_20_28_29_user_8 :: Cookie () testObject_Cookie_20_28_29_user_8 = Cookie (CookieId {cookieIdNum = 2}) PersistentCookie (read "1864-05-13 23:20:18.620984948327 UTC") (read "1864-05-10 17:19:51.999573387671 UTC") (Just (CookieLabel {cookieLabelText = "W\1095116"})) Nothing () testObject_Cookie_20_28_29_user_9 :: Cookie () testObject_Cookie_20_28_29_user_9 = Cookie (CookieId {cookieIdNum = 0}) PersistentCookie (read "1864-05-10 21:07:17.237535753229 UTC") (read "1864-05-07 13:26:23.632337100061 UTC") (Just (CookieLabel {cookieLabelText = "_"})) (Just (CookieId {cookieIdNum = 3})) () testObject_Cookie_20_28_29_user_10 :: Cookie () testObject_Cookie_20_28_29_user_10 = Cookie (CookieId {cookieIdNum = 0}) PersistentCookie (read "1864-05-05 13:10:26.655350748893 UTC") (read "1864-05-11 07:40:26.20362225993 UTC") (Just (CookieLabel {cookieLabelText = "@\129045f"})) (Just (CookieId {cookieIdNum = 2})) () testObject_Cookie_20_28_29_user_11 :: Cookie () testObject_Cookie_20_28_29_user_11 = Cookie (CookieId {cookieIdNum = 1}) SessionCookie (read "1864-05-05 18:46:43.751100514127 UTC") (read "1864-05-05 20:09:58.51051779151 UTC") (Just (CookieLabel {cookieLabelText = ""})) (Just (CookieId {cookieIdNum = 2})) () testObject_Cookie_20_28_29_user_12 :: Cookie () testObject_Cookie_20_28_29_user_12 = Cookie (CookieId {cookieIdNum = 3}) PersistentCookie (read "1864-05-08 10:13:20.99278185582 UTC") (read "1864-05-13 09:17:06.972542913972 UTC") (Just (CookieLabel {cookieLabelText = "0i"})) (Just (CookieId {cookieIdNum = 1})) () testObject_Cookie_20_28_29_user_13 :: Cookie () testObject_Cookie_20_28_29_user_13 = Cookie (CookieId {cookieIdNum = 0}) PersistentCookie (read "1864-05-08 13:32:34.77859094095 UTC") (read "1864-05-11 23:26:06.481608900736 UTC") (Just (CookieLabel {cookieLabelText = "\SI"})) (Just (CookieId {cookieIdNum = 2})) () testObject_Cookie_20_28_29_user_14 :: Cookie () testObject_Cookie_20_28_29_user_14 = Cookie (CookieId {cookieIdNum = 3}) SessionCookie (read "1864-05-13 05:03:36.689760525241 UTC") (read "1864-05-13 09:20:52.214909900547 UTC") (Just (CookieLabel {cookieLabelText = "\a5"})) (Just (CookieId {cookieIdNum = 2})) () testObject_Cookie_20_28_29_user_15 :: Cookie () testObject_Cookie_20_28_29_user_15 = Cookie (CookieId {cookieIdNum = 4}) SessionCookie (read "1864-05-13 15:06:06.162467079651 UTC") (read "1864-05-07 20:56:24.910663768998 UTC") Nothing Nothing () testObject_Cookie_20_28_29_user_16 :: Cookie () testObject_Cookie_20_28_29_user_16 = Cookie (CookieId {cookieIdNum = 1}) PersistentCookie (read "1864-05-11 01:41:37.159116274364 UTC") (read "1864-05-08 08:29:26.712811058187 UTC") Nothing Nothing () testObject_Cookie_20_28_29_user_17 :: Cookie () testObject_Cookie_20_28_29_user_17 = Cookie (CookieId {cookieIdNum = 3}) SessionCookie (read "1864-05-12 11:59:56.901830591377 UTC") (read "1864-05-10 21:32:23.833192157326 UTC") (Just (CookieLabel {cookieLabelText = "\13875"})) Nothing () testObject_Cookie_20_28_29_user_18 :: Cookie () testObject_Cookie_20_28_29_user_18 = Cookie (CookieId {cookieIdNum = 0}) PersistentCookie (read "1864-05-13 18:38:28.752407147796 UTC") (read "1864-05-12 15:17:29.299354245486 UTC") (Just (CookieLabel {cookieLabelText = "\1070053"})) (Just (CookieId {cookieIdNum = 0})) () testObject_Cookie_20_28_29_user_19 :: Cookie () testObject_Cookie_20_28_29_user_19 = Cookie (CookieId {cookieIdNum = 4}) SessionCookie (read "1864-05-13 07:03:36.619050229877 UTC") (read "1864-05-10 10:06:17.906037443659 UTC") Nothing (Just (CookieId {cookieIdNum = 3})) () testObject_Cookie_20_28_29_user_20 :: Cookie () testObject_Cookie_20_28_29_user_20 = Cookie (CookieId {cookieIdNum = 2}) PersistentCookie (read "1864-05-13 12:22:12.980555635796 UTC") (read "1864-05-06 11:24:34.525397249315 UTC") (Just (CookieLabel {cookieLabelText = "\1081398\&0\DC4W"})) (Just (CookieId {cookieIdNum = 0})) ()
180bc463443dd3831c6eb73674ed45cfeff59b2cca07e240f2cc63bbbfe39ebe
slyrus/cl-bio
utilities.lisp
(in-package :bio) ;; utility functions (defun split-string-into-lines-list (string &key (max-line-length 70)) (let ((line-buffer (make-string max-line-length))) (with-input-from-string (stream string) (loop for count = (read-sequence line-buffer stream) while (plusp count) collect (subseq line-buffer 0 count))))) (defgeneric split-string-into-lines (string &key stream max-line-length)) (defmethod split-string-into-lines (string &key stream max-line-length) (format stream "~{~A~^~&~}" (apply #'split-string-into-lines-list string (when max-line-length `(:max-line-length ,max-line-length))))) (defun char-lookup-array-length (char-list) (1+ (apply #'max (mapcar #'char-code (mapcan #'(lambda (x) (list (char-upcase x) (char-downcase x))) char-list))))) (defun flexichain-to-list (fc) (loop for i below (flexichain:nb-elements fc) collect (flexichain:element* fc i))) (defun general-flexichain-to-string (fc) (coerce (loop for i below (flexichain:nb-elements fc) append (let ((el (flexichain:element* fc i))) (cond ((characterp el) (list el)) ((stringp el) (coerce el 'list))))) 'string)) (defun vector-flexichain-to-string (fc) (coerce (loop for i below (flexichain:nb-elements fc) collect (flexichain:element* fc i)) 'string)) (defun find-matches (seq1 seq2) "Returns a list of the occurences of seq1 in seq2. Note that the instances of seq1 in seq2 can overlap such that (find-matches \"AA\" \"AAA\" returns (0 1)." (butlast (loop with i = 0 while i collect (setf i (search seq1 seq2 :start2 i)) when i do (incf i))))
null
https://raw.githubusercontent.com/slyrus/cl-bio/e6de2bc7f4accaa11466902407e43fae3184973f/utilities.lisp
lisp
utility functions
(in-package :bio) (defun split-string-into-lines-list (string &key (max-line-length 70)) (let ((line-buffer (make-string max-line-length))) (with-input-from-string (stream string) (loop for count = (read-sequence line-buffer stream) while (plusp count) collect (subseq line-buffer 0 count))))) (defgeneric split-string-into-lines (string &key stream max-line-length)) (defmethod split-string-into-lines (string &key stream max-line-length) (format stream "~{~A~^~&~}" (apply #'split-string-into-lines-list string (when max-line-length `(:max-line-length ,max-line-length))))) (defun char-lookup-array-length (char-list) (1+ (apply #'max (mapcar #'char-code (mapcan #'(lambda (x) (list (char-upcase x) (char-downcase x))) char-list))))) (defun flexichain-to-list (fc) (loop for i below (flexichain:nb-elements fc) collect (flexichain:element* fc i))) (defun general-flexichain-to-string (fc) (coerce (loop for i below (flexichain:nb-elements fc) append (let ((el (flexichain:element* fc i))) (cond ((characterp el) (list el)) ((stringp el) (coerce el 'list))))) 'string)) (defun vector-flexichain-to-string (fc) (coerce (loop for i below (flexichain:nb-elements fc) collect (flexichain:element* fc i)) 'string)) (defun find-matches (seq1 seq2) "Returns a list of the occurences of seq1 in seq2. Note that the instances of seq1 in seq2 can overlap such that (find-matches \"AA\" \"AAA\" returns (0 1)." (butlast (loop with i = 0 while i collect (setf i (search seq1 seq2 :start2 i)) when i do (incf i))))
4f2163c538c54658e881caa2093952e2a11b171fb018d3c6277b02d27dc4a27e
screenshotbot/screenshotbot-oss
test-auto-cleanup.lisp
;;;; Copyright 2018-Present Modern Interpreters Inc. ;;;; This Source Code Form is subject to the terms of the Mozilla Public License , v. 2.0 . If a copy of the MPL was not distributed with this file , You can obtain one at /. (defpackage :screenshotbot/model/test-auto-cleanup (:use #:cl #:fiveam) (:import-from #:util/store #:with-test-store) (:import-from #:screenshotbot/model/auto-cleanup #:dispatch-cleanups #:register-auto-cleanup #:*cleanups*) (:import-from #:bknr.datastore #:class-instances) (:import-from #:bknr.datastore #:store-object) (:import-from #:bknr.datastore #:persistent-class) (:import-from #:bknr.datastore #:all-store-objects) (:local-nicknames (#:a #:alexandria))) (in-package :screenshotbot/model/test-auto-cleanup) (util/fiveam:def-suite) (def-fixture state () (with-test-store () (let ((*cleanups* nil)) (register-auto-cleanup 'simple-obj :timestamp #'ts) (&body)))) (defclass simple-obj (store-object) ((ts :initarg :ts :reader ts)) (:default-initargs :ts (get-universal-time)) (:metaclass persistent-class)) (defclass simple-obj-2 (store-object) ((ts :initarg :ts :reader ts)) (:default-initargs :ts (get-universal-time)) (:metaclass persistent-class)) (test simple-cleanup (with-fixture state () (is (= 1 (length *cleanups*))) (register-auto-cleanup 'simple-obj :timestamp #'ts) (is (= 1 (length *cleanups*))))) (test attempt-cleanup (with-fixture state () (make-instance 'simple-obj) (dispatch-cleanups) (is (eql 1 (length (class-instances 'simple-obj)))))) (test attempt-cleanup-with-old-objects (with-fixture state () (let ((obj1 (make-instance 'simple-obj)) (obj2 (make-instance 'simple-obj :ts (- (get-universal-time) (* 24 3600 60))))) (dispatch-cleanups) (is (equal (list obj1) (class-instances 'simple-obj)))))) (test only-delete-the-right-objects (with-fixture state () (let ((ts (- (get-universal-time) (* 24 3600 60)))) (let ((obj1 (make-instance 'simple-obj-2 :ts ts)) (obj2 (make-instance 'simple-obj :ts ts))) (dispatch-cleanups) (is (equal (list obj1) (all-store-objects)))))))
null
https://raw.githubusercontent.com/screenshotbot/screenshotbot-oss/7d884c485b2693945578ab19bc5ea45ff654b437/src/screenshotbot/model/test-auto-cleanup.lisp
lisp
Copyright 2018-Present Modern Interpreters Inc.
This Source Code Form is subject to the terms of the Mozilla Public License , v. 2.0 . If a copy of the MPL was not distributed with this file , You can obtain one at /. (defpackage :screenshotbot/model/test-auto-cleanup (:use #:cl #:fiveam) (:import-from #:util/store #:with-test-store) (:import-from #:screenshotbot/model/auto-cleanup #:dispatch-cleanups #:register-auto-cleanup #:*cleanups*) (:import-from #:bknr.datastore #:class-instances) (:import-from #:bknr.datastore #:store-object) (:import-from #:bknr.datastore #:persistent-class) (:import-from #:bknr.datastore #:all-store-objects) (:local-nicknames (#:a #:alexandria))) (in-package :screenshotbot/model/test-auto-cleanup) (util/fiveam:def-suite) (def-fixture state () (with-test-store () (let ((*cleanups* nil)) (register-auto-cleanup 'simple-obj :timestamp #'ts) (&body)))) (defclass simple-obj (store-object) ((ts :initarg :ts :reader ts)) (:default-initargs :ts (get-universal-time)) (:metaclass persistent-class)) (defclass simple-obj-2 (store-object) ((ts :initarg :ts :reader ts)) (:default-initargs :ts (get-universal-time)) (:metaclass persistent-class)) (test simple-cleanup (with-fixture state () (is (= 1 (length *cleanups*))) (register-auto-cleanup 'simple-obj :timestamp #'ts) (is (= 1 (length *cleanups*))))) (test attempt-cleanup (with-fixture state () (make-instance 'simple-obj) (dispatch-cleanups) (is (eql 1 (length (class-instances 'simple-obj)))))) (test attempt-cleanup-with-old-objects (with-fixture state () (let ((obj1 (make-instance 'simple-obj)) (obj2 (make-instance 'simple-obj :ts (- (get-universal-time) (* 24 3600 60))))) (dispatch-cleanups) (is (equal (list obj1) (class-instances 'simple-obj)))))) (test only-delete-the-right-objects (with-fixture state () (let ((ts (- (get-universal-time) (* 24 3600 60)))) (let ((obj1 (make-instance 'simple-obj-2 :ts ts)) (obj2 (make-instance 'simple-obj :ts ts))) (dispatch-cleanups) (is (equal (list obj1) (all-store-objects)))))))
1655f2598ce0c4cdfa858f9e3eeae80e6f6aa9e0d72882ca7a8235aea0124f3d
caiorss/Functional-Programming
integral.hs
{- Reference: /~cazelais/187/simpson.pdf: -} f :: Double -> Double f x = x g x = sqrt(1+x^3) integratorSimple n f a b = area where dx = (b - a)/n xi = map (\i -> a + i*dx) [0..n] fxi = map f xi area = dx * sum fxi Consecutive Points Patterns - [ ( , x1 ) , ( x1 , x2 ) ... ( xk-1 , xk ) ] - [(x0, x1), (x1, x2) ... (xk-1, xk)] -} pairs lst = zip lst (tail lst) triples lst = zip3 lst (tail lst) (tail $ tail lst) {- Trapezius Rule Integration - -} integratorTrapezius n f a b = area where dx = (b - a)/n xi = map (\i -> a + i*dx) [0..n] fxiPairs = pairs $ map f xi area = 1/2*dx * ( sum $ map (\(a, b) -> a+b) fxiPairs) --{- integratorSimpson ns f a b = area where n = fromIntegral ns dx = (b - a)/n xi = map (\i -> a + i*dx) [0..n] fxi = map f xi area2y = (*2) $ sum $ map (\i -> fxi !! i) (filter even [1..(ns-1)]) area4y = (*4) $ sum $ map (\i -> fxi !! i) (filter odd [1..(ns-1)]) area = dx/3*( area2y + area4y + ( head fxi) + (last fxi)) serieConvergence tol maxit serie = (snd converged, iterations) where testError = (\(a, b) -> abs(a-b) > tol) sequence = take maxit $ takeWhile testError (pairs serie) converged = last sequence iterations = length(sequence) integ1 n = integratorSimple n g 2 6 integ2 n = integratorTrapezius n g 2 6 integ3 n = integratorSimpson n g 2 6
null
https://raw.githubusercontent.com/caiorss/Functional-Programming/ef3526898e3014e9c99bf495033ff36a4530503d/codes/integral.hs
haskell
Reference: /~cazelais/187/simpson.pdf: Trapezius Rule Integration - {-
f :: Double -> Double f x = x g x = sqrt(1+x^3) integratorSimple n f a b = area where dx = (b - a)/n xi = map (\i -> a + i*dx) [0..n] fxi = map f xi area = dx * sum fxi Consecutive Points Patterns - [ ( , x1 ) , ( x1 , x2 ) ... ( xk-1 , xk ) ] - [(x0, x1), (x1, x2) ... (xk-1, xk)] -} pairs lst = zip lst (tail lst) triples lst = zip3 lst (tail lst) (tail $ tail lst) integratorTrapezius n f a b = area where dx = (b - a)/n xi = map (\i -> a + i*dx) [0..n] fxiPairs = pairs $ map f xi area = 1/2*dx * ( sum $ map (\(a, b) -> a+b) fxiPairs) integratorSimpson ns f a b = area where n = fromIntegral ns dx = (b - a)/n xi = map (\i -> a + i*dx) [0..n] fxi = map f xi area2y = (*2) $ sum $ map (\i -> fxi !! i) (filter even [1..(ns-1)]) area4y = (*4) $ sum $ map (\i -> fxi !! i) (filter odd [1..(ns-1)]) area = dx/3*( area2y + area4y + ( head fxi) + (last fxi)) serieConvergence tol maxit serie = (snd converged, iterations) where testError = (\(a, b) -> abs(a-b) > tol) sequence = take maxit $ takeWhile testError (pairs serie) converged = last sequence iterations = length(sequence) integ1 n = integratorSimple n g 2 6 integ2 n = integratorTrapezius n g 2 6 integ3 n = integratorSimpson n g 2 6
4cb3b5c6eb9c1a460fede75bf495d6449ed2be8c8016d7d43171fbd82f3c3278
johnstonskj/rml-core
individual.rkt
#lang racket ;; ;; Racket Machine Learning - Core. ;; ~ 2018 . ;; (provide (contract-out [make-individual (->* () (#:data-set data-set?) #:rest any/c individual?)] [data-set-individual (-> data-set? individual?)] [individual? (-> any/c boolean?)] [no-more-individuals symbol?] [individuals (-> data-set? exact-nonnegative-integer? generator?)])) ;; ---------- Requirements (require "data.rkt" "private/dataset.rkt" racket/generator) ;; ---------- Implementation (define (individual? a) (if (hash? a) (empty? (filter-not string? (hash-keys a))) #f)) (define (make-individual #:data-set [dataset #f] . lst) (let ([ind (apply hash lst)]) (when (not (individual? ind)) (raise-argument-error 'make-individual "not a valid hash construction list" 0 lst)) (when dataset (let ([ds-names (list->set (append (features dataset) (classifiers dataset)))] [in-names (list->set (hash-keys ind))]) (when (not (set=? ds-names in-names)) (raise-argument-error 'make-individual "construction list does not match data-set" 0 lst)))) ind)) (define (data-set-individual dataset) (make-hash (hash-map (data-set-name-index dataset) (λ (k v) (cons k #f))))) (define no-more-individuals (gensym)) (define (individuals ds partition-id) (generator () (let ([source (partition ds partition-id)]) (for ([row (range (vector-length (vector-ref source 0)))]) (yield (make-hash (hash-map (data-set-name-index ds) (λ (k v) (cons k (vector-ref (vector-ref source (hash-ref (data-set-name-index ds) k)) row))))))) no-more-individuals)))
null
https://raw.githubusercontent.com/johnstonskj/rml-core/8f3ca8b47e552911054f2aa12b296dbf40dad637/rml/individual.rkt
racket
Racket Machine Learning - Core. ---------- Requirements ---------- Implementation
#lang racket ~ 2018 . (provide (contract-out [make-individual (->* () (#:data-set data-set?) #:rest any/c individual?)] [data-set-individual (-> data-set? individual?)] [individual? (-> any/c boolean?)] [no-more-individuals symbol?] [individuals (-> data-set? exact-nonnegative-integer? generator?)])) (require "data.rkt" "private/dataset.rkt" racket/generator) (define (individual? a) (if (hash? a) (empty? (filter-not string? (hash-keys a))) #f)) (define (make-individual #:data-set [dataset #f] . lst) (let ([ind (apply hash lst)]) (when (not (individual? ind)) (raise-argument-error 'make-individual "not a valid hash construction list" 0 lst)) (when dataset (let ([ds-names (list->set (append (features dataset) (classifiers dataset)))] [in-names (list->set (hash-keys ind))]) (when (not (set=? ds-names in-names)) (raise-argument-error 'make-individual "construction list does not match data-set" 0 lst)))) ind)) (define (data-set-individual dataset) (make-hash (hash-map (data-set-name-index dataset) (λ (k v) (cons k #f))))) (define no-more-individuals (gensym)) (define (individuals ds partition-id) (generator () (let ([source (partition ds partition-id)]) (for ([row (range (vector-length (vector-ref source 0)))]) (yield (make-hash (hash-map (data-set-name-index ds) (λ (k v) (cons k (vector-ref (vector-ref source (hash-ref (data-set-name-index ds) k)) row))))))) no-more-individuals)))
a45b74434e8d1b1cb5c108026b30edba208b800cd7f355754a5252d1f7b8fc95
sellout/haskerwaul
Full.hs
module Haskerwaul.Functor.Full ( module Haskerwaul.Functor.Full -- * extended modules , module Haskerwaul.Functor ) where import Data.Constraint ((:-), Dict) import Data.Functor.Identity (Identity) import Haskerwaul.Functor -- | [nLab](+functor) class Functor c d f => FullFunctor c d f -- | `Dict` is a `Haskerwaul.Functor.Faithful.Full.FullFaithfulFunctor` between -- the category of constraints and __Hask__. instance FullFunctor (:-) (->) Dict -- | `Identity` is a `Haskerwaul.Functor.Faithful.Full.FullFaithfulFunctor` -- (endofunctor, actually) in __Hask__. instance FullFunctor (->) (->) Identity
null
https://raw.githubusercontent.com/sellout/haskerwaul/cf54bd7ce5bf4f3d1fd0d9d991dc733785b66a73/src/Haskerwaul/Functor/Full.hs
haskell
* extended modules | [nLab](+functor) | `Dict` is a `Haskerwaul.Functor.Faithful.Full.FullFaithfulFunctor` between the category of constraints and __Hask__. | `Identity` is a `Haskerwaul.Functor.Faithful.Full.FullFaithfulFunctor` (endofunctor, actually) in __Hask__.
module Haskerwaul.Functor.Full ( module Haskerwaul.Functor.Full , module Haskerwaul.Functor ) where import Data.Constraint ((:-), Dict) import Data.Functor.Identity (Identity) import Haskerwaul.Functor class Functor c d f => FullFunctor c d f instance FullFunctor (:-) (->) Dict instance FullFunctor (->) (->) Identity
8a21875a350bbd88436be68147883c3ae3e87a0a9eef9adccb7355f6f31b74ee
BenjaminVanRyseghem/great-things-done
due_date_picker.cljs
Copyright ( c ) 2015 , . All rights reserved . ; The use and distribution terms for this software are covered by the Eclipse Public License 1.0 ( -1.0.php ) ; which can be found in the file epl-v10.html at the root of this distribution. ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. ; You must not remove this notice, or any other, from this software. (ns ui.widgets.due-date-picker (:use [jayq.core :only [$]]) (:require [gtd.settings :as settings] [reagent.core :as reagent :refer [atom]] [ui.widgets.show-in-today-picker :as show-in-today-picker])) (defn- clear-date [entity] (reagent/create-class {:component-did-mount #(.click ($ (str "#clear-due-date-" (:id entity))) (fn [] (.datepicker ($ (str "#entity-due-date-picker-" (:id entity))) "clearDates"))) :reagent-render (fn [] [:div {:id (str "clear-due-date-" (:id entity)) :class "clear-due-date"} [:i.fa.fa-times]])})) (defn- build [entity callback on-enter] (let [date (atom (:due-date entity))] (reagent/create-class {:component-did-mount (fn [] (.on ($ (str "#entity-due-date-picker-" (:id entity))) "keydown" (fn [e] (when (and (= (.-keyCode e) 13) (= (.-length ($ :.dropdown-menu.datepicker-dropdown)) 0) (on-enter))) (when (= (.-keyCode e) 8) (.datepicker ($ (str "#entity-due-date-picker-" (:id entity))) "clearDates")))) (.on (.datepicker ($ (str "#entity-due-date-picker-" (:id entity))) (clj->js {:todayBtn "linked", :autoclose true :keyboardNavigation true :format {:toDisplay (fn [d _ _] (.format (.moment js/window (js/Date. d)) (settings/date-format))) :toValue (fn [d, f, t] (js/Date. (.format (.moment js/window d (settings/date-format)))))}})) "changeDate" (fn [e] (reset! date (.-date e)) (callback entity (.-date e))))) :reagent-render (fn [entity callback on-enter] [:div (if @date [:div [:input {:id (str "entity-due-date-picker-" (:id entity)) :class "form-control due-date-picker" :placeholder "Add a due date" :value (if @date (.format (.moment js/window @date) (settings/date-format)) "")}] [clear-date entity] [show-in-today-picker/render entity callback]] [:div [:input {:id (str "entity-due-date-picker-" (:id entity)) :placeholder "Add a due date" :class "due-date-picker empty"}]])])}))) (defn render [entity callback & [on-enter]] [:div.date-picker [build entity callback on-enter]])
null
https://raw.githubusercontent.com/BenjaminVanRyseghem/great-things-done/1db9adc871556a347426df842a4f5ea6b3a1b7e0/src/front/ui/widgets/due_date_picker.cljs
clojure
The use and distribution terms for this software are covered by the which can be found in the file epl-v10.html at the root of this distribution. By using this software in any fashion, you are agreeing to be bound by the terms of this license. You must not remove this notice, or any other, from this software.
Copyright ( c ) 2015 , . All rights reserved . Eclipse Public License 1.0 ( -1.0.php ) (ns ui.widgets.due-date-picker (:use [jayq.core :only [$]]) (:require [gtd.settings :as settings] [reagent.core :as reagent :refer [atom]] [ui.widgets.show-in-today-picker :as show-in-today-picker])) (defn- clear-date [entity] (reagent/create-class {:component-did-mount #(.click ($ (str "#clear-due-date-" (:id entity))) (fn [] (.datepicker ($ (str "#entity-due-date-picker-" (:id entity))) "clearDates"))) :reagent-render (fn [] [:div {:id (str "clear-due-date-" (:id entity)) :class "clear-due-date"} [:i.fa.fa-times]])})) (defn- build [entity callback on-enter] (let [date (atom (:due-date entity))] (reagent/create-class {:component-did-mount (fn [] (.on ($ (str "#entity-due-date-picker-" (:id entity))) "keydown" (fn [e] (when (and (= (.-keyCode e) 13) (= (.-length ($ :.dropdown-menu.datepicker-dropdown)) 0) (on-enter))) (when (= (.-keyCode e) 8) (.datepicker ($ (str "#entity-due-date-picker-" (:id entity))) "clearDates")))) (.on (.datepicker ($ (str "#entity-due-date-picker-" (:id entity))) (clj->js {:todayBtn "linked", :autoclose true :keyboardNavigation true :format {:toDisplay (fn [d _ _] (.format (.moment js/window (js/Date. d)) (settings/date-format))) :toValue (fn [d, f, t] (js/Date. (.format (.moment js/window d (settings/date-format)))))}})) "changeDate" (fn [e] (reset! date (.-date e)) (callback entity (.-date e))))) :reagent-render (fn [entity callback on-enter] [:div (if @date [:div [:input {:id (str "entity-due-date-picker-" (:id entity)) :class "form-control due-date-picker" :placeholder "Add a due date" :value (if @date (.format (.moment js/window @date) (settings/date-format)) "")}] [clear-date entity] [show-in-today-picker/render entity callback]] [:div [:input {:id (str "entity-due-date-picker-" (:id entity)) :placeholder "Add a due date" :class "due-date-picker empty"}]])])}))) (defn render [entity callback & [on-enter]] [:div.date-picker [build entity callback on-enter]])
c6b5e1a4a83e9f88ba21f61eba9605d54a9fa6d780a2d36062d84a5efa20c062
camllight/camllight
filename.mli
Operations on file names value current_dir_name : string (* The conventional name for the current directory (e.g. [.] in Unix). *) and concat : string -> string -> string (* [concat dir file] returns a file name that designates file [file] in directory [dir]. *) and is_absolute : string -> bool (* Return [true] if the file name is absolute or starts with an explicit reference to the current directory ([./] or [../] in Unix), and [false] if it is relative to the current directory. *) and check_suffix : string -> string -> bool [ name suff ] returns [ true ] if the filename [ name ] ends with the suffix [ suff ] . ends with the suffix [suff]. *) and chop_suffix : string -> string -> string (* [chop_suffix name suff] removes the suffix [suff] from the filename [name]. The behavior is undefined if [name] does not end with the suffix [suff]. *) and basename : string -> string and dirname : string -> string Split a file name into directory name / base file name . [ concat ( name ) ( basename name ) ] returns a file name which is equivalent to [ name ] . Moreover , after setting the current directory to [ name ] ( with [ sys__chdir ] ) , references to [ basename name ] ( which is a relative file name ) designate the same file as [ name ] before the call to [ chdir ] . [concat (dirname name) (basename name)] returns a file name which is equivalent to [name]. Moreover, after setting the current directory to [dirname name] (with [sys__chdir]), references to [basename name] (which is a relative file name) designate the same file as [name] before the call to [chdir]. *) ;;
null
https://raw.githubusercontent.com/camllight/camllight/0cc537de0846393322058dbb26449427bfc76786/windows/src/lib/filename.mli
ocaml
The conventional name for the current directory (e.g. [.] in Unix). [concat dir file] returns a file name that designates file [file] in directory [dir]. Return [true] if the file name is absolute or starts with an explicit reference to the current directory ([./] or [../] in Unix), and [false] if it is relative to the current directory. [chop_suffix name suff] removes the suffix [suff] from the filename [name]. The behavior is undefined if [name] does not end with the suffix [suff].
Operations on file names value current_dir_name : string and concat : string -> string -> string and is_absolute : string -> bool and check_suffix : string -> string -> bool [ name suff ] returns [ true ] if the filename [ name ] ends with the suffix [ suff ] . ends with the suffix [suff]. *) and chop_suffix : string -> string -> string and basename : string -> string and dirname : string -> string Split a file name into directory name / base file name . [ concat ( name ) ( basename name ) ] returns a file name which is equivalent to [ name ] . Moreover , after setting the current directory to [ name ] ( with [ sys__chdir ] ) , references to [ basename name ] ( which is a relative file name ) designate the same file as [ name ] before the call to [ chdir ] . [concat (dirname name) (basename name)] returns a file name which is equivalent to [name]. Moreover, after setting the current directory to [dirname name] (with [sys__chdir]), references to [basename name] (which is a relative file name) designate the same file as [name] before the call to [chdir]. *) ;;
78f79834501778d4c2ba4914f6e4919ee48e01eda902755e23e5818b9c373669
fakedata-haskell/fakedata
AddressSpec.hs
# LANGUAGE ScopedTypeVariables # {-# LANGUAGE OverloadedStrings #-} module AddressSpec where import qualified Data.Map as M import Data.Text hiding (all, map) import qualified Data.Text as T import qualified Data.Vector as V import Faker hiding (defaultFakerSettings) import Faker.Address import Test.Hspec import TestImport import Faker.Internal import Faker.Internal.Types (aesonKeyToText) fakerException :: Selector FakerException fakerException = const True spec :: Spec spec = do describe "Address" $ do it "preserves unwanted things and works with numbers" $ do txt <- resolveUnresolved defaultFakerSettings (pure $ pure $ "32-????-####") (\s t -> pure $ aesonKeyToText t) txt `shouldBeOneOf` ["32-SZJX-4351", "32-GODI-8116"] it "doesn't get confused with garbage" $ do txt <- resolveUnresolved defaultFakerSettings (pure $ pure $ "abjakf-324jak") (\s t -> pure $ aesonKeyToText t) txt `shouldBe` "abjakf-324jak" describe "Address functions" $ do it "basic check" $ do fakeCountry <- generate country fakeCountry `shouldBeOneOf` ["Ecuador", "Macedonia"] it "Monad instance of Fake" $ do let someCountry :: Fake Text someCountry = do c1 <- country pure c1 fakeCountry <- generate someCountry fakeCountry `shouldBeOneOf` ["Ecuador", "Macedonia"] it "Equality of normal generation and Monad" $ do fakeCountry <- generate country let someCountry :: Fake Text someCountry = do c1 <- country pure c1 c2 <- generate someCountry fakeCountry `shouldBe` c2 it "Monad instance of Fake (tuple)" $ do let someCountry :: Fake (Text, Text) someCountry = do c1 <- country c2 <- country pure (c1, c2) fakeCountry <- generate someCountry fakeCountry `shouldBeOneOf` [("Ecuador", "Ecuador"), ("Macedonia","Macedonia")] it "Monad instance of Fake (tuple)" $ do let someCountry :: Fake (Text, Text) someCountry = do c1 <- country c2 <- country pure (c1, c2) fakeCountry <- generateWithSettings (setNonDeterministic defaultFakerSettings) someCountry (fst fakeCountry) `shouldNotBe` (snd fakeCountry) it "Equality of sequence" $ do let someCountry :: Fake (Text, Text) someCountry = do c1 <- country c2 <- country pure (c1, c2) (c1, c2) <- generate someCountry c1 `shouldBe` c2 it "Resolver based function" $ do bno <- generate buildingNumber bno `shouldBeOneOf` ["351", "116"] it "Resolver fullAddress" $ do bno <- generate fullAddress bno `shouldSatisfy` (\x -> T.length x > 25) it "Resolver based function - monad" $ do let someBuilding :: Fake (Text, Text) someBuilding = do c1 <- buildingNumber c2 <- buildingNumber pure (c1, c2) (c1, c2) <- generate someBuilding c1 `shouldBe` c2 describe "Empty data sources" $ do it "For ee locale, throws exception" $ do let action = generateWithSettings (setLocale "ee" defaultFakerSettings) country action `shouldThrow` fakerException describe "Functions in address module" $ do it "Country" $ do val <- generateWithSettings defaultFakerSettings country val `shouldBeOneOf` ["Ecuador", "Macedonia"] it "cityPrefix" $ do val <- generateWithSettings defaultFakerSettings cityPrefix val `shouldBeOneOf` ["East", "Port"] it "citySuffix" $ do val <- generateWithSettings defaultFakerSettings citySuffix val `shouldBeOneOf` ["burgh", "borough"] it "countryCode" $ do val <- generateWithSettings defaultFakerSettings countryCode val `shouldBeOneOf` ["FJ", "LB"] it "countryCodeLong" $ do val <- generateWithSettings defaultFakerSettings countryCodeLong val `shouldBeOneOf` ["CYM", "LBY"] it "buildingNumber" $ do val <- generateWithSettings defaultFakerSettings buildingNumber val `shouldBeOneOf` ["351", "116"] it "communityPrefix" $ do val <- generateWithSettings defaultFakerSettings communityPrefix val `shouldBeOneOf` ["Pine", "Royal"] it "communitySuffix" $ do val <- generateWithSettings defaultFakerSettings communitySuffix val `shouldBeOneOf` ["Oaks", "Gardens"] it "community" $ do val <- generateWithSettings defaultFakerSettings community val `shouldBeOneOf` ["Pine Place", "Royal Pointe"] it "streetSuffix" $ do val <- generateWithSettings defaultFakerSettings streetSuffix val `shouldBeOneOf` ["Way", "Parks"] it "secondaryAddress" $ do val <- generateWithSettings defaultFakerSettings secondaryAddress val `shouldBeOneOf` ["Suite 351", "Suite 116"] it "postcode" $ do val <- generateWithSettings defaultFakerSettings postcode val `shouldBeOneOf` ["24351-4351", "68116-8116"] it "state" $ do val <- generateWithSettings defaultFakerSettings state val `shouldBeOneOf` ["Michigan", "Rhode Island"] it "stateAbbr" $ do val <- generateWithSettings defaultFakerSettings stateAbbr val `shouldBeOneOf` ["MI", "RI"] it "timeZone" $ do val <- generateWithSettings defaultFakerSettings timeZone val `shouldBeOneOf` ["America/Chicago", "Australia/Brisbane"] it "city" $ do val <- generateWithSettings defaultFakerSettings city val `shouldBeOneOf` ["East Vernita", "Goldnerton"] it "streetName" $ do val <- generateWithSettings defaultFakerSettings streetName val `shouldBeOneOf` ["Schmidt Ferry", "Goldner Track"] it "streetAddress" $ do val <- generateWithSettings defaultFakerSettings streetAddress val `shouldBeOneOf` ["351 Vernita Avenue", "116 Will Manor"] it "fullAddress" $ do val <- generateWithSettings defaultFakerSettings fullAddress val `shouldBeOneOf` [ "Suite 351 892 Donnelly Points, Kelleymouth, AK 66043-6043" , "Suite 116 663 Russel Locks, Assuntamouth, UT 86075-6075" ] it "mailBox" $ do val <- generateWithSettings defaultFakerSettings mailBox val `shouldBeOneOf` ["PO Box 4351", "PO Box 8116"] it "cityWithState" $ do val <- generateWithSettings defaultFakerSettings cityWithState val `shouldBeOneOf` ["East Vernita, Minnesota", "Goldnerton, Arkansas"]
null
https://raw.githubusercontent.com/fakedata-haskell/fakedata/7b0875067386e9bb844c8b985c901c91a58842ff/test/AddressSpec.hs
haskell
# LANGUAGE OverloadedStrings #
# LANGUAGE ScopedTypeVariables # module AddressSpec where import qualified Data.Map as M import Data.Text hiding (all, map) import qualified Data.Text as T import qualified Data.Vector as V import Faker hiding (defaultFakerSettings) import Faker.Address import Test.Hspec import TestImport import Faker.Internal import Faker.Internal.Types (aesonKeyToText) fakerException :: Selector FakerException fakerException = const True spec :: Spec spec = do describe "Address" $ do it "preserves unwanted things and works with numbers" $ do txt <- resolveUnresolved defaultFakerSettings (pure $ pure $ "32-????-####") (\s t -> pure $ aesonKeyToText t) txt `shouldBeOneOf` ["32-SZJX-4351", "32-GODI-8116"] it "doesn't get confused with garbage" $ do txt <- resolveUnresolved defaultFakerSettings (pure $ pure $ "abjakf-324jak") (\s t -> pure $ aesonKeyToText t) txt `shouldBe` "abjakf-324jak" describe "Address functions" $ do it "basic check" $ do fakeCountry <- generate country fakeCountry `shouldBeOneOf` ["Ecuador", "Macedonia"] it "Monad instance of Fake" $ do let someCountry :: Fake Text someCountry = do c1 <- country pure c1 fakeCountry <- generate someCountry fakeCountry `shouldBeOneOf` ["Ecuador", "Macedonia"] it "Equality of normal generation and Monad" $ do fakeCountry <- generate country let someCountry :: Fake Text someCountry = do c1 <- country pure c1 c2 <- generate someCountry fakeCountry `shouldBe` c2 it "Monad instance of Fake (tuple)" $ do let someCountry :: Fake (Text, Text) someCountry = do c1 <- country c2 <- country pure (c1, c2) fakeCountry <- generate someCountry fakeCountry `shouldBeOneOf` [("Ecuador", "Ecuador"), ("Macedonia","Macedonia")] it "Monad instance of Fake (tuple)" $ do let someCountry :: Fake (Text, Text) someCountry = do c1 <- country c2 <- country pure (c1, c2) fakeCountry <- generateWithSettings (setNonDeterministic defaultFakerSettings) someCountry (fst fakeCountry) `shouldNotBe` (snd fakeCountry) it "Equality of sequence" $ do let someCountry :: Fake (Text, Text) someCountry = do c1 <- country c2 <- country pure (c1, c2) (c1, c2) <- generate someCountry c1 `shouldBe` c2 it "Resolver based function" $ do bno <- generate buildingNumber bno `shouldBeOneOf` ["351", "116"] it "Resolver fullAddress" $ do bno <- generate fullAddress bno `shouldSatisfy` (\x -> T.length x > 25) it "Resolver based function - monad" $ do let someBuilding :: Fake (Text, Text) someBuilding = do c1 <- buildingNumber c2 <- buildingNumber pure (c1, c2) (c1, c2) <- generate someBuilding c1 `shouldBe` c2 describe "Empty data sources" $ do it "For ee locale, throws exception" $ do let action = generateWithSettings (setLocale "ee" defaultFakerSettings) country action `shouldThrow` fakerException describe "Functions in address module" $ do it "Country" $ do val <- generateWithSettings defaultFakerSettings country val `shouldBeOneOf` ["Ecuador", "Macedonia"] it "cityPrefix" $ do val <- generateWithSettings defaultFakerSettings cityPrefix val `shouldBeOneOf` ["East", "Port"] it "citySuffix" $ do val <- generateWithSettings defaultFakerSettings citySuffix val `shouldBeOneOf` ["burgh", "borough"] it "countryCode" $ do val <- generateWithSettings defaultFakerSettings countryCode val `shouldBeOneOf` ["FJ", "LB"] it "countryCodeLong" $ do val <- generateWithSettings defaultFakerSettings countryCodeLong val `shouldBeOneOf` ["CYM", "LBY"] it "buildingNumber" $ do val <- generateWithSettings defaultFakerSettings buildingNumber val `shouldBeOneOf` ["351", "116"] it "communityPrefix" $ do val <- generateWithSettings defaultFakerSettings communityPrefix val `shouldBeOneOf` ["Pine", "Royal"] it "communitySuffix" $ do val <- generateWithSettings defaultFakerSettings communitySuffix val `shouldBeOneOf` ["Oaks", "Gardens"] it "community" $ do val <- generateWithSettings defaultFakerSettings community val `shouldBeOneOf` ["Pine Place", "Royal Pointe"] it "streetSuffix" $ do val <- generateWithSettings defaultFakerSettings streetSuffix val `shouldBeOneOf` ["Way", "Parks"] it "secondaryAddress" $ do val <- generateWithSettings defaultFakerSettings secondaryAddress val `shouldBeOneOf` ["Suite 351", "Suite 116"] it "postcode" $ do val <- generateWithSettings defaultFakerSettings postcode val `shouldBeOneOf` ["24351-4351", "68116-8116"] it "state" $ do val <- generateWithSettings defaultFakerSettings state val `shouldBeOneOf` ["Michigan", "Rhode Island"] it "stateAbbr" $ do val <- generateWithSettings defaultFakerSettings stateAbbr val `shouldBeOneOf` ["MI", "RI"] it "timeZone" $ do val <- generateWithSettings defaultFakerSettings timeZone val `shouldBeOneOf` ["America/Chicago", "Australia/Brisbane"] it "city" $ do val <- generateWithSettings defaultFakerSettings city val `shouldBeOneOf` ["East Vernita", "Goldnerton"] it "streetName" $ do val <- generateWithSettings defaultFakerSettings streetName val `shouldBeOneOf` ["Schmidt Ferry", "Goldner Track"] it "streetAddress" $ do val <- generateWithSettings defaultFakerSettings streetAddress val `shouldBeOneOf` ["351 Vernita Avenue", "116 Will Manor"] it "fullAddress" $ do val <- generateWithSettings defaultFakerSettings fullAddress val `shouldBeOneOf` [ "Suite 351 892 Donnelly Points, Kelleymouth, AK 66043-6043" , "Suite 116 663 Russel Locks, Assuntamouth, UT 86075-6075" ] it "mailBox" $ do val <- generateWithSettings defaultFakerSettings mailBox val `shouldBeOneOf` ["PO Box 4351", "PO Box 8116"] it "cityWithState" $ do val <- generateWithSettings defaultFakerSettings cityWithState val `shouldBeOneOf` ["East Vernita, Minnesota", "Goldnerton, Arkansas"]
be17254c84053cc98b7a9ef5da36bc20cef1c285fdc1d4e3261a5b0d33819953
CryptoKami/cryptokami-core
Node.hs
# OPTIONS_GHC -fno - warn - name - shadowing # # LANGUAGE BangPatterns # {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} # LANGUAGE ExistentialQuantification # # LANGUAGE FlexibleContexts # # LANGUAGE GADTSyntax # # LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE KindSignatures # # LANGUAGE NamedFieldPuns # {-# LANGUAGE RankNTypes #-} # LANGUAGE RecordWildCards # {-# LANGUAGE RecursiveDo #-} # LANGUAGE ScopedTypeVariables # # LANGUAGE StandaloneDeriving # # LANGUAGE TypeApplications # module Node ( Node(..) , LL.NodeId(..) , LL.NodeEnvironment(..) , LL.defaultNodeEnvironment , LL.ReceiveDelay , LL.noReceiveDelay , LL.constantReceiveDelay , nodeEndPointAddress , NodeAction(..) , node , LL.NodeEndPoint(..) , simpleNodeEndPoint , manualNodeEndPoint , LL.NodeState(..) , MessageCode , Message (..) , Converse(..) , Conversation(..) , ConversationActions(send, recv) , converseWith , Listener (..) , ListenerAction , hoistListenerAction , hoistListener , hoistConversationActions , LL.Statistics(..) , LL.PeerStatistics(..) , LL.Timeout(..) ) where import Control.Exception.Safe (Exception (..), MonadMask, MonadThrow, SomeException, catch, onException, throwM) import Control.Monad (unless, when) import Control.Monad.Fix (MonadFix) import qualified Data.ByteString as BS import Data.Map.Strict (Map) import qualified Data.Map.Strict as M import Data.Proxy (Proxy (..)) import qualified Data.Text as T import Data.Typeable (Typeable) import Data.Word (Word32) import Formatting (sformat, shown, (%)) import qualified Mockable.Channel as Channel import Mockable.Class import Mockable.Concurrent import Mockable.CurrentTime import qualified Mockable.Metrics as Metrics import Mockable.SharedAtomic import Mockable.SharedExclusive import qualified Network.Transport.Abstract as NT import Node.Conversation import Node.Internal (ChannelIn, ChannelOut) import qualified Node.Internal as LL import Node.Message.Class (Message (..), MessageCode, Packing, Serializable (..), pack, unpack) import Node.Message.Decoder (ByteOffset, Decoder (..), DecoderStep (..), continueDecoding) import System.Random (StdGen) import System.Wlog (WithLogger, logDebug, logError, logInfo) data Node m = Node { nodeId :: LL.NodeId , nodeEndPoint :: NT.EndPoint m , nodeStatistics :: m (LL.Statistics m) } nodeEndPointAddress :: Node m -> NT.EndPointAddress nodeEndPointAddress (Node addr _ _) = LL.nodeEndPointAddress addr data Input t = Input t | End data LimitExceeded = LimitExceeded deriving (Show, Typeable) instance Exception LimitExceeded -- | Custom exception thrown by recvNext -- -- This carries the fields of the 'Fail' constructor of 'Decoder' data NoParse = NoParse !BS.ByteString !ByteOffset !T.Text deriving (Show, Typeable) instance Exception NoParse where displayException (NoParse trailing offset err) = "recvNext failed with " ++ T.unpack err ++ " (length trailing = " ++ show (BS.length trailing) ++ ", offset = " ++ show offset ++ ")" | A ListenerAction with existential snd and rcv types and suitable -- constraints on them. data Listener packingType peerData m where Listener :: ( Serializable packingType snd, Serializable packingType rcv, Message rcv ) => ListenerAction packingType peerData snd rcv m -> Listener packingType peerData m -- | A listener that handles an incoming bi-directional conversation. type ListenerAction packingType peerData snd rcv m = TODO do not take the peer data here , it 's already in scope because -- the listeners are given as a function of the remote peer's -- peer data. This remains just because cryptokami-core will need a big change -- to use it properly. peerData -> LL.NodeId -> ConversationActions snd rcv m -> m () hoistListenerAction :: ( ) => (forall a. n a -> m a) -> (forall a. m a -> n a) -> ListenerAction packingType peerData snd rcv n -> ListenerAction packingType peerData snd rcv m hoistListenerAction nat rnat f = \peerData nId convActions -> nat $ f peerData nId (hoistConversationActions rnat convActions) hoistListener :: ( ) => (forall a. n a -> m a) -> (forall a. m a -> n a) -> Listener packing peerData n -> Listener packing peerData m hoistListener nat rnat (Listener la) = Listener $ hoistListenerAction nat rnat la -- | Gets message type basing on type of incoming messages listenerMessageCode :: Listener packing peerData m -> MessageCode listenerMessageCode (Listener ( _ :: peerData -> LL.NodeId -> ConversationActions snd rcv m -> m () )) = messageCode (Proxy :: Proxy rcv) type ListenerIndex packing peerData m = Map MessageCode (Listener packing peerData m) makeListenerIndex :: [Listener packing peerData m] -> (ListenerIndex packing peerData m, [MessageCode]) makeListenerIndex = foldr combine (M.empty, []) where combine action (dict, existing) = let name = listenerMessageCode action (replaced, dict') = M.insertLookupWithKey (\_ _ _ -> action) name action dict overlapping = maybe [] (const [name]) replaced in (dict', overlapping ++ existing) nodeConverse :: forall m packing peerData . ( Mockable Channel.Channel m , MonadMask m, Mockable SharedAtomic m, Mockable SharedExclusive m , Mockable Async m, Ord (ThreadId m) , Mockable CurrentTime m, Mockable Metrics.Metrics m , Mockable Delay m , WithLogger m, MonadFix m , Serializable packing peerData , Serializable packing MessageCode ) => LL.Node packing peerData m -> Packing packing m -> Converse packing peerData m nodeConverse nodeUnit packing = Converse nodeConverse where mtu = LL.nodeMtu (LL.nodeEnvironment nodeUnit) nodeConverse :: forall t . LL.NodeId -> (peerData -> Conversation packing m t) -> m t nodeConverse = \nodeId k -> LL.withInOutChannel nodeUnit nodeId $ \peerData inchan outchan -> case k peerData of Conversation (converse :: ConversationActions snd rcv m -> m t) -> do let msgCode = messageCode (Proxy :: Proxy snd) cactions :: ConversationActions snd rcv m cactions = nodeConversationActions nodeUnit nodeId packing inchan outchan pack packing msgCode >>= LL.writeMany mtu outchan converse cactions -- | Conversation actions for a given peer and in/out channels. nodeConversationActions :: forall packing peerData snd rcv m . ( MonadThrow m , Mockable Channel.Channel m , Serializable packing snd , Serializable packing rcv ) => LL.Node packing peerData m -> LL.NodeId -> Packing packing m -> ChannelIn m -> ChannelOut m -> ConversationActions snd rcv m nodeConversationActions node _ packing inchan outchan = ConversationActions nodeSend nodeRecv nodeSendRaw where mtu = LL.nodeMtu (LL.nodeEnvironment node) nodeSend = \body -> pack packing body >>= nodeSendRaw nodeRecv :: Word32 -> m (Maybe rcv) nodeRecv limit = do next <- recvNext packing (fromIntegral limit :: Int) inchan case next of End -> pure Nothing Input t -> pure (Just t) nodeSendRaw = LL.writeMany mtu outchan data NodeAction packing peerData m t = NodeAction (peerData -> [Listener packing peerData m]) (Converse packing peerData m -> m t) simpleNodeEndPoint :: NT.Transport m -> m (LL.Statistics m) -> LL.NodeEndPoint m simpleNodeEndPoint transport _ = LL.NodeEndPoint { newNodeEndPoint = NT.newEndPoint transport , closeNodeEndPoint = NT.closeEndPoint } manualNodeEndPoint :: ( Applicative m ) => NT.EndPoint m -> m (LL.Statistics m) -> LL.NodeEndPoint m manualNodeEndPoint ep _ = LL.NodeEndPoint { newNodeEndPoint = pure $ Right ep , closeNodeEndPoint = NT.closeEndPoint } -- | Spin up a node. You must give a function to create listeners given the -- 'NodeId', and an action to do given the 'NodeId' and sending actions. -- The ' NodeAction ' must be lazy in the components of the ' Node ' passed to -- it. Its 'NodeId', for instance, may be useful for the listeners, but is -- not defined until after the node's end point is created, which cannot -- happen until the listeners are defined--as soon as the end point is brought -- up, traffic may come in and cause a listener to run, so they must be defined first . -- -- The node will stop and clean up once that action has completed. If at -- this time there are any listeners running, they will be allowed to -- finish. node :: forall packing peerData m t . ( Mockable Fork m, Mockable Channel.Channel m , Mockable SharedAtomic m, MonadMask m , Mockable Async m, Mockable Concurrently m , Ord (ThreadId m), Show (ThreadId m) , Mockable SharedExclusive m , Mockable Delay m , Mockable CurrentTime m, Mockable Metrics.Metrics m , MonadFix m, Serializable packing MessageCode, WithLogger m , Serializable packing peerData ) => (m (LL.Statistics m) -> LL.NodeEndPoint m) -> (m (LL.Statistics m) -> LL.ReceiveDelay m) -- ^ delay on receiving input events. -> (m (LL.Statistics m) -> LL.ReceiveDelay m) -- ^ delay on receiving new connections. -> StdGen -> Packing packing m -> peerData -> LL.NodeEnvironment m -> (Node m -> NodeAction packing peerData m t) -> m t node mkEndPoint mkReceiveDelay mkConnectDelay prng packing peerData nodeEnv k = do rec { let nId = LL.nodeId llnode endPoint = LL.nodeEndPoint llnode nodeUnit = Node nId endPoint (LL.nodeStatistics llnode) NodeAction mkListeners (act :: Converse packing peerData m -> m t) = k nodeUnit -- Index the listeners by message name, for faster lookup. -- TODO: report conflicting names, or statically eliminate them using DataKinds and TypeFamilies . listenerIndices :: peerData -> ListenerIndex packing peerData m listenerIndices = fmap (fst . makeListenerIndex) mkListeners converse :: Converse packing peerData m converse = nodeConverse llnode packing unexceptional :: m t unexceptional = do t <- act converse logNormalShutdown (LL.stopNode llnode `catch` logNodeException) return t ; llnode <- LL.startNode packing peerData (mkEndPoint . LL.nodeStatistics) (mkReceiveDelay . LL.nodeStatistics) (mkConnectDelay . LL.nodeStatistics) prng nodeEnv (handlerInOut llnode listenerIndices) } unexceptional `catch` logException `onException` (LL.stopNode llnode `catch` logNodeException) where logNormalShutdown :: m () logNormalShutdown = logInfo $ sformat ("node stopping normally") logException :: forall s . SomeException -> m s logException e = do logError $ sformat ("node stopped with exception " % shown) e throwM e logNodeException :: forall s . SomeException -> m s logNodeException e = do logError $ sformat ("exception while stopping node " % shown) e throwM e -- Handle incoming data from a bidirectional connection: try to read the -- message name, then choose a listener and fork a thread to run it. handlerInOut :: LL.Node packing peerData m -> (peerData -> ListenerIndex packing peerData m) -> peerData -> LL.NodeId -> ChannelIn m -> ChannelOut m -> m () handlerInOut nodeUnit listenerIndices peerData peerId inchan outchan = do let listenerIndex = listenerIndices peerData Use maxBound to receive the MessageCode . The understanding is that the instance for it against -- the given packing type shouldn't accept arbitrarily-long input (it's a , surely it serializes to ( 2 + c ) bytes for some c ) . input <- recvNext packing maxBound inchan case input of End -> logDebug "handlerInOut : unexpected end of input" Input msgCode -> do let listener = M.lookup msgCode listenerIndex case listener of Just (Listener action) -> let cactions = nodeConversationActions nodeUnit peerId packing inchan outchan in action peerData peerId cactions Nothing -> error ("handlerInOut : no listener for " ++ show msgCode) -- | Try to receive and parse the next message, subject to a limit on the -- number of bytes which will be read. -- An empty ByteString will never be passed to a decoder . recvNext :: forall packing m thing . ( Mockable Channel.Channel m , MonadThrow m , Serializable packing thing ) => Packing packing m -> Int -> ChannelIn m -> m (Input thing) recvNext packing limit (LL.ChannelIn channel) = readNonEmpty (return End) $ \bs -> do -- limit' is the number of bytes that 'go' is allowed to pull. -- It's assumed that reading from the channel will bring in at most -- some limited number of bytes, so 'go' may bring in at most this -- many more than the limit. let limit' = limit - BS.length bs decoderStep <- runDecoder (unpack packing) (trailing, outcome) <- continueDecoding decoderStep bs >>= go limit' unless (BS.null trailing) (Channel.unGetChannel channel (Just trailing)) return outcome where readNonEmpty :: m t -> (BS.ByteString -> m t) -> m t readNonEmpty nothing just = do mbs <- Channel.readChannel channel case mbs of Nothing -> nothing Just bs -> if BS.null bs then readNonEmpty nothing just else just bs go !remaining decoderStep = case decoderStep of Fail trailing offset err -> throwM $ NoParse trailing offset err Done trailing _ thing -> return (trailing, Input thing) Partial next -> do when (remaining < 0) (throwM LimitExceeded) readNonEmpty (runDecoder (next Nothing) >>= go remaining) $ \bs -> let remaining' = remaining - BS.length bs in runDecoder (next (Just bs)) >>= go remaining'
null
https://raw.githubusercontent.com/CryptoKami/cryptokami-core/12ca60a9ad167b6327397b3b2f928c19436ae114/networking/src/Node.hs
haskell
# LANGUAGE DeriveDataTypeable # # LANGUAGE DeriveGeneric # # LANGUAGE RankNTypes # # LANGUAGE RecursiveDo # | Custom exception thrown by recvNext This carries the fields of the 'Fail' constructor of 'Decoder' constraints on them. | A listener that handles an incoming bi-directional conversation. the listeners are given as a function of the remote peer's peer data. This remains just because cryptokami-core will need a big change to use it properly. | Gets message type basing on type of incoming messages | Conversation actions for a given peer and in/out channels. | Spin up a node. You must give a function to create listeners given the 'NodeId', and an action to do given the 'NodeId' and sending actions. it. Its 'NodeId', for instance, may be useful for the listeners, but is not defined until after the node's end point is created, which cannot happen until the listeners are defined--as soon as the end point is brought up, traffic may come in and cause a listener to run, so they must be The node will stop and clean up once that action has completed. If at this time there are any listeners running, they will be allowed to finish. ^ delay on receiving input events. ^ delay on receiving new connections. Index the listeners by message name, for faster lookup. TODO: report conflicting names, or statically eliminate them using Handle incoming data from a bidirectional connection: try to read the message name, then choose a listener and fork a thread to run it. the given packing type shouldn't accept arbitrarily-long input (it's | Try to receive and parse the next message, subject to a limit on the number of bytes which will be read. limit' is the number of bytes that 'go' is allowed to pull. It's assumed that reading from the channel will bring in at most some limited number of bytes, so 'go' may bring in at most this many more than the limit.
# OPTIONS_GHC -fno - warn - name - shadowing # # LANGUAGE BangPatterns # # LANGUAGE ExistentialQuantification # # LANGUAGE FlexibleContexts # # LANGUAGE GADTSyntax # # LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE KindSignatures # # LANGUAGE NamedFieldPuns # # LANGUAGE RecordWildCards # # LANGUAGE ScopedTypeVariables # # LANGUAGE StandaloneDeriving # # LANGUAGE TypeApplications # module Node ( Node(..) , LL.NodeId(..) , LL.NodeEnvironment(..) , LL.defaultNodeEnvironment , LL.ReceiveDelay , LL.noReceiveDelay , LL.constantReceiveDelay , nodeEndPointAddress , NodeAction(..) , node , LL.NodeEndPoint(..) , simpleNodeEndPoint , manualNodeEndPoint , LL.NodeState(..) , MessageCode , Message (..) , Converse(..) , Conversation(..) , ConversationActions(send, recv) , converseWith , Listener (..) , ListenerAction , hoistListenerAction , hoistListener , hoistConversationActions , LL.Statistics(..) , LL.PeerStatistics(..) , LL.Timeout(..) ) where import Control.Exception.Safe (Exception (..), MonadMask, MonadThrow, SomeException, catch, onException, throwM) import Control.Monad (unless, when) import Control.Monad.Fix (MonadFix) import qualified Data.ByteString as BS import Data.Map.Strict (Map) import qualified Data.Map.Strict as M import Data.Proxy (Proxy (..)) import qualified Data.Text as T import Data.Typeable (Typeable) import Data.Word (Word32) import Formatting (sformat, shown, (%)) import qualified Mockable.Channel as Channel import Mockable.Class import Mockable.Concurrent import Mockable.CurrentTime import qualified Mockable.Metrics as Metrics import Mockable.SharedAtomic import Mockable.SharedExclusive import qualified Network.Transport.Abstract as NT import Node.Conversation import Node.Internal (ChannelIn, ChannelOut) import qualified Node.Internal as LL import Node.Message.Class (Message (..), MessageCode, Packing, Serializable (..), pack, unpack) import Node.Message.Decoder (ByteOffset, Decoder (..), DecoderStep (..), continueDecoding) import System.Random (StdGen) import System.Wlog (WithLogger, logDebug, logError, logInfo) data Node m = Node { nodeId :: LL.NodeId , nodeEndPoint :: NT.EndPoint m , nodeStatistics :: m (LL.Statistics m) } nodeEndPointAddress :: Node m -> NT.EndPointAddress nodeEndPointAddress (Node addr _ _) = LL.nodeEndPointAddress addr data Input t = Input t | End data LimitExceeded = LimitExceeded deriving (Show, Typeable) instance Exception LimitExceeded data NoParse = NoParse !BS.ByteString !ByteOffset !T.Text deriving (Show, Typeable) instance Exception NoParse where displayException (NoParse trailing offset err) = "recvNext failed with " ++ T.unpack err ++ " (length trailing = " ++ show (BS.length trailing) ++ ", offset = " ++ show offset ++ ")" | A ListenerAction with existential snd and rcv types and suitable data Listener packingType peerData m where Listener :: ( Serializable packingType snd, Serializable packingType rcv, Message rcv ) => ListenerAction packingType peerData snd rcv m -> Listener packingType peerData m type ListenerAction packingType peerData snd rcv m = TODO do not take the peer data here , it 's already in scope because peerData -> LL.NodeId -> ConversationActions snd rcv m -> m () hoistListenerAction :: ( ) => (forall a. n a -> m a) -> (forall a. m a -> n a) -> ListenerAction packingType peerData snd rcv n -> ListenerAction packingType peerData snd rcv m hoistListenerAction nat rnat f = \peerData nId convActions -> nat $ f peerData nId (hoistConversationActions rnat convActions) hoistListener :: ( ) => (forall a. n a -> m a) -> (forall a. m a -> n a) -> Listener packing peerData n -> Listener packing peerData m hoistListener nat rnat (Listener la) = Listener $ hoistListenerAction nat rnat la listenerMessageCode :: Listener packing peerData m -> MessageCode listenerMessageCode (Listener ( _ :: peerData -> LL.NodeId -> ConversationActions snd rcv m -> m () )) = messageCode (Proxy :: Proxy rcv) type ListenerIndex packing peerData m = Map MessageCode (Listener packing peerData m) makeListenerIndex :: [Listener packing peerData m] -> (ListenerIndex packing peerData m, [MessageCode]) makeListenerIndex = foldr combine (M.empty, []) where combine action (dict, existing) = let name = listenerMessageCode action (replaced, dict') = M.insertLookupWithKey (\_ _ _ -> action) name action dict overlapping = maybe [] (const [name]) replaced in (dict', overlapping ++ existing) nodeConverse :: forall m packing peerData . ( Mockable Channel.Channel m , MonadMask m, Mockable SharedAtomic m, Mockable SharedExclusive m , Mockable Async m, Ord (ThreadId m) , Mockable CurrentTime m, Mockable Metrics.Metrics m , Mockable Delay m , WithLogger m, MonadFix m , Serializable packing peerData , Serializable packing MessageCode ) => LL.Node packing peerData m -> Packing packing m -> Converse packing peerData m nodeConverse nodeUnit packing = Converse nodeConverse where mtu = LL.nodeMtu (LL.nodeEnvironment nodeUnit) nodeConverse :: forall t . LL.NodeId -> (peerData -> Conversation packing m t) -> m t nodeConverse = \nodeId k -> LL.withInOutChannel nodeUnit nodeId $ \peerData inchan outchan -> case k peerData of Conversation (converse :: ConversationActions snd rcv m -> m t) -> do let msgCode = messageCode (Proxy :: Proxy snd) cactions :: ConversationActions snd rcv m cactions = nodeConversationActions nodeUnit nodeId packing inchan outchan pack packing msgCode >>= LL.writeMany mtu outchan converse cactions nodeConversationActions :: forall packing peerData snd rcv m . ( MonadThrow m , Mockable Channel.Channel m , Serializable packing snd , Serializable packing rcv ) => LL.Node packing peerData m -> LL.NodeId -> Packing packing m -> ChannelIn m -> ChannelOut m -> ConversationActions snd rcv m nodeConversationActions node _ packing inchan outchan = ConversationActions nodeSend nodeRecv nodeSendRaw where mtu = LL.nodeMtu (LL.nodeEnvironment node) nodeSend = \body -> pack packing body >>= nodeSendRaw nodeRecv :: Word32 -> m (Maybe rcv) nodeRecv limit = do next <- recvNext packing (fromIntegral limit :: Int) inchan case next of End -> pure Nothing Input t -> pure (Just t) nodeSendRaw = LL.writeMany mtu outchan data NodeAction packing peerData m t = NodeAction (peerData -> [Listener packing peerData m]) (Converse packing peerData m -> m t) simpleNodeEndPoint :: NT.Transport m -> m (LL.Statistics m) -> LL.NodeEndPoint m simpleNodeEndPoint transport _ = LL.NodeEndPoint { newNodeEndPoint = NT.newEndPoint transport , closeNodeEndPoint = NT.closeEndPoint } manualNodeEndPoint :: ( Applicative m ) => NT.EndPoint m -> m (LL.Statistics m) -> LL.NodeEndPoint m manualNodeEndPoint ep _ = LL.NodeEndPoint { newNodeEndPoint = pure $ Right ep , closeNodeEndPoint = NT.closeEndPoint } The ' NodeAction ' must be lazy in the components of the ' Node ' passed to defined first . node :: forall packing peerData m t . ( Mockable Fork m, Mockable Channel.Channel m , Mockable SharedAtomic m, MonadMask m , Mockable Async m, Mockable Concurrently m , Ord (ThreadId m), Show (ThreadId m) , Mockable SharedExclusive m , Mockable Delay m , Mockable CurrentTime m, Mockable Metrics.Metrics m , MonadFix m, Serializable packing MessageCode, WithLogger m , Serializable packing peerData ) => (m (LL.Statistics m) -> LL.NodeEndPoint m) -> (m (LL.Statistics m) -> LL.ReceiveDelay m) -> (m (LL.Statistics m) -> LL.ReceiveDelay m) -> StdGen -> Packing packing m -> peerData -> LL.NodeEnvironment m -> (Node m -> NodeAction packing peerData m t) -> m t node mkEndPoint mkReceiveDelay mkConnectDelay prng packing peerData nodeEnv k = do rec { let nId = LL.nodeId llnode endPoint = LL.nodeEndPoint llnode nodeUnit = Node nId endPoint (LL.nodeStatistics llnode) NodeAction mkListeners (act :: Converse packing peerData m -> m t) = k nodeUnit DataKinds and TypeFamilies . listenerIndices :: peerData -> ListenerIndex packing peerData m listenerIndices = fmap (fst . makeListenerIndex) mkListeners converse :: Converse packing peerData m converse = nodeConverse llnode packing unexceptional :: m t unexceptional = do t <- act converse logNormalShutdown (LL.stopNode llnode `catch` logNodeException) return t ; llnode <- LL.startNode packing peerData (mkEndPoint . LL.nodeStatistics) (mkReceiveDelay . LL.nodeStatistics) (mkConnectDelay . LL.nodeStatistics) prng nodeEnv (handlerInOut llnode listenerIndices) } unexceptional `catch` logException `onException` (LL.stopNode llnode `catch` logNodeException) where logNormalShutdown :: m () logNormalShutdown = logInfo $ sformat ("node stopping normally") logException :: forall s . SomeException -> m s logException e = do logError $ sformat ("node stopped with exception " % shown) e throwM e logNodeException :: forall s . SomeException -> m s logNodeException e = do logError $ sformat ("exception while stopping node " % shown) e throwM e handlerInOut :: LL.Node packing peerData m -> (peerData -> ListenerIndex packing peerData m) -> peerData -> LL.NodeId -> ChannelIn m -> ChannelOut m -> m () handlerInOut nodeUnit listenerIndices peerData peerId inchan outchan = do let listenerIndex = listenerIndices peerData Use maxBound to receive the MessageCode . The understanding is that the instance for it against a , surely it serializes to ( 2 + c ) bytes for some c ) . input <- recvNext packing maxBound inchan case input of End -> logDebug "handlerInOut : unexpected end of input" Input msgCode -> do let listener = M.lookup msgCode listenerIndex case listener of Just (Listener action) -> let cactions = nodeConversationActions nodeUnit peerId packing inchan outchan in action peerData peerId cactions Nothing -> error ("handlerInOut : no listener for " ++ show msgCode) An empty ByteString will never be passed to a decoder . recvNext :: forall packing m thing . ( Mockable Channel.Channel m , MonadThrow m , Serializable packing thing ) => Packing packing m -> Int -> ChannelIn m -> m (Input thing) recvNext packing limit (LL.ChannelIn channel) = readNonEmpty (return End) $ \bs -> do let limit' = limit - BS.length bs decoderStep <- runDecoder (unpack packing) (trailing, outcome) <- continueDecoding decoderStep bs >>= go limit' unless (BS.null trailing) (Channel.unGetChannel channel (Just trailing)) return outcome where readNonEmpty :: m t -> (BS.ByteString -> m t) -> m t readNonEmpty nothing just = do mbs <- Channel.readChannel channel case mbs of Nothing -> nothing Just bs -> if BS.null bs then readNonEmpty nothing just else just bs go !remaining decoderStep = case decoderStep of Fail trailing offset err -> throwM $ NoParse trailing offset err Done trailing _ thing -> return (trailing, Input thing) Partial next -> do when (remaining < 0) (throwM LimitExceeded) readNonEmpty (runDecoder (next Nothing) >>= go remaining) $ \bs -> let remaining' = remaining - BS.length bs in runDecoder (next (Just bs)) >>= go remaining'
0e746277cec26a728564e8d3fb047c02d14fe8b0123d5829dc0c9fcbbce7d502
dfinity/motoko
prelude.ml
let prelude = [%blob "prelude/prelude.mo"] let internals = [%blob "prelude/internals.mo"] let timers_api = [%blob "prelude/timers-api.mo"] let prim_module' = [%blob "prelude/prim.mo"] let prim_module ~timers:required = if required then prim_module' ^ timers_api else prim_module'
null
https://raw.githubusercontent.com/dfinity/motoko/e0a934029f0d927545317ecb90d1a829696c7ae3/src/prelude/prelude.ml
ocaml
let prelude = [%blob "prelude/prelude.mo"] let internals = [%blob "prelude/internals.mo"] let timers_api = [%blob "prelude/timers-api.mo"] let prim_module' = [%blob "prelude/prim.mo"] let prim_module ~timers:required = if required then prim_module' ^ timers_api else prim_module'
96622e5ca70e81bad2c8aacd63e12d5b133826d0ce518d2b5820871afbc3b46d
yuriy-chumak/ol
sum_digits_of_an_integer.scm
(define (sum n base) (if (zero? n) n (+ (mod n base) (sum (div n base) base)))) (print (sum 1 10)) (print (sum 1234 10)) (print (sum #xfe 16)) (print (sum #xf0e 16))
null
https://raw.githubusercontent.com/yuriy-chumak/ol/83dd03d311339763682eab02cbe0c1321daa25bc/tests/rosettacode/sum_digits_of_an_integer.scm
scheme
(define (sum n base) (if (zero? n) n (+ (mod n base) (sum (div n base) base)))) (print (sum 1 10)) (print (sum 1234 10)) (print (sum #xfe 16)) (print (sum #xf0e 16))
73bf613b2ddbf8b8144cc0f57cabeceab6b3ee596460207765ed5ee9482b509d
rm-hull/markov-chains
core_test.clj
(ns markov-chains.core-test (:require [clojure.test :refer :all] [markov-chains.core :refer :all])) (def bag {:red 0.2 :black 0.5 :blue 0.3}) (deftest check-cumulative (is (= [[:black 0.5] [:blue 0.8] [:red 1.0]] (cumulative bag)))) (deftest check-select (is (= :black (select 0.0 bag))) (is (= :black (select 0.5 bag))) (is (= :blue (select 0.51 bag))) (is (= :blue (select 0.7 bag))) (is (= :red (select 0.80001 bag))) (is (= :red (select 1.0 bag))) (is (nil? (select 1.5 bag)))) (deftest check-first-order-system (is (= [:A :A :A] (take 3 (generate {[:A] {:A 1.0}})))) (is (= [:A] (generate {[:A] {}}))) (is (= [] (generate nil)))) (deftest check-second-order-system (is (= [:B :A :A :B :B :A :A :B] (take 8 (generate [:A :B] {[:A :A] {:A 0 :B 1} [:A :B] {:A 0 :B 1} [:B :A] {:A 1 :B 0} [:B :B] {:A 1 :B 0}})))))
null
https://raw.githubusercontent.com/rm-hull/markov-chains/9b7b7e9ba3c81a4259dd3ecb3a20b1fd27e9b118/test/markov_chains/core_test.clj
clojure
(ns markov-chains.core-test (:require [clojure.test :refer :all] [markov-chains.core :refer :all])) (def bag {:red 0.2 :black 0.5 :blue 0.3}) (deftest check-cumulative (is (= [[:black 0.5] [:blue 0.8] [:red 1.0]] (cumulative bag)))) (deftest check-select (is (= :black (select 0.0 bag))) (is (= :black (select 0.5 bag))) (is (= :blue (select 0.51 bag))) (is (= :blue (select 0.7 bag))) (is (= :red (select 0.80001 bag))) (is (= :red (select 1.0 bag))) (is (nil? (select 1.5 bag)))) (deftest check-first-order-system (is (= [:A :A :A] (take 3 (generate {[:A] {:A 1.0}})))) (is (= [:A] (generate {[:A] {}}))) (is (= [] (generate nil)))) (deftest check-second-order-system (is (= [:B :A :A :B :B :A :A :B] (take 8 (generate [:A :B] {[:A :A] {:A 0 :B 1} [:A :B] {:A 0 :B 1} [:B :A] {:A 1 :B 0} [:B :B] {:A 1 :B 0}})))))
5aba57b5d8c5969c4f7c046d66eba32795662c8393b4f4e34db61572dd68862b
arenadotio/pgx
pgx_lwt_mirage.mli
Copyright ( C ) 2020 Petter * * This library is free software ; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation ; either * version 2 of the License , or ( at your option ) any later version , * with the OCaml static compilation exception . * * This library is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU * Library General Public License for more details . * * You should have received a copy of the GNU General Public License * along with this library ; see the file COPYING . If not , write to * the Free Software Foundation , Inc. , 59 Temple Place - Suite 330 , * Boston , MA 02111 - 1307 , USA . * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version, * with the OCaml static compilation exception. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this library; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. *) module Make (RANDOM : Mirage_random.S) (TIME : Mirage_time.S) (MCLOCK : Mirage_clock.MCLOCK) (PCLOCK : Mirage_clock.PCLOCK) (STACK : Tcpip.Stack.V4V6) : sig val connect : STACK.t -> (module Pgx_lwt.S) end
null
https://raw.githubusercontent.com/arenadotio/pgx/3f2c0fc385db40d108466df80dad7980587d4342/pgx_lwt_mirage/src/pgx_lwt_mirage.mli
ocaml
Copyright ( C ) 2020 Petter * * This library is free software ; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation ; either * version 2 of the License , or ( at your option ) any later version , * with the OCaml static compilation exception . * * This library is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU * Library General Public License for more details . * * You should have received a copy of the GNU General Public License * along with this library ; see the file COPYING . If not , write to * the Free Software Foundation , Inc. , 59 Temple Place - Suite 330 , * Boston , MA 02111 - 1307 , USA . * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version, * with the OCaml static compilation exception. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this library; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. *) module Make (RANDOM : Mirage_random.S) (TIME : Mirage_time.S) (MCLOCK : Mirage_clock.MCLOCK) (PCLOCK : Mirage_clock.PCLOCK) (STACK : Tcpip.Stack.V4V6) : sig val connect : STACK.t -> (module Pgx_lwt.S) end
04a1b77915eecf4124fff91d718875e852d7f33807130816dfd9e84ada5a2b5d
amitayh/elm-cljs
render.cljs
(ns elm-cljs.render (:require-macros [cljs.core.async.macros :refer [go]]) (:require [cljs.core.async :refer [>!]] [clojure.string :as str] [elm-cljs.channels :refer [messages]] [react :refer [createElement]] [react-dom :as react-dom])) (defn- callback? [key] (str/starts-with? (name key) "on")) (defn- wrap-callback [callback] (fn [e] (let [message (callback e)] (go (>! messages message))))) (defn- to-prop [key value] (if (callback? key) (wrap-callback value) value)) (defn- props-reducer [acc [key value]] (aset acc (name key) (to-prop key value)) acc) (defn- to-props [props] (reduce props-reducer (js-obj) props)) (declare to-react) (defn- create-element [[tag props & children]] (apply createElement (name tag) (to-props props) (map to-react children))) (defn- to-react [view] (if (vector? view) (create-element view) view)) (defn render [view el] (react-dom/render (to-react view) el))
null
https://raw.githubusercontent.com/amitayh/elm-cljs/a451962844f8d96adc0d7bbcab8ddc97f6e8209e/src/elm_cljs/render.cljs
clojure
(ns elm-cljs.render (:require-macros [cljs.core.async.macros :refer [go]]) (:require [cljs.core.async :refer [>!]] [clojure.string :as str] [elm-cljs.channels :refer [messages]] [react :refer [createElement]] [react-dom :as react-dom])) (defn- callback? [key] (str/starts-with? (name key) "on")) (defn- wrap-callback [callback] (fn [e] (let [message (callback e)] (go (>! messages message))))) (defn- to-prop [key value] (if (callback? key) (wrap-callback value) value)) (defn- props-reducer [acc [key value]] (aset acc (name key) (to-prop key value)) acc) (defn- to-props [props] (reduce props-reducer (js-obj) props)) (declare to-react) (defn- create-element [[tag props & children]] (apply createElement (name tag) (to-props props) (map to-react children))) (defn- to-react [view] (if (vector? view) (create-element view) view)) (defn render [view el] (react-dom/render (to-react view) el))
d86e11cc44c80a2ae090407a3a3669f1f79a3c86e669b7765cf393864168063e
skanev/playground
38.scm
SICP exercise 5.38 ; ; Our compiler is clever about avoiding unnecessary stack operations, but it ; is not clever at all when it comes to compiling calls to the primitive ; procedures of the language in terms of the primitive operations supplied by ; the machine. For example, consider how much code is compiled to compute ( + a 1 ): The code sets up an argument list in argl , puts the primitive ; addition procedure (which it finds by lookup up the symbol + in the ; environment) into proc, and tests whether the procedure is primitive or ; compound. The compiler always generates code to perform the test, as well as code for primitive and compound branches ( only one of which will be ; executed). We have not shown the part of the controller that implements ; primitives, but we presume that these instructions make use of primitive ; arithmetic operations in the machine's data path. Consider how much less ; code would be generated if the compiler could open-code primitives -- that ; is, if it could generate code to directly use these primitive machine ; operations. The expression (+ a 1) might be compiled into something as ; simple as ; ( assign ( op lookup - variable - value ) ( const a ) ( reg env ) ) ( assign ( op + ) ( reg val ) ( const 1 ) ) ; ; In this exercise, we will extend our compiler to support open coding of ; selected primitives. Special-purpose code will be generated fo calls to ; these primitive procedures instead of the general proedure-application code. ; In order to support this, we will augment our machine with special argument registers arg1 and . The primitive arithmetic operations of the machine will take their inputs from arg1 and . The results may be put into val , arg1 , or . ; ; The compiler must be able to recognize the application of an open-coded ; primitive in the source program. We will augment the dispatch in the compile ; procedure to recognize the names of these primitives in addition to the ; reserved words (the special forms) it currently recognizes. For each special ; form our compiler has a code generator. In this exercise we will construct a ; family of code generators for the open-coded primitives. ; ; a. The open-coded primitives, unlike the special forms, all need their ; operands evaluated. Write a code generator spread-arguments for use by all ; the open-coding code generators. spread-arguments should take an operand ; list and compile the given operands targeted to successive argument ; registers. Note that an operand may contain a call to an open-coded ; primitive, so argument registers will have to be preserved during operand ; evaluation. ; ; b. For each of the primitive procedures =, *, -, and +, write a code ; generator that takes a combination with that operator, together with a ; target and a linkage descriptor, and produces code to spread the arguments ; into the registers and then performs the operation targeted to the given target with the given linkage . You need only handle expressions with two ; operands. Make compile dispatch to these code generators. ; ; c. Try your new compiler on the factorial example. Compare the resulting ; code with the result produced without open coding. ; ; d. Extend your code generators for + and * so that they can handle ; expressions with arbitrary numbers of operands. An expression with more than two operands will have to be compiled into a sequence of operations , each with only two inputs . ; I will just ignore the spread-arguments nonsense, since I cannot figure out ; how to get it working with the results I want. ; ; What I want is the expression (+ 1 2 3) to be compiled to: ; ( assign arg1 ( const 1 ) ) ( assign ( const 2 ) ) ( assign arg1 ( op + ) ( reg arg1 ) ( reg ) ) ( assign ( const 3 ) ) ( assign ( op + ) ( reg arg1 ) ( reg ) ) ; That is , the first operand gets assign to arg1 and every other gets assigned to and subsequently added to arg1 . ; The compiled factorial is below. The differences are highlighted. (define compiled-factorial '( (assign val (op make-compiled-procedure) (label entry1) (reg env)) (goto (label after-lambda2)) entry1 (assign env (op compiled-procedure-env) (reg proc)) (assign env (op extend-environment) (const (n)) (reg argl) (reg env)) ; <changed> ; We don't need to do a call here, which removes a bunch of instructions ; and a save/restore of continue and env (assign arg1 (op lookup-variable-value) (const n) (reg env)) (assign arg2 (const 1)) (assign val (op =) (reg arg1) (reg arg2)) ; </changed> (test (op false?) (reg val)) (branch (label false-branch4)) true-branch3 (assign val (const 1)) (goto (reg continue)) false-branch4 ; <changed> ; We skip another call, which saves a save/restore of proc and argl and ; another bunch of instruction (save continue) (save env) ; Saving env happens here, instead of when entering the procedure (assign proc (op lookup-variable-value) (const factorial) (reg env)) (assign arg1 (op lookup-variable-value) (const n) (reg env)) (assign arg2 (const 1)) (assign val (op -) (reg arg1) (reg arg2)) ; </changed> (assign argl (op list) (reg val)) (test (op primitive-procedure?) (reg proc)) (branch (label primitive-branch6)) compiled-branch7 (assign continue (label proc-return9)) ; Different return label (assign val (op compiled-procedure-entry) (reg proc)) (goto (reg val)) proc-return9 ; This is different, since we store result in arg1, not val. (assign arg1 (reg val)) (goto (label after-call8)) primitive-branch6 (assign arg1 (op apply-primitive-procedure) (reg proc) (reg argl)) after-call8 ; <changed> ; We save another call, including a save/restore of argl. (restore env) (restore continue) (assign arg2 (op lookup-variable-value) (const n) (reg env)) (assign val (op *) (reg arg1) (reg arg2)) ; </changed> (goto (reg continue)) after-if5 after-lambda2 (perform (op define-variable!) (const factorial) (reg val) (reg env)) (assign val (const ok)))) ; I need to modify compile-exp to check if an operation should be open-coded. (define (compile-exp exp target linkage) (cond ((self-evaluating? exp) (compile-self-evaluating exp target linkage)) ((quoted? exp) (compile-quoted exp target linkage)) ((variable? exp) (compile-variable exp target linkage)) ((assignment? exp) (compile-assignment exp target linkage)) ((definition? exp) (compile-definition exp target linkage)) ((if? exp) (compile-if exp target linkage)) ((lambda? exp) (compile-lambda exp target linkage)) ((begin? exp) (compile-sequence (begin-actions exp) target linkage)) ((cond? exp) (compile-exp (cond->if exp) target linkage)) ((open-coded? exp) (compile-open-coded exp target linkage)) ((application? exp) (compile-application exp target linkage)) (else (error "Unknown expression type -- COMPILE" exp)))) I need to add arg1 and to all - regs , so they will be preserved when ; there is a function call. (define all-regs (append '(arg1 arg2) all-regs)) ; Methods to check open coding (define (open-coded? exp) (and (pair? exp) (memq (car exp) '(+ * - =)))) (define (vararg-open-coded-exp? exp) (and (pair? exp) (memq (car exp) '(+ *)))) ; The real work (define (compile-open-coded exp target linkage) (when (and (not (vararg-open-coded-exp? exp)) (not (= (length exp) 3))) (error "Expression should be binary" exp)) (let ((code (car exp)) (first-operand (cadr exp)) (rest-operands (cddr exp))) (preserving '(env continue) (compile-exp first-operand 'arg1 'next) (compile-open-coded-rest-args code rest-operands target linkage)))) (define (compile-open-coded-rest-args code operands target linkage) (if (null? (cdr operands)) (preserving '(arg1 continue) (compile-exp (car operands) 'arg2 'next) (end-with-linkage linkage (make-instruction-sequence '(arg1 arg2) (list target) `((assign ,target (op ,code) (reg arg1) (reg arg2)))))) (preserving '(env continue) (preserving '(arg1) (compile-exp (car operands) 'arg2 'next) (make-instruction-sequence '(arg1 arg2) '(arg1) `((assign arg1 (op ,code) (reg arg1) (reg arg2))))) (compile-open-coded-rest-args code (cdr operands) target linkage)))) (define factorial-code '(define (factorial n) (if (= n 1) 1 (* (factorial (- n 1)) n)))) ;(pretty-print (statements (compile-exp factorial-code 'val 'next)))
null
https://raw.githubusercontent.com/skanev/playground/d88e53a7f277b35041c2f709771a0b96f993b310/scheme/sicp/05/38.scm
scheme
Our compiler is clever about avoiding unnecessary stack operations, but it is not clever at all when it comes to compiling calls to the primitive procedures of the language in terms of the primitive operations supplied by the machine. For example, consider how much code is compiled to compute addition procedure (which it finds by lookup up the symbol + in the environment) into proc, and tests whether the procedure is primitive or compound. The compiler always generates code to perform the test, as well as executed). We have not shown the part of the controller that implements primitives, but we presume that these instructions make use of primitive arithmetic operations in the machine's data path. Consider how much less code would be generated if the compiler could open-code primitives -- that is, if it could generate code to directly use these primitive machine operations. The expression (+ a 1) might be compiled into something as simple as In this exercise, we will extend our compiler to support open coding of selected primitives. Special-purpose code will be generated fo calls to these primitive procedures instead of the general proedure-application code. In order to support this, we will augment our machine with special argument The compiler must be able to recognize the application of an open-coded primitive in the source program. We will augment the dispatch in the compile procedure to recognize the names of these primitives in addition to the reserved words (the special forms) it currently recognizes. For each special form our compiler has a code generator. In this exercise we will construct a family of code generators for the open-coded primitives. a. The open-coded primitives, unlike the special forms, all need their operands evaluated. Write a code generator spread-arguments for use by all the open-coding code generators. spread-arguments should take an operand list and compile the given operands targeted to successive argument registers. Note that an operand may contain a call to an open-coded primitive, so argument registers will have to be preserved during operand evaluation. b. For each of the primitive procedures =, *, -, and +, write a code generator that takes a combination with that operator, together with a target and a linkage descriptor, and produces code to spread the arguments into the registers and then performs the operation targeted to the given operands. Make compile dispatch to these code generators. c. Try your new compiler on the factorial example. Compare the resulting code with the result produced without open coding. d. Extend your code generators for + and * so that they can handle expressions with arbitrary numbers of operands. An expression with more I will just ignore the spread-arguments nonsense, since I cannot figure out how to get it working with the results I want. What I want is the expression (+ 1 2 3) to be compiled to: The compiled factorial is below. The differences are highlighted. <changed> We don't need to do a call here, which removes a bunch of instructions and a save/restore of continue and env </changed> <changed> We skip another call, which saves a save/restore of proc and argl and another bunch of instruction Saving env happens here, instead of when entering the procedure </changed> Different return label This is different, since we store result in arg1, not val. <changed> We save another call, including a save/restore of argl. </changed> I need to modify compile-exp to check if an operation should be open-coded. there is a function call. Methods to check open coding The real work (pretty-print (statements (compile-exp factorial-code 'val 'next)))
SICP exercise 5.38 ( + a 1 ): The code sets up an argument list in argl , puts the primitive code for primitive and compound branches ( only one of which will be ( assign ( op lookup - variable - value ) ( const a ) ( reg env ) ) ( assign ( op + ) ( reg val ) ( const 1 ) ) registers arg1 and . The primitive arithmetic operations of the machine will take their inputs from arg1 and . The results may be put into val , arg1 , or . target with the given linkage . You need only handle expressions with two than two operands will have to be compiled into a sequence of operations , each with only two inputs . ( assign arg1 ( const 1 ) ) ( assign ( const 2 ) ) ( assign arg1 ( op + ) ( reg arg1 ) ( reg ) ) ( assign ( const 3 ) ) ( assign ( op + ) ( reg arg1 ) ( reg ) ) That is , the first operand gets assign to arg1 and every other gets assigned to and subsequently added to arg1 . (define compiled-factorial '( (assign val (op make-compiled-procedure) (label entry1) (reg env)) (goto (label after-lambda2)) entry1 (assign env (op compiled-procedure-env) (reg proc)) (assign env (op extend-environment) (const (n)) (reg argl) (reg env)) (assign arg1 (op lookup-variable-value) (const n) (reg env)) (assign arg2 (const 1)) (assign val (op =) (reg arg1) (reg arg2)) (test (op false?) (reg val)) (branch (label false-branch4)) true-branch3 (assign val (const 1)) (goto (reg continue)) false-branch4 (save continue) (assign proc (op lookup-variable-value) (const factorial) (reg env)) (assign arg1 (op lookup-variable-value) (const n) (reg env)) (assign arg2 (const 1)) (assign val (op -) (reg arg1) (reg arg2)) (assign argl (op list) (reg val)) (test (op primitive-procedure?) (reg proc)) (branch (label primitive-branch6)) compiled-branch7 (assign val (op compiled-procedure-entry) (reg proc)) (goto (reg val)) proc-return9 (assign arg1 (reg val)) (goto (label after-call8)) primitive-branch6 (assign arg1 (op apply-primitive-procedure) (reg proc) (reg argl)) after-call8 (restore env) (restore continue) (assign arg2 (op lookup-variable-value) (const n) (reg env)) (assign val (op *) (reg arg1) (reg arg2)) (goto (reg continue)) after-if5 after-lambda2 (perform (op define-variable!) (const factorial) (reg val) (reg env)) (assign val (const ok)))) (define (compile-exp exp target linkage) (cond ((self-evaluating? exp) (compile-self-evaluating exp target linkage)) ((quoted? exp) (compile-quoted exp target linkage)) ((variable? exp) (compile-variable exp target linkage)) ((assignment? exp) (compile-assignment exp target linkage)) ((definition? exp) (compile-definition exp target linkage)) ((if? exp) (compile-if exp target linkage)) ((lambda? exp) (compile-lambda exp target linkage)) ((begin? exp) (compile-sequence (begin-actions exp) target linkage)) ((cond? exp) (compile-exp (cond->if exp) target linkage)) ((open-coded? exp) (compile-open-coded exp target linkage)) ((application? exp) (compile-application exp target linkage)) (else (error "Unknown expression type -- COMPILE" exp)))) I need to add arg1 and to all - regs , so they will be preserved when (define all-regs (append '(arg1 arg2) all-regs)) (define (open-coded? exp) (and (pair? exp) (memq (car exp) '(+ * - =)))) (define (vararg-open-coded-exp? exp) (and (pair? exp) (memq (car exp) '(+ *)))) (define (compile-open-coded exp target linkage) (when (and (not (vararg-open-coded-exp? exp)) (not (= (length exp) 3))) (error "Expression should be binary" exp)) (let ((code (car exp)) (first-operand (cadr exp)) (rest-operands (cddr exp))) (preserving '(env continue) (compile-exp first-operand 'arg1 'next) (compile-open-coded-rest-args code rest-operands target linkage)))) (define (compile-open-coded-rest-args code operands target linkage) (if (null? (cdr operands)) (preserving '(arg1 continue) (compile-exp (car operands) 'arg2 'next) (end-with-linkage linkage (make-instruction-sequence '(arg1 arg2) (list target) `((assign ,target (op ,code) (reg arg1) (reg arg2)))))) (preserving '(env continue) (preserving '(arg1) (compile-exp (car operands) 'arg2 'next) (make-instruction-sequence '(arg1 arg2) '(arg1) `((assign arg1 (op ,code) (reg arg1) (reg arg2))))) (compile-open-coded-rest-args code (cdr operands) target linkage)))) (define factorial-code '(define (factorial n) (if (= n 1) 1 (* (factorial (- n 1)) n))))
8798218cb88a8b25f436e56ed62f10679b63ed894b66e45241d2a931a5d878df
haskell/cabal
setup-external-ok.test.hs
import Test.Cabal.Prelude import Data.List import qualified Data.Char as Char main = setupAndCabalTest $ do skipUnlessGhcVersion ">= 8.1" ghc <- isGhcVersion "== 9.0.2 || == 9.2.* || == 9.4.* || == 9.6.*" expectBrokenIf ghc 7987 $ withPackageDb $ do containers_id <- getIPID "containers" withDirectory "repo/sigs-0.1.0.0" $ setup_install_with_docs ["--ipid", "sigs-0.1.0.0"] withDirectory "repo/indef-0.1.0.0" $ setup_install_with_docs ["--ipid", "indef-0.1.0.0"] withDirectory "repo/sigs-0.1.0.0" $ do NB : this REUSES the dist directory that we typechecked -- indefinitely, but it's OK; the recompile checker should get it. setup_install_with_docs ["--ipid", "sigs-0.1.0.0", "--instantiate-with", "Data.Map=" ++ containers_id ++ ":Data.Map"] withDirectory "repo/indef-0.1.0.0" $ do -- Ditto. setup_install_with_docs ["--ipid", "indef-0.1.0.0", "--instantiate-with", "Data.Map=" ++ containers_id ++ ":Data.Map"] withDirectory "repo/exe-0.1.0.0" $ do setup_install [] runExe' "exe" [] >>= assertOutputContains "fromList [(0,2),(2,4)]"
null
https://raw.githubusercontent.com/haskell/cabal/0eb638fb18e4ef215413d1a1c25b5175e54f2158/cabal-testsuite/PackageTests/Backpack/Includes3/setup-external-ok.test.hs
haskell
indefinitely, but it's OK; the recompile checker should get it. Ditto.
import Test.Cabal.Prelude import Data.List import qualified Data.Char as Char main = setupAndCabalTest $ do skipUnlessGhcVersion ">= 8.1" ghc <- isGhcVersion "== 9.0.2 || == 9.2.* || == 9.4.* || == 9.6.*" expectBrokenIf ghc 7987 $ withPackageDb $ do containers_id <- getIPID "containers" withDirectory "repo/sigs-0.1.0.0" $ setup_install_with_docs ["--ipid", "sigs-0.1.0.0"] withDirectory "repo/indef-0.1.0.0" $ setup_install_with_docs ["--ipid", "indef-0.1.0.0"] withDirectory "repo/sigs-0.1.0.0" $ do NB : this REUSES the dist directory that we typechecked setup_install_with_docs ["--ipid", "sigs-0.1.0.0", "--instantiate-with", "Data.Map=" ++ containers_id ++ ":Data.Map"] withDirectory "repo/indef-0.1.0.0" $ do setup_install_with_docs ["--ipid", "indef-0.1.0.0", "--instantiate-with", "Data.Map=" ++ containers_id ++ ":Data.Map"] withDirectory "repo/exe-0.1.0.0" $ do setup_install [] runExe' "exe" [] >>= assertOutputContains "fromList [(0,2),(2,4)]"
c86b0f480264fdec5733b6da4f7e7c594f3196464f3d1281a504393763576dc6
8c6794b6/haskell-sc-scratch
Util.hs
------------------------------------------------------------------------------ -- | -- Module : $Header$ CopyRight : ( c ) 8c6794b6 -- License : BSD3 Maintainer : -- Stability : unstable -- Portability : non-portable -- -- Utility used in DesigningSound codes. -- module DesigningSound.Util where import Data.List (isPrefixOf) import Sound.SC3 import Sound.OpenSoundControl ------------------------------------------------------------------------------ -- -- Server communication -- ------------------------------------------------------------------------------ -- | Send new synth with specifying synthdef name. -- Return newly created negative node id. audit :: String -> UGen -> IO Int audit name ug = withSC3 $ \fd -> do let name' | null name = "anon" | otherwise = name send fd . d_recv $ synthdef name' ug _ <- wait fd "/done" send fd $ s_new name' (-1) AddToTail 1 [] send fd $ s_get (-1) [] (Message _ (Int i:_)) <- wait fd "/n_set" return i -- | Send new synth, return newly created negative node id. anon :: UGen -> IO Int anon ug = audit "" ug anonymous :: (Transport t) => t -> UGen -> IO Int anonymous fd ug = do send fd $ d_recv $ synthdef "anon" ug _ <- wait fd "/done" send fd $ s_new "anon" (-1) AddToTail 1 [] send fd $ s_get (-1) [] (Message _ (Int i:_)) <- wait fd "/n_set" return i -- | Send new synthdef. drecv :: String -> UGen -> IO OSC drecv name ug = withSC3 $ \fd -> async fd . d_recv $ synthdef name ug -- | add new synth bo default scsynth, specified by name and params. snew :: String -> [(String, Double)] -> IO Int snew name ps = withSC3 $ \fd -> do send fd $ s_new name (-1) AddToTail 1 ps send fd $ s_get (-1) [] (Message _ (Int i:_)) <- wait fd "/n_set" return i s_new_id :: (Transport t) => t -> String -> AddAction -> Int -> [(String, Double)] -> IO Int s_new_id fd name addAction target params = do send fd $ s_new name (-1) addAction target params send fd $ s_get (-1) [] (Message _ (Int i:_)) <- wait fd "/n_set" return i -- | Free the node from default scsynth. nfree :: Int -> IO () nfree n = withSC3 $ \fd -> send fd $ n_free [n] -- | Set the param in default scsynth. nset :: Int -> [(String, Double)] -> IO () nset n ps = withSC3 $ \fd -> send fd $ n_set n ps -- | Dump root node dumpTree :: Transport t => (t -> IO ()) dumpTree fd = send fd $ Message "/g_dumpTree" [Int 0, Int 1] ------------------------------------------------------------------------------ -- UGen -- ------------------------------------------------------------------------------ | Select a sound from given ugen array . selectX :: UGen -> UGen -> UGen selectX i a = mkFilterMCE "SelectX" [i] a 1 -- | lag ud lagUD :: UGen -> UGen -> UGen -> UGen lagUD u d t = mkFilter "LagUD" [u, d, t] 1 ------------------------------------------------------------------------------ -- -- For convinience -- ------------------------------------------------------------------------------ | Makes control for ugen , rate is always control rate . -- When the control name starts with 't_', makes trigger control. kcont :: String -> Double -> UGen kcont name val | "t_" `isPrefixOf` name = tr_control name val | otherwise = control kr name val
null
https://raw.githubusercontent.com/8c6794b6/haskell-sc-scratch/22de2199359fa56f256b544609cd6513b5e40f43/designing-sound/src/DesigningSound/Util.hs
haskell
---------------------------------------------------------------------------- | Module : $Header$ License : BSD3 Stability : unstable Portability : non-portable Utility used in DesigningSound codes. ---------------------------------------------------------------------------- Server communication ---------------------------------------------------------------------------- | Send new synth with specifying synthdef name. Return newly created negative node id. | Send new synth, return newly created negative node id. | Send new synthdef. | add new synth bo default scsynth, specified by name and params. | Free the node from default scsynth. | Set the param in default scsynth. | Dump root node ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- | lag ud ---------------------------------------------------------------------------- For convinience ---------------------------------------------------------------------------- When the control name starts with 't_', makes trigger control.
CopyRight : ( c ) 8c6794b6 Maintainer : module DesigningSound.Util where import Data.List (isPrefixOf) import Sound.SC3 import Sound.OpenSoundControl audit :: String -> UGen -> IO Int audit name ug = withSC3 $ \fd -> do let name' | null name = "anon" | otherwise = name send fd . d_recv $ synthdef name' ug _ <- wait fd "/done" send fd $ s_new name' (-1) AddToTail 1 [] send fd $ s_get (-1) [] (Message _ (Int i:_)) <- wait fd "/n_set" return i anon :: UGen -> IO Int anon ug = audit "" ug anonymous :: (Transport t) => t -> UGen -> IO Int anonymous fd ug = do send fd $ d_recv $ synthdef "anon" ug _ <- wait fd "/done" send fd $ s_new "anon" (-1) AddToTail 1 [] send fd $ s_get (-1) [] (Message _ (Int i:_)) <- wait fd "/n_set" return i drecv :: String -> UGen -> IO OSC drecv name ug = withSC3 $ \fd -> async fd . d_recv $ synthdef name ug snew :: String -> [(String, Double)] -> IO Int snew name ps = withSC3 $ \fd -> do send fd $ s_new name (-1) AddToTail 1 ps send fd $ s_get (-1) [] (Message _ (Int i:_)) <- wait fd "/n_set" return i s_new_id :: (Transport t) => t -> String -> AddAction -> Int -> [(String, Double)] -> IO Int s_new_id fd name addAction target params = do send fd $ s_new name (-1) addAction target params send fd $ s_get (-1) [] (Message _ (Int i:_)) <- wait fd "/n_set" return i nfree :: Int -> IO () nfree n = withSC3 $ \fd -> send fd $ n_free [n] nset :: Int -> [(String, Double)] -> IO () nset n ps = withSC3 $ \fd -> send fd $ n_set n ps dumpTree :: Transport t => (t -> IO ()) dumpTree fd = send fd $ Message "/g_dumpTree" [Int 0, Int 1] UGen | Select a sound from given ugen array . selectX :: UGen -> UGen -> UGen selectX i a = mkFilterMCE "SelectX" [i] a 1 lagUD :: UGen -> UGen -> UGen -> UGen lagUD u d t = mkFilter "LagUD" [u, d, t] 1 | Makes control for ugen , rate is always control rate . kcont :: String -> Double -> UGen kcont name val | "t_" `isPrefixOf` name = tr_control name val | otherwise = control kr name val
292f8676c8de4d6d73f3df6d0c1f275cc2b7cb68317197e480780b3784f40fd3
mindpool/gambit-termite
termite.scm
Copyright ( C ) 2005 - 2009 by , All Rights Reserved . ;; File: "termite.scm" ;; this is the main file for the Termite system (##namespace ("termite#")) (##include "~~/lib/gambit#.scm") (##include "termite#.scm") (declare (standard-bindings) (extended-bindings) (block)) ;; ---------------------------------------------------------------------------- System configuration & global data (define current-node (lambda () (error "uninitialized node"))) (define *global-mutex* (make-mutex "global termite mutex")) ;; translation tables for "published" PIDs (define *foreign->local* (make-table weak-values: #t)) (define *local->foreign* (make-table weak-keys: #t)) ;; translation table for "published" tags (define *uuid->tag* (make-table weak-values: #t)) Get the current time in seconds . (define (now) (time->seconds (current-time))) ;; TODO Improve this (define (formatted-current-time) (let* ((port (open-process "date")) (time (read-line port))) (close-port port) time)) ;; ---------------------------------------------------------------------------- (define (process? obj) (thread? obj)) (define (process-links pid) (thread-specific pid)) (define (process-links-set! pid obj) (thread-specific-set! pid obj)) ;; universal pid (define-type upid id: 9e096e09-8c66-4058-bddb-e061f2209838 tag node) ;; nodes (define-type node id: 8992144e-4f3e-4ce4-9d01-077576f98bc5 read-only: host port) ;; tags (define-type tag id: efa4f5f8-c74c-465b-af93-720d44a08374 (uuid init: #f)) ;; * Test whether 'obj' is a pid. (define (pid? obj) (or (process? obj) (upid? obj))) ;; NOTE It might be better to integrate with Gambit's exception mechanism (define-type termite-exception id: 6a3a285f-02c4-49ac-b00a-aa57b1ad02cf origin reason object) ;; ---------------------------------------------------------------------------- ;; process manipulation primitives ;; * Get the pid of the current process. (define self current-thread) ;; Base exception handler for Termite processes. (define (base-exception-handler e) (continuation-capture (lambda (k) (let ((log-crash (lambda (e) (termite-log 'error (list (call-with-output-string "" (lambda (port) (display-exception-in-context e k port)))))))) (cond Propagated Termite exception ? ((termite-exception? e) (if (not (eq? (termite-exception-reason e) 'normal)) (log-crash (termite-exception-object e))) (for-each (lambda (pid) (! pid e)) (process-links (self))) (halt!)) ;; Gambit exception in the current process (else (log-crash e) (for-each (lambda (pid) (! pid (make-termite-exception (self) 'failure e))) (process-links (self))) (halt!))))))) ;; * Start a new process executing the code in 'thunk'. (define (spawn thunk #!key (links '()) (name 'anonymous)) (let ((t (make-thread (lambda () (with-exception-handler base-exception-handler thunk) (shutdown!)) name))) (thread-specific-set! t links) (thread-start! t) t)) (define (spawn-linked-to to thunk #!key (name 'anonymous-linked-to)) (spawn thunk links: (list to) name: name)) ;; * Start a new process with a bidirectional link to the current ;; process. (define (spawn-link thunk #!key (name 'anonymous-linked)) (let ((pid (spawn thunk links: (list (self)) name: name))) (outbound-link pid) pid)) ;; * Start a new process on remote node 'node', executing the code ;; in 'thunk'. (define (remote-spawn node thunk #!key (links '()) (name 'anonymous-remote)) (if (equal? node (current-node)) (spawn thunk links: links name: name) (!? (remote-service 'spawner node) (list 'spawn thunk links name)))) ;; * Start a new process on remote node 'node', with a bidirectional ;; link to the current process. (define (remote-spawn-link node thunk) (let ((pid (remote-spawn node thunk links: (list (self))))) (outbound-link pid) pid)) ;; * Cleanly stop the execution of the current process. Linked ;; processes will receive a "normal" exit message. (define (shutdown!) (for-each (lambda (pid) (! pid (make-termite-exception (self) 'normal #f))) (process-links (self))) (halt!)) ;; this is *not* nice: it wont propagate the exit message to the other ;; processes (define (halt!) (thread-terminate! (current-thread))) ;; * Forcefully terminate a local process. Warning: it only works on ;; local processes! This should be used with caution. (define (terminate! victim) (thread-terminate! victim) (for-each (lambda (link) (! link (make-termite-exception victim 'terminated #f))) (process-links victim))) ;; TODO 'wait-for' and 'alive?' should be grouped in a more general ;; procedure able to determine the status of a process (alive, dead, ;; waiting, etc.) and the procedure should work on remote processes ;; * Wait for the end of a process 'pid'. Does not return anything. ;; Warning: will not work on remote processes. (define (%wait-for pid) (with-exception-catcher (lambda (e) (void)) (lambda () (thread-join! pid) (void)))) ;; Check whether the process 'pid' is still alive. Warning: will not ;; work on remote processes. (define (%alive? pid) (with-exception-catcher (lambda (e) (join-timeout-exception? e)) (lambda () (thread-join! pid 0) #f))) ;; ---------------------------------------------------------------------------- ;; Sending messages ;; * Send a message 'msg' to 'pid'. This means that the message will ;; be enqueued in the mailbox of the destination process. ;; ;; Delivery of the message is unreliable in theory, but in practice ;; local messages will always be delivered, and remote messages will ;; not be delivered only if the connection is currently broken to the ;; remote node, or if the remote node is down. ;; ;; Note that you will not get an error or an exception if the message ;; doesn't get there: you need to handle errors yourself. (define (! to msg) (cond ((process? to) (thread-send to msg)) ((upid? to) (thread-send dispatcher (list 'relay to msg))) (else (error "invalid-message-destination" to)))) ;; ---------------------------------------------------------------------------- ;; Receiving messages ;; incorrect, because it doesn't handle exception messages ;; (define ? thread-receive) * Retrieve the first message from the mailbox of the current ;; process. If no message is available, the process will block until ;; a message is received. If 'timeout' is specified, the process will ;; only block for that amount of time, and then raise an exception. ;; It is possible to also pass the 'default' argument to return a ;; value instead of raising an exception. (define (? . opt) ;; TODO: inefficient, fix (match opt (() (recv (msg msg))) ((timeout) (recv (msg msg) (after timeout (thread-receive 0)))) ((timeout default) (recv (msg msg) (after timeout default))))) ;; benchmark to see if faster... ;; (define (? #!optional (timeout +inf.0) (default (lambda (thread-receive 0)))) ;; (with-exception-catcher ;; (lambda (exception) ;; (if (mailbox-receive-timeout-exception? exception) ;; (default) ;; (raise exception))) ;; (lambda () ;; (thread-receive timeout)))) * Retrieve the first message from the mailbox of the current ;; process that satisfised the predicate 'pred?'. If no message ;; qualifies, the process will block until a message satisfying the ;; predicate is received. If 'timeout' is specified, the process will ;; only block for that amount of time, and then raise an exception. ;; It is possible to also pass the 'default' argument to return a ;; value instead of raising an exception. ;; TODO: inefficient, fix (define (?? pred? . opt) (match opt (() (recv (msg (where (pred? msg)) msg))) ((timeout) (recv (msg (where (pred? msg)) msg) (after timeout (thread-receive 0)))) ((timeout default) (recv (msg (where (pred? msg)) msg) (after timeout default))))) ;; ---------------------------------------------------------------------------- ;; Higher-order concurrency primitives ;; * Send a "synchronous" message to a process. The message will be ;; annotated with a tag and the pid of the current process, therefore ;; sending a message of the form '(from tag msg)'. The server ;; receiving the message must specifically handle that format of ;; message, and reply with a message of the form '(tag reply)'. ;; ;; Like for the |?| and |??| message retrieving operators, it is ;; possible to specify a 'timeout' to limit the amount of time to wait ;; for a reply, and a 'default' value to return if no reply has been ;; received. ;; RPC (define (!? pid msg . opt) (let ((tag (make-tag))) (! pid (list (self) tag msg)) (match opt (() (recv ((,tag reply) reply))) ((timeout) (recv ((,tag reply) reply) (after timeout (raise 'timeout)))) ((timeout default) (recv ((,tag reply) reply) (after timeout default)))))) ;; * Evaluate a 'thunk' on a remote node and return the result of that evaluation . Just like for |!?| , |?| and , it is possible to ;; specify a 'timeout' and a 'default' argument. (define (on node thunk) (let ((tag (make-tag)) (from (self))) (remote-spawn node (lambda () (! from (list tag (thunk))))) (recv ((,tag reply) reply)))) ;; ---------------------------------------------------------------------------- ;; Links and exception handling ;; Default callback for received exceptions. (define (handle-exception-message event) (raise event)) ;; * Link another process 'pid' /to/ the current one: any exception ;; not being caught by the remote process and making it crash will be ;; propagated to the current process. (define (inbound-link pid) (! linker (list 'link pid (self)))) ;; * Link the current process /to/ another process 'pid': any ;; exception not being caught by the current process will be ;; propagated to the remote process. (define (outbound-link pid) (let* ((links (process-links (self)))) (if (not (memq pid links)) (process-links-set! (self) (cons pid links))))) ;; * Link bidirectionally the current process with another process ' pid ' : any exception not being caught in any of the two processes ;; will be propagated to the other one. (define (full-link pid) (inbound-link pid) (outbound-link pid)) ;; ---------------------------------------------------------------------------- ;; Termite I/O ;; Wraps 'pid's representing Gambit output ports. (define-type termite-output-port id: b0c30401-474c-4e83-94b4-d516e00fe363 unprintable: pid) ;; Wraps 'pid's representing Gambit input ports. (define-type termite-input-port id: ebb22fcb-ca61-4765-9896-49e6716471c3 unprintable: pid) ;; Start a process representing a Gambit output port. (define (spawn-output-port port #!optional (serialize? #f)) (output-port-readtable-set! port (readtable-sharing-allowed?-set (output-port-readtable port) serialize?)) (make-termite-output-port (spawn (lambda () (let loop () (recv (proc (where (procedure? proc)) (proc port)) (x (warning "unknown message sent to output port: " x))) (loop))) name: 'termite-output-port))) ;; Start a process representing a Gambit input port. (define (spawn-input-port port #!optional (serialize? #f)) (input-port-readtable-set! port (readtable-sharing-allowed?-set (input-port-readtable port) serialize?)) (make-termite-input-port (spawn (lambda () (let loop () (recv ((from token proc) (where (procedure? proc)) (! from (list token (proc port)))) (x (warning "unknown message sent to input port: " x))) (loop))) name: 'termite-input-port))) IO parameterization ;; (define current-termite-input-port (make-parameter #f)) ;; (define current-termite-output-port (make-parameter #f)) insert IO overrides ;; (include "termiteio.scm") ;; ---------------------------------------------------------------------------- ;; Distribution Convert a ' pid ' (define (pid->upid obj) (mutex-lock! *global-mutex*) (cond ((table-ref *local->foreign* obj #f) => (lambda (x) (mutex-unlock! *global-mutex*) x)) (else (let ((upid (make-upid (make-uuid) (current-node)))) (table-set! *local->foreign* obj upid) (table-set! *foreign->local* upid obj) (mutex-unlock! *global-mutex*) upid)))) (define (tag->utag obj) (mutex-lock! *global-mutex*) (cond ((tag-uuid obj) (mutex-unlock! *global-mutex*) obj) (else (let ((uuid (make-uuid))) (tag-uuid-set! obj uuid) (table-set! *uuid->tag* uuid obj) (mutex-unlock! *global-mutex*) obj)))) (define (serialize-hook obj) (cond ((process? obj) (pid->upid obj)) ((tag? obj) (tag->utag obj)) ;; unserializable objects, so instead of crashing we set them to #f ((or (port? obj)) #f) (else obj))) (define (upid->pid obj) (cond ((table-ref *foreign->local* obj #f) => (lambda (pid) pid)) ((and (symbol? (upid-tag obj)) (resolve-service (upid-tag obj))) => (lambda (pid) pid)) (else (error "don't know how to upid->pid")))) (define (utag->tag obj) (let ((uuid (tag-uuid obj))) (cond ((table-ref *uuid->tag* uuid #f) => (lambda (tag) tag)) (else obj)))) (define (deserialize-hook obj) (cond ((and (upid? obj) (equal? (upid-node obj) (current-node))) (upid->pid obj)) ((tag? obj) (utag->tag obj)) (else obj))) (define (serialize obj port) (let* ((serialized-obj (object->u8vector obj serialize-hook)) (len (u8vector-length serialized-obj)) (serialized-len (u8vector (bitwise-and len #xff) (bitwise-and (arithmetic-shift len -8) #xff) (bitwise-and (arithmetic-shift len -16) #xff) (bitwise-and (arithmetic-shift len -24) #xff)))) (begin (write-subu8vector serialized-len 0 4 port) (write-subu8vector serialized-obj 0 len port)))) (define (deserialize port) (let* ((serialized-len (u8vector 0 0 0 0)) (n (read-subu8vector serialized-len 0 4 port))) (cond ((= 0 n) #!eof) ((not (= 4 n)) (error "deserialization error")) (else (let* ((len (+ (u8vector-ref serialized-len 0) (arithmetic-shift (u8vector-ref serialized-len 1) 8) (arithmetic-shift (u8vector-ref serialized-len 2) 16) (arithmetic-shift (u8vector-ref serialized-len 3) 24))) (serialized-obj (make-u8vector len)) (n (read-subu8vector serialized-obj 0 len port))) (if (not (eqv? len n)) (begin (error "deserialization error" (list len: len n: n))) (let ((obj (u8vector->object serialized-obj deserialize-hook))) (if (vector? obj) (vector->list obj) obj)))))))) (define (start-serializing-output-port port) (spawn-link (lambda () (let loop () (recv (('write data) ;; (debug out: data) (serialize data port) (force-output port)) ;; io override (msg (warning "serializing-output-port ignored message: " msg))) (loop))) name: 'termite-serializing-output-port)) (define (start-serializing-active-input-port port receiver) (spawn-link (lambda () (let loop () (let ((data (deserialize port))) ;; to receive exceptions... (? 0 'ok) ;; (debug in: data) (if (eof-object? data) (shutdown!)) (! receiver (list (self) data)) (loop)))) name: 'termite-serializing-active-input-port)) ;; a tcp server listens on a certain port for new tcp connection requests , and call ON - CONNECT to deal with those new connections . (define (start-tcp-server tcp-port-number on-connect) (let ((tcp-server-port (open-tcp-server (list port-number: tcp-port-number coalesce: #f)))) (spawn (lambda () (let loop () (on-connect (read tcp-server-port)) ;; io override (loop))) name: 'termite-tcp-server))) MESSENGERs act as proxies for sockets to other nodes ;; initiate a new bidirectional connection to another node important: ;; caller is responsible for registering it with the dispatcher (define (initiate-messenger node) ;; (print "OUTBOUND connection established\n") (spawn (lambda () (with-exception-catcher (lambda (e) (! dispatcher (list 'unregister (self))) (shutdown!)) (lambda () (let ((socket (open-tcp-client (list server-address: (node-host node) port-number: (node-port node) coalesce: #f)))) ;; the real interesting part (let ((in (start-serializing-active-input-port socket (self))) (out (start-serializing-output-port socket))) (! out (list 'write (current-node))) (messenger-loop node in out)))))) name: 'termite-outbound-messenger)) start a for an ' inbound ' connection ( another node ;; initiated the bidirectional connection, see initiate-messenger) (define (start-messenger socket) ;; (print "INBOUND connection established\n") (spawn (lambda () (with-exception-catcher (lambda (e) (! dispatcher (list 'unregister (self))) (shutdown!)) (lambda () (let ((in (start-serializing-active-input-port socket (self))) (out (start-serializing-output-port socket))) (recv ((,in node) ;; registering messenger to local dispatcher (! dispatcher (list 'register (self) node)) (messenger-loop node in out))))))) name: 'termite-inbound-messenger)) (define (messenger-loop node in out) (recv ;; incoming message ((,in ('relay id message)) (let ((to (upid->pid (make-upid id (current-node))))) (! to message))) ;; outgoing message (('relay to message) ;; 'to' is a upid (let* ((id (upid-tag to)) ;; (node (upid-node to)) ;; (host (node-host node)) ;; (port (node-id node)) ) (! out (list 'write (list 'relay id message))))) ;; unknown message (msg (warning "messenger-loop ignored message: " msg))) (messenger-loop node in out)) the DISPATCHER dispatches messages to the right , it keeps ;; track of known remote nodes (define dispatcher (spawn (lambda () the KNOWN - NODES of the DISPATCHER LOOP is an a - list of NODE = > (let loop ((known-nodes '())) (recv (('register messenger node) (loop (cons (cons node messenger) known-nodes))) (('unregister messenger) (loop (remove (lambda (m) (equal? (cdr m) messenger)) known-nodes))) (('relay upid message) (let ((node (upid-node upid))) (cond ;; the message should be sent locally (ideally should not happen ;; for performance reasons, but if the programmer wants to do ;; that, then OK...) ((equal? node (current-node)) (! (upid->pid upid) message) (loop known-nodes)) ;; the message is destined to a pid on a known node ((assoc node known-nodes) => (lambda (messenger) (! (cdr messenger) (list 'relay upid message)) (loop known-nodes))) ;; unconnected node, must connect (else (let ((messenger (initiate-messenger node))) (! messenger (list 'relay upid message)) (loop (cons (cons node messenger) known-nodes))))))) (msg (warning "dispatcher ignored message: " msg) ;; uh... (loop known-nodes))))) name: 'termite-dispatcher)) ;; ---------------------------------------------------------------------------- ;; Services ;; LINKER (to establish exception-propagation links between processes) (define linker (spawn (lambda () (let loop () (recv (('link from to) (cond ((process? from) (process-links-set! from (cons to (process-links from)))) ;;;;;;;;;; ((upid? from) (! (remote-service 'linker (upid-node from)) (list 'link from to))) (else (warning "in linker-loop: unknown object")))) (msg (warning "linker ignored message: " msg))) (loop))) name: 'termite-linker)) ;; Remote spawning ;; the SPAWNER answers remote-spawn request (define spawner (spawn (lambda () (let loop () (recv ((from tag ('spawn thunk links name)) (! from (list tag (spawn thunk links: links name: name)))) (msg (warning "spawner ignored message: " msg))) (loop))) name: 'termite-spawner)) ;; the PUBLISHER is used to implement a mutable global env. for ;; process names (define publisher (spawn (lambda () (define dict (make-dict)) (let loop () (recv (('publish name pid) (dict-set! dict name pid)) (('unpublish name pid) (dict-set! dict name)) ((from tag ('resolve name)) (! from (list tag (dict-ref dict name)))) (msg (warning "puslisher ignored message: " msg))) (loop))) name: 'termite-publisher)) (define (publish-service name pid) (! publisher (list 'publish name pid))) (define (unpublish-service name pid) (! publisher (list 'unpublish name pid))) ;; This should probably only used internally (define (resolve-service name #!optional host) (!? publisher (list 'resolve name))) ;; * Get the pid of a service on a remote node 'node' which has been ;; published with |publish-service| to the name 'service-name'. (define (remote-service service-name node) (make-upid service-name node)) ;; ---------------------------------------------------------------------------- Erlang / OTP - like behavior for " generic servers " and " event handlers " (include "otp/gen_server.scm") (include "otp/gen_event.scm") ;; ---------------------------------------------------------------------------- ;; Some datastrutures (include "data.scm") ;; ---------------------------------------------------------------------------- ;; Migration Task moves away , lose identity (define (migrate-task node) (call/cc (lambda (k) (remote-spawn node (lambda () (k #t))) (halt!)))) Task moves away , leave a proxy behind (define (migrate/proxy node) (define (proxy pid) (let loop () (! pid (?)) (loop))) (call/cc (lambda (k) (proxy (remote-spawn-link node (lambda () (k #t))))))) ;; ---------------------------------------------------------------------------- ;; A logging facility for Termite ;; (Ideally, this should be included with the services, but the ;; writing style is much different. Eventually, the other services ;; might use similar style.) (define (report-event event port) (match event ((type who messages) (with-output-to-port port (lambda () (newline) (display "[") (display type) (display "] ") (display (formatted-current-time)) (newline) (display who) (newline) (for-each (lambda (m) (display m) (newline)) messages) (force-output)))) (_ (display "catch-all rule invoked in reporte-event"))) port) (define file-output-log-handler (make-event-handler ;; init (lambda (args) (match args ((filename) (open-output-file (list path: filename create: 'maybe append: #t))))) ;; event report-event ;; call (lambda (term port) (values (void) port)) ;; shutdown (lambda (reason port) (close-output-port port)))) ;; 'type' is a keyword (error warning info debug) (define (termite-log type message-list) (event-manager:notify logger (list type (self) message-list))) (define (warning . terms) (termite-log 'warning terms)) (define (info . terms) (termite-log 'info terms)) (define (debug . terms) (termite-log 'debug terms)) (define logger (let ((logger (event-manager:start name: 'termite-logger))) (event-manager:add-handler logger (make-simple-event-handler report-event (current-error-port))) (event-manager:add-handler logger file-output-log-handler "_termite.log") logger)) (define ping-server (spawn (lambda () (let loop () (recv ((from tag 'ping) (! from (list tag 'pong))) (msg (debug "ping-server ignored message" msg))) (loop))) name: 'termite-ping-server)) (define (ping node #!optional (timeout 1.0)) (!? (remote-service 'ping-server node) 'ping timeout 'no-reply)) ;; ---------------------------------------------------------------------------- ;; Initialization (process-links-set! (self) '()) (define (node-init node) (start-tcp-server (node-port node) start-messenger) (set! current-node (lambda () node)) (publish-external-services) 'ok) (define (publish-external-services) ;; -------------------- ;; Services ;; publishing the accessible exterior services ;; (essentially, opening the node to other nodes) (publish-service 'spawner spawner) (publish-service 'linker linker) (publish-service 'ping-server ping-server)) ;; Some convenient definitions (define node1 (make-node "localhost" 3001)) (define node2 (make-node "localhost" 3002))
null
https://raw.githubusercontent.com/mindpool/gambit-termite/391b75253cc3a5abd77dfc29392a72b2eca0d09e/termite.scm
scheme
File: "termite.scm" this is the main file for the Termite system ---------------------------------------------------------------------------- translation tables for "published" PIDs translation table for "published" tags TODO Improve this ---------------------------------------------------------------------------- universal pid nodes tags * Test whether 'obj' is a pid. NOTE It might be better to integrate with Gambit's exception mechanism ---------------------------------------------------------------------------- process manipulation primitives * Get the pid of the current process. Base exception handler for Termite processes. Gambit exception in the current process * Start a new process executing the code in 'thunk'. * Start a new process with a bidirectional link to the current process. * Start a new process on remote node 'node', executing the code in 'thunk'. * Start a new process on remote node 'node', with a bidirectional link to the current process. * Cleanly stop the execution of the current process. Linked processes will receive a "normal" exit message. this is *not* nice: it wont propagate the exit message to the other processes * Forcefully terminate a local process. Warning: it only works on local processes! This should be used with caution. TODO 'wait-for' and 'alive?' should be grouped in a more general procedure able to determine the status of a process (alive, dead, waiting, etc.) and the procedure should work on remote processes * Wait for the end of a process 'pid'. Does not return anything. Warning: will not work on remote processes. Check whether the process 'pid' is still alive. Warning: will not work on remote processes. ---------------------------------------------------------------------------- Sending messages * Send a message 'msg' to 'pid'. This means that the message will be enqueued in the mailbox of the destination process. Delivery of the message is unreliable in theory, but in practice local messages will always be delivered, and remote messages will not be delivered only if the connection is currently broken to the remote node, or if the remote node is down. Note that you will not get an error or an exception if the message doesn't get there: you need to handle errors yourself. ---------------------------------------------------------------------------- Receiving messages incorrect, because it doesn't handle exception messages (define ? thread-receive) process. If no message is available, the process will block until a message is received. If 'timeout' is specified, the process will only block for that amount of time, and then raise an exception. It is possible to also pass the 'default' argument to return a value instead of raising an exception. TODO: inefficient, fix benchmark to see if faster... (define (? #!optional (timeout +inf.0) (default (lambda (thread-receive 0)))) (with-exception-catcher (lambda (exception) (if (mailbox-receive-timeout-exception? exception) (default) (raise exception))) (lambda () (thread-receive timeout)))) process that satisfised the predicate 'pred?'. If no message qualifies, the process will block until a message satisfying the predicate is received. If 'timeout' is specified, the process will only block for that amount of time, and then raise an exception. It is possible to also pass the 'default' argument to return a value instead of raising an exception. TODO: inefficient, fix ---------------------------------------------------------------------------- Higher-order concurrency primitives * Send a "synchronous" message to a process. The message will be annotated with a tag and the pid of the current process, therefore sending a message of the form '(from tag msg)'. The server receiving the message must specifically handle that format of message, and reply with a message of the form '(tag reply)'. Like for the |?| and |??| message retrieving operators, it is possible to specify a 'timeout' to limit the amount of time to wait for a reply, and a 'default' value to return if no reply has been received. RPC * Evaluate a 'thunk' on a remote node and return the result of that specify a 'timeout' and a 'default' argument. ---------------------------------------------------------------------------- Links and exception handling Default callback for received exceptions. * Link another process 'pid' /to/ the current one: any exception not being caught by the remote process and making it crash will be propagated to the current process. * Link the current process /to/ another process 'pid': any exception not being caught by the current process will be propagated to the remote process. * Link bidirectionally the current process with another process will be propagated to the other one. ---------------------------------------------------------------------------- Termite I/O Wraps 'pid's representing Gambit output ports. Wraps 'pid's representing Gambit input ports. Start a process representing a Gambit output port. Start a process representing a Gambit input port. (define current-termite-input-port (make-parameter #f)) (define current-termite-output-port (make-parameter #f)) (include "termiteio.scm") ---------------------------------------------------------------------------- Distribution unserializable objects, so instead of crashing we set them to #f (debug out: data) io override to receive exceptions... (debug in: data) a tcp server listens on a certain port for new tcp connection io override initiate a new bidirectional connection to another node important: caller is responsible for registering it with the dispatcher (print "OUTBOUND connection established\n") the real interesting part initiated the bidirectional connection, see initiate-messenger) (print "INBOUND connection established\n") registering messenger to local dispatcher incoming message outgoing message 'to' is a upid (node (upid-node to)) (host (node-host node)) (port (node-id node)) unknown message track of known remote nodes the message should be sent locally (ideally should not happen for performance reasons, but if the programmer wants to do that, then OK...) the message is destined to a pid on a known node unconnected node, must connect uh... ---------------------------------------------------------------------------- Services LINKER (to establish exception-propagation links between processes) Remote spawning the SPAWNER answers remote-spawn request the PUBLISHER is used to implement a mutable global env. for process names This should probably only used internally * Get the pid of a service on a remote node 'node' which has been published with |publish-service| to the name 'service-name'. ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- Some datastrutures ---------------------------------------------------------------------------- Migration ---------------------------------------------------------------------------- A logging facility for Termite (Ideally, this should be included with the services, but the writing style is much different. Eventually, the other services might use similar style.) init event call shutdown 'type' is a keyword (error warning info debug) ---------------------------------------------------------------------------- Initialization -------------------- Services publishing the accessible exterior services (essentially, opening the node to other nodes) Some convenient definitions
Copyright ( C ) 2005 - 2009 by , All Rights Reserved . (##namespace ("termite#")) (##include "~~/lib/gambit#.scm") (##include "termite#.scm") (declare (standard-bindings) (extended-bindings) (block)) System configuration & global data (define current-node (lambda () (error "uninitialized node"))) (define *global-mutex* (make-mutex "global termite mutex")) (define *foreign->local* (make-table weak-values: #t)) (define *local->foreign* (make-table weak-keys: #t)) (define *uuid->tag* (make-table weak-values: #t)) Get the current time in seconds . (define (now) (time->seconds (current-time))) (define (formatted-current-time) (let* ((port (open-process "date")) (time (read-line port))) (close-port port) time)) (define (process? obj) (thread? obj)) (define (process-links pid) (thread-specific pid)) (define (process-links-set! pid obj) (thread-specific-set! pid obj)) (define-type upid id: 9e096e09-8c66-4058-bddb-e061f2209838 tag node) (define-type node id: 8992144e-4f3e-4ce4-9d01-077576f98bc5 read-only: host port) (define-type tag id: efa4f5f8-c74c-465b-af93-720d44a08374 (uuid init: #f)) (define (pid? obj) (or (process? obj) (upid? obj))) (define-type termite-exception id: 6a3a285f-02c4-49ac-b00a-aa57b1ad02cf origin reason object) (define self current-thread) (define (base-exception-handler e) (continuation-capture (lambda (k) (let ((log-crash (lambda (e) (termite-log 'error (list (call-with-output-string "" (lambda (port) (display-exception-in-context e k port)))))))) (cond Propagated Termite exception ? ((termite-exception? e) (if (not (eq? (termite-exception-reason e) 'normal)) (log-crash (termite-exception-object e))) (for-each (lambda (pid) (! pid e)) (process-links (self))) (halt!)) (else (log-crash e) (for-each (lambda (pid) (! pid (make-termite-exception (self) 'failure e))) (process-links (self))) (halt!))))))) (define (spawn thunk #!key (links '()) (name 'anonymous)) (let ((t (make-thread (lambda () (with-exception-handler base-exception-handler thunk) (shutdown!)) name))) (thread-specific-set! t links) (thread-start! t) t)) (define (spawn-linked-to to thunk #!key (name 'anonymous-linked-to)) (spawn thunk links: (list to) name: name)) (define (spawn-link thunk #!key (name 'anonymous-linked)) (let ((pid (spawn thunk links: (list (self)) name: name))) (outbound-link pid) pid)) (define (remote-spawn node thunk #!key (links '()) (name 'anonymous-remote)) (if (equal? node (current-node)) (spawn thunk links: links name: name) (!? (remote-service 'spawner node) (list 'spawn thunk links name)))) (define (remote-spawn-link node thunk) (let ((pid (remote-spawn node thunk links: (list (self))))) (outbound-link pid) pid)) (define (shutdown!) (for-each (lambda (pid) (! pid (make-termite-exception (self) 'normal #f))) (process-links (self))) (halt!)) (define (halt!) (thread-terminate! (current-thread))) (define (terminate! victim) (thread-terminate! victim) (for-each (lambda (link) (! link (make-termite-exception victim 'terminated #f))) (process-links victim))) (define (%wait-for pid) (with-exception-catcher (lambda (e) (void)) (lambda () (thread-join! pid) (void)))) (define (%alive? pid) (with-exception-catcher (lambda (e) (join-timeout-exception? e)) (lambda () (thread-join! pid 0) #f))) (define (! to msg) (cond ((process? to) (thread-send to msg)) ((upid? to) (thread-send dispatcher (list 'relay to msg))) (else (error "invalid-message-destination" to)))) * Retrieve the first message from the mailbox of the current (match opt (() (recv (msg msg))) ((timeout) (recv (msg msg) (after timeout (thread-receive 0)))) ((timeout default) (recv (msg msg) (after timeout default))))) * Retrieve the first message from the mailbox of the current (define (?? pred? . opt) (match opt (() (recv (msg (where (pred? msg)) msg))) ((timeout) (recv (msg (where (pred? msg)) msg) (after timeout (thread-receive 0)))) ((timeout default) (recv (msg (where (pred? msg)) msg) (after timeout default))))) (define (!? pid msg . opt) (let ((tag (make-tag))) (! pid (list (self) tag msg)) (match opt (() (recv ((,tag reply) reply))) ((timeout) (recv ((,tag reply) reply) (after timeout (raise 'timeout)))) ((timeout default) (recv ((,tag reply) reply) (after timeout default)))))) evaluation . Just like for |!?| , |?| and , it is possible to (define (on node thunk) (let ((tag (make-tag)) (from (self))) (remote-spawn node (lambda () (! from (list tag (thunk))))) (recv ((,tag reply) reply)))) (define (handle-exception-message event) (raise event)) (define (inbound-link pid) (! linker (list 'link pid (self)))) (define (outbound-link pid) (let* ((links (process-links (self)))) (if (not (memq pid links)) (process-links-set! (self) (cons pid links))))) ' pid ' : any exception not being caught in any of the two processes (define (full-link pid) (inbound-link pid) (outbound-link pid)) (define-type termite-output-port id: b0c30401-474c-4e83-94b4-d516e00fe363 unprintable: pid) (define-type termite-input-port id: ebb22fcb-ca61-4765-9896-49e6716471c3 unprintable: pid) (define (spawn-output-port port #!optional (serialize? #f)) (output-port-readtable-set! port (readtable-sharing-allowed?-set (output-port-readtable port) serialize?)) (make-termite-output-port (spawn (lambda () (let loop () (recv (proc (where (procedure? proc)) (proc port)) (x (warning "unknown message sent to output port: " x))) (loop))) name: 'termite-output-port))) (define (spawn-input-port port #!optional (serialize? #f)) (input-port-readtable-set! port (readtable-sharing-allowed?-set (input-port-readtable port) serialize?)) (make-termite-input-port (spawn (lambda () (let loop () (recv ((from token proc) (where (procedure? proc)) (! from (list token (proc port)))) (x (warning "unknown message sent to input port: " x))) (loop))) name: 'termite-input-port))) IO parameterization insert IO overrides Convert a ' pid ' (define (pid->upid obj) (mutex-lock! *global-mutex*) (cond ((table-ref *local->foreign* obj #f) => (lambda (x) (mutex-unlock! *global-mutex*) x)) (else (let ((upid (make-upid (make-uuid) (current-node)))) (table-set! *local->foreign* obj upid) (table-set! *foreign->local* upid obj) (mutex-unlock! *global-mutex*) upid)))) (define (tag->utag obj) (mutex-lock! *global-mutex*) (cond ((tag-uuid obj) (mutex-unlock! *global-mutex*) obj) (else (let ((uuid (make-uuid))) (tag-uuid-set! obj uuid) (table-set! *uuid->tag* uuid obj) (mutex-unlock! *global-mutex*) obj)))) (define (serialize-hook obj) (cond ((process? obj) (pid->upid obj)) ((tag? obj) (tag->utag obj)) ((or (port? obj)) #f) (else obj))) (define (upid->pid obj) (cond ((table-ref *foreign->local* obj #f) => (lambda (pid) pid)) ((and (symbol? (upid-tag obj)) (resolve-service (upid-tag obj))) => (lambda (pid) pid)) (else (error "don't know how to upid->pid")))) (define (utag->tag obj) (let ((uuid (tag-uuid obj))) (cond ((table-ref *uuid->tag* uuid #f) => (lambda (tag) tag)) (else obj)))) (define (deserialize-hook obj) (cond ((and (upid? obj) (equal? (upid-node obj) (current-node))) (upid->pid obj)) ((tag? obj) (utag->tag obj)) (else obj))) (define (serialize obj port) (let* ((serialized-obj (object->u8vector obj serialize-hook)) (len (u8vector-length serialized-obj)) (serialized-len (u8vector (bitwise-and len #xff) (bitwise-and (arithmetic-shift len -8) #xff) (bitwise-and (arithmetic-shift len -16) #xff) (bitwise-and (arithmetic-shift len -24) #xff)))) (begin (write-subu8vector serialized-len 0 4 port) (write-subu8vector serialized-obj 0 len port)))) (define (deserialize port) (let* ((serialized-len (u8vector 0 0 0 0)) (n (read-subu8vector serialized-len 0 4 port))) (cond ((= 0 n) #!eof) ((not (= 4 n)) (error "deserialization error")) (else (let* ((len (+ (u8vector-ref serialized-len 0) (arithmetic-shift (u8vector-ref serialized-len 1) 8) (arithmetic-shift (u8vector-ref serialized-len 2) 16) (arithmetic-shift (u8vector-ref serialized-len 3) 24))) (serialized-obj (make-u8vector len)) (n (read-subu8vector serialized-obj 0 len port))) (if (not (eqv? len n)) (begin (error "deserialization error" (list len: len n: n))) (let ((obj (u8vector->object serialized-obj deserialize-hook))) (if (vector? obj) (vector->list obj) obj)))))))) (define (start-serializing-output-port port) (spawn-link (lambda () (let loop () (recv (('write data) (serialize data port) (msg (warning "serializing-output-port ignored message: " msg))) (loop))) name: 'termite-serializing-output-port)) (define (start-serializing-active-input-port port receiver) (spawn-link (lambda () (let loop () (let ((data (deserialize port))) (? 0 'ok) (if (eof-object? data) (shutdown!)) (! receiver (list (self) data)) (loop)))) name: 'termite-serializing-active-input-port)) requests , and call ON - CONNECT to deal with those new connections . (define (start-tcp-server tcp-port-number on-connect) (let ((tcp-server-port (open-tcp-server (list port-number: tcp-port-number coalesce: #f)))) (spawn (lambda () (let loop () (loop))) name: 'termite-tcp-server))) MESSENGERs act as proxies for sockets to other nodes (define (initiate-messenger node) (spawn (lambda () (with-exception-catcher (lambda (e) (! dispatcher (list 'unregister (self))) (shutdown!)) (lambda () (let ((socket (open-tcp-client (list server-address: (node-host node) port-number: (node-port node) coalesce: #f)))) (let ((in (start-serializing-active-input-port socket (self))) (out (start-serializing-output-port socket))) (! out (list 'write (current-node))) (messenger-loop node in out)))))) name: 'termite-outbound-messenger)) start a for an ' inbound ' connection ( another node (define (start-messenger socket) (spawn (lambda () (with-exception-catcher (lambda (e) (! dispatcher (list 'unregister (self))) (shutdown!)) (lambda () (let ((in (start-serializing-active-input-port socket (self))) (out (start-serializing-output-port socket))) (recv ((,in node) (! dispatcher (list 'register (self) node)) (messenger-loop node in out))))))) name: 'termite-inbound-messenger)) (define (messenger-loop node in out) (recv ((,in ('relay id message)) (let ((to (upid->pid (make-upid id (current-node))))) (! to message))) (('relay to message) (let* ((id (upid-tag to)) ) (! out (list 'write (list 'relay id message))))) (msg (warning "messenger-loop ignored message: " msg))) (messenger-loop node in out)) the DISPATCHER dispatches messages to the right , it keeps (define dispatcher (spawn (lambda () the KNOWN - NODES of the DISPATCHER LOOP is an a - list of NODE = > (let loop ((known-nodes '())) (recv (('register messenger node) (loop (cons (cons node messenger) known-nodes))) (('unregister messenger) (loop (remove (lambda (m) (equal? (cdr m) messenger)) known-nodes))) (('relay upid message) (let ((node (upid-node upid))) (cond ((equal? node (current-node)) (! (upid->pid upid) message) (loop known-nodes)) ((assoc node known-nodes) => (lambda (messenger) (! (cdr messenger) (list 'relay upid message)) (loop known-nodes))) (else (let ((messenger (initiate-messenger node))) (! messenger (list 'relay upid message)) (loop (cons (cons node messenger) known-nodes))))))) (msg (loop known-nodes))))) name: 'termite-dispatcher)) (define linker (spawn (lambda () (let loop () (recv (('link from to) (cond ((process? from) ((upid? from) (! (remote-service 'linker (upid-node from)) (list 'link from to))) (else (warning "in linker-loop: unknown object")))) (msg (warning "linker ignored message: " msg))) (loop))) name: 'termite-linker)) (define spawner (spawn (lambda () (let loop () (recv ((from tag ('spawn thunk links name)) (! from (list tag (spawn thunk links: links name: name)))) (msg (warning "spawner ignored message: " msg))) (loop))) name: 'termite-spawner)) (define publisher (spawn (lambda () (define dict (make-dict)) (let loop () (recv (('publish name pid) (dict-set! dict name pid)) (('unpublish name pid) (dict-set! dict name)) ((from tag ('resolve name)) (! from (list tag (dict-ref dict name)))) (msg (warning "puslisher ignored message: " msg))) (loop))) name: 'termite-publisher)) (define (publish-service name pid) (! publisher (list 'publish name pid))) (define (unpublish-service name pid) (! publisher (list 'unpublish name pid))) (define (resolve-service name #!optional host) (!? publisher (list 'resolve name))) (define (remote-service service-name node) (make-upid service-name node)) Erlang / OTP - like behavior for " generic servers " and " event handlers " (include "otp/gen_server.scm") (include "otp/gen_event.scm") (include "data.scm") Task moves away , lose identity (define (migrate-task node) (call/cc (lambda (k) (remote-spawn node (lambda () (k #t))) (halt!)))) Task moves away , leave a proxy behind (define (migrate/proxy node) (define (proxy pid) (let loop () (! pid (?)) (loop))) (call/cc (lambda (k) (proxy (remote-spawn-link node (lambda () (k #t))))))) (define (report-event event port) (match event ((type who messages) (with-output-to-port port (lambda () (newline) (display "[") (display type) (display "] ") (display (formatted-current-time)) (newline) (display who) (newline) (for-each (lambda (m) (display m) (newline)) messages) (force-output)))) (_ (display "catch-all rule invoked in reporte-event"))) port) (define file-output-log-handler (make-event-handler (lambda (args) (match args ((filename) (open-output-file (list path: filename create: 'maybe append: #t))))) report-event (lambda (term port) (values (void) port)) (lambda (reason port) (close-output-port port)))) (define (termite-log type message-list) (event-manager:notify logger (list type (self) message-list))) (define (warning . terms) (termite-log 'warning terms)) (define (info . terms) (termite-log 'info terms)) (define (debug . terms) (termite-log 'debug terms)) (define logger (let ((logger (event-manager:start name: 'termite-logger))) (event-manager:add-handler logger (make-simple-event-handler report-event (current-error-port))) (event-manager:add-handler logger file-output-log-handler "_termite.log") logger)) (define ping-server (spawn (lambda () (let loop () (recv ((from tag 'ping) (! from (list tag 'pong))) (msg (debug "ping-server ignored message" msg))) (loop))) name: 'termite-ping-server)) (define (ping node #!optional (timeout 1.0)) (!? (remote-service 'ping-server node) 'ping timeout 'no-reply)) (process-links-set! (self) '()) (define (node-init node) (start-tcp-server (node-port node) start-messenger) (set! current-node (lambda () node)) (publish-external-services) 'ok) (define (publish-external-services) (publish-service 'spawner spawner) (publish-service 'linker linker) (publish-service 'ping-server ping-server)) (define node1 (make-node "localhost" 3001)) (define node2 (make-node "localhost" 3002))
f20f2d40a8810951623e0a55b2dffe315ea2575d13887282ecb350df4d8c42de
parapluu/monadic-typechecker
Typechecker.hs
-- | Module : MultiError . Typechecker Copyright : © 2019 and License : MIT -- -- Stability : experimental -- Portability : portable -- -- This module includes everything you need to get started type checking a program . To build the Abstract Syntax Tree ( AST ) , please import and build the AST from " MultiError . AST " . -- -- The main entry point to the type checker is the combinator 'tcProgram', which takes an AST and returns either a list of errors , or the typed program . -- For example, for the following program (using a made up syntax): -- -- > -- > class C > f : -- > -- -- should be parsed to generate this AST: -- -- > testClass1 = > ClassDef { cname = " C " > , fields = [ FieldDef { fmod = Val , fname = " f " , ftype = ClassType " " } ] -- > ,methods = []} -- > -- To type check the AST , run the ' tcProgram ' combinator as follows : -- -- > tcProgram testClass1 -- This is an increment on top of the ' Backtrace . Typechecker ' module , -- that refactors the type checker to be able to throw multiple errors. -- # LANGUAGE NamedFieldPuns , TypeSynonymInstances , FlexibleInstances , FlexibleContexts , RankNTypes , ConstrainedClassMethods , GeneralizedNewtypeDeriving # FlexibleContexts, RankNTypes, ConstrainedClassMethods, GeneralizedNewtypeDeriving #-} module MultiError.Typechecker where import Data.Map as Map hiding (foldl, map) import Data.List as List import Data.Either (fromLeft) import Data.List.NonEmpty(NonEmpty) import qualified Data.List.NonEmpty as NE import Text.Printf (printf) import Control.Monad import Control.Monad.Reader import Control.Monad.Except import MultiError.AST -- |The type checking monad. The type checking monad is the stacking -- of the 'Reader' and 'Exception' monads. type TypecheckM a = forall m. (MonadReader Env m, MonadError TCErrors m) => m a | The function ' < :> ' takes two ' Either ' monads and returns an error if one of them is an error or aggregates both results . For example : -- > let error = Left " Error " < :> Right 42 -- > let errors = Left "Error" <:> Left "Error2" > let valid = Right " 42 " < :> Right " 0 " -- evaluates @error = Left " Error"@ , @errors = Left " ErrorError2"@ , and @valid = 420@. -- (<:>) :: Semigroup e => Either e a -> Either e b -> Either e (a, b) (Right v1) <:> (Right v2) = Right (v1, v2) (Left e1) <:> (Left e2) = Left $ e1 <> e2 (Left e1) <:> _ = Left e1 _ <:> (Left e2) = Left e2 | Forks two computations in the ' Except ' monad , and either returns both of their results , or aggregates the errors of one or both of the computations . -- For example: -- > ( fields ' , methods ' ) < - forkM precheck fields < & > -- > forkM precheck methods -- In this example , if the evaluation of and and return errors , we aggregate them using ' < :> ' . If only one of them fails , then return the single error . If both computation -- succeed, return a monad wrapped around the tuple with both results. -- (<&>) :: (Semigroup e, MonadError e m) => m a -> m b -> m (a, b) tc1 <&> tc2 = do res1 <- (tc1 >>= return . Right) `catchError` (\err -> return $ Left err) res2 <- (tc2 >>= return . Right) `catchError` (\err -> return $ Left err) liftEither $ res1 <:> res2 -- | Allows typechecking a list of items, collecting error messages -- from all of them. forkM :: (Semigroup e, MonadError e m) => (a -> m b) -> [a] -> m [b] forkM _ [] = return [] forkM f (x:xs) = uncurry (:) <$> (f x <&> forkM f xs) -- | Declaration of type checking errors. An error will (usually) be -- created using the helper function 'tcError'. As an example: -- -- > tcError $ DuplicateClassError (Name "Foo") -- -- throws an error that indicates that the class is defined multiple times. -- newtype TCErrors = TCErrors (NonEmpty TCError) deriving (Semigroup) instance Show TCErrors where show (TCErrors errs) = " *** Error during typechecking *** \n" ++ intercalate "\n" (map show (NE.toList errs)) -- | Declaration of a type checking error, where 'Error' represents the current type checking error and ' Backtrace ' the up - to - date backtrace . data TCError = TCError -- ^ Type checking error value constructor Error -- ^ Current type checking error Backtrace -- ^ Backtrace of the type checker instance Show TCError where show (TCError err bt) = show err ++ "\n" ++ show bt -- | Throw a type checking 'Error' tcError :: Error -> TypecheckM a tcError err = do bt <- asks bt throwError $ TCErrors (NE.fromList [TCError err bt]) -- |Data declaration of available errors. Value constructors are used -- to create statically known errors. For example: -- > UnknownClassError ( Name c ) -- creates a ' UnknownClassError ' . This error should be created whenever there -- is a class whose declaration is unknown or inexistent. data Error = UnknownClassError Name -- ^ Reference of a class that does not exists | UnknownFieldError Name -- ^ Reference of a field that does not exists | UnknownMethodError Name -- ^ Reference of a method that does not exists | UnboundVariableError Name -- ^ Unbound variable | Type mismatch error , the first @Type@ refers to the formal type argument , the second @Type@ refers to the actual type argument . | TypeMismatchError Type Type -- | Immutable field error, used when someone violates immutability | ImmutableFieldError Expr | Error to indicate that a one can not assign a value to expression @Expr@ | NonLValError Expr -- | Error indicating that the return type cannot be @Null@ | PrimitiveNullError Type -- | Used to indicate that @Type@ is not of a class type | NonClassTypeError Type -- | Expecting a function (arrow) type but got another type instead. | NonArrowTypeError Type -- | Tried to call a constructor outside of instantiation | ConstructorCallError Type | Can not infer type of @Expr@ | UninferrableError Expr instance Show Error where show (UnknownClassError c) = printf "Unknown class '%s'" c show (UnknownFieldError f) = printf "Unknown field '%s'" f show (UnknownMethodError m) = printf "Unknown method '%s'" m show (UnboundVariableError x) = printf "Unbound variable '%s'" x show (TypeMismatchError actual expected) = printf "Type '%s' does not match expected type '%s'" (show actual) (show expected) show (ImmutableFieldError e) = printf "Cannot write to immutable field '%s'" (show e) show (NonLValError e) = printf "Cannot assign to expression '%s'" (show e) show (PrimitiveNullError t) = printf "Type '%s' cannot be null" (show t) show (NonClassTypeError t) = printf "Expected class type, got '%s'" (show t) show (NonArrowTypeError t) = printf "Expected function type, got '%s'" (show t) show (ConstructorCallError t) = printf "Tried to call constructor of class '%s' outside of instantiation" (show t) show (UninferrableError e) = printf "Cannot infer the type of '%s'" (show e) -- | Environment. The 'Env' is used during type checking, and is updated as -- the type checker runs. Most likely, one uses the 'Reader' monad to hide details -- of how the environment is updated, via the common 'local' function. data Env = Env {ctable :: Map Name ClassDef ,vartable :: Map Name Type ,bt :: Backtrace ,constructor :: Bool} -- | Conditionally update the environment to track if we are in a -- constructor method. setConstructor :: Name -> Env -> Env setConstructor m env = env{constructor = isConstructorName m} -- | Generates an empty environment. emptyEnv = Env {ctable = Map.empty ,vartable = Map.empty ,bt = emptyBt ,constructor = False} -- | Helper function to lookup a class given a 'Name' and an 'Env'. Usually -- it relies on the 'Reader' monad, so that passing the 'Env' can be omitted. -- For example: -- > findClass : : Type - > TypecheckM ClassDef -- > findClass ty@(ClassType c) = do -- > cls <- asks $ lookupClass c -- > case cls of > Just cdef - > return cdef > Nothing - > tcError $ UnknownClassError c > findClass ty = tcError $ NonClassTypeError ty -- -- In this function ('findClass'), the 'Reader' function 'asks' injects -- the 'Reader' monad as the last argument. More details in the paper. lookupClass :: Name -> Env -> Maybe ClassDef lookupClass c Env{ctable} = Map.lookup c ctable -- | Look up a variable by its 'Name' in the 'Env', returning an option type -- indicating whether the variable was found or not. lookupVar :: Name -> Env -> Maybe Type lookupVar x Env{vartable} = Map.lookup x vartable -- | Find a class declaration by its 'Type' findClass :: Type -> TypecheckM ClassDef findClass (ClassType c) = do cls <- asks $ lookupClass c case cls of Just cdef -> return cdef Nothing -> tcError $ UnknownClassError c findClass ty = tcError $ NonClassTypeError ty -- | Find a method declaration by its 'Type' and method name @m@ findMethod :: Type -> Name -> TypecheckM MethodDef findMethod ty m = do ClassDef{methods} <- findClass ty case List.find ((== m) . mname) methods of Just mdef -> return mdef Nothing -> tcError $ UnknownMethodError m | Find a field declaration by its ' Type ' ( @ty@ ) and field name findField :: Type -> Name -> TypecheckM FieldDef findField ty f = do ClassDef{fields} <- findClass ty case List.find ((== f) . fname) fields of Just fdef -> return fdef Nothing -> tcError $ UnknownFieldError f -- | Find a variable in the environment by its name @x@ findVar :: Name -> TypecheckM Type findVar x = do result <- asks $ lookupVar x case result of Just t -> return t Nothing -> tcError $ UnboundVariableError x -- | Generates an environment (symbol's table) from a 'Program', genEnv :: Program -> Env genEnv (Program cls) = foldl generateEnv emptyEnv cls where generateEnv :: Env -> ClassDef -> Env generateEnv env cls = Env {ctable = Map.insert (cname cls) cls (ctable env) ,vartable = vartable env ,bt = emptyBt ,constructor = False} -- | Add a variable name and its type to the environment 'Env'. addVariable :: Name -> Type -> Env -> Env addVariable x t env@Env{vartable} = env{vartable = Map.insert x t vartable} | Add a list of parameters , ' ' , to the environment . addParameters :: [Param] -> Env -> Env addParameters params env = foldl addParameter env params where addParameter env (Param name ty) = addVariable name ty env -- | Main entry point of the type checker. This function type checks an AST -- returning either a list of errors or a well-typed program. For instance, -- assuming the following made up language: -- > -- > class C > f : -- > -- -- it should be parsed to generate the following AST: -- -- > testClass1 = > ClassDef { cname = " C " > , fields = [ FieldDef { fmod = Val , fname = " f " , ftype = ClassType " " } ] -- > ,methods = []} -- > -- To type check the AST , run the ' tcProgram ' combinator as follows : -- -- > tcProgram testClass1 -- which either returns a list of errors or the resulting typed AST . -- tcProgram :: Program -> Either TCErrors Program tcProgram p = do let env = genEnv p exceptM = runReaderT (doTypecheck p) env runExcept exceptM -- | The type class defines how to type check an AST node. class Typecheckable a where -- | Type check the well-formedness of an AST node. doTypecheck :: a -> TypecheckM a | Type check an AST node , updating the environment 's backtrace . typecheck :: (Backtraceable a) => a -> TypecheckM a typecheck x = local pushBT $ doTypecheck x where pushBT env@Env{bt} = env{bt = push x bt} -- Type checking the well-formedness of types instance Typecheckable Type where doTypecheck (ClassType c) = do _ <- findClass (ClassType c) return $ ClassType c doTypecheck IntType = return IntType doTypecheck BoolType = return BoolType doTypecheck UnitType = return UnitType doTypecheck (Arrow ts t) = do ts' <- forkM typecheck ts t' <- typecheck t return $ Arrow ts' t' instance Typecheckable Program where doTypecheck (Program cls) = Program <$> forkM typecheck cls instance Typecheckable ClassDef where doTypecheck cdef@ClassDef{cname, fields, methods} = do let withThisAdded = local $ addVariable thisName (ClassType cname) (fields', methods') <- withThisAdded $ forkM typecheck fields <&> forkM typecheck methods return $ cdef {fields = fields' ,methods = methods'} instance Typecheckable FieldDef where doTypecheck fdef@FieldDef{ftype} = do ftype' <- typecheck ftype return fdef{ftype = ftype'} instance Typecheckable Param where doTypecheck param@(Param {ptype}) = do ptype' <- typecheck ptype return param{ptype = ptype'} instance Typecheckable MethodDef where doTypecheck mdef@(MethodDef {mname, mparams, mbody, mtype}) = do -- typecheck the well-formedness of types of method parameters (mparams', mtype') <- forkM typecheck mparams <&> typecheck mtype -- extend environment with method parameters and typecheck body mbody' <- local (addParameters mparams . setConstructor mname) $ hasType mbody mtype' return $ mdef {mparams = mparams' ,mtype = mtype' ,mbody = mbody'} instance Typecheckable Expr where doTypecheck e@(BoolLit {}) = return $ setType BoolType e doTypecheck e@(IntLit {}) = return $ setType IntType e doTypecheck e@(Lambda {params, body}) = do params' <- forkM typecheck params body' <- local (addParameters params) $ typecheck body let parameterTypes = map ptype params' bodyType = getType body' funType = Arrow parameterTypes bodyType return $ setType funType e{params = params' ,body = body'} doTypecheck e@(VarAccess {name}) = do ty <- findVar name return $ setType ty e doTypecheck e@(FieldAccess {target, name}) = do target' <- typecheck target let targetType = getType target' FieldDef {ftype} <- findField targetType name return $ setType ftype e{target = target'} doTypecheck e@(Assignment {lhs, rhs}) = do unless (isLVal lhs) $ tcError $ NonLValError lhs lhs' <- typecheck lhs let lType = getType lhs' rhs' <- hasType rhs lType let rType = getType rhs' checkMutability lhs' return $ setType UnitType e{lhs = lhs' ,rhs = rhs'} where checkMutability e@FieldAccess{target, name} = do field <- findField (getType target) name inConstructor <- asks constructor unless (isVarField field || inConstructor && isThisAccess target) $ tcError $ ImmutableFieldError e checkMutability _ = return () doTypecheck e@(New {ty, args}) = do ty' <- typecheck ty MethodDef {mparams} <- findMethod ty' "init" let paramTypes = map ptype mparams args' <- zipWithM hasType args paramTypes return $ setType ty' $ e{ty = ty' ,args = args'} doTypecheck e@(MethodCall {target, name, args}) = do target' <- typecheck target let targetType = getType target' when (isConstructorName name) $ tcError $ ConstructorCallError targetType MethodDef {mparams, mtype} <- findMethod targetType name let paramTypes = map ptype mparams args' <- zipWithM hasType args paramTypes return $ setType mtype $ e{target = target' ,args = args'} doTypecheck e@(FunctionCall {target, args}) = do target' <- typecheck target let targetType = getType target' unless (isArrowType targetType) $ tcError $ NonArrowTypeError targetType let paramTypes = tparams targetType resultType = tresult targetType args' <- zipWithM hasType args paramTypes return $ setType resultType e{target = target' ,args = args'} doTypecheck e@(BinOp {op, lhs, rhs}) = do lhs' <- hasType lhs IntType rhs' <- hasType rhs IntType return $ setType IntType e{lhs = lhs' ,rhs = rhs'} doTypecheck e@(Cast {body, ty}) = do ty' <- typecheck ty body' <- hasType body ty' return $ setType ty' e{body = body' ,ty = ty'} doTypecheck e@(If {cond, thn, els}) = do cond' <- hasType cond BoolType thn' <- typecheck thn let thnType = getType thn' els' <- hasType els thnType return $ setType thnType e{cond = cond' ,thn = thn' ,els = els'} doTypecheck e@(Let {name, val, body}) = do val' <- typecheck val let ty = getType val' body' <- local (addVariable name ty) $ typecheck body let bodyType = getType body' return $ setType bodyType e{val = val' ,body = body'} doTypecheck e = tcError $ UninferrableError e -- | This combinator is used whenever a certain type is expected. This function -- is quite important. Here follows an example: -- > doTypecheck mdef@(MethodDef , mtype } ) = do -- > -- typecheck the well-formedness of types of method parameters > mparams ' < - mapM -- > mtype' <- typecheck mtype -- > -- > -- extend environment with method parameters and typecheck body > mbody ' < - local ( addParameters mparams ) $ hasType mbody mtype ' -- > ... -- -- in the last line, because we are type checking a method declaration, -- it is statically known what should be the return type of the function body. In these -- cases, one should use the 'hasType' combinator. -- hasType :: Expr -> Type -> TypecheckM Expr hasType e@Null{} expected = do unless (isClassType expected) $ tcError $ PrimitiveNullError expected return $ setType expected e hasType e expected = do e' <- typecheck e let eType = getType e' unless (eType == expected) $ tcError $ TypeMismatchError eType expected return $ setType expected e' | Class definition for didactic purposes . This AST represents the following class , which is named @C@ , contains an immutable field @f@ of type @Foo@ : -- -- > class C: > f : -- -- This class is ill-typed, as there is no declaration of @Foo@ anywhere. -- To check how to type checker catches this error, run: -- -- > tcProgram (Program [testClass1]) -- testClass1 = ClassDef {cname = "C" ,fields = [FieldDef {fmod = Val, fname = "f", ftype = ClassType "Foo"}] ,methods = []} -- | Test program with a class, field, method, and variable access. The class @Bar@ -- does not exist in the environment. The variable access is unbound. -- This program is the AST equivalent of the following syntax : -- -- > class D -- > val g: Bar -- > def m(): Int -- > x -- testClass2 = ClassDef {cname = "D" ,fields = [FieldDef {fmod = Val, fname = "g", ftype = ClassType "Bar"}] ,methods = [MethodDef {mname = "m", mparams = [], mtype = IntType, mbody = VarAccess Nothing "x"}]} testProgram = Program $ [testClass1, testClass2] -- | Test suite that runs 'testProgram'. testSuite = do putStrLn $ "\n************************************************" putStrLn $ "5. Multiple errors.\n" ++ "Showing a program with 3 errors:\n" ++ "- type checker catches multiple error\n" ++ "- there is support for backtrace\n" putStrLn "Output:" putStrLn "" putStrLn $ show $ fromLeft undefined (tcProgram testProgram) putStrLn "" putStrLn $ "************************************************"
null
https://raw.githubusercontent.com/parapluu/monadic-typechecker/9f737a9ed2a3ac4ff5245e2e48deeac7bc2ee73d/artifact/typechecker-oopl/src/MultiError/Typechecker.hs
haskell
| Stability : experimental Portability : portable This module includes everything you need to get started type checking The main entry point to the type checker is the combinator 'tcProgram', which For example, for the following program (using a made up syntax): > > class C > should be parsed to generate this AST: > testClass1 = > ,methods = []} > > tcProgram testClass1 that refactors the type checker to be able to throw multiple errors. |The type checking monad. The type checking monad is the stacking of the 'Reader' and 'Exception' monads. > let errors = Left "Error" <:> Left "Error2" For example: > forkM precheck methods succeed, return a monad wrapped around the tuple with both results. | Allows typechecking a list of items, collecting error messages from all of them. | Declaration of type checking errors. An error will (usually) be created using the helper function 'tcError'. As an example: > tcError $ DuplicateClassError (Name "Foo") throws an error that indicates that the class is defined multiple times. | Declaration of a type checking error, where 'Error' represents ^ Type checking error value constructor ^ Current type checking error ^ Backtrace of the type checker | Throw a type checking 'Error' |Data declaration of available errors. Value constructors are used to create statically known errors. For example: is a class whose declaration is unknown or inexistent. ^ Reference of a class that does not exists ^ Reference of a field that does not exists ^ Reference of a method that does not exists ^ Unbound variable | Immutable field error, used when someone violates immutability | Error indicating that the return type cannot be @Null@ | Used to indicate that @Type@ is not of a class type | Expecting a function (arrow) type but got another type instead. | Tried to call a constructor outside of instantiation | Environment. The 'Env' is used during type checking, and is updated as the type checker runs. Most likely, one uses the 'Reader' monad to hide details of how the environment is updated, via the common 'local' function. | Conditionally update the environment to track if we are in a constructor method. | Generates an empty environment. | Helper function to lookup a class given a 'Name' and an 'Env'. Usually it relies on the 'Reader' monad, so that passing the 'Env' can be omitted. For example: > findClass ty@(ClassType c) = do > cls <- asks $ lookupClass c > case cls of In this function ('findClass'), the 'Reader' function 'asks' injects the 'Reader' monad as the last argument. More details in the paper. | Look up a variable by its 'Name' in the 'Env', returning an option type indicating whether the variable was found or not. | Find a class declaration by its 'Type' | Find a method declaration by its 'Type' and method name @m@ | Find a variable in the environment by its name @x@ | Generates an environment (symbol's table) from a 'Program', | Add a variable name and its type to the environment 'Env'. | Main entry point of the type checker. This function type checks an AST returning either a list of errors or a well-typed program. For instance, assuming the following made up language: > > class C > it should be parsed to generate the following AST: > testClass1 = > ,methods = []} > > tcProgram testClass1 | The type class defines how to type check an AST node. | Type check the well-formedness of an AST node. Type checking the well-formedness of types typecheck the well-formedness of types of method parameters extend environment with method parameters and typecheck body | This combinator is used whenever a certain type is expected. This function is quite important. Here follows an example: > -- typecheck the well-formedness of types of method parameters > mtype' <- typecheck mtype > > -- extend environment with method parameters and typecheck body > ... in the last line, because we are type checking a method declaration, it is statically known what should be the return type of the function body. In these cases, one should use the 'hasType' combinator. > class C: This class is ill-typed, as there is no declaration of @Foo@ anywhere. To check how to type checker catches this error, run: > tcProgram (Program [testClass1]) | Test program with a class, field, method, and variable access. The class @Bar@ does not exist in the environment. The variable access is unbound. > class D > val g: Bar > def m(): Int > x | Test suite that runs 'testProgram'.
Module : MultiError . Typechecker Copyright : © 2019 and License : MIT a program . To build the Abstract Syntax Tree ( AST ) , please import and build the AST from " MultiError . AST " . takes an AST and returns either a list of errors , or the typed program . > f : > ClassDef { cname = " C " > , fields = [ FieldDef { fmod = Val , fname = " f " , ftype = ClassType " " } ] To type check the AST , run the ' tcProgram ' combinator as follows : This is an increment on top of the ' Backtrace . Typechecker ' module , # LANGUAGE NamedFieldPuns , TypeSynonymInstances , FlexibleInstances , FlexibleContexts , RankNTypes , ConstrainedClassMethods , GeneralizedNewtypeDeriving # FlexibleContexts, RankNTypes, ConstrainedClassMethods, GeneralizedNewtypeDeriving #-} module MultiError.Typechecker where import Data.Map as Map hiding (foldl, map) import Data.List as List import Data.Either (fromLeft) import Data.List.NonEmpty(NonEmpty) import qualified Data.List.NonEmpty as NE import Text.Printf (printf) import Control.Monad import Control.Monad.Reader import Control.Monad.Except import MultiError.AST type TypecheckM a = forall m. (MonadReader Env m, MonadError TCErrors m) => m a | The function ' < :> ' takes two ' Either ' monads and returns an error if one of them is an error or aggregates both results . For example : > let error = Left " Error " < :> Right 42 > let valid = Right " 42 " < :> Right " 0 " evaluates @error = Left " Error"@ , @errors = Left " ErrorError2"@ , and @valid = 420@. (<:>) :: Semigroup e => Either e a -> Either e b -> Either e (a, b) (Right v1) <:> (Right v2) = Right (v1, v2) (Left e1) <:> (Left e2) = Left $ e1 <> e2 (Left e1) <:> _ = Left e1 _ <:> (Left e2) = Left e2 | Forks two computations in the ' Except ' monad , and either returns both of their results , or aggregates the errors of one or both of the computations . > ( fields ' , methods ' ) < - forkM precheck fields < & > In this example , if the evaluation of and and return errors , we aggregate them using ' < :> ' . If only one of them fails , then return the single error . If both computation (<&>) :: (Semigroup e, MonadError e m) => m a -> m b -> m (a, b) tc1 <&> tc2 = do res1 <- (tc1 >>= return . Right) `catchError` (\err -> return $ Left err) res2 <- (tc2 >>= return . Right) `catchError` (\err -> return $ Left err) liftEither $ res1 <:> res2 forkM :: (Semigroup e, MonadError e m) => (a -> m b) -> [a] -> m [b] forkM _ [] = return [] forkM f (x:xs) = uncurry (:) <$> (f x <&> forkM f xs) newtype TCErrors = TCErrors (NonEmpty TCError) deriving (Semigroup) instance Show TCErrors where show (TCErrors errs) = " *** Error during typechecking *** \n" ++ intercalate "\n" (map show (NE.toList errs)) the current type checking error and ' Backtrace ' the up - to - date backtrace . instance Show TCError where show (TCError err bt) = show err ++ "\n" ++ show bt tcError :: Error -> TypecheckM a tcError err = do bt <- asks bt throwError $ TCErrors (NE.fromList [TCError err bt]) > UnknownClassError ( Name c ) creates a ' UnknownClassError ' . This error should be created whenever there data Error = | Type mismatch error , the first @Type@ refers to the formal type argument , the second @Type@ refers to the actual type argument . | TypeMismatchError Type Type | ImmutableFieldError Expr | Error to indicate that a one can not assign a value to expression @Expr@ | NonLValError Expr | PrimitiveNullError Type | NonClassTypeError Type | NonArrowTypeError Type | ConstructorCallError Type | Can not infer type of @Expr@ | UninferrableError Expr instance Show Error where show (UnknownClassError c) = printf "Unknown class '%s'" c show (UnknownFieldError f) = printf "Unknown field '%s'" f show (UnknownMethodError m) = printf "Unknown method '%s'" m show (UnboundVariableError x) = printf "Unbound variable '%s'" x show (TypeMismatchError actual expected) = printf "Type '%s' does not match expected type '%s'" (show actual) (show expected) show (ImmutableFieldError e) = printf "Cannot write to immutable field '%s'" (show e) show (NonLValError e) = printf "Cannot assign to expression '%s'" (show e) show (PrimitiveNullError t) = printf "Type '%s' cannot be null" (show t) show (NonClassTypeError t) = printf "Expected class type, got '%s'" (show t) show (NonArrowTypeError t) = printf "Expected function type, got '%s'" (show t) show (ConstructorCallError t) = printf "Tried to call constructor of class '%s' outside of instantiation" (show t) show (UninferrableError e) = printf "Cannot infer the type of '%s'" (show e) data Env = Env {ctable :: Map Name ClassDef ,vartable :: Map Name Type ,bt :: Backtrace ,constructor :: Bool} setConstructor :: Name -> Env -> Env setConstructor m env = env{constructor = isConstructorName m} emptyEnv = Env {ctable = Map.empty ,vartable = Map.empty ,bt = emptyBt ,constructor = False} > findClass : : Type - > TypecheckM ClassDef > Just cdef - > return cdef > Nothing - > tcError $ UnknownClassError c > findClass ty = tcError $ NonClassTypeError ty lookupClass :: Name -> Env -> Maybe ClassDef lookupClass c Env{ctable} = Map.lookup c ctable lookupVar :: Name -> Env -> Maybe Type lookupVar x Env{vartable} = Map.lookup x vartable findClass :: Type -> TypecheckM ClassDef findClass (ClassType c) = do cls <- asks $ lookupClass c case cls of Just cdef -> return cdef Nothing -> tcError $ UnknownClassError c findClass ty = tcError $ NonClassTypeError ty findMethod :: Type -> Name -> TypecheckM MethodDef findMethod ty m = do ClassDef{methods} <- findClass ty case List.find ((== m) . mname) methods of Just mdef -> return mdef Nothing -> tcError $ UnknownMethodError m | Find a field declaration by its ' Type ' ( @ty@ ) and field name findField :: Type -> Name -> TypecheckM FieldDef findField ty f = do ClassDef{fields} <- findClass ty case List.find ((== f) . fname) fields of Just fdef -> return fdef Nothing -> tcError $ UnknownFieldError f findVar :: Name -> TypecheckM Type findVar x = do result <- asks $ lookupVar x case result of Just t -> return t Nothing -> tcError $ UnboundVariableError x genEnv :: Program -> Env genEnv (Program cls) = foldl generateEnv emptyEnv cls where generateEnv :: Env -> ClassDef -> Env generateEnv env cls = Env {ctable = Map.insert (cname cls) cls (ctable env) ,vartable = vartable env ,bt = emptyBt ,constructor = False} addVariable :: Name -> Type -> Env -> Env addVariable x t env@Env{vartable} = env{vartable = Map.insert x t vartable} | Add a list of parameters , ' ' , to the environment . addParameters :: [Param] -> Env -> Env addParameters params env = foldl addParameter env params where addParameter env (Param name ty) = addVariable name ty env > f : > ClassDef { cname = " C " > , fields = [ FieldDef { fmod = Val , fname = " f " , ftype = ClassType " " } ] To type check the AST , run the ' tcProgram ' combinator as follows : which either returns a list of errors or the resulting typed AST . tcProgram :: Program -> Either TCErrors Program tcProgram p = do let env = genEnv p exceptM = runReaderT (doTypecheck p) env runExcept exceptM class Typecheckable a where doTypecheck :: a -> TypecheckM a | Type check an AST node , updating the environment 's backtrace . typecheck :: (Backtraceable a) => a -> TypecheckM a typecheck x = local pushBT $ doTypecheck x where pushBT env@Env{bt} = env{bt = push x bt} instance Typecheckable Type where doTypecheck (ClassType c) = do _ <- findClass (ClassType c) return $ ClassType c doTypecheck IntType = return IntType doTypecheck BoolType = return BoolType doTypecheck UnitType = return UnitType doTypecheck (Arrow ts t) = do ts' <- forkM typecheck ts t' <- typecheck t return $ Arrow ts' t' instance Typecheckable Program where doTypecheck (Program cls) = Program <$> forkM typecheck cls instance Typecheckable ClassDef where doTypecheck cdef@ClassDef{cname, fields, methods} = do let withThisAdded = local $ addVariable thisName (ClassType cname) (fields', methods') <- withThisAdded $ forkM typecheck fields <&> forkM typecheck methods return $ cdef {fields = fields' ,methods = methods'} instance Typecheckable FieldDef where doTypecheck fdef@FieldDef{ftype} = do ftype' <- typecheck ftype return fdef{ftype = ftype'} instance Typecheckable Param where doTypecheck param@(Param {ptype}) = do ptype' <- typecheck ptype return param{ptype = ptype'} instance Typecheckable MethodDef where doTypecheck mdef@(MethodDef {mname, mparams, mbody, mtype}) = do (mparams', mtype') <- forkM typecheck mparams <&> typecheck mtype mbody' <- local (addParameters mparams . setConstructor mname) $ hasType mbody mtype' return $ mdef {mparams = mparams' ,mtype = mtype' ,mbody = mbody'} instance Typecheckable Expr where doTypecheck e@(BoolLit {}) = return $ setType BoolType e doTypecheck e@(IntLit {}) = return $ setType IntType e doTypecheck e@(Lambda {params, body}) = do params' <- forkM typecheck params body' <- local (addParameters params) $ typecheck body let parameterTypes = map ptype params' bodyType = getType body' funType = Arrow parameterTypes bodyType return $ setType funType e{params = params' ,body = body'} doTypecheck e@(VarAccess {name}) = do ty <- findVar name return $ setType ty e doTypecheck e@(FieldAccess {target, name}) = do target' <- typecheck target let targetType = getType target' FieldDef {ftype} <- findField targetType name return $ setType ftype e{target = target'} doTypecheck e@(Assignment {lhs, rhs}) = do unless (isLVal lhs) $ tcError $ NonLValError lhs lhs' <- typecheck lhs let lType = getType lhs' rhs' <- hasType rhs lType let rType = getType rhs' checkMutability lhs' return $ setType UnitType e{lhs = lhs' ,rhs = rhs'} where checkMutability e@FieldAccess{target, name} = do field <- findField (getType target) name inConstructor <- asks constructor unless (isVarField field || inConstructor && isThisAccess target) $ tcError $ ImmutableFieldError e checkMutability _ = return () doTypecheck e@(New {ty, args}) = do ty' <- typecheck ty MethodDef {mparams} <- findMethod ty' "init" let paramTypes = map ptype mparams args' <- zipWithM hasType args paramTypes return $ setType ty' $ e{ty = ty' ,args = args'} doTypecheck e@(MethodCall {target, name, args}) = do target' <- typecheck target let targetType = getType target' when (isConstructorName name) $ tcError $ ConstructorCallError targetType MethodDef {mparams, mtype} <- findMethod targetType name let paramTypes = map ptype mparams args' <- zipWithM hasType args paramTypes return $ setType mtype $ e{target = target' ,args = args'} doTypecheck e@(FunctionCall {target, args}) = do target' <- typecheck target let targetType = getType target' unless (isArrowType targetType) $ tcError $ NonArrowTypeError targetType let paramTypes = tparams targetType resultType = tresult targetType args' <- zipWithM hasType args paramTypes return $ setType resultType e{target = target' ,args = args'} doTypecheck e@(BinOp {op, lhs, rhs}) = do lhs' <- hasType lhs IntType rhs' <- hasType rhs IntType return $ setType IntType e{lhs = lhs' ,rhs = rhs'} doTypecheck e@(Cast {body, ty}) = do ty' <- typecheck ty body' <- hasType body ty' return $ setType ty' e{body = body' ,ty = ty'} doTypecheck e@(If {cond, thn, els}) = do cond' <- hasType cond BoolType thn' <- typecheck thn let thnType = getType thn' els' <- hasType els thnType return $ setType thnType e{cond = cond' ,thn = thn' ,els = els'} doTypecheck e@(Let {name, val, body}) = do val' <- typecheck val let ty = getType val' body' <- local (addVariable name ty) $ typecheck body let bodyType = getType body' return $ setType bodyType e{val = val' ,body = body'} doTypecheck e = tcError $ UninferrableError e > doTypecheck mdef@(MethodDef , mtype } ) = do > mparams ' < - mapM > mbody ' < - local ( addParameters mparams ) $ hasType mbody mtype ' hasType :: Expr -> Type -> TypecheckM Expr hasType e@Null{} expected = do unless (isClassType expected) $ tcError $ PrimitiveNullError expected return $ setType expected e hasType e expected = do e' <- typecheck e let eType = getType e' unless (eType == expected) $ tcError $ TypeMismatchError eType expected return $ setType expected e' | Class definition for didactic purposes . This AST represents the following class , which is named @C@ , contains an immutable field @f@ of type @Foo@ : > f : testClass1 = ClassDef {cname = "C" ,fields = [FieldDef {fmod = Val, fname = "f", ftype = ClassType "Foo"}] ,methods = []} This program is the AST equivalent of the following syntax : testClass2 = ClassDef {cname = "D" ,fields = [FieldDef {fmod = Val, fname = "g", ftype = ClassType "Bar"}] ,methods = [MethodDef {mname = "m", mparams = [], mtype = IntType, mbody = VarAccess Nothing "x"}]} testProgram = Program $ [testClass1, testClass2] testSuite = do putStrLn $ "\n************************************************" putStrLn $ "5. Multiple errors.\n" ++ "Showing a program with 3 errors:\n" ++ "- type checker catches multiple error\n" ++ "- there is support for backtrace\n" putStrLn "Output:" putStrLn "" putStrLn $ show $ fromLeft undefined (tcProgram testProgram) putStrLn "" putStrLn $ "************************************************"
09187971269e49c12dbf0a660f19c765b7ef569424e2f2adee456f579d5032a2
crategus/cl-cffi-gtk
atdoc.lisp
;;; ---------------------------------------------------------------------------- ;;; atdoc.lisp ;;; ;;; Functions for generating the documentation for GTK+. ;;; ;;; The documentation of this file has been copied from the GLib 2.32.3 Reference Manual . See . ;;; Copyright ( C ) 2012 ;;; ;;; This program is free software: you can redistribute it and/or modify ;;; it under the terms of the GNU Lesser General Public License for Lisp as published by the Free Software Foundation , either version 3 of the ;;; License, or (at your option) any later version and with a preamble to the GNU Lesser General Public License that clarifies the terms for use ;;; with Lisp programs and is referred as the LLGPL. ;;; ;;; This program is distributed in the hope that it will be useful, ;;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details . ;;; You should have received a copy of the GNU Lesser General Public License along with this program and the preamble to the Gnu Lesser ;;; General Public License. If not, see </> ;;; and <>. ;;; ---------------------------------------------------------------------------- (push :cl-cffi-gtk-documentation *features*) (asdf:load-system :atdoc) (asdf:load-system :cl-cffi-gtk) (defpackage :atdoc-gtk (:use :gtk :common-lisp) (:export #:generate-html #:generate-html-single-page #:generate-latex #:generate-info)) (in-package :atdoc-gtk) (defun generate-html () (let* ((base (asdf:component-pathname (asdf:find-system :cl-cffi-gtk))) (output-directory (merge-pathnames "atdoc/" base))) (ensure-directories-exist output-directory) (atdoc:generate-html-documentation '(:gtk) output-directory :author "Crategus" :author-url "" :index-title "cl-cffi-gtk API documentation" :heading "cl-cffi-gtk" :css "crategus.css" :logo nil :single-page-p nil :include-slot-definitions-p t :include-internal-symbols-p nil))) (defun generate-html-single-page () (let* ((base (asdf:component-pathname (asdf:find-system :cl-cffi-gtk))) (output-directory (merge-pathnames "atdoc/single-page/" base))) (ensure-directories-exist output-directory) (atdoc:generate-html-documentation '(:gtk) output-directory :author "Crategus" :author-url "" :index-title "cl-cffi-gtk API documentation" :heading "cl-cffi-gtk" :css "crategus.css" :logo nil :single-page-p t :include-slot-definitions-p t :include-internal-symbols-p nil))) (generate-html) ;(generate-html-single-page) ;;; --- End of file atdoc.lisp -------------------------------------------------
null
https://raw.githubusercontent.com/crategus/cl-cffi-gtk/22156e3e2356f71a67231d9868abcab3582356f3/gtk/atdoc/atdoc.lisp
lisp
---------------------------------------------------------------------------- atdoc.lisp Functions for generating the documentation for GTK+. The documentation of this file has been copied from the This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License for Lisp License, or (at your option) any later version and with a preamble to with Lisp programs and is referred as the LLGPL. 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 General Public License. If not, see </> and <>. ---------------------------------------------------------------------------- (generate-html-single-page) --- End of file atdoc.lisp -------------------------------------------------
GLib 2.32.3 Reference Manual . See . Copyright ( C ) 2012 as published by the Free Software Foundation , either version 3 of the the GNU Lesser General Public License that clarifies the terms for use GNU Lesser General Public License for more details . You should have received a copy of the GNU Lesser General Public License along with this program and the preamble to the Gnu Lesser (push :cl-cffi-gtk-documentation *features*) (asdf:load-system :atdoc) (asdf:load-system :cl-cffi-gtk) (defpackage :atdoc-gtk (:use :gtk :common-lisp) (:export #:generate-html #:generate-html-single-page #:generate-latex #:generate-info)) (in-package :atdoc-gtk) (defun generate-html () (let* ((base (asdf:component-pathname (asdf:find-system :cl-cffi-gtk))) (output-directory (merge-pathnames "atdoc/" base))) (ensure-directories-exist output-directory) (atdoc:generate-html-documentation '(:gtk) output-directory :author "Crategus" :author-url "" :index-title "cl-cffi-gtk API documentation" :heading "cl-cffi-gtk" :css "crategus.css" :logo nil :single-page-p nil :include-slot-definitions-p t :include-internal-symbols-p nil))) (defun generate-html-single-page () (let* ((base (asdf:component-pathname (asdf:find-system :cl-cffi-gtk))) (output-directory (merge-pathnames "atdoc/single-page/" base))) (ensure-directories-exist output-directory) (atdoc:generate-html-documentation '(:gtk) output-directory :author "Crategus" :author-url "" :index-title "cl-cffi-gtk API documentation" :heading "cl-cffi-gtk" :css "crategus.css" :logo nil :single-page-p t :include-slot-definitions-p t :include-internal-symbols-p nil))) (generate-html)
eef428559eac130b6cc4be1121fad9a92d1e02aefc0f9c83c36ba0e098c8b385
jrwdunham/tegere
runner.clj
(ns tegere.fiddle.runner "Fiddle file for playing around with runner.clj." (:require [tegere.runner :as r] [tegere.parser :as p] [tegere.fiddle.grammar :refer [chimpanzee-feature]])) (defn update-step-rets "Convenience fiddle function that appends val to the :step-rets key of the map context, while ensuring that the val of :step-rets is a vec." [context val] (update-in context [:step-rets] (fn [step-rets] (if (seq step-rets) (conj step-rets val) [val])))) A fake registry of step functions to test our Chimpanzee Feature (def fake-registry {:given {"a chimpanzee" (fn [context] (update-step-rets context :a-chimpanzee))} :when {"I give him a banana" (fn [context] (update-step-rets context :give-banana)) "I give him a pear" (fn [context] (update-step-rets context :give-pear))} :then {"he doesn't eat it" (fn [context] (update-step-rets context :not-eat)) "he is happy" (fn [context] (update-step-rets context (/ 1 0))) "he is sad" (fn [context] (update-step-rets context :is-sad)) "he looks at me loathingly" (fn [context] (update-step-rets context :looks-loathingly)) "he looks at me quizzically" (fn [context] (update-step-rets context :looks-quizzically))}}) (defn for-repl "Call this in a REPL to see how printing to stdout works." [& {:keys [stop?] :or {stop? false}}] (let [features [(p/parse chimpanzee-feature) (p/parse chimpanzee-feature)] config {:tags {:and-tags #{"chimpanzees" "fruit-reactions"}} :stop stop?} fake-registry {:given {"a chimpanzee" (fn [context] (update-step-rets context :a-chimpanzee))} :when {"I give him a banana" (fn [context] (update-step-rets context :give-banana)) "I give him a pear" (fn [context] (update-step-rets context :give-pear))} :then {"he doesn't eat it" (fn [_] (assert (= :not-eat true) "He DOES eat it you fool!")) "he is happy" (fn [context] (update-step-rets context (/ 1 0))) "he is sad" (fn [context] (update-step-rets context :is-sad)) "he looks at me loathingly" (fn [context] (update-step-rets context :looks-loathingly)) "he looks at me quizzically" (fn [context] (update-step-rets context :looks-quizzically))}}] (r/run features fake-registry config))) ;; Fake seq of scenario executions (def fake-run-outcome [{:steps [{:type :given :text "a chimpanzee" ::r/fn nil :execution {:start-time #inst "2019-07-28T15:42:19.389-00:00" :end-time #inst "2019-07-28T15:42:19.389-00:00" :ctx-after-exec {:step-rets [:a-chimpanzee]} :err nil}} {:type :when :text "I give him a banana" ::r/fn nil :execution {:start-time #inst "2019-07-28T15:42:19.390-00:00" :end-time #inst "2019-07-28T15:42:19.390-00:00" :ctx-after-exec {:step-rets [:a-chimpanzee :give-with-var-banana]} :err nil}} {:type :then :text "he is happy" ::r/fn nil :execution {:start-time #inst "2019-07-28T15:42:19.390-00:00" :end-time #inst "2019-07-28T15:42:19.391-00:00" :ctx-after-exec nil :err {:type :error :message "Divide by zero" :stack-trace (list "clojure.lang.Numbers.divide(Numbers.java:163)" "clojure.lang.Numbers.divide(Numbers.java:3833)" "tegere.runner_fiddle$eval17086$fn__17093.invoke(form-init5595963778114898981.clj:96)" "clojure.core$partial$fn__5561.invoke(core.clj:2615)" "clojure.lang.AFn.applyToHelper(AFn.java:152)" "clojure.lang.RestFn.applyTo(RestFn.java:132)" "clojure.core$apply.invokeStatic(core.clj:657)" "clojure.core$apply.invoke(core.clj:652)" "tegere.runner$get_step_fn$fn__16239$fn__16243.invoke(runner.clj:107)" "tegere.runner$call_step_fn.invokeStatic(runner.clj:193)" "tegere.runner$call_step_fn.invoke(runner.clj:187)" "tegere.runner$execute_step.invokeStatic(runner.clj:208)" "tegere.runner$execute_step.invoke(runner.clj:199)" "tegere.runner$execute_steps.invokeStatic(runner.clj:224)" "tegere.runner$execute_steps.invoke(runner.clj:220)" "tegere.runner$execute_steps.invokeStatic(runner.clj:227)" "tegere.runner$execute_steps.invoke(runner.clj:220)" "tegere.runner$execute_steps.invokeStatic(runner.clj:227)" "tegere.runner$execute_steps.invoke(runner.clj:220)" "tegere.runner$execute_steps_map.invokeStatic(runner.clj:235)" "tegere.runner$execute_steps_map.invoke(runner.clj:230)" "tegere.runner$execute_steps_map_seq.invokeStatic(runner.clj:268)" "tegere.runner$execute_steps_map_seq.invoke(runner.clj:261)" "clojure.core$partial$fn__5565.invoke(core.clj:2630)" "tegere.runner$execute.invokeStatic(runner.clj:288)" "tegere.runner$execute.invoke(runner.clj:277)" "clojure.core$partial$fn__5563.invoke(core.clj:2623)" "tegere.utils$bind.invokeStatic(utils.clj:9)" "tegere.utils$bind.invoke(utils.clj:4)" "tegere.runner$run.invokeStatic(runner.clj:435)" "tegere.runner$run.doInvoke(runner.clj:430)" "clojure.lang.RestFn.invoke(RestFn.java:445)" "tegere.runner_fiddle$eval17086.invokeStatic(form-init5595963778114898981.clj:102)" "tegere.runner_fiddle$eval17086.invoke(form-init5595963778114898981.clj:86)" "clojure.lang.Compiler.eval(Compiler.java:7062)" "clojure.lang.Compiler.eval(Compiler.java:7025)" "clojure.core$eval.invokeStatic(core.clj:3206)" "clojure.core$eval.invoke(core.clj:3202)" "clojure.main$repl$read_eval_print__8572$fn__8575.invoke(main.clj:243)" "clojure.main$repl$read_eval_print__8572.invoke(main.clj:243)" "clojure.main$repl$fn__8581.invoke(main.clj:261)" "clojure.main$repl.invokeStatic(main.clj:261)" "clojure.main$repl.doInvoke(main.clj:177)" "clojure.lang.RestFn.applyTo(RestFn.java:137)" "clojure.core$apply.invokeStatic(core.clj:657)" "clojure.core$apply.invoke(core.clj:652)" "refactor_nrepl.ns.slam.hound.regrow$wrap_clojure_repl$fn__12537.doInvoke(regrow.clj:18)" "clojure.lang.RestFn.invoke(RestFn.java:1523)" "nrepl.middleware.interruptible_eval$evaluate$fn__3175.invoke(interruptible_eval.clj:83)" "clojure.lang.AFn.applyToHelper(AFn.java:152)" "clojure.lang.AFn.applyTo(AFn.java:144)" "clojure.core$apply.invokeStatic(core.clj:657)" "clojure.core$with_bindings_STAR_.invokeStatic(core.clj:1965)" "clojure.core$with_bindings_STAR_.doInvoke(core.clj:1965)" "clojure.lang.RestFn.invoke(RestFn.java:425)" "nrepl.middleware.interruptible_eval$evaluate.invokeStatic(interruptible_eval.clj:81)" "nrepl.middleware.interruptible_eval$evaluate.invoke(interruptible_eval.clj:50)" "nrepl.middleware.interruptible_eval$interruptible_eval$fn__3218$fn__3221.invoke(interruptible_eval.clj:221)" "nrepl.middleware.interruptible_eval$run_next$fn__3213.invoke(interruptible_eval.clj:189)" "clojure.lang.AFn.run(AFn.java:22)" "java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)" "java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)" "java.lang.Thread.run(Thread.java:745)")}}} {:type :then :text "he doesn't eat it" :original-type :but ::r/fn nil :execution nil} {:type :then :text "he looks at me quizzically" :original-type :and ::r/fn nil :execution nil}] :feature {:name "Chimpanzees behave as expected" :description "Experimenters want to ensure that their chimpanzee simulations are behaving correctly." :tags (list "chimpanzees")} :scenario {:description "Chimpanzees behave as expected when offered various foods." :tags (list "fruit-reactions")}} {:steps [{:type :given :text "a chimpanzee" ::r/fn nil :execution {:start-time #inst "2019-07-28T15:42:19.392-00:00" :end-time #inst "2019-07-28T15:42:19.392-00:00" :ctx-after-exec {:step-rets [:a-chimpanzee]} :err nil}} {:type :when :text "I give him a pear" ::r/fn nil :execution {:start-time #inst "2019-07-28T15:42:19.392-00:00" :end-time #inst "2019-07-28T15:42:19.392-00:00" :ctx-after-exec {:step-rets [:a-chimpanzee :give-with-var-pear]} :err nil}} {:type :then :text "he is sad" ::r/fn nil :execution {:start-time #inst "2019-07-28T15:42:19.392-00:00" :end-time #inst "2019-07-28T15:42:19.392-00:00" :ctx-after-exec {:step-rets [:a-chimpanzee :give-with-var-pear :is-sad]} :err nil}} {:type :then :text "he doesn't eat it" :original-type :but ::r/fn nil :execution {:start-time #inst "2019-07-28T15:42:19.392-00:00" :end-time #inst "2019-07-28T15:42:19.392-00:00" :ctx-after-exec {:step-rets [:a-chimpanzee :give-with-var-pear :is-sad :not-eat]} :err nil}} {:type :then :text "he looks at me loathingly" :original-type :and ::r/fn nil :execution {:start-time #inst "2019-07-28T15:42:19.393-00:00" :end-time #inst "2019-07-28T15:42:19.393-00:00" :ctx-after-exec {:step-rets [:a-chimpanzee :give-with-var-pear :is-sad :not-eat :looks-loathingly]} :err nil}}] :feature {:name "Chimpanzees behave as expected" :description "Experimenters want to ensure that their chimpanzee simulations are behaving correctly." :tags (list "chimpanzees")} :scenario {:description "Chimpanzees behave as expected when offered various foods." :tags (list "fruit-reactions")}} {:steps [{:type :given :text "a chimpanzee" ::r/fn nil :execution {:start-time #inst "2019-07-28T15:42:19.393-00:00" :end-time #inst "2019-07-28T15:42:19.393-00:00" :ctx-after-exec {:step-rets [:a-chimpanzee]} :err nil}} {:type :when :text "I give him a banana" ::r/fn nil :execution {:start-time #inst "2019-07-28T15:42:19.394-00:00" :end-time #inst "2019-07-28T15:42:19.394-00:00" :ctx-after-exec {:step-rets [:a-chimpanzee :give-with-var-banana]} :err nil}} {:type :then :text "he is happy" ::r/fn nil :execution {:start-time #inst "2019-07-28T15:42:19.394-00:00" :end-time #inst "2019-07-28T15:42:19.394-00:00" :ctx-after-exec nil :err {:type :error :message "Divide by zero" :stack-trace (list "clojure.lang.Numbers.divide(Numbers.java:163)" "clojure.lang.Numbers.divide(Numbers.java:3833)" "tegere.runner_fiddle$eval17086$fn__17093.invoke(form-init5595963778114898981.clj:96)" "clojure.core$partial$fn__5561.invoke(core.clj:2615)" "clojure.lang.AFn.applyToHelper(AFn.java:152)" "clojure.lang.RestFn.applyTo(RestFn.java:132)" "clojure.core$apply.invokeStatic(core.clj:657)" "clojure.core$apply.invoke(core.clj:652)" "tegere.runner$get_step_fn$fn__16239$fn__16243.invoke(runner.clj:107)" "tegere.runner$call_step_fn.invokeStatic(runner.clj:193)" "tegere.runner$call_step_fn.invoke(runner.clj:187)" "tegere.runner$execute_step.invokeStatic(runner.clj:208)" "tegere.runner$execute_step.invoke(runner.clj:199)" "tegere.runner$execute_steps.invokeStatic(runner.clj:224)" "tegere.runner$execute_steps.invoke(runner.clj:220)" "tegere.runner$execute_steps.invokeStatic(runner.clj:227)" "tegere.runner$execute_steps.invoke(runner.clj:220)" "tegere.runner$execute_steps.invokeStatic(runner.clj:227)" "tegere.runner$execute_steps.invoke(runner.clj:220)" "tegere.runner$execute_steps_map.invokeStatic(runner.clj:235)" "tegere.runner$execute_steps_map.invoke(runner.clj:230)" "tegere.runner$execute_steps_map_seq.invokeStatic(runner.clj:268)" "tegere.runner$execute_steps_map_seq.invoke(runner.clj:261)" "tegere.runner$execute_steps_map_seq.invokeStatic(runner.clj:273)" "tegere.runner$execute_steps_map_seq.invoke(runner.clj:261)" "tegere.runner$execute_steps_map_seq.invokeStatic(runner.clj:273)" "tegere.runner$execute_steps_map_seq.invoke(runner.clj:261)" "clojure.core$partial$fn__5565.invoke(core.clj:2630)" "tegere.runner$execute.invokeStatic(runner.clj:288)" "tegere.runner$execute.invoke(runner.clj:277)" "clojure.core$partial$fn__5563.invoke(core.clj:2623)" "tegere.utils$bind.invokeStatic(utils.clj:9)" "tegere.utils$bind.invoke(utils.clj:4)" "tegere.runner$run.invokeStatic(runner.clj:435)" "tegere.runner$run.doInvoke(runner.clj:430)" "clojure.lang.RestFn.invoke(RestFn.java:445)" "tegere.runner_fiddle$eval17086.invokeStatic(form-init5595963778114898981.clj:102)" "tegere.runner_fiddle$eval17086.invoke(form-init5595963778114898981.clj:86)" "clojure.lang.Compiler.eval(Compiler.java:7062)" "clojure.lang.Compiler.eval(Compiler.java:7025)" "clojure.core$eval.invokeStatic(core.clj:3206)" "clojure.core$eval.invoke(core.clj:3202)" "clojure.main$repl$read_eval_print__8572$fn__8575.invoke(main.clj:243)" "clojure.main$repl$read_eval_print__8572.invoke(main.clj:243)" "clojure.main$repl$fn__8581.invoke(main.clj:261)" "clojure.main$repl.invokeStatic(main.clj:261)" "clojure.main$repl.doInvoke(main.clj:177)" "clojure.lang.RestFn.applyTo(RestFn.java:137)" "clojure.core$apply.invokeStatic(core.clj:657)" "clojure.core$apply.invoke(core.clj:652)" "refactor_nrepl.ns.slam.hound.regrow$wrap_clojure_repl$fn__12537.doInvoke(regrow.clj:18)" "clojure.lang.RestFn.invoke(RestFn.java:1523)" "nrepl.middleware.interruptible_eval$evaluate$fn__3175.invoke(interruptible_eval.clj:83)" "clojure.lang.AFn.applyToHelper(AFn.java:152)" "clojure.lang.AFn.applyTo(AFn.java:144)" "clojure.core$apply.invokeStatic(core.clj:657)" "clojure.core$with_bindings_STAR_.invokeStatic(core.clj:1965)" "clojure.core$with_bindings_STAR_.doInvoke(core.clj:1965)" "clojure.lang.RestFn.invoke(RestFn.java:425)" "nrepl.middleware.interruptible_eval$evaluate.invokeStatic(interruptible_eval.clj:81)" "nrepl.middleware.interruptible_eval$evaluate.invoke(interruptible_eval.clj:50)" "nrepl.middleware.interruptible_eval$interruptible_eval$fn__3218$fn__3221.invoke(interruptible_eval.clj:221)" "nrepl.middleware.interruptible_eval$run_next$fn__3213.invoke(interruptible_eval.clj:189)" "clojure.lang.AFn.run(AFn.java:22)" "java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)" "java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)" "java.lang.Thread.run(Thread.java:745)")}}} {:type :then :text "he doesn't eat it" :original-type :but ::r/fn nil :execution nil} {:type :then :text "he looks at me quizzically" :original-type :and ::r/fn nil :execution nil}] :feature {:name "Chimpanzees behave as expected" :description "Experimenters want to ensure that their chimpanzee simulations are behaving correctly." :tags (list "chimpanzees")} :scenario {:description "Chimpanzees behave as expected when offered various foods." :tags (list "fruit-reactions")}} {:steps [{:type :given :text "a chimpanzee" ::r/fn nil :execution {:start-time #inst "2019-07-28T15:42:19.394-00:00" :end-time #inst "2019-07-28T15:42:19.394-00:00" :ctx-after-exec {:step-rets [:a-chimpanzee]} :err nil}} {:type :when :text "I give him a pear" ::r/fn nil :execution {:start-time #inst "2019-07-28T15:42:19.394-00:00" :end-time #inst "2019-07-28T15:42:19.394-00:00" :ctx-after-exec {:step-rets [:a-chimpanzee :give-with-var-pear]} :err nil}} {:type :then :text "he is sad" ::r/fn nil :execution {:start-time #inst "2019-07-28T15:42:19.395-00:00" :end-time #inst "2019-07-28T15:42:19.395-00:00" :ctx-after-exec {:step-rets [:a-chimpanzee :give-with-var-pear :is-sad]} :err nil}} {:type :then :text "he doesn't eat it" :original-type :but ::r/fn nil :execution {:start-time #inst "2019-07-28T15:42:19.395-00:00" :end-time #inst "2019-07-28T15:42:19.395-00:00" :ctx-after-exec {:step-rets [:a-chimpanzee :give-with-var-pear :is-sad :not-eat]} :err nil}} {:type :then :text "he looks at me loathingly" :original-type :and ::r/fn nil :execution {:start-time #inst "2019-07-28T15:42:19.395-00:00" :end-time #inst "2019-07-28T15:42:19.395-00:00" :ctx-after-exec {:step-rets [:a-chimpanzee :give-with-var-pear :is-sad :not-eat :looks-loathingly]} :err nil}}] :feature {:name "Chimpanzees behave as expected" :description "Experimenters want to ensure that their chimpanzee simulations are behaving correctly." :tags (list "chimpanzees")} :scenario {:description "Chimpanzees behave as expected when offered various foods." :tags (list "fruit-reactions")}}]) (def other-fake-run-outcome [{:steps [{:type :when :text "a well-formed request is made to update the chimpanzee-integrated liquidity for space 3170 of pork 651 owned by company 13" ::r/fn nil :execution {:start-time #inst "2019-07-28T16:09:24.804-00:00" :end-time #inst "2019-07-28T16:09:26.200-00:00" :ctx-after-exec {:update-chimpanzee-liquidity-resp [{:status "success" :updated-at "2019-07-28T12:09:25.943674"} nil]} :err nil}} {:type :then :text "a successful response is received" ::r/fn nil :execution {:start-time #inst "2019-07-28T16:09:26.201-00:00" :end-time #inst "2019-07-28T16:09:26.201-00:00" :ctx-after-exec {:step-return-value nil} :err nil}}] :feature {:name "the porkcase chimpanzee integration liquidity endpoint works" :description "porkcase wants to ensure that requests to the chimpanzee integration liquidity endpoint are handled correctly." :tags (list "chimpanzee" "liquidity")} :scenario {:description "Well-formed update requests to the chimpanzee liquidity endpoint are handled correctly." :tags (list "update")}}]) Like runner_test::fake - run - outcome-3 but split across two scenarios in one feature . (def fake-run-outcome-3 [{:steps ;; pass, pass, error, untested, untested [{:type :given :text "a chimpanzee" ::r/fn nil :execution {:start-time #inst "2019-07-28T15:42:19.389-00:00" :end-time #inst "2019-07-28T15:42:19.389-00:00" :ctx-after-exec {:step-rets [:a-chimpanzee]} :err nil}} {:type :when :text "I give him a banana" ::r/fn nil :execution {:start-time #inst "2019-07-28T15:42:19.390-00:00" :end-time #inst "2019-07-28T15:42:19.390-00:00" :ctx-after-exec {:step-rets [:a-chimpanzee :give-with-var-banana]} :err nil}} {:type :then :text "he is happy" ::r/fn nil :execution {:start-time #inst "2019-07-28T15:42:19.390-00:00" :end-time #inst "2019-07-28T15:42:19.391-00:00" :ctx-after-exec nil :err {:type :error :message "Divide by zero" :stack-trace (list "clojure.lang.Numbers.divide(Numbers.java:163)" "java.lang.Thread.run(Thread.java:745)")}}} {:type :then :text "he doesn't eat it" :original-type :but ::r/fn nil :execution nil} {:type :then :text "he looks at me quizzically" :original-type :and ::r/fn nil :execution nil}] :feature {:name "Chimpanzees behave as expected" :description "Experimenters want to ensure that their chimpanzee simulations are behaving correctly." :tags (list "chimpanzees")} :scenario {:description "A" :tags (list "a")}} {:steps ;; pass, pass, pass, pass, pass [{:type :given :text "a chimpanzee" ::r/fn nil :execution {:start-time #inst "2019-07-28T15:42:19.392-00:00" :end-time #inst "2019-07-28T15:42:19.392-00:00" :ctx-after-exec {:step-rets [:a-chimpanzee]} :err nil}} {:type :when :text "I give him a pear" ::r/fn nil :execution {:start-time #inst "2019-07-28T15:42:19.392-00:00" :end-time #inst "2019-07-28T15:42:19.392-00:00" :ctx-after-exec {:step-rets [:a-chimpanzee :give-with-var-pear]} :err nil}} {:type :then :text "he is sad" ::r/fn nil :execution {:start-time #inst "2019-07-28T15:42:19.392-00:00" :end-time #inst "2019-07-28T15:42:19.392-00:00" :ctx-after-exec {:step-rets [:a-chimpanzee :give-with-var-pear :is-sad]} :err nil}} {:type :then :text "he doesn't eat it" :original-type :but ::r/fn nil :execution {:start-time #inst "2019-07-28T15:42:19.392-00:00" :end-time #inst "2019-07-28T15:42:19.392-00:00" :ctx-after-exec {:step-rets [:a-chimpanzee :give-with-var-pear :is-sad :not-eat]} :err nil}} {:type :then :text "he looks at me loathingly" :original-type :and ::r/fn nil :execution {:start-time #inst "2019-07-28T15:42:19.393-00:00" :end-time #inst "2019-07-28T15:42:19.393-00:00" :ctx-after-exec {:step-rets [:a-chimpanzee :give-with-var-pear :is-sad :not-eat :looks-loathingly]} :err nil}}] :feature {:name "Chimpanzees behave as expected" :description "Experimenters want to ensure that their chimpanzee simulations are behaving correctly." :tags (list "chimpanzees")} :scenario {:description "A" :tags (list "a")}} {:steps ;; pass, pass, error, untested, untested [{:type :given :text "a chimpanzee" ::r/fn nil :execution {:start-time #inst "2019-07-28T15:42:19.393-00:00" :end-time #inst "2019-07-28T15:42:19.393-00:00" :ctx-after-exec {:step-rets [:a-chimpanzee]} :err nil}} {:type :when :text "I give him a banana" ::r/fn nil :execution {:start-time #inst "2019-07-28T15:42:19.394-00:00" :end-time #inst "2019-07-28T15:42:19.394-00:00" :ctx-after-exec {:step-rets [:a-chimpanzee :give-with-var-banana]} :err nil}} {:type :then :text "he is happy" ::r/fn nil :execution {:start-time #inst "2019-07-28T15:42:19.394-00:00" :end-time #inst "2019-07-28T15:42:19.394-00:00" :ctx-after-exec nil :err {:type :error :message "Divide by zero" :stack-trace (list "clojure.lang.Numbers.divide(Numbers.java:163)" "java.lang.Thread.run(Thread.java:745)")}}} {:type :then :text "he doesn't eat it" :original-type :but ::r/fn nil :execution nil} {:type :then :text "he looks at me quizzically" :original-type :and ::r/fn nil :execution nil}] :feature {:name "Chimpanzees behave as expected" :description "Experimenters want to ensure that their chimpanzee simulations are behaving correctly." :tags (list "chimpanzees")} :scenario {:description "B" :tags (list "b")}} {:steps ;; pass, pass, pass, pass, pass [{:type :given :text "a chimpanzee" ::r/fn nil :execution {:start-time #inst "2019-07-28T15:42:19.394-00:00" :end-time #inst "2019-07-28T15:42:19.394-00:00" :ctx-after-exec {:step-rets [:a-chimpanzee]} :err nil}} {:type :when :text "I give him a pear" ::r/fn nil :execution {:start-time #inst "2019-07-28T15:42:19.394-00:00" :end-time #inst "2019-07-28T15:42:19.394-00:00" :ctx-after-exec {:step-rets [:a-chimpanzee :give-with-var-pear]} :err nil}} {:type :then :text "he is sad" ::r/fn nil :execution {:start-time #inst "2019-07-28T15:42:19.395-00:00" :end-time #inst "2019-07-28T15:42:19.395-00:00" :ctx-after-exec {:step-rets [:a-chimpanzee :give-with-var-pear :is-sad]} :err nil}} {:type :then :text "he doesn't eat it" :original-type :but ::r/fn nil :execution {:start-time #inst "2019-07-28T15:42:19.395-00:00" :end-time #inst "2019-07-28T15:42:19.395-00:00" :ctx-after-exec {:step-rets [:a-chimpanzee :give-with-var-pear :is-sad :not-eat]} :err nil}} {:type :then :text "he looks at me loathingly" :original-type :and ::r/fn nil :execution {:start-time #inst "2019-07-28T15:42:19.395-00:00" :end-time #inst "2019-07-28T15:42:19.395-00:00" :ctx-after-exec {:step-rets [:a-chimpanzee :give-with-var-pear :is-sad :not-eat :looks-loathingly]} :err nil}}] :feature {:name "Chimpanzees behave as expected" :description "Experimenters want to ensure that their chimpanzee simulations are behaving correctly." :tags (list "chimpanzees")} :scenario {:description "B" :tags (list "b")}}]) (def minimal-run-outcome [{:steps ;; pass, pass, error, untested, untested [{:execution {:err nil}} {:execution {:err nil}} {:execution {:err {:type :error}}} {:execution nil} {:execution nil}] :feature "f-a" :scenario "s-a"} ]) (comment ((juxt :feature :scenario :outcome) (first other-fake-run-outcome)) (->> other-fake-run-outcome first r/analyze-step-execution ((juxt :feature :scenario :outcome))) (->> other-fake-run-outcome r/executions->outcome-map r/outcome-map->outcome-summary-map) (->> fake-run-outcome-3 r/executions->outcome-map r/outcome-map->outcome-summary-map) (let [scenarios {{:description "A" :tags (list "a")} {:step-pass-count 7 :step-untested-count 2 :step-fail-count 1 :execution-pass-count 1 :execution-fail-count 1} {:description "B" :tags (list "b")} {:step-pass-count 7 :step-untested-count 2 :step-fail-count 1 :execution-pass-count 1 :execution-fail-count 1}}] (apply (partial merge-with + {:passed 0 :failed 0}) (->> scenarios vals (map (fn [scen-val] (println "scen-val") (println scen-val) (reduce (fn [agg [k v]] (let [new-k (if (some #{k} [:error :fail]) :failed :passed)] (merge-with + agg {new-k v}))) {:passed 0 :failed 0} scen-val)))))) (let [scenarios {{:description "A" :tags (list "a")} {:step-pass-count 7 :step-untested-count 2 :step-fail-count 1 :execution-pass-count 1 :execution-fail-count 1} {:description "B" :tags (list "b")} {:step-pass-count 7 :step-untested-count 2 :step-fail-count 1 :execution-pass-count 1 :execution-fail-count 1}}] (apply merge-with + (vals scenarios))) (let [scenarios {{:description "A" :tags (list "a")} {:step-pass-count 7 :step-untested-count 2 :step-fail-count 1 :execution-pass-count 1 :execution-fail-count 1} {:description "B" :tags (list "b")} {:step-pass-count 7 :step-untested-count 2 :step-fail-count 1 :execution-pass-count 1 :execution-fail-count 1}}] (->> scenarios vals (map (fn [step-stats-map] (if (= 0 (:execution-fail-count step-stats-map)) {:scenario-pass-count 1 :scenario-fail-count 0} {:scenario-pass-count 0 :scenario-fail-count 1}))) (apply merge-with +))) (let [scenarios {{:description "A" :tags (list "a")} {:step-pass-count 7 :step-untested-count 2 :step-fail-count 1 :execution-pass-count 1 :execution-fail-count 1} {:description "B" :tags (list "b")} {:step-pass-count 7 :step-untested-count 2 :step-fail-count 1 :execution-pass-count 1 :execution-fail-count 1}} steps-stats (apply merge-with + (vals scenarios)) scenarios-stats (->> scenarios vals (map (fn [step-stats-map] (if (= 0 (:execution-fail-count step-stats-map)) {:scenario-pass-count 1 :scenario-fail-count 0} {:scenario-pass-count 0 :scenario-fail-count 1}))) (apply merge-with +)) feature-stats (if (= 0 (:scenario-fail-count scenarios-stats)) {:feature-pass-count 1 :feature-fail-count 0} {:feature-pass-count 0 :feature-fail-count 1})] (merge steps-stats scenarios-stats feature-stats)) (r/executions->outcome-map other-fake-run-outcome) (r/analyze-step-execution (first other-fake-run-outcome)) (r/executions->outcome-map fake-run-outcome) (r/analyze-step-execution (first fake-run-outcome)) (r/analyze-step-execution (second fake-run-outcome)) (r/analyze-step-execution (nth fake-run-outcome 2)) (r/analyze-step-execution (nth fake-run-outcome 3)) (r/get-outcome-summary minimal-run-outcome) (-> [{:steps ;; pass, pass, error, untested, untested [{:execution {:err nil}} {:execution {:err nil}} {:execution {:err {:type :error}}} {:execution nil} {:execution nil}] :feature "f-a" :scenario "s-a"} {:steps ;; pass, pass [{:execution {:err nil}} {:execution {:err nil}}] :feature "f-a" :scenario "s-a"} {:steps ;; pass, pass [{:execution {:err nil}} {:execution {:err nil}}] :feature "f-b" :scenario "s-b"}] (r/summarize-run)) (r/get-outcome-summary fake-run-outcome) (r/get-outcome-summary other-fake-run-outcome) (r/get-outcome-summary fake-run-outcome-3) (r/get-step-fn-args "I ate a {fruit-type}" "I ate a banana") (r/get-step-fn-args "I ate a banana" "I ate a pear") (r/get-step-fn-args "I ate a pear" "I ate a pear") ((r/get-step-fn fake-registry {:type :when :text "I give him a pear"}) {}) ((r/get-step-fn fake-registry {:type :when :text "I give him a banana"}) {}) ((r/get-step-fn fake-registry {:type :when :text "I give him a pear"}) {}) (let [features [(p/parse chimpanzee-feature) (p/parse chimpanzee-feature)] config {:tags {:and-tags #{"chimpanzees" "fruit-reactions"}} :stop false} fake-registry {:given {"a chimpanzee" (fn [context] (update-step-rets context :a-chimpanzee))} :when {"I give him a banana" (fn [context] (update-step-rets context :give-banana)) "I give him a pear" (fn [context] (update-step-rets context :give-pear))} :then {"he doesn't eat it" (fn [context] (update-step-rets context :not-eat)) ;"he is happy" (fn [context] (update-step-rets context :is-happy)) "he is happy" (fn [context] (update-step-rets context (/ 1 0))) "he is sad" (fn [context] (update-step-rets context :is-sad)) "he looks at me loathingly" (fn [context] (update-step-rets context :looks-loathingly)) "he looks at me quizzically" (fn [context] (update-step-rets context :looks-quizzically))}}] (r/run features fake-registry config)) (let [features [(p/parse chimpanzee-feature) (p/parse chimpanzee-feature)] config {:tags {:and-tags #{"chimpanzees" "fruit-reactions"}} :stop false} fake-registry {:given {"a chimpanzee" (fn [context] (update-step-rets context :a-chimpanzee))} :when {"I give him a {fruit}" (fn [context fruit] (update-step-rets context (keyword (format "give-with-var-%s" fruit))))} :then {"he doesn't eat it" (fn [context] (update-step-rets context :not-eat)) ;"he is happy" (fn [context] (update-step-rets context :is-happy)) "he is happy" (fn [context] (update-step-rets context (/ 1 0))) "he is sad" (fn [context] (update-step-rets context :is-sad)) "he looks at me loathingly" (fn [context] (update-step-rets context :looks-loathingly)) "he looks at me quizzically" (fn [context] (update-step-rets context :looks-quizzically))}}] (r/run features fake-registry config)) (r/get-step-fn-args "I give {recipient} a {fruit}" "I give him a big ole banana") ;; ("him" "big ole banana") (r/get-step-fn-args "I gave {recipient} a {fruit}" "I give him a big ole banana") ;; => nil (r/get-step-fn-args "I give him a big ole banana" "I give him a big ole banana") ;; => () )
null
https://raw.githubusercontent.com/jrwdunham/tegere/ee05eec87419d7d4cf91aebd2da121225bb8b3eb/src/tegere/fiddle/runner.clj
clojure
Fake seq of scenario executions pass, pass, error, untested, untested pass, pass, pass, pass, pass pass, pass, error, untested, untested pass, pass, pass, pass, pass pass, pass, error, untested, untested pass, pass, error, untested, untested pass, pass pass, pass "he is happy" (fn [context] (update-step-rets context :is-happy)) "he is happy" (fn [context] (update-step-rets context :is-happy)) ("him" "big ole banana") => nil => ()
(ns tegere.fiddle.runner "Fiddle file for playing around with runner.clj." (:require [tegere.runner :as r] [tegere.parser :as p] [tegere.fiddle.grammar :refer [chimpanzee-feature]])) (defn update-step-rets "Convenience fiddle function that appends val to the :step-rets key of the map context, while ensuring that the val of :step-rets is a vec." [context val] (update-in context [:step-rets] (fn [step-rets] (if (seq step-rets) (conj step-rets val) [val])))) A fake registry of step functions to test our Chimpanzee Feature (def fake-registry {:given {"a chimpanzee" (fn [context] (update-step-rets context :a-chimpanzee))} :when {"I give him a banana" (fn [context] (update-step-rets context :give-banana)) "I give him a pear" (fn [context] (update-step-rets context :give-pear))} :then {"he doesn't eat it" (fn [context] (update-step-rets context :not-eat)) "he is happy" (fn [context] (update-step-rets context (/ 1 0))) "he is sad" (fn [context] (update-step-rets context :is-sad)) "he looks at me loathingly" (fn [context] (update-step-rets context :looks-loathingly)) "he looks at me quizzically" (fn [context] (update-step-rets context :looks-quizzically))}}) (defn for-repl "Call this in a REPL to see how printing to stdout works." [& {:keys [stop?] :or {stop? false}}] (let [features [(p/parse chimpanzee-feature) (p/parse chimpanzee-feature)] config {:tags {:and-tags #{"chimpanzees" "fruit-reactions"}} :stop stop?} fake-registry {:given {"a chimpanzee" (fn [context] (update-step-rets context :a-chimpanzee))} :when {"I give him a banana" (fn [context] (update-step-rets context :give-banana)) "I give him a pear" (fn [context] (update-step-rets context :give-pear))} :then {"he doesn't eat it" (fn [_] (assert (= :not-eat true) "He DOES eat it you fool!")) "he is happy" (fn [context] (update-step-rets context (/ 1 0))) "he is sad" (fn [context] (update-step-rets context :is-sad)) "he looks at me loathingly" (fn [context] (update-step-rets context :looks-loathingly)) "he looks at me quizzically" (fn [context] (update-step-rets context :looks-quizzically))}}] (r/run features fake-registry config))) (def fake-run-outcome [{:steps [{:type :given :text "a chimpanzee" ::r/fn nil :execution {:start-time #inst "2019-07-28T15:42:19.389-00:00" :end-time #inst "2019-07-28T15:42:19.389-00:00" :ctx-after-exec {:step-rets [:a-chimpanzee]} :err nil}} {:type :when :text "I give him a banana" ::r/fn nil :execution {:start-time #inst "2019-07-28T15:42:19.390-00:00" :end-time #inst "2019-07-28T15:42:19.390-00:00" :ctx-after-exec {:step-rets [:a-chimpanzee :give-with-var-banana]} :err nil}} {:type :then :text "he is happy" ::r/fn nil :execution {:start-time #inst "2019-07-28T15:42:19.390-00:00" :end-time #inst "2019-07-28T15:42:19.391-00:00" :ctx-after-exec nil :err {:type :error :message "Divide by zero" :stack-trace (list "clojure.lang.Numbers.divide(Numbers.java:163)" "clojure.lang.Numbers.divide(Numbers.java:3833)" "tegere.runner_fiddle$eval17086$fn__17093.invoke(form-init5595963778114898981.clj:96)" "clojure.core$partial$fn__5561.invoke(core.clj:2615)" "clojure.lang.AFn.applyToHelper(AFn.java:152)" "clojure.lang.RestFn.applyTo(RestFn.java:132)" "clojure.core$apply.invokeStatic(core.clj:657)" "clojure.core$apply.invoke(core.clj:652)" "tegere.runner$get_step_fn$fn__16239$fn__16243.invoke(runner.clj:107)" "tegere.runner$call_step_fn.invokeStatic(runner.clj:193)" "tegere.runner$call_step_fn.invoke(runner.clj:187)" "tegere.runner$execute_step.invokeStatic(runner.clj:208)" "tegere.runner$execute_step.invoke(runner.clj:199)" "tegere.runner$execute_steps.invokeStatic(runner.clj:224)" "tegere.runner$execute_steps.invoke(runner.clj:220)" "tegere.runner$execute_steps.invokeStatic(runner.clj:227)" "tegere.runner$execute_steps.invoke(runner.clj:220)" "tegere.runner$execute_steps.invokeStatic(runner.clj:227)" "tegere.runner$execute_steps.invoke(runner.clj:220)" "tegere.runner$execute_steps_map.invokeStatic(runner.clj:235)" "tegere.runner$execute_steps_map.invoke(runner.clj:230)" "tegere.runner$execute_steps_map_seq.invokeStatic(runner.clj:268)" "tegere.runner$execute_steps_map_seq.invoke(runner.clj:261)" "clojure.core$partial$fn__5565.invoke(core.clj:2630)" "tegere.runner$execute.invokeStatic(runner.clj:288)" "tegere.runner$execute.invoke(runner.clj:277)" "clojure.core$partial$fn__5563.invoke(core.clj:2623)" "tegere.utils$bind.invokeStatic(utils.clj:9)" "tegere.utils$bind.invoke(utils.clj:4)" "tegere.runner$run.invokeStatic(runner.clj:435)" "tegere.runner$run.doInvoke(runner.clj:430)" "clojure.lang.RestFn.invoke(RestFn.java:445)" "tegere.runner_fiddle$eval17086.invokeStatic(form-init5595963778114898981.clj:102)" "tegere.runner_fiddle$eval17086.invoke(form-init5595963778114898981.clj:86)" "clojure.lang.Compiler.eval(Compiler.java:7062)" "clojure.lang.Compiler.eval(Compiler.java:7025)" "clojure.core$eval.invokeStatic(core.clj:3206)" "clojure.core$eval.invoke(core.clj:3202)" "clojure.main$repl$read_eval_print__8572$fn__8575.invoke(main.clj:243)" "clojure.main$repl$read_eval_print__8572.invoke(main.clj:243)" "clojure.main$repl$fn__8581.invoke(main.clj:261)" "clojure.main$repl.invokeStatic(main.clj:261)" "clojure.main$repl.doInvoke(main.clj:177)" "clojure.lang.RestFn.applyTo(RestFn.java:137)" "clojure.core$apply.invokeStatic(core.clj:657)" "clojure.core$apply.invoke(core.clj:652)" "refactor_nrepl.ns.slam.hound.regrow$wrap_clojure_repl$fn__12537.doInvoke(regrow.clj:18)" "clojure.lang.RestFn.invoke(RestFn.java:1523)" "nrepl.middleware.interruptible_eval$evaluate$fn__3175.invoke(interruptible_eval.clj:83)" "clojure.lang.AFn.applyToHelper(AFn.java:152)" "clojure.lang.AFn.applyTo(AFn.java:144)" "clojure.core$apply.invokeStatic(core.clj:657)" "clojure.core$with_bindings_STAR_.invokeStatic(core.clj:1965)" "clojure.core$with_bindings_STAR_.doInvoke(core.clj:1965)" "clojure.lang.RestFn.invoke(RestFn.java:425)" "nrepl.middleware.interruptible_eval$evaluate.invokeStatic(interruptible_eval.clj:81)" "nrepl.middleware.interruptible_eval$evaluate.invoke(interruptible_eval.clj:50)" "nrepl.middleware.interruptible_eval$interruptible_eval$fn__3218$fn__3221.invoke(interruptible_eval.clj:221)" "nrepl.middleware.interruptible_eval$run_next$fn__3213.invoke(interruptible_eval.clj:189)" "clojure.lang.AFn.run(AFn.java:22)" "java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)" "java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)" "java.lang.Thread.run(Thread.java:745)")}}} {:type :then :text "he doesn't eat it" :original-type :but ::r/fn nil :execution nil} {:type :then :text "he looks at me quizzically" :original-type :and ::r/fn nil :execution nil}] :feature {:name "Chimpanzees behave as expected" :description "Experimenters want to ensure that their chimpanzee simulations are behaving correctly." :tags (list "chimpanzees")} :scenario {:description "Chimpanzees behave as expected when offered various foods." :tags (list "fruit-reactions")}} {:steps [{:type :given :text "a chimpanzee" ::r/fn nil :execution {:start-time #inst "2019-07-28T15:42:19.392-00:00" :end-time #inst "2019-07-28T15:42:19.392-00:00" :ctx-after-exec {:step-rets [:a-chimpanzee]} :err nil}} {:type :when :text "I give him a pear" ::r/fn nil :execution {:start-time #inst "2019-07-28T15:42:19.392-00:00" :end-time #inst "2019-07-28T15:42:19.392-00:00" :ctx-after-exec {:step-rets [:a-chimpanzee :give-with-var-pear]} :err nil}} {:type :then :text "he is sad" ::r/fn nil :execution {:start-time #inst "2019-07-28T15:42:19.392-00:00" :end-time #inst "2019-07-28T15:42:19.392-00:00" :ctx-after-exec {:step-rets [:a-chimpanzee :give-with-var-pear :is-sad]} :err nil}} {:type :then :text "he doesn't eat it" :original-type :but ::r/fn nil :execution {:start-time #inst "2019-07-28T15:42:19.392-00:00" :end-time #inst "2019-07-28T15:42:19.392-00:00" :ctx-after-exec {:step-rets [:a-chimpanzee :give-with-var-pear :is-sad :not-eat]} :err nil}} {:type :then :text "he looks at me loathingly" :original-type :and ::r/fn nil :execution {:start-time #inst "2019-07-28T15:42:19.393-00:00" :end-time #inst "2019-07-28T15:42:19.393-00:00" :ctx-after-exec {:step-rets [:a-chimpanzee :give-with-var-pear :is-sad :not-eat :looks-loathingly]} :err nil}}] :feature {:name "Chimpanzees behave as expected" :description "Experimenters want to ensure that their chimpanzee simulations are behaving correctly." :tags (list "chimpanzees")} :scenario {:description "Chimpanzees behave as expected when offered various foods." :tags (list "fruit-reactions")}} {:steps [{:type :given :text "a chimpanzee" ::r/fn nil :execution {:start-time #inst "2019-07-28T15:42:19.393-00:00" :end-time #inst "2019-07-28T15:42:19.393-00:00" :ctx-after-exec {:step-rets [:a-chimpanzee]} :err nil}} {:type :when :text "I give him a banana" ::r/fn nil :execution {:start-time #inst "2019-07-28T15:42:19.394-00:00" :end-time #inst "2019-07-28T15:42:19.394-00:00" :ctx-after-exec {:step-rets [:a-chimpanzee :give-with-var-banana]} :err nil}} {:type :then :text "he is happy" ::r/fn nil :execution {:start-time #inst "2019-07-28T15:42:19.394-00:00" :end-time #inst "2019-07-28T15:42:19.394-00:00" :ctx-after-exec nil :err {:type :error :message "Divide by zero" :stack-trace (list "clojure.lang.Numbers.divide(Numbers.java:163)" "clojure.lang.Numbers.divide(Numbers.java:3833)" "tegere.runner_fiddle$eval17086$fn__17093.invoke(form-init5595963778114898981.clj:96)" "clojure.core$partial$fn__5561.invoke(core.clj:2615)" "clojure.lang.AFn.applyToHelper(AFn.java:152)" "clojure.lang.RestFn.applyTo(RestFn.java:132)" "clojure.core$apply.invokeStatic(core.clj:657)" "clojure.core$apply.invoke(core.clj:652)" "tegere.runner$get_step_fn$fn__16239$fn__16243.invoke(runner.clj:107)" "tegere.runner$call_step_fn.invokeStatic(runner.clj:193)" "tegere.runner$call_step_fn.invoke(runner.clj:187)" "tegere.runner$execute_step.invokeStatic(runner.clj:208)" "tegere.runner$execute_step.invoke(runner.clj:199)" "tegere.runner$execute_steps.invokeStatic(runner.clj:224)" "tegere.runner$execute_steps.invoke(runner.clj:220)" "tegere.runner$execute_steps.invokeStatic(runner.clj:227)" "tegere.runner$execute_steps.invoke(runner.clj:220)" "tegere.runner$execute_steps.invokeStatic(runner.clj:227)" "tegere.runner$execute_steps.invoke(runner.clj:220)" "tegere.runner$execute_steps_map.invokeStatic(runner.clj:235)" "tegere.runner$execute_steps_map.invoke(runner.clj:230)" "tegere.runner$execute_steps_map_seq.invokeStatic(runner.clj:268)" "tegere.runner$execute_steps_map_seq.invoke(runner.clj:261)" "tegere.runner$execute_steps_map_seq.invokeStatic(runner.clj:273)" "tegere.runner$execute_steps_map_seq.invoke(runner.clj:261)" "tegere.runner$execute_steps_map_seq.invokeStatic(runner.clj:273)" "tegere.runner$execute_steps_map_seq.invoke(runner.clj:261)" "clojure.core$partial$fn__5565.invoke(core.clj:2630)" "tegere.runner$execute.invokeStatic(runner.clj:288)" "tegere.runner$execute.invoke(runner.clj:277)" "clojure.core$partial$fn__5563.invoke(core.clj:2623)" "tegere.utils$bind.invokeStatic(utils.clj:9)" "tegere.utils$bind.invoke(utils.clj:4)" "tegere.runner$run.invokeStatic(runner.clj:435)" "tegere.runner$run.doInvoke(runner.clj:430)" "clojure.lang.RestFn.invoke(RestFn.java:445)" "tegere.runner_fiddle$eval17086.invokeStatic(form-init5595963778114898981.clj:102)" "tegere.runner_fiddle$eval17086.invoke(form-init5595963778114898981.clj:86)" "clojure.lang.Compiler.eval(Compiler.java:7062)" "clojure.lang.Compiler.eval(Compiler.java:7025)" "clojure.core$eval.invokeStatic(core.clj:3206)" "clojure.core$eval.invoke(core.clj:3202)" "clojure.main$repl$read_eval_print__8572$fn__8575.invoke(main.clj:243)" "clojure.main$repl$read_eval_print__8572.invoke(main.clj:243)" "clojure.main$repl$fn__8581.invoke(main.clj:261)" "clojure.main$repl.invokeStatic(main.clj:261)" "clojure.main$repl.doInvoke(main.clj:177)" "clojure.lang.RestFn.applyTo(RestFn.java:137)" "clojure.core$apply.invokeStatic(core.clj:657)" "clojure.core$apply.invoke(core.clj:652)" "refactor_nrepl.ns.slam.hound.regrow$wrap_clojure_repl$fn__12537.doInvoke(regrow.clj:18)" "clojure.lang.RestFn.invoke(RestFn.java:1523)" "nrepl.middleware.interruptible_eval$evaluate$fn__3175.invoke(interruptible_eval.clj:83)" "clojure.lang.AFn.applyToHelper(AFn.java:152)" "clojure.lang.AFn.applyTo(AFn.java:144)" "clojure.core$apply.invokeStatic(core.clj:657)" "clojure.core$with_bindings_STAR_.invokeStatic(core.clj:1965)" "clojure.core$with_bindings_STAR_.doInvoke(core.clj:1965)" "clojure.lang.RestFn.invoke(RestFn.java:425)" "nrepl.middleware.interruptible_eval$evaluate.invokeStatic(interruptible_eval.clj:81)" "nrepl.middleware.interruptible_eval$evaluate.invoke(interruptible_eval.clj:50)" "nrepl.middleware.interruptible_eval$interruptible_eval$fn__3218$fn__3221.invoke(interruptible_eval.clj:221)" "nrepl.middleware.interruptible_eval$run_next$fn__3213.invoke(interruptible_eval.clj:189)" "clojure.lang.AFn.run(AFn.java:22)" "java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)" "java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)" "java.lang.Thread.run(Thread.java:745)")}}} {:type :then :text "he doesn't eat it" :original-type :but ::r/fn nil :execution nil} {:type :then :text "he looks at me quizzically" :original-type :and ::r/fn nil :execution nil}] :feature {:name "Chimpanzees behave as expected" :description "Experimenters want to ensure that their chimpanzee simulations are behaving correctly." :tags (list "chimpanzees")} :scenario {:description "Chimpanzees behave as expected when offered various foods." :tags (list "fruit-reactions")}} {:steps [{:type :given :text "a chimpanzee" ::r/fn nil :execution {:start-time #inst "2019-07-28T15:42:19.394-00:00" :end-time #inst "2019-07-28T15:42:19.394-00:00" :ctx-after-exec {:step-rets [:a-chimpanzee]} :err nil}} {:type :when :text "I give him a pear" ::r/fn nil :execution {:start-time #inst "2019-07-28T15:42:19.394-00:00" :end-time #inst "2019-07-28T15:42:19.394-00:00" :ctx-after-exec {:step-rets [:a-chimpanzee :give-with-var-pear]} :err nil}} {:type :then :text "he is sad" ::r/fn nil :execution {:start-time #inst "2019-07-28T15:42:19.395-00:00" :end-time #inst "2019-07-28T15:42:19.395-00:00" :ctx-after-exec {:step-rets [:a-chimpanzee :give-with-var-pear :is-sad]} :err nil}} {:type :then :text "he doesn't eat it" :original-type :but ::r/fn nil :execution {:start-time #inst "2019-07-28T15:42:19.395-00:00" :end-time #inst "2019-07-28T15:42:19.395-00:00" :ctx-after-exec {:step-rets [:a-chimpanzee :give-with-var-pear :is-sad :not-eat]} :err nil}} {:type :then :text "he looks at me loathingly" :original-type :and ::r/fn nil :execution {:start-time #inst "2019-07-28T15:42:19.395-00:00" :end-time #inst "2019-07-28T15:42:19.395-00:00" :ctx-after-exec {:step-rets [:a-chimpanzee :give-with-var-pear :is-sad :not-eat :looks-loathingly]} :err nil}}] :feature {:name "Chimpanzees behave as expected" :description "Experimenters want to ensure that their chimpanzee simulations are behaving correctly." :tags (list "chimpanzees")} :scenario {:description "Chimpanzees behave as expected when offered various foods." :tags (list "fruit-reactions")}}]) (def other-fake-run-outcome [{:steps [{:type :when :text "a well-formed request is made to update the chimpanzee-integrated liquidity for space 3170 of pork 651 owned by company 13" ::r/fn nil :execution {:start-time #inst "2019-07-28T16:09:24.804-00:00" :end-time #inst "2019-07-28T16:09:26.200-00:00" :ctx-after-exec {:update-chimpanzee-liquidity-resp [{:status "success" :updated-at "2019-07-28T12:09:25.943674"} nil]} :err nil}} {:type :then :text "a successful response is received" ::r/fn nil :execution {:start-time #inst "2019-07-28T16:09:26.201-00:00" :end-time #inst "2019-07-28T16:09:26.201-00:00" :ctx-after-exec {:step-return-value nil} :err nil}}] :feature {:name "the porkcase chimpanzee integration liquidity endpoint works" :description "porkcase wants to ensure that requests to the chimpanzee integration liquidity endpoint are handled correctly." :tags (list "chimpanzee" "liquidity")} :scenario {:description "Well-formed update requests to the chimpanzee liquidity endpoint are handled correctly." :tags (list "update")}}]) Like runner_test::fake - run - outcome-3 but split across two scenarios in one feature . (def fake-run-outcome-3 [{:type :given :text "a chimpanzee" ::r/fn nil :execution {:start-time #inst "2019-07-28T15:42:19.389-00:00" :end-time #inst "2019-07-28T15:42:19.389-00:00" :ctx-after-exec {:step-rets [:a-chimpanzee]} :err nil}} {:type :when :text "I give him a banana" ::r/fn nil :execution {:start-time #inst "2019-07-28T15:42:19.390-00:00" :end-time #inst "2019-07-28T15:42:19.390-00:00" :ctx-after-exec {:step-rets [:a-chimpanzee :give-with-var-banana]} :err nil}} {:type :then :text "he is happy" ::r/fn nil :execution {:start-time #inst "2019-07-28T15:42:19.390-00:00" :end-time #inst "2019-07-28T15:42:19.391-00:00" :ctx-after-exec nil :err {:type :error :message "Divide by zero" :stack-trace (list "clojure.lang.Numbers.divide(Numbers.java:163)" "java.lang.Thread.run(Thread.java:745)")}}} {:type :then :text "he doesn't eat it" :original-type :but ::r/fn nil :execution nil} {:type :then :text "he looks at me quizzically" :original-type :and ::r/fn nil :execution nil}] :feature {:name "Chimpanzees behave as expected" :description "Experimenters want to ensure that their chimpanzee simulations are behaving correctly." :tags (list "chimpanzees")} :scenario {:description "A" :tags (list "a")}} [{:type :given :text "a chimpanzee" ::r/fn nil :execution {:start-time #inst "2019-07-28T15:42:19.392-00:00" :end-time #inst "2019-07-28T15:42:19.392-00:00" :ctx-after-exec {:step-rets [:a-chimpanzee]} :err nil}} {:type :when :text "I give him a pear" ::r/fn nil :execution {:start-time #inst "2019-07-28T15:42:19.392-00:00" :end-time #inst "2019-07-28T15:42:19.392-00:00" :ctx-after-exec {:step-rets [:a-chimpanzee :give-with-var-pear]} :err nil}} {:type :then :text "he is sad" ::r/fn nil :execution {:start-time #inst "2019-07-28T15:42:19.392-00:00" :end-time #inst "2019-07-28T15:42:19.392-00:00" :ctx-after-exec {:step-rets [:a-chimpanzee :give-with-var-pear :is-sad]} :err nil}} {:type :then :text "he doesn't eat it" :original-type :but ::r/fn nil :execution {:start-time #inst "2019-07-28T15:42:19.392-00:00" :end-time #inst "2019-07-28T15:42:19.392-00:00" :ctx-after-exec {:step-rets [:a-chimpanzee :give-with-var-pear :is-sad :not-eat]} :err nil}} {:type :then :text "he looks at me loathingly" :original-type :and ::r/fn nil :execution {:start-time #inst "2019-07-28T15:42:19.393-00:00" :end-time #inst "2019-07-28T15:42:19.393-00:00" :ctx-after-exec {:step-rets [:a-chimpanzee :give-with-var-pear :is-sad :not-eat :looks-loathingly]} :err nil}}] :feature {:name "Chimpanzees behave as expected" :description "Experimenters want to ensure that their chimpanzee simulations are behaving correctly." :tags (list "chimpanzees")} :scenario {:description "A" :tags (list "a")}} [{:type :given :text "a chimpanzee" ::r/fn nil :execution {:start-time #inst "2019-07-28T15:42:19.393-00:00" :end-time #inst "2019-07-28T15:42:19.393-00:00" :ctx-after-exec {:step-rets [:a-chimpanzee]} :err nil}} {:type :when :text "I give him a banana" ::r/fn nil :execution {:start-time #inst "2019-07-28T15:42:19.394-00:00" :end-time #inst "2019-07-28T15:42:19.394-00:00" :ctx-after-exec {:step-rets [:a-chimpanzee :give-with-var-banana]} :err nil}} {:type :then :text "he is happy" ::r/fn nil :execution {:start-time #inst "2019-07-28T15:42:19.394-00:00" :end-time #inst "2019-07-28T15:42:19.394-00:00" :ctx-after-exec nil :err {:type :error :message "Divide by zero" :stack-trace (list "clojure.lang.Numbers.divide(Numbers.java:163)" "java.lang.Thread.run(Thread.java:745)")}}} {:type :then :text "he doesn't eat it" :original-type :but ::r/fn nil :execution nil} {:type :then :text "he looks at me quizzically" :original-type :and ::r/fn nil :execution nil}] :feature {:name "Chimpanzees behave as expected" :description "Experimenters want to ensure that their chimpanzee simulations are behaving correctly." :tags (list "chimpanzees")} :scenario {:description "B" :tags (list "b")}} [{:type :given :text "a chimpanzee" ::r/fn nil :execution {:start-time #inst "2019-07-28T15:42:19.394-00:00" :end-time #inst "2019-07-28T15:42:19.394-00:00" :ctx-after-exec {:step-rets [:a-chimpanzee]} :err nil}} {:type :when :text "I give him a pear" ::r/fn nil :execution {:start-time #inst "2019-07-28T15:42:19.394-00:00" :end-time #inst "2019-07-28T15:42:19.394-00:00" :ctx-after-exec {:step-rets [:a-chimpanzee :give-with-var-pear]} :err nil}} {:type :then :text "he is sad" ::r/fn nil :execution {:start-time #inst "2019-07-28T15:42:19.395-00:00" :end-time #inst "2019-07-28T15:42:19.395-00:00" :ctx-after-exec {:step-rets [:a-chimpanzee :give-with-var-pear :is-sad]} :err nil}} {:type :then :text "he doesn't eat it" :original-type :but ::r/fn nil :execution {:start-time #inst "2019-07-28T15:42:19.395-00:00" :end-time #inst "2019-07-28T15:42:19.395-00:00" :ctx-after-exec {:step-rets [:a-chimpanzee :give-with-var-pear :is-sad :not-eat]} :err nil}} {:type :then :text "he looks at me loathingly" :original-type :and ::r/fn nil :execution {:start-time #inst "2019-07-28T15:42:19.395-00:00" :end-time #inst "2019-07-28T15:42:19.395-00:00" :ctx-after-exec {:step-rets [:a-chimpanzee :give-with-var-pear :is-sad :not-eat :looks-loathingly]} :err nil}}] :feature {:name "Chimpanzees behave as expected" :description "Experimenters want to ensure that their chimpanzee simulations are behaving correctly." :tags (list "chimpanzees")} :scenario {:description "B" :tags (list "b")}}]) (def minimal-run-outcome [{:execution {:err nil}} {:execution {:err nil}} {:execution {:err {:type :error}}} {:execution nil} {:execution nil}] :feature "f-a" :scenario "s-a"} ]) (comment ((juxt :feature :scenario :outcome) (first other-fake-run-outcome)) (->> other-fake-run-outcome first r/analyze-step-execution ((juxt :feature :scenario :outcome))) (->> other-fake-run-outcome r/executions->outcome-map r/outcome-map->outcome-summary-map) (->> fake-run-outcome-3 r/executions->outcome-map r/outcome-map->outcome-summary-map) (let [scenarios {{:description "A" :tags (list "a")} {:step-pass-count 7 :step-untested-count 2 :step-fail-count 1 :execution-pass-count 1 :execution-fail-count 1} {:description "B" :tags (list "b")} {:step-pass-count 7 :step-untested-count 2 :step-fail-count 1 :execution-pass-count 1 :execution-fail-count 1}}] (apply (partial merge-with + {:passed 0 :failed 0}) (->> scenarios vals (map (fn [scen-val] (println "scen-val") (println scen-val) (reduce (fn [agg [k v]] (let [new-k (if (some #{k} [:error :fail]) :failed :passed)] (merge-with + agg {new-k v}))) {:passed 0 :failed 0} scen-val)))))) (let [scenarios {{:description "A" :tags (list "a")} {:step-pass-count 7 :step-untested-count 2 :step-fail-count 1 :execution-pass-count 1 :execution-fail-count 1} {:description "B" :tags (list "b")} {:step-pass-count 7 :step-untested-count 2 :step-fail-count 1 :execution-pass-count 1 :execution-fail-count 1}}] (apply merge-with + (vals scenarios))) (let [scenarios {{:description "A" :tags (list "a")} {:step-pass-count 7 :step-untested-count 2 :step-fail-count 1 :execution-pass-count 1 :execution-fail-count 1} {:description "B" :tags (list "b")} {:step-pass-count 7 :step-untested-count 2 :step-fail-count 1 :execution-pass-count 1 :execution-fail-count 1}}] (->> scenarios vals (map (fn [step-stats-map] (if (= 0 (:execution-fail-count step-stats-map)) {:scenario-pass-count 1 :scenario-fail-count 0} {:scenario-pass-count 0 :scenario-fail-count 1}))) (apply merge-with +))) (let [scenarios {{:description "A" :tags (list "a")} {:step-pass-count 7 :step-untested-count 2 :step-fail-count 1 :execution-pass-count 1 :execution-fail-count 1} {:description "B" :tags (list "b")} {:step-pass-count 7 :step-untested-count 2 :step-fail-count 1 :execution-pass-count 1 :execution-fail-count 1}} steps-stats (apply merge-with + (vals scenarios)) scenarios-stats (->> scenarios vals (map (fn [step-stats-map] (if (= 0 (:execution-fail-count step-stats-map)) {:scenario-pass-count 1 :scenario-fail-count 0} {:scenario-pass-count 0 :scenario-fail-count 1}))) (apply merge-with +)) feature-stats (if (= 0 (:scenario-fail-count scenarios-stats)) {:feature-pass-count 1 :feature-fail-count 0} {:feature-pass-count 0 :feature-fail-count 1})] (merge steps-stats scenarios-stats feature-stats)) (r/executions->outcome-map other-fake-run-outcome) (r/analyze-step-execution (first other-fake-run-outcome)) (r/executions->outcome-map fake-run-outcome) (r/analyze-step-execution (first fake-run-outcome)) (r/analyze-step-execution (second fake-run-outcome)) (r/analyze-step-execution (nth fake-run-outcome 2)) (r/analyze-step-execution (nth fake-run-outcome 3)) (r/get-outcome-summary minimal-run-outcome) (-> [{:execution {:err nil}} {:execution {:err nil}} {:execution {:err {:type :error}}} {:execution nil} {:execution nil}] :feature "f-a" :scenario "s-a"} [{:execution {:err nil}} {:execution {:err nil}}] :feature "f-a" :scenario "s-a"} [{:execution {:err nil}} {:execution {:err nil}}] :feature "f-b" :scenario "s-b"}] (r/summarize-run)) (r/get-outcome-summary fake-run-outcome) (r/get-outcome-summary other-fake-run-outcome) (r/get-outcome-summary fake-run-outcome-3) (r/get-step-fn-args "I ate a {fruit-type}" "I ate a banana") (r/get-step-fn-args "I ate a banana" "I ate a pear") (r/get-step-fn-args "I ate a pear" "I ate a pear") ((r/get-step-fn fake-registry {:type :when :text "I give him a pear"}) {}) ((r/get-step-fn fake-registry {:type :when :text "I give him a banana"}) {}) ((r/get-step-fn fake-registry {:type :when :text "I give him a pear"}) {}) (let [features [(p/parse chimpanzee-feature) (p/parse chimpanzee-feature)] config {:tags {:and-tags #{"chimpanzees" "fruit-reactions"}} :stop false} fake-registry {:given {"a chimpanzee" (fn [context] (update-step-rets context :a-chimpanzee))} :when {"I give him a banana" (fn [context] (update-step-rets context :give-banana)) "I give him a pear" (fn [context] (update-step-rets context :give-pear))} :then {"he doesn't eat it" (fn [context] (update-step-rets context :not-eat)) "he is happy" (fn [context] (update-step-rets context (/ 1 0))) "he is sad" (fn [context] (update-step-rets context :is-sad)) "he looks at me loathingly" (fn [context] (update-step-rets context :looks-loathingly)) "he looks at me quizzically" (fn [context] (update-step-rets context :looks-quizzically))}}] (r/run features fake-registry config)) (let [features [(p/parse chimpanzee-feature) (p/parse chimpanzee-feature)] config {:tags {:and-tags #{"chimpanzees" "fruit-reactions"}} :stop false} fake-registry {:given {"a chimpanzee" (fn [context] (update-step-rets context :a-chimpanzee))} :when {"I give him a {fruit}" (fn [context fruit] (update-step-rets context (keyword (format "give-with-var-%s" fruit))))} :then {"he doesn't eat it" (fn [context] (update-step-rets context :not-eat)) "he is happy" (fn [context] (update-step-rets context (/ 1 0))) "he is sad" (fn [context] (update-step-rets context :is-sad)) "he looks at me loathingly" (fn [context] (update-step-rets context :looks-loathingly)) "he looks at me quizzically" (fn [context] (update-step-rets context :looks-quizzically))}}] (r/run features fake-registry config)) (r/get-step-fn-args "I give {recipient} a {fruit}" (r/get-step-fn-args "I gave {recipient} a {fruit}" (r/get-step-fn-args "I give him a big ole banana" )
7bd1b53a5be2e2885c0c690debd86c626f042ca861bbda0c4f463ce45871bb8f
grayswandyr/electrod
Gen_goal_recursor.ml
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * electrod - a model finder for relational first - order linear temporal logic * * Copyright ( C ) 2016 - 2020 ONERA * Authors : ( ONERA ) , ( ONERA ) * * This Source Code Form is subject to the terms of the Mozilla Public * License , v. 2.0 . If a copy of the MPL was not distributed with this * file , You can obtain one at /. * * SPDX - License - Identifier : MPL-2.0 * License - Filename : LICENSE.md * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * electrod - a model finder for relational first-order linear temporal logic * * Copyright (C) 2016-2020 ONERA * Authors: Julien Brunel (ONERA), David Chemouil (ONERA) * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at /. * * SPDX-License-Identifier: MPL-2.0 * License-Filename: LICENSE.md ******************************************************************************) (** Implements a recursor over generic goals (necessary for conversion to LTL). *) open Gen_goal class virtual ['self] recursor = object (self : 'self) inherit [_] VisitorsRuntime.map method virtual build_Add : _ method virtual build_All : _ method virtual build_And : _ method virtual build_Block : _ method virtual build_BoxJoin : _ method virtual build_Card : _ method virtual build_Compr : _ method virtual build_Diff : _ method virtual build_F : _ method virtual build_FIte : _ method virtual build_False : _ method virtual build_G : _ method virtual build_Gt : _ method virtual build_Gte : _ method virtual build_H : _ method virtual build_IBin : _ method virtual build_IComp : _ method virtual build_IEq : _ method virtual build_INEq : _ method virtual build_IUn : _ method virtual build_Iden : _ method virtual build_Ident : _ method virtual build_Iff : _ method virtual build_Imp : _ method virtual build_In : _ method virtual build_Inter : _ method virtual build_Join : _ method virtual build_LBin : _ method virtual build_LProj : _ method virtual build_LUn : _ method virtual build_Let : _ method virtual build_Lone : _ method virtual build_Lt : _ method virtual build_Lte : _ method virtual build_Neg : _ method virtual build_No : _ method virtual build_None_ : _ method virtual build_Not : _ method virtual build_NotIn : _ method virtual build_Num : _ method virtual build_O : _ method virtual build_One : _ method virtual build_Or : _ method virtual build_Over : _ method virtual build_P : _ method virtual build_Prime : _ method virtual build_Prod : _ method virtual build_Qual : _ method virtual build_Quant : _ method virtual build_R : _ method virtual build_RBin : _ method virtual build_RComp : _ method virtual build_REq : _ method virtual build_RIte : _ method virtual build_RLone : _ method virtual build_RNEq : _ method virtual build_RNo : _ method virtual build_ROne : _ method virtual build_RProj : _ method virtual build_RSome : _ method virtual build_RTClos : _ method virtual build_RUn : _ method virtual build_S : _ method virtual build_Run : _ method virtual build_Some_ : _ method virtual build_Sub : _ method virtual build_T : _ method virtual build_TClos : _ method virtual build_Transpose : _ method virtual build_True : _ method virtual build_U : _ method virtual build_Union : _ method virtual build_Univ : _ method virtual build_X : _ method virtual build_exp : _ method virtual build_fml : _ method virtual build_iexp : _ method virtual visit_'i : _ method virtual visit_'v : _ method visit_Run env _visitors_c0 _visitors_c1 = let _visitors_r0 = self#visit_list self#visit_fml env _visitors_c0 in self#build_Run env _visitors_c0 _visitors_c1 _visitors_r0 method visit_t env _visitors_this = match _visitors_this with | Run (_visitors_c0, _visitors_c1) -> self#visit_Run env _visitors_c0 _visitors_c1 method visit_fml env _visitors_this = let _visitors_r0 = self#visit_prim_fml env _visitors_this.prim_fml in let _visitors_r1 = (fun _visitors_this -> _visitors_this) _visitors_this.fml_loc in self#build_fml env _visitors_this _visitors_r0 _visitors_r1 method visit_True env = self#build_True env method visit_False env = self#build_False env method visit_Qual env _visitors_c0 _visitors_c1 = let _visitors_r0 = self#visit_rqualify env _visitors_c0 in let _visitors_r1 = self#visit_exp env _visitors_c1 in self#build_Qual env _visitors_c0 _visitors_c1 _visitors_r0 _visitors_r1 method visit_RComp env _visitors_c0 _visitors_c1 _visitors_c2 = let _visitors_r0 = self#visit_exp env _visitors_c0 in let _visitors_r1 = self#visit_comp_op env _visitors_c1 in let _visitors_r2 = self#visit_exp env _visitors_c2 in self#build_RComp env _visitors_c0 _visitors_c1 _visitors_c2 _visitors_r0 _visitors_r1 _visitors_r2 method visit_IComp env _visitors_c0 _visitors_c1 _visitors_c2 = let _visitors_r0 = self#visit_iexp env _visitors_c0 in let _visitors_r1 = self#visit_icomp_op env _visitors_c1 in let _visitors_r2 = self#visit_iexp env _visitors_c2 in self#build_IComp env _visitors_c0 _visitors_c1 _visitors_c2 _visitors_r0 _visitors_r1 _visitors_r2 method visit_LUn env _visitors_c0 _visitors_c1 = let _visitors_r0 = self#visit_lunop env _visitors_c0 in let _visitors_r1 = self#visit_fml env _visitors_c1 in self#build_LUn env _visitors_c0 _visitors_c1 _visitors_r0 _visitors_r1 method visit_LBin env _visitors_c0 _visitors_c1 _visitors_c2 = let _visitors_r0 = self#visit_fml env _visitors_c0 in let _visitors_r1 = self#visit_lbinop env _visitors_c1 in let _visitors_r2 = self#visit_fml env _visitors_c2 in self#build_LBin env _visitors_c0 _visitors_c1 _visitors_c2 _visitors_r0 _visitors_r1 _visitors_r2 method visit_Quant env _visitors_c0 _visitors_c1 _visitors_c2 = let _visitors_r0 = self#visit_quant env _visitors_c0 in let _visitors_r1 = self#visit_list self#visit_sim_binding env _visitors_c1 in let _visitors_r2 = self#visit_block env _visitors_c2 in self#build_Quant env _visitors_c0 _visitors_c1 _visitors_c2 _visitors_r0 _visitors_r1 _visitors_r2 method visit_Let env _visitors_c0 _visitors_c1 = let _visitors_r0 = self#visit_list self#visit_binding env _visitors_c0 in let _visitors_r1 = self#visit_block env _visitors_c1 in self#build_Let env _visitors_c0 _visitors_c1 _visitors_r0 _visitors_r1 method visit_FIte env _visitors_c0 _visitors_c1 _visitors_c2 = let _visitors_r0 = self#visit_fml env _visitors_c0 in let _visitors_r1 = self#visit_fml env _visitors_c1 in let _visitors_r2 = self#visit_fml env _visitors_c2 in self#build_FIte env _visitors_c0 _visitors_c1 _visitors_c2 _visitors_r0 _visitors_r1 _visitors_r2 method visit_Block env _visitors_c0 = let _visitors_r0 = self#visit_block env _visitors_c0 in self#build_Block env _visitors_c0 _visitors_r0 method visit_prim_fml env _visitors_this = match _visitors_this with | True -> self#visit_True env | False -> self#visit_False env | Qual (_visitors_c0, _visitors_c1) -> self#visit_Qual env _visitors_c0 _visitors_c1 | RComp (_visitors_c0, _visitors_c1, _visitors_c2) -> self#visit_RComp env _visitors_c0 _visitors_c1 _visitors_c2 | IComp (_visitors_c0, _visitors_c1, _visitors_c2) -> self#visit_IComp env _visitors_c0 _visitors_c1 _visitors_c2 | LUn (_visitors_c0, _visitors_c1) -> self#visit_LUn env _visitors_c0 _visitors_c1 | LBin (_visitors_c0, _visitors_c1, _visitors_c2) -> self#visit_LBin env _visitors_c0 _visitors_c1 _visitors_c2 | Quant (_visitors_c0, _visitors_c1, _visitors_c2) -> self#visit_Quant env _visitors_c0 _visitors_c1 _visitors_c2 | Let (_visitors_c0, _visitors_c1) -> self#visit_Let env _visitors_c0 _visitors_c1 | FIte (_visitors_c0, _visitors_c1, _visitors_c2) -> self#visit_FIte env _visitors_c0 _visitors_c1 _visitors_c2 | Block _visitors_c0 -> self#visit_Block env _visitors_c0 method visit_binding env (_visitors_c0, _visitors_c1) = let _visitors_r0 = self#visit_'v env _visitors_c0 in let _visitors_r1 = self#visit_exp env _visitors_c1 in (_visitors_r0, _visitors_r1) method visit_sim_binding env (_visitors_c0, _visitors_c1, _visitors_c2) = let _visitors_r0 = self#visit_disj env _visitors_c0 in let _visitors_r1 = self#visit_list self#visit_'v env _visitors_c1 in let _visitors_r2 = self#visit_exp env _visitors_c2 in (_visitors_r0, _visitors_r1, _visitors_r2) method visit_disj __env _visitors_this = _visitors_this method visit_block env = self#visit_list self#visit_fml env method visit_All env = self#build_All env method visit_Some_ env = self#build_Some_ env method visit_No env = self#build_No env method visit_One env = self#build_One env method visit_Lone env = self#build_Lone env method visit_quant env _visitors_this = match _visitors_this with | All -> self#visit_All env | Some_ -> self#visit_Some_ env | No -> self#visit_No env | One -> self#visit_One env | Lone -> self#visit_Lone env method visit_And env = self#build_And env method visit_Or env = self#build_Or env method visit_Imp env = self#build_Imp env method visit_Iff env = self#build_Iff env method visit_U env = self#build_U env method visit_R env = self#build_R env method visit_S env = self#build_S env method visit_T env = self#build_T env method visit_lbinop env _visitors_this = match _visitors_this with | And -> self#visit_And env | Or -> self#visit_Or env | Imp -> self#visit_Imp env | Iff -> self#visit_Iff env | U -> self#visit_U env | R -> self#visit_R env | S -> self#visit_S env | T -> self#visit_T env method visit_F env = self#build_F env method visit_G env = self#build_G env method visit_Not env = self#build_Not env method visit_O env = self#build_O env method visit_X env = self#build_X env method visit_H env = self#build_H env method visit_P env = self#build_P env method visit_lunop env _visitors_this = match _visitors_this with | F -> self#visit_F env | G -> self#visit_G env | Not -> self#visit_Not env | O -> self#visit_O env | X -> self#visit_X env | H -> self#visit_H env | P -> self#visit_P env method visit_In env = self#build_In env method visit_NotIn env = self#build_NotIn env method visit_REq env = self#build_REq env method visit_RNEq env = self#build_RNEq env method visit_comp_op env _visitors_this = match _visitors_this with | In -> self#visit_In env | NotIn -> self#visit_NotIn env | REq -> self#visit_REq env | RNEq -> self#visit_RNEq env method visit_IEq env = self#build_IEq env method visit_INEq env = self#build_INEq env method visit_Lt env = self#build_Lt env method visit_Lte env = self#build_Lte env method visit_Gt env = self#build_Gt env method visit_Gte env = self#build_Gte env method visit_icomp_op env _visitors_this = match _visitors_this with | IEq -> self#visit_IEq env | INEq -> self#visit_INEq env | Lt -> self#visit_Lt env | Lte -> self#visit_Lte env | Gt -> self#visit_Gt env | Gte -> self#visit_Gte env method visit_exp env _visitors_this = let _visitors_r0 = self#visit_prim_exp env _visitors_this.prim_exp in let _visitors_r1 = (fun _visitors_this -> _visitors_this) _visitors_this.exp_loc in let _visitors_r2 = (fun _visitors_this -> _visitors_this) _visitors_this.arity in self#build_exp env _visitors_this _visitors_r0 _visitors_r1 _visitors_r2 method visit_None_ env = self#build_None_ env method visit_Univ env = self#build_Univ env method visit_Iden env = self#build_Iden env method visit_Ident env _visitors_c0 = let _visitors_r0 = self#visit_'i env _visitors_c0 in self#build_Ident env _visitors_c0 _visitors_r0 method visit_RUn env _visitors_c0 _visitors_c1 = let _visitors_r0 = self#visit_runop env _visitors_c0 in let _visitors_r1 = self#visit_exp env _visitors_c1 in self#build_RUn env _visitors_c0 _visitors_c1 _visitors_r0 _visitors_r1 method visit_RBin env _visitors_c0 _visitors_c1 _visitors_c2 = let _visitors_r0 = self#visit_exp env _visitors_c0 in let _visitors_r1 = self#visit_rbinop env _visitors_c1 in let _visitors_r2 = self#visit_exp env _visitors_c2 in self#build_RBin env _visitors_c0 _visitors_c1 _visitors_c2 _visitors_r0 _visitors_r1 _visitors_r2 method visit_RIte env _visitors_c0 _visitors_c1 _visitors_c2 = let _visitors_r0 = self#visit_fml env _visitors_c0 in let _visitors_r1 = self#visit_exp env _visitors_c1 in let _visitors_r2 = self#visit_exp env _visitors_c2 in self#build_RIte env _visitors_c0 _visitors_c1 _visitors_c2 _visitors_r0 _visitors_r1 _visitors_r2 method visit_BoxJoin env _visitors_c0 _visitors_c1 = let _visitors_r0 = self#visit_exp env _visitors_c0 in let _visitors_r1 = self#visit_list self#visit_exp env _visitors_c1 in self#build_BoxJoin env _visitors_c0 _visitors_c1 _visitors_r0 _visitors_r1 method visit_Compr env _visitors_c0 _visitors_c1 = let _visitors_r0 = self#visit_list self#visit_sim_binding env _visitors_c0 in let _visitors_r1 = self#visit_block env _visitors_c1 in self#build_Compr env _visitors_c0 _visitors_c1 _visitors_r0 _visitors_r1 method visit_Prime env _visitors_c0 = let _visitors_r0 = self#visit_exp env _visitors_c0 in self#build_Prime env _visitors_c0 _visitors_r0 method visit_prim_exp env _visitors_this = match _visitors_this with | None_ -> self#visit_None_ env | Univ -> self#visit_Univ env | Iden -> self#visit_Iden env | Ident _visitors_c0 -> self#visit_Ident env _visitors_c0 | RUn (_visitors_c0, _visitors_c1) -> self#visit_RUn env _visitors_c0 _visitors_c1 | RBin (_visitors_c0, _visitors_c1, _visitors_c2) -> self#visit_RBin env _visitors_c0 _visitors_c1 _visitors_c2 | RIte (_visitors_c0, _visitors_c1, _visitors_c2) -> self#visit_RIte env _visitors_c0 _visitors_c1 _visitors_c2 | BoxJoin (_visitors_c0, _visitors_c1) -> self#visit_BoxJoin env _visitors_c0 _visitors_c1 | Compr (_visitors_c0, _visitors_c1) -> self#visit_Compr env _visitors_c0 _visitors_c1 | Prime _visitors_c0 -> self#visit_Prime env _visitors_c0 method visit_ROne env = self#build_ROne env method visit_RLone env = self#build_RLone env method visit_RSome env = self#build_RSome env method visit_RNo env = self#build_RNo env method visit_rqualify env _visitors_this = match _visitors_this with | ROne -> self#visit_ROne env | RLone -> self#visit_RLone env | RSome -> self#visit_RSome env | RNo -> self#visit_RNo env method visit_Transpose env = self#build_Transpose env method visit_TClos env = self#build_TClos env method visit_RTClos env = self#build_RTClos env method visit_runop env _visitors_this = match _visitors_this with | Transpose -> self#visit_Transpose env | TClos -> self#visit_TClos env | RTClos -> self#visit_RTClos env method visit_Union env _visitors_c0 _visitors_c1 = self#build_Union env _visitors_c0 _visitors_c1 method visit_Inter env = self#build_Inter env method visit_Over env = self#build_Over env method visit_LProj env = self#build_LProj env method visit_RProj env = self#build_RProj env method visit_Prod env = self#build_Prod env method visit_Diff env = self#build_Diff env method visit_Join env = self#build_Join env method visit_rbinop env _visitors_this = match _visitors_this with | Union -> self#visit_Union env | Inter -> self#visit_Inter env | Over -> self#visit_Over env | LProj -> self#visit_LProj env | RProj -> self#visit_RProj env | Prod -> self#visit_Prod env | Diff -> self#visit_Diff env | Join -> self#visit_Join env method visit_iexp env _visitors_this = let _visitors_r0 = self#visit_prim_iexp env _visitors_this.prim_iexp in let _visitors_r1 = (fun _visitors_this -> _visitors_this) _visitors_this.iexp_loc in self#build_iexp env _visitors_this _visitors_r0 _visitors_r1 method visit_Num env _visitors_c0 = let _visitors_r0 = (fun _visitors_this -> _visitors_this) _visitors_c0 in self#build_Num env _visitors_c0 _visitors_r0 method visit_Card env _visitors_c0 = let _visitors_r0 = self#visit_exp env _visitors_c0 in self#build_Card env _visitors_c0 _visitors_r0 method visit_IUn env _visitors_c0 _visitors_c1 = let _visitors_r0 = self#visit_iunop env _visitors_c0 in let _visitors_r1 = self#visit_iexp env _visitors_c1 in self#build_IUn env _visitors_c0 _visitors_c1 _visitors_r0 _visitors_r1 method visit_IBin env _visitors_c0 _visitors_c1 _visitors_c2 = let _visitors_r0 = self#visit_iexp env _visitors_c0 in let _visitors_r1 = self#visit_ibinop env _visitors_c1 in let _visitors_r2 = self#visit_iexp env _visitors_c2 in self#build_IBin env _visitors_c0 _visitors_c1 _visitors_c2 _visitors_r0 _visitors_r1 _visitors_r2 method visit_prim_iexp env _visitors_this = match _visitors_this with | Num _visitors_c0 -> self#visit_Num env _visitors_c0 | Card _visitors_c0 -> self#visit_Card env _visitors_c0 | IUn (_visitors_c0, _visitors_c1) -> self#visit_IUn env _visitors_c0 _visitors_c1 | IBin (_visitors_c0, _visitors_c1, _visitors_c2) -> self#visit_IBin env _visitors_c0 _visitors_c1 _visitors_c2 method visit_Neg env = self#build_Neg env method visit_iunop env _visitors_this = match _visitors_this with Neg -> self#visit_Neg env method visit_Add env = self#build_Add env method visit_Sub env = self#build_Sub env method visit_ibinop env _visitors_this = match _visitors_this with | Add -> self#visit_Add env | Sub -> self#visit_Sub env end
null
https://raw.githubusercontent.com/grayswandyr/electrod/eb0b02eafb34b6c921f99716cb5e90c946aae51b/src/Gen_goal_recursor.ml
ocaml
* Implements a recursor over generic goals (necessary for conversion to LTL).
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * electrod - a model finder for relational first - order linear temporal logic * * Copyright ( C ) 2016 - 2020 ONERA * Authors : ( ONERA ) , ( ONERA ) * * This Source Code Form is subject to the terms of the Mozilla Public * License , v. 2.0 . If a copy of the MPL was not distributed with this * file , You can obtain one at /. * * SPDX - License - Identifier : MPL-2.0 * License - Filename : LICENSE.md * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * electrod - a model finder for relational first-order linear temporal logic * * Copyright (C) 2016-2020 ONERA * Authors: Julien Brunel (ONERA), David Chemouil (ONERA) * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at /. * * SPDX-License-Identifier: MPL-2.0 * License-Filename: LICENSE.md ******************************************************************************) open Gen_goal class virtual ['self] recursor = object (self : 'self) inherit [_] VisitorsRuntime.map method virtual build_Add : _ method virtual build_All : _ method virtual build_And : _ method virtual build_Block : _ method virtual build_BoxJoin : _ method virtual build_Card : _ method virtual build_Compr : _ method virtual build_Diff : _ method virtual build_F : _ method virtual build_FIte : _ method virtual build_False : _ method virtual build_G : _ method virtual build_Gt : _ method virtual build_Gte : _ method virtual build_H : _ method virtual build_IBin : _ method virtual build_IComp : _ method virtual build_IEq : _ method virtual build_INEq : _ method virtual build_IUn : _ method virtual build_Iden : _ method virtual build_Ident : _ method virtual build_Iff : _ method virtual build_Imp : _ method virtual build_In : _ method virtual build_Inter : _ method virtual build_Join : _ method virtual build_LBin : _ method virtual build_LProj : _ method virtual build_LUn : _ method virtual build_Let : _ method virtual build_Lone : _ method virtual build_Lt : _ method virtual build_Lte : _ method virtual build_Neg : _ method virtual build_No : _ method virtual build_None_ : _ method virtual build_Not : _ method virtual build_NotIn : _ method virtual build_Num : _ method virtual build_O : _ method virtual build_One : _ method virtual build_Or : _ method virtual build_Over : _ method virtual build_P : _ method virtual build_Prime : _ method virtual build_Prod : _ method virtual build_Qual : _ method virtual build_Quant : _ method virtual build_R : _ method virtual build_RBin : _ method virtual build_RComp : _ method virtual build_REq : _ method virtual build_RIte : _ method virtual build_RLone : _ method virtual build_RNEq : _ method virtual build_RNo : _ method virtual build_ROne : _ method virtual build_RProj : _ method virtual build_RSome : _ method virtual build_RTClos : _ method virtual build_RUn : _ method virtual build_S : _ method virtual build_Run : _ method virtual build_Some_ : _ method virtual build_Sub : _ method virtual build_T : _ method virtual build_TClos : _ method virtual build_Transpose : _ method virtual build_True : _ method virtual build_U : _ method virtual build_Union : _ method virtual build_Univ : _ method virtual build_X : _ method virtual build_exp : _ method virtual build_fml : _ method virtual build_iexp : _ method virtual visit_'i : _ method virtual visit_'v : _ method visit_Run env _visitors_c0 _visitors_c1 = let _visitors_r0 = self#visit_list self#visit_fml env _visitors_c0 in self#build_Run env _visitors_c0 _visitors_c1 _visitors_r0 method visit_t env _visitors_this = match _visitors_this with | Run (_visitors_c0, _visitors_c1) -> self#visit_Run env _visitors_c0 _visitors_c1 method visit_fml env _visitors_this = let _visitors_r0 = self#visit_prim_fml env _visitors_this.prim_fml in let _visitors_r1 = (fun _visitors_this -> _visitors_this) _visitors_this.fml_loc in self#build_fml env _visitors_this _visitors_r0 _visitors_r1 method visit_True env = self#build_True env method visit_False env = self#build_False env method visit_Qual env _visitors_c0 _visitors_c1 = let _visitors_r0 = self#visit_rqualify env _visitors_c0 in let _visitors_r1 = self#visit_exp env _visitors_c1 in self#build_Qual env _visitors_c0 _visitors_c1 _visitors_r0 _visitors_r1 method visit_RComp env _visitors_c0 _visitors_c1 _visitors_c2 = let _visitors_r0 = self#visit_exp env _visitors_c0 in let _visitors_r1 = self#visit_comp_op env _visitors_c1 in let _visitors_r2 = self#visit_exp env _visitors_c2 in self#build_RComp env _visitors_c0 _visitors_c1 _visitors_c2 _visitors_r0 _visitors_r1 _visitors_r2 method visit_IComp env _visitors_c0 _visitors_c1 _visitors_c2 = let _visitors_r0 = self#visit_iexp env _visitors_c0 in let _visitors_r1 = self#visit_icomp_op env _visitors_c1 in let _visitors_r2 = self#visit_iexp env _visitors_c2 in self#build_IComp env _visitors_c0 _visitors_c1 _visitors_c2 _visitors_r0 _visitors_r1 _visitors_r2 method visit_LUn env _visitors_c0 _visitors_c1 = let _visitors_r0 = self#visit_lunop env _visitors_c0 in let _visitors_r1 = self#visit_fml env _visitors_c1 in self#build_LUn env _visitors_c0 _visitors_c1 _visitors_r0 _visitors_r1 method visit_LBin env _visitors_c0 _visitors_c1 _visitors_c2 = let _visitors_r0 = self#visit_fml env _visitors_c0 in let _visitors_r1 = self#visit_lbinop env _visitors_c1 in let _visitors_r2 = self#visit_fml env _visitors_c2 in self#build_LBin env _visitors_c0 _visitors_c1 _visitors_c2 _visitors_r0 _visitors_r1 _visitors_r2 method visit_Quant env _visitors_c0 _visitors_c1 _visitors_c2 = let _visitors_r0 = self#visit_quant env _visitors_c0 in let _visitors_r1 = self#visit_list self#visit_sim_binding env _visitors_c1 in let _visitors_r2 = self#visit_block env _visitors_c2 in self#build_Quant env _visitors_c0 _visitors_c1 _visitors_c2 _visitors_r0 _visitors_r1 _visitors_r2 method visit_Let env _visitors_c0 _visitors_c1 = let _visitors_r0 = self#visit_list self#visit_binding env _visitors_c0 in let _visitors_r1 = self#visit_block env _visitors_c1 in self#build_Let env _visitors_c0 _visitors_c1 _visitors_r0 _visitors_r1 method visit_FIte env _visitors_c0 _visitors_c1 _visitors_c2 = let _visitors_r0 = self#visit_fml env _visitors_c0 in let _visitors_r1 = self#visit_fml env _visitors_c1 in let _visitors_r2 = self#visit_fml env _visitors_c2 in self#build_FIte env _visitors_c0 _visitors_c1 _visitors_c2 _visitors_r0 _visitors_r1 _visitors_r2 method visit_Block env _visitors_c0 = let _visitors_r0 = self#visit_block env _visitors_c0 in self#build_Block env _visitors_c0 _visitors_r0 method visit_prim_fml env _visitors_this = match _visitors_this with | True -> self#visit_True env | False -> self#visit_False env | Qual (_visitors_c0, _visitors_c1) -> self#visit_Qual env _visitors_c0 _visitors_c1 | RComp (_visitors_c0, _visitors_c1, _visitors_c2) -> self#visit_RComp env _visitors_c0 _visitors_c1 _visitors_c2 | IComp (_visitors_c0, _visitors_c1, _visitors_c2) -> self#visit_IComp env _visitors_c0 _visitors_c1 _visitors_c2 | LUn (_visitors_c0, _visitors_c1) -> self#visit_LUn env _visitors_c0 _visitors_c1 | LBin (_visitors_c0, _visitors_c1, _visitors_c2) -> self#visit_LBin env _visitors_c0 _visitors_c1 _visitors_c2 | Quant (_visitors_c0, _visitors_c1, _visitors_c2) -> self#visit_Quant env _visitors_c0 _visitors_c1 _visitors_c2 | Let (_visitors_c0, _visitors_c1) -> self#visit_Let env _visitors_c0 _visitors_c1 | FIte (_visitors_c0, _visitors_c1, _visitors_c2) -> self#visit_FIte env _visitors_c0 _visitors_c1 _visitors_c2 | Block _visitors_c0 -> self#visit_Block env _visitors_c0 method visit_binding env (_visitors_c0, _visitors_c1) = let _visitors_r0 = self#visit_'v env _visitors_c0 in let _visitors_r1 = self#visit_exp env _visitors_c1 in (_visitors_r0, _visitors_r1) method visit_sim_binding env (_visitors_c0, _visitors_c1, _visitors_c2) = let _visitors_r0 = self#visit_disj env _visitors_c0 in let _visitors_r1 = self#visit_list self#visit_'v env _visitors_c1 in let _visitors_r2 = self#visit_exp env _visitors_c2 in (_visitors_r0, _visitors_r1, _visitors_r2) method visit_disj __env _visitors_this = _visitors_this method visit_block env = self#visit_list self#visit_fml env method visit_All env = self#build_All env method visit_Some_ env = self#build_Some_ env method visit_No env = self#build_No env method visit_One env = self#build_One env method visit_Lone env = self#build_Lone env method visit_quant env _visitors_this = match _visitors_this with | All -> self#visit_All env | Some_ -> self#visit_Some_ env | No -> self#visit_No env | One -> self#visit_One env | Lone -> self#visit_Lone env method visit_And env = self#build_And env method visit_Or env = self#build_Or env method visit_Imp env = self#build_Imp env method visit_Iff env = self#build_Iff env method visit_U env = self#build_U env method visit_R env = self#build_R env method visit_S env = self#build_S env method visit_T env = self#build_T env method visit_lbinop env _visitors_this = match _visitors_this with | And -> self#visit_And env | Or -> self#visit_Or env | Imp -> self#visit_Imp env | Iff -> self#visit_Iff env | U -> self#visit_U env | R -> self#visit_R env | S -> self#visit_S env | T -> self#visit_T env method visit_F env = self#build_F env method visit_G env = self#build_G env method visit_Not env = self#build_Not env method visit_O env = self#build_O env method visit_X env = self#build_X env method visit_H env = self#build_H env method visit_P env = self#build_P env method visit_lunop env _visitors_this = match _visitors_this with | F -> self#visit_F env | G -> self#visit_G env | Not -> self#visit_Not env | O -> self#visit_O env | X -> self#visit_X env | H -> self#visit_H env | P -> self#visit_P env method visit_In env = self#build_In env method visit_NotIn env = self#build_NotIn env method visit_REq env = self#build_REq env method visit_RNEq env = self#build_RNEq env method visit_comp_op env _visitors_this = match _visitors_this with | In -> self#visit_In env | NotIn -> self#visit_NotIn env | REq -> self#visit_REq env | RNEq -> self#visit_RNEq env method visit_IEq env = self#build_IEq env method visit_INEq env = self#build_INEq env method visit_Lt env = self#build_Lt env method visit_Lte env = self#build_Lte env method visit_Gt env = self#build_Gt env method visit_Gte env = self#build_Gte env method visit_icomp_op env _visitors_this = match _visitors_this with | IEq -> self#visit_IEq env | INEq -> self#visit_INEq env | Lt -> self#visit_Lt env | Lte -> self#visit_Lte env | Gt -> self#visit_Gt env | Gte -> self#visit_Gte env method visit_exp env _visitors_this = let _visitors_r0 = self#visit_prim_exp env _visitors_this.prim_exp in let _visitors_r1 = (fun _visitors_this -> _visitors_this) _visitors_this.exp_loc in let _visitors_r2 = (fun _visitors_this -> _visitors_this) _visitors_this.arity in self#build_exp env _visitors_this _visitors_r0 _visitors_r1 _visitors_r2 method visit_None_ env = self#build_None_ env method visit_Univ env = self#build_Univ env method visit_Iden env = self#build_Iden env method visit_Ident env _visitors_c0 = let _visitors_r0 = self#visit_'i env _visitors_c0 in self#build_Ident env _visitors_c0 _visitors_r0 method visit_RUn env _visitors_c0 _visitors_c1 = let _visitors_r0 = self#visit_runop env _visitors_c0 in let _visitors_r1 = self#visit_exp env _visitors_c1 in self#build_RUn env _visitors_c0 _visitors_c1 _visitors_r0 _visitors_r1 method visit_RBin env _visitors_c0 _visitors_c1 _visitors_c2 = let _visitors_r0 = self#visit_exp env _visitors_c0 in let _visitors_r1 = self#visit_rbinop env _visitors_c1 in let _visitors_r2 = self#visit_exp env _visitors_c2 in self#build_RBin env _visitors_c0 _visitors_c1 _visitors_c2 _visitors_r0 _visitors_r1 _visitors_r2 method visit_RIte env _visitors_c0 _visitors_c1 _visitors_c2 = let _visitors_r0 = self#visit_fml env _visitors_c0 in let _visitors_r1 = self#visit_exp env _visitors_c1 in let _visitors_r2 = self#visit_exp env _visitors_c2 in self#build_RIte env _visitors_c0 _visitors_c1 _visitors_c2 _visitors_r0 _visitors_r1 _visitors_r2 method visit_BoxJoin env _visitors_c0 _visitors_c1 = let _visitors_r0 = self#visit_exp env _visitors_c0 in let _visitors_r1 = self#visit_list self#visit_exp env _visitors_c1 in self#build_BoxJoin env _visitors_c0 _visitors_c1 _visitors_r0 _visitors_r1 method visit_Compr env _visitors_c0 _visitors_c1 = let _visitors_r0 = self#visit_list self#visit_sim_binding env _visitors_c0 in let _visitors_r1 = self#visit_block env _visitors_c1 in self#build_Compr env _visitors_c0 _visitors_c1 _visitors_r0 _visitors_r1 method visit_Prime env _visitors_c0 = let _visitors_r0 = self#visit_exp env _visitors_c0 in self#build_Prime env _visitors_c0 _visitors_r0 method visit_prim_exp env _visitors_this = match _visitors_this with | None_ -> self#visit_None_ env | Univ -> self#visit_Univ env | Iden -> self#visit_Iden env | Ident _visitors_c0 -> self#visit_Ident env _visitors_c0 | RUn (_visitors_c0, _visitors_c1) -> self#visit_RUn env _visitors_c0 _visitors_c1 | RBin (_visitors_c0, _visitors_c1, _visitors_c2) -> self#visit_RBin env _visitors_c0 _visitors_c1 _visitors_c2 | RIte (_visitors_c0, _visitors_c1, _visitors_c2) -> self#visit_RIte env _visitors_c0 _visitors_c1 _visitors_c2 | BoxJoin (_visitors_c0, _visitors_c1) -> self#visit_BoxJoin env _visitors_c0 _visitors_c1 | Compr (_visitors_c0, _visitors_c1) -> self#visit_Compr env _visitors_c0 _visitors_c1 | Prime _visitors_c0 -> self#visit_Prime env _visitors_c0 method visit_ROne env = self#build_ROne env method visit_RLone env = self#build_RLone env method visit_RSome env = self#build_RSome env method visit_RNo env = self#build_RNo env method visit_rqualify env _visitors_this = match _visitors_this with | ROne -> self#visit_ROne env | RLone -> self#visit_RLone env | RSome -> self#visit_RSome env | RNo -> self#visit_RNo env method visit_Transpose env = self#build_Transpose env method visit_TClos env = self#build_TClos env method visit_RTClos env = self#build_RTClos env method visit_runop env _visitors_this = match _visitors_this with | Transpose -> self#visit_Transpose env | TClos -> self#visit_TClos env | RTClos -> self#visit_RTClos env method visit_Union env _visitors_c0 _visitors_c1 = self#build_Union env _visitors_c0 _visitors_c1 method visit_Inter env = self#build_Inter env method visit_Over env = self#build_Over env method visit_LProj env = self#build_LProj env method visit_RProj env = self#build_RProj env method visit_Prod env = self#build_Prod env method visit_Diff env = self#build_Diff env method visit_Join env = self#build_Join env method visit_rbinop env _visitors_this = match _visitors_this with | Union -> self#visit_Union env | Inter -> self#visit_Inter env | Over -> self#visit_Over env | LProj -> self#visit_LProj env | RProj -> self#visit_RProj env | Prod -> self#visit_Prod env | Diff -> self#visit_Diff env | Join -> self#visit_Join env method visit_iexp env _visitors_this = let _visitors_r0 = self#visit_prim_iexp env _visitors_this.prim_iexp in let _visitors_r1 = (fun _visitors_this -> _visitors_this) _visitors_this.iexp_loc in self#build_iexp env _visitors_this _visitors_r0 _visitors_r1 method visit_Num env _visitors_c0 = let _visitors_r0 = (fun _visitors_this -> _visitors_this) _visitors_c0 in self#build_Num env _visitors_c0 _visitors_r0 method visit_Card env _visitors_c0 = let _visitors_r0 = self#visit_exp env _visitors_c0 in self#build_Card env _visitors_c0 _visitors_r0 method visit_IUn env _visitors_c0 _visitors_c1 = let _visitors_r0 = self#visit_iunop env _visitors_c0 in let _visitors_r1 = self#visit_iexp env _visitors_c1 in self#build_IUn env _visitors_c0 _visitors_c1 _visitors_r0 _visitors_r1 method visit_IBin env _visitors_c0 _visitors_c1 _visitors_c2 = let _visitors_r0 = self#visit_iexp env _visitors_c0 in let _visitors_r1 = self#visit_ibinop env _visitors_c1 in let _visitors_r2 = self#visit_iexp env _visitors_c2 in self#build_IBin env _visitors_c0 _visitors_c1 _visitors_c2 _visitors_r0 _visitors_r1 _visitors_r2 method visit_prim_iexp env _visitors_this = match _visitors_this with | Num _visitors_c0 -> self#visit_Num env _visitors_c0 | Card _visitors_c0 -> self#visit_Card env _visitors_c0 | IUn (_visitors_c0, _visitors_c1) -> self#visit_IUn env _visitors_c0 _visitors_c1 | IBin (_visitors_c0, _visitors_c1, _visitors_c2) -> self#visit_IBin env _visitors_c0 _visitors_c1 _visitors_c2 method visit_Neg env = self#build_Neg env method visit_iunop env _visitors_this = match _visitors_this with Neg -> self#visit_Neg env method visit_Add env = self#build_Add env method visit_Sub env = self#build_Sub env method visit_ibinop env _visitors_this = match _visitors_this with | Add -> self#visit_Add env | Sub -> self#visit_Sub env end
0bc48fc785eca135c6784aeaddd8630ac1480bc82808ff1fc4d92ed9cb237c2f
technomancy/leiningen
default.clj
(ns leiningen.new.default "Generate a library project." (:require [leiningen.new.templates :refer [renderer year date project-name ->files sanitize-ns name-to-path multi-segment]] [leiningen.core.main :as main])) (defn default "A general project template for libraries. Accepts a group id in the project name: `lein new foo.bar/baz`" [name] (let [render (renderer "default") main-ns (multi-segment (sanitize-ns name)) data {:raw-name name :name (project-name name) :namespace main-ns :nested-dirs (name-to-path main-ns) :year (year) :date (date)}] (main/info "Generating a project called" name "based on the 'default' template.") (main/info "The default template is intended for library projects, not applications.") (main/info "To see other templates (app, plugin, etc), try `lein help new`.") (->files data ["project.clj" (render "project.clj" data)] ["README.md" (render "README.md" data)] ["doc/intro.md" (render "intro.md" data)] [".gitignore" (render "gitignore" data)] [".hgignore" (render "hgignore" data)] ["src/{{nested-dirs}}.clj" (render "core.clj" data)] ["test/{{nested-dirs}}_test.clj" (render "test.clj" data)] ["LICENSE" (render "LICENSE" data)] ["CHANGELOG.md" (render "CHANGELOG.md" data)] "resources")))
null
https://raw.githubusercontent.com/technomancy/leiningen/24fb93936133bd7fc30c393c127e9e69bb5f2392/src/leiningen/new/default.clj
clojure
(ns leiningen.new.default "Generate a library project." (:require [leiningen.new.templates :refer [renderer year date project-name ->files sanitize-ns name-to-path multi-segment]] [leiningen.core.main :as main])) (defn default "A general project template for libraries. Accepts a group id in the project name: `lein new foo.bar/baz`" [name] (let [render (renderer "default") main-ns (multi-segment (sanitize-ns name)) data {:raw-name name :name (project-name name) :namespace main-ns :nested-dirs (name-to-path main-ns) :year (year) :date (date)}] (main/info "Generating a project called" name "based on the 'default' template.") (main/info "The default template is intended for library projects, not applications.") (main/info "To see other templates (app, plugin, etc), try `lein help new`.") (->files data ["project.clj" (render "project.clj" data)] ["README.md" (render "README.md" data)] ["doc/intro.md" (render "intro.md" data)] [".gitignore" (render "gitignore" data)] [".hgignore" (render "hgignore" data)] ["src/{{nested-dirs}}.clj" (render "core.clj" data)] ["test/{{nested-dirs}}_test.clj" (render "test.clj" data)] ["LICENSE" (render "LICENSE" data)] ["CHANGELOG.md" (render "CHANGELOG.md" data)] "resources")))
c38d09a76a739387c185a213725935010833b4d09fa5633deb5b3e28e579aa5a
nyu-acsys/drift
a-reverse.ml
let rec reverse ri rn (ra: int array) (rb: int array) = if (ri < rn) then let _ = Array.set rb (rn - ri - 1) (Array.get ra ri) in reverse (ri + 1) rn ra rb else () let main (n(*-:{v:Int | true}*)) = if n > 0 then let a = Array.make n 0 in let b = Array.make n 0 in reverse 0 n a b else ()
null
https://raw.githubusercontent.com/nyu-acsys/drift/51a3160d74b761626180da4f7dd0bb950cfe40c0/tests/benchmarks/DRIFT/array/a-reverse.ml
ocaml
-:{v:Int | true}
let rec reverse ri rn (ra: int array) (rb: int array) = if (ri < rn) then let _ = Array.set rb (rn - ri - 1) (Array.get ra ri) in reverse (ri + 1) rn ra rb else () if n > 0 then let a = Array.make n 0 in let b = Array.make n 0 in reverse 0 n a b else ()
c34c50bf328306a8c2b7ec1489f6318189f6bd4265c2058103373aca1e9de698
nikodemus/SBCL
frlock.lisp
;;;; FRLocks for SBCL ;;;; ;;;; frlock is a "fast read lock", which allows readers to gain unlocked access ;;;; to values, and provides post-read verification. Readers which intersected ;;;; with writers need to retry. frlock is very efficient when there are many ;;;; readers and writes are both fast and relatively scarce. It is, however, unsuitable when readers and writers need exclusion , such as with SBCL 's ;;;; current hash-table implementation. 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-concurrency) (defstruct (frlock (:constructor %make-frlock (name)) (:predicate nil) (:copier nil)) "FRlock, aka Fast Read Lock. Fast Read Locks allow multiple readers and one potential writer to operate in parallel while providing for consistency for readers and mutual exclusion for writers. Readers gain entry to protected regions without waiting, but need to retry if a writer operated inside the region while they were reading. This makes frlocks very efficient when readers are much more common than writers. FRlocks are NOT suitable when it is not safe at all for readers and writers to operate on the same data in parallel: they provide consistency, not exclusion between readers and writers. Hence using an frlock to eg. protect an SBCL hash-table is unsafe. If multiple readers operating in parallel with a writer would be safe but inconsistent without a lock, frlocks are suitable. The recommended interface to use is FRLOCK-READ and FRLOCK-WRITE, but those needing it can also use a lower-level interface. Example: Values returned by FOO are always consistent so that the third value is the sum of the two first ones . (let ((a 0) (b 0) (c 0) (lk (make-frlock))) (defun foo () (frlock-read (lk) a b c)) (defun bar (x y) (frlock-write (lk) (setf a x b y c (+ x y))))) " (mutex (make-mutex :name "FRLock mutex") :type mutex :read-only t) ;; Using FIXNUM counters makes sure we don't need to cons a bignum ;; for the return value, ever. (pre-counter 0 :type (and unsigned-byte fixnum)) (post-counter 0 :type (and unsigned-byte fixnum)) On 32bit platforms a fixnum can roll over pretty easily , so we also use ;; an epoch marker to keep track of that. (epoch (list t) :type cons) (name nil)) (declaim (inline make-frlock)) (defun make-frlock (&key name) "Returns a new FRLOCK with NAME." (%make-frlock name)) (declaim (inline frlock-read-begin)) (defun frlock-read-begin (frlock) "Start a read sequence on FRLOCK. Returns a read-token and an epoch to be validated later. Using FRLOCK-READ instead is recommended." (barrier (:read)) (values (frlock-post-counter frlock) (frlock-epoch frlock))) (declaim (inline frlock-read-end)) (defun frlock-read-end (frlock) "Ends a read sequence on FRLOCK. Returns a token and an epoch. If the token and epoch are EQL to the read-token and epoch returned by FRLOCK-READ-BEGIN, the values read under the FRLOCK are consistent and can be used: if the values differ, the values are inconsistent and the read must be restated. Using FRLOCK-READ instead is recommended. Example: (multiple-value-bind (t0 e0) (frlock-read-begin *fr*) (let ((a (get-a)) (b (get-b))) (multiple-value-bind (t1 e1) (frlock-read-end *fr*) (if (and (eql t0 t1) (eql e0 e1)) (list :a a :b b) :aborted)))) " (barrier (:read)) (values (frlock-pre-counter frlock) (frlock-epoch frlock))) (defmacro frlock-read ((frlock) &body value-forms) "Evaluates VALUE-FORMS under FRLOCK till it obtains a consistent set, and returns that as multiple values." (once-only ((frlock frlock)) (with-unique-names (t0 t1 e0 e1) (let ((syms (make-gensym-list (length value-forms)))) `(loop (multiple-value-bind (,t0 ,e0) (frlock-read-begin ,frlock) (let ,(mapcar 'list syms value-forms) (barrier (:compiler)) (multiple-value-bind (,t1 ,e1) (frlock-read-end ,frlock) (when (and (eql ,t1 ,t0) (eql ,e1 ,e0)) (return (values ,@syms))))))))))) ;;; Actual implementation. (defun %%grab-frlock-write-lock (frlock wait-p timeout) (when (grab-mutex (frlock-mutex frlock) :waitp wait-p :timeout timeout) (let ((new (logand most-positive-fixnum (1+ (frlock-pre-counter frlock))))) ;; Here's our roll-over protection: if a reader has been unlucky enough ;; to stand inside the lock long enough for the counter to go from 0 to ;; 0, they will still be holding on to the old epoch. While it is ;; extremely unlikely, it isn't quite "not before heath death of the universe " stuff : a 30 bit counter can roll over in a couple of ;; seconds -- and a thread can easily be interrupted by eg. a timer for ;; that long, so a pathological system could be have a thread in a danger - zone every second . Run that system for a year , and it would have a 1 in 3 chance of hitting the incipient bug . Adding an epoch ;; makes sure that isn't going to happen. (when (zerop new) (setf (frlock-epoch frlock) (list t))) (setf (frlock-pre-counter frlock) new)) (barrier (:write)) t)) ;;; Interrupt-mangling free entry point for FRLOCK-WRITE. (declaim (inline %grab-frlock-write-lock)) (defun %grab-frlock-write-lock (frlock &key (wait-p t) timeout) (%%grab-frlock-write-lock frlock wait-p timeout)) ;;; Normal entry-point. (declaim (inline grab-frlock-write-lock)) (defun grab-frlock-write-lock (frlock &key (wait-p t) timeout) "Acquires FRLOCK for writing, invalidating existing and future read-tokens for the duration. Returns T on success, and NIL if the lock wasn't acquired due to eg. a timeout. Using FRLOCK-WRITE instead is recommended." (without-interrupts (allow-with-interrupts (%%grab-frlock-write-lock frlock wait-p timeout)))) (declaim (inline release-frlock-write-lock)) (defun release-frlock-write-lock (frlock) "Releases FRLOCK after writing, allowing valid read-tokens to be acquired again. Signals an error if the current thread doesn't hold FRLOCK for writing. Using FRLOCK-WRITE instead is recommended." (setf (frlock-post-counter frlock) (logand most-positive-fixnum (1+ (frlock-post-counter frlock)))) (release-mutex (frlock-mutex frlock) :if-not-owner :error) (barrier (:write))) (defmacro frlock-write ((frlock &key (wait-p t) timeout) &body body) "Executes BODY while holding FRLOCK for writing." (once-only ((frlock frlock)) (with-unique-names (got-it) `(without-interrupts (let (,got-it) (unwind-protect (when (setf ,got-it (allow-with-interrupts (%grab-frlock-write-lock ,frlock :timeout ,timeout :wait-p ,wait-p))) (with-local-interrupts ,@body)) (when ,got-it (release-frlock-write-lock ,frlock))))))))
null
https://raw.githubusercontent.com/nikodemus/SBCL/3c11847d1e12db89b24a7887b18a137c45ed4661/contrib/sb-concurrency/frlock.lisp
lisp
frlock is a "fast read lock", which allows readers to gain unlocked access to values, and provides post-read verification. Readers which intersected with writers need to retry. frlock is very efficient when there are many readers and writes are both fast and relatively scarce. It is, however, current hash-table implementation. 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. Using FIXNUM counters makes sure we don't need to cons a bignum for the return value, ever. an epoch marker to keep track of that. Actual implementation. Here's our roll-over protection: if a reader has been unlucky enough to stand inside the lock long enough for the counter to go from 0 to 0, they will still be holding on to the old epoch. While it is extremely unlikely, it isn't quite "not before heath death of the seconds -- and a thread can easily be interrupted by eg. a timer for that long, so a pathological system could be have a thread in a makes sure that isn't going to happen. Interrupt-mangling free entry point for FRLOCK-WRITE. Normal entry-point.
FRLocks for SBCL unsuitable when readers and writers need exclusion , such as with SBCL 's 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-concurrency) (defstruct (frlock (:constructor %make-frlock (name)) (:predicate nil) (:copier nil)) "FRlock, aka Fast Read Lock. Fast Read Locks allow multiple readers and one potential writer to operate in parallel while providing for consistency for readers and mutual exclusion for writers. Readers gain entry to protected regions without waiting, but need to retry if a writer operated inside the region while they were reading. This makes frlocks very efficient when readers are much more common than writers. FRlocks are NOT suitable when it is not safe at all for readers and writers to operate on the same data in parallel: they provide consistency, not exclusion between readers and writers. Hence using an frlock to eg. protect an SBCL hash-table is unsafe. If multiple readers operating in parallel with a writer would be safe but inconsistent without a lock, frlocks are suitable. The recommended interface to use is FRLOCK-READ and FRLOCK-WRITE, but those needing it can also use a lower-level interface. Example: Values returned by FOO are always consistent so that the third value is the sum of the two first ones . (let ((a 0) (b 0) (c 0) (lk (make-frlock))) (defun foo () (frlock-read (lk) a b c)) (defun bar (x y) (frlock-write (lk) (setf a x b y c (+ x y))))) " (mutex (make-mutex :name "FRLock mutex") :type mutex :read-only t) (pre-counter 0 :type (and unsigned-byte fixnum)) (post-counter 0 :type (and unsigned-byte fixnum)) On 32bit platforms a fixnum can roll over pretty easily , so we also use (epoch (list t) :type cons) (name nil)) (declaim (inline make-frlock)) (defun make-frlock (&key name) "Returns a new FRLOCK with NAME." (%make-frlock name)) (declaim (inline frlock-read-begin)) (defun frlock-read-begin (frlock) "Start a read sequence on FRLOCK. Returns a read-token and an epoch to be validated later. Using FRLOCK-READ instead is recommended." (barrier (:read)) (values (frlock-post-counter frlock) (frlock-epoch frlock))) (declaim (inline frlock-read-end)) (defun frlock-read-end (frlock) "Ends a read sequence on FRLOCK. Returns a token and an epoch. If the token and epoch are EQL to the read-token and epoch returned by FRLOCK-READ-BEGIN, the values read under the FRLOCK are consistent and can be used: if the values differ, the values are inconsistent and the read must be restated. Using FRLOCK-READ instead is recommended. Example: (multiple-value-bind (t0 e0) (frlock-read-begin *fr*) (let ((a (get-a)) (b (get-b))) (multiple-value-bind (t1 e1) (frlock-read-end *fr*) (if (and (eql t0 t1) (eql e0 e1)) (list :a a :b b) :aborted)))) " (barrier (:read)) (values (frlock-pre-counter frlock) (frlock-epoch frlock))) (defmacro frlock-read ((frlock) &body value-forms) "Evaluates VALUE-FORMS under FRLOCK till it obtains a consistent set, and returns that as multiple values." (once-only ((frlock frlock)) (with-unique-names (t0 t1 e0 e1) (let ((syms (make-gensym-list (length value-forms)))) `(loop (multiple-value-bind (,t0 ,e0) (frlock-read-begin ,frlock) (let ,(mapcar 'list syms value-forms) (barrier (:compiler)) (multiple-value-bind (,t1 ,e1) (frlock-read-end ,frlock) (when (and (eql ,t1 ,t0) (eql ,e1 ,e0)) (return (values ,@syms))))))))))) (defun %%grab-frlock-write-lock (frlock wait-p timeout) (when (grab-mutex (frlock-mutex frlock) :waitp wait-p :timeout timeout) (let ((new (logand most-positive-fixnum (1+ (frlock-pre-counter frlock))))) universe " stuff : a 30 bit counter can roll over in a couple of danger - zone every second . Run that system for a year , and it would have a 1 in 3 chance of hitting the incipient bug . Adding an epoch (when (zerop new) (setf (frlock-epoch frlock) (list t))) (setf (frlock-pre-counter frlock) new)) (barrier (:write)) t)) (declaim (inline %grab-frlock-write-lock)) (defun %grab-frlock-write-lock (frlock &key (wait-p t) timeout) (%%grab-frlock-write-lock frlock wait-p timeout)) (declaim (inline grab-frlock-write-lock)) (defun grab-frlock-write-lock (frlock &key (wait-p t) timeout) "Acquires FRLOCK for writing, invalidating existing and future read-tokens for the duration. Returns T on success, and NIL if the lock wasn't acquired due to eg. a timeout. Using FRLOCK-WRITE instead is recommended." (without-interrupts (allow-with-interrupts (%%grab-frlock-write-lock frlock wait-p timeout)))) (declaim (inline release-frlock-write-lock)) (defun release-frlock-write-lock (frlock) "Releases FRLOCK after writing, allowing valid read-tokens to be acquired again. Signals an error if the current thread doesn't hold FRLOCK for writing. Using FRLOCK-WRITE instead is recommended." (setf (frlock-post-counter frlock) (logand most-positive-fixnum (1+ (frlock-post-counter frlock)))) (release-mutex (frlock-mutex frlock) :if-not-owner :error) (barrier (:write))) (defmacro frlock-write ((frlock &key (wait-p t) timeout) &body body) "Executes BODY while holding FRLOCK for writing." (once-only ((frlock frlock)) (with-unique-names (got-it) `(without-interrupts (let (,got-it) (unwind-protect (when (setf ,got-it (allow-with-interrupts (%grab-frlock-write-lock ,frlock :timeout ,timeout :wait-p ,wait-p))) (with-local-interrupts ,@body)) (when ,got-it (release-frlock-write-lock ,frlock))))))))
a69f05cf01498dfbf64c7ca7b62f468043dd13e627863ba9f76ebd86b5bdcf7a
satos---jp/mincaml_self_hosting
mandelblot_edit.ml
let rec dbl f = f +. f in let rec yloop y = if y >= 40 then () else let rec xloop x y = if x >= 40 then () else let cr = dbl (float_of_int x) /. 40.0 -. 1.5 in let ci = dbl (float_of_int y) /. 40.0 -. 1.0 in let rec iloop i zr zi zr2 zi2 cr ci = if i = 0 then print_int 1 else let tr = zr2 -. zi2 +. cr in let ti = dbl zr *. zi +. ci in let zr = tr in let zi = ti in let zr2 = zr *. zr in let zi2 = zi *. zi in if fless (2.0 *. 2.0) (zr2 +. zi2) then print_int 0 else iloop (i - 1) zr zi zr2 zi2 cr ci in iloop 1000 0.0 0.0 0.0 0.0 cr ci; xloop (x + 1) y in xloop 0 y; print_char 10; yloop (y + 1) in yloop 0
null
https://raw.githubusercontent.com/satos---jp/mincaml_self_hosting/5fdf8b5083437d7607a924142eea52d9b1de0439/test/mandelblot_edit.ml
ocaml
let rec dbl f = f +. f in let rec yloop y = if y >= 40 then () else let rec xloop x y = if x >= 40 then () else let cr = dbl (float_of_int x) /. 40.0 -. 1.5 in let ci = dbl (float_of_int y) /. 40.0 -. 1.0 in let rec iloop i zr zi zr2 zi2 cr ci = if i = 0 then print_int 1 else let tr = zr2 -. zi2 +. cr in let ti = dbl zr *. zi +. ci in let zr = tr in let zi = ti in let zr2 = zr *. zr in let zi2 = zi *. zi in if fless (2.0 *. 2.0) (zr2 +. zi2) then print_int 0 else iloop (i - 1) zr zi zr2 zi2 cr ci in iloop 1000 0.0 0.0 0.0 0.0 cr ci; xloop (x + 1) y in xloop 0 y; print_char 10; yloop (y + 1) in yloop 0
a18767cf8a5e2915b1cb5d0160949be85dea9c5a01d1348a74fd494ba1127eb0
annenkov/unmix
xgen.rkt
#lang racket (require srfi/13) (require "x-misc.rkt" "xio.rkt" "xsettings.rkt" "xcgr.rkt" "xar.rkt" "xcgr.rkt" "xensg.rkt" (prefix-in settings: "xsettings.rkt")) (require-by-mode) (define (ugen:switch action) (define (make-res-filename file-names) (if (null? file-names) "RES" (merge-file-names file-names))) (define (merge-file-names names) (foldr1 (lambda (name1 name2) (string-append name1 "-" name2)) (map uio:cut-off-ext names))) (define (request-data-file-names) (norm-ext* "dat" (request-tokens "Static data file names [.dat]: "))) (define (norm-ext* ext names) (map (lambda (name) (uio:norm-file-name "" ext name)) names)) (define (request-tokens msg) (define input-string #f) (define len #f) (define pos #f) (define tokens #f) (define current-token #f) (define (current-char) (string-ref input-string pos)) (define (scan-tokens!) (cond ((= pos len) #f) ((eqv? (current-char) #\space) (set! pos (+ 1 pos)) (scan-tokens!)) (else (set! current-token '()) (scan-1-token!)))) (define (scan-1-token!) (cond ((or (= pos len) (eqv? (current-char) #\space)) (set! tokens (cons (list->string (reverse current-token)) tokens)) (set! current-token '()) (scan-tokens!)) (else (set! current-token (cons (current-char) current-token)) (set! pos (+ 1 pos)) (scan-1-token!)))) (newline) (display msg) (do () ((not (char-ready?))) (read-char)) (set! input-string (uio:read-line)) (set! len (string-length input-string)) (set! pos 0) (set! tokens '()) (scan-tokens!) (reverse tokens)) (define (run-pe) (newline) (let* ((ann-file-name (uio:request-file-name "Annotated program file name" "" "ann")) (data-file-names (request-data-file-names)) (res (make-res-filename data-file-names)) (program (uio:file->list ann-file-name)) (static-inputs (append-map uio:file->list data-file-names))) (pe-aux ann-file-name data-file-names res program static-inputs))) (define (run-pepepe) (newline) (let* ((ann-file-name (uio:request-file-name "Annotated program file name" "xpe" "ann")) (res (uio:request-name "Residual program file name " "GGG")) (program (uio:file->list ann-file-name)) (static-inputs (list program))) (pe-aux ann-file-name (list ann-file-name) res program static-inputs))) (define (generate-residual-program dst program static-inputs [gen #f]) (umainpe:generate-residual-program dst program static-inputs gen)) (define (pe-aux src data-file-names res program static-inputs) (let ((dst (string-append res ".mwr")) (scm (string-append res settings:**program-file-ext**))) (check-static-inputs program static-inputs) (newline) (display "Residual program generation:") (newline) (display " pe( ") (display src) (display " , ") (display data-file-names) (display " ) -> ") (display dst) (newline) (generate-residual-program dst program static-inputs) (newline) (display "Residual program has been written into ") (display dst) (newline) (post-processing dst scm))) (define (check-static-inputs prog data) (let ((s-fundef* (caddr prog)) (svn (car (cdaadr prog))) (rf (car prog))) (when (not (= (length svn) (length data))) (begin (error "Mismatch in mumber of data files"))))) (define (run-pepe) (newline) (let* ((ann (uio:request-file-name "Annotated program file name" "" "ann")) (res (uio:request-name "Residual program file name " "GENGEN")) (dst (string-append res ".mwr")) (scm (string-append res settings:**program-file-ext**)) (program (uio:file->list (string-append **unmix-path** "xpe.ann"))) (static-inputs (list (uio:file->list ann)))) (newline) (display "Generation of the Residual Program Generator:") (newline) (display " pe( xpe.ann , ") (display (list ann)) (display " ) -> ") (display dst) (newline) (generate-residual-program dst program static-inputs) (newline) (display "Residual program generator has been written into ") (display dst) (newline) (post-processing dst scm))) (define (run-gen) (newline) (let* ((gen (uio:request-file-name "Generator file name" "" (string-drop settings:**program-file-ext** 1))) (data-file-names (request-data-file-names)) (res (make-res-filename data-file-names)) (dst (string-append res ".mwr")) (scm (string-append res settings:**program-file-ext**)) (static-inputs (append-map uio:file->list data-file-names))) (newline) (display "Residual program generation:") (newline) (display " ") (display gen) (display "( ") (display (list data-file-names)) (display " ) -> ") (display dst) (newline) ;(load gen) (generate-residual-program dst '() static-inputs gen) (newline) (display "Residual program has been written into ") (display dst) (newline) (post-processing dst scm))) (define (run-gengen) (newline) (let* ((ann (uio:request-file-name "Annotated program file name" "" "ann")) (res (uio:request-name "Residual program file name " "GENGEN")) (dst (string-append res ".mwr")) (scm (string-append res settings:**program-file-ext**)) (static-inputs (list (uio:file->list ann)))) (newline) (display "Generation of the Residual Program Generator:") (newline) (display " gengen( ") (display ann) (display " ) -> ") (display dst) (newline) (generate-residual-program dst '() static-inputs) (newline) (display "Residual program generator has been written into ") (display dst) (newline) (post-processing dst scm))) (define (post-processing src dst) (let ((pgm (uio:cut-off-ext src)) (program #f)) (newline) (display "Post-processing:") (newline) (display " post( ") (display src) (display " ) -> ") (display dst) (newline) (set! program (uio:file->list src)) (set! program (ucgr:main pgm pgm program)) (set! program (uar:main pgm pgm program)) (set! program (ucgr:main pgm pgm program)) (set! program (uensg:main pgm pgm program)) (uio:list->pp-target-file dst program 79) (newline) (display "Target program has been written into ") (display dst) (newline))) (case action ((pe) (run-pe)) ((pepe) (run-pepe)) ((pepepe) (run-pepepe)) ((gengen) (run-gengen)) ((gen) (run-gen)))) (provide (all-defined-out))
null
https://raw.githubusercontent.com/annenkov/unmix/e156fb706e52994f86029ac512a79c737d7ee0d8/xgen.rkt
racket
(load gen)
#lang racket (require srfi/13) (require "x-misc.rkt" "xio.rkt" "xsettings.rkt" "xcgr.rkt" "xar.rkt" "xcgr.rkt" "xensg.rkt" (prefix-in settings: "xsettings.rkt")) (require-by-mode) (define (ugen:switch action) (define (make-res-filename file-names) (if (null? file-names) "RES" (merge-file-names file-names))) (define (merge-file-names names) (foldr1 (lambda (name1 name2) (string-append name1 "-" name2)) (map uio:cut-off-ext names))) (define (request-data-file-names) (norm-ext* "dat" (request-tokens "Static data file names [.dat]: "))) (define (norm-ext* ext names) (map (lambda (name) (uio:norm-file-name "" ext name)) names)) (define (request-tokens msg) (define input-string #f) (define len #f) (define pos #f) (define tokens #f) (define current-token #f) (define (current-char) (string-ref input-string pos)) (define (scan-tokens!) (cond ((= pos len) #f) ((eqv? (current-char) #\space) (set! pos (+ 1 pos)) (scan-tokens!)) (else (set! current-token '()) (scan-1-token!)))) (define (scan-1-token!) (cond ((or (= pos len) (eqv? (current-char) #\space)) (set! tokens (cons (list->string (reverse current-token)) tokens)) (set! current-token '()) (scan-tokens!)) (else (set! current-token (cons (current-char) current-token)) (set! pos (+ 1 pos)) (scan-1-token!)))) (newline) (display msg) (do () ((not (char-ready?))) (read-char)) (set! input-string (uio:read-line)) (set! len (string-length input-string)) (set! pos 0) (set! tokens '()) (scan-tokens!) (reverse tokens)) (define (run-pe) (newline) (let* ((ann-file-name (uio:request-file-name "Annotated program file name" "" "ann")) (data-file-names (request-data-file-names)) (res (make-res-filename data-file-names)) (program (uio:file->list ann-file-name)) (static-inputs (append-map uio:file->list data-file-names))) (pe-aux ann-file-name data-file-names res program static-inputs))) (define (run-pepepe) (newline) (let* ((ann-file-name (uio:request-file-name "Annotated program file name" "xpe" "ann")) (res (uio:request-name "Residual program file name " "GGG")) (program (uio:file->list ann-file-name)) (static-inputs (list program))) (pe-aux ann-file-name (list ann-file-name) res program static-inputs))) (define (generate-residual-program dst program static-inputs [gen #f]) (umainpe:generate-residual-program dst program static-inputs gen)) (define (pe-aux src data-file-names res program static-inputs) (let ((dst (string-append res ".mwr")) (scm (string-append res settings:**program-file-ext**))) (check-static-inputs program static-inputs) (newline) (display "Residual program generation:") (newline) (display " pe( ") (display src) (display " , ") (display data-file-names) (display " ) -> ") (display dst) (newline) (generate-residual-program dst program static-inputs) (newline) (display "Residual program has been written into ") (display dst) (newline) (post-processing dst scm))) (define (check-static-inputs prog data) (let ((s-fundef* (caddr prog)) (svn (car (cdaadr prog))) (rf (car prog))) (when (not (= (length svn) (length data))) (begin (error "Mismatch in mumber of data files"))))) (define (run-pepe) (newline) (let* ((ann (uio:request-file-name "Annotated program file name" "" "ann")) (res (uio:request-name "Residual program file name " "GENGEN")) (dst (string-append res ".mwr")) (scm (string-append res settings:**program-file-ext**)) (program (uio:file->list (string-append **unmix-path** "xpe.ann"))) (static-inputs (list (uio:file->list ann)))) (newline) (display "Generation of the Residual Program Generator:") (newline) (display " pe( xpe.ann , ") (display (list ann)) (display " ) -> ") (display dst) (newline) (generate-residual-program dst program static-inputs) (newline) (display "Residual program generator has been written into ") (display dst) (newline) (post-processing dst scm))) (define (run-gen) (newline) (let* ((gen (uio:request-file-name "Generator file name" "" (string-drop settings:**program-file-ext** 1))) (data-file-names (request-data-file-names)) (res (make-res-filename data-file-names)) (dst (string-append res ".mwr")) (scm (string-append res settings:**program-file-ext**)) (static-inputs (append-map uio:file->list data-file-names))) (newline) (display "Residual program generation:") (newline) (display " ") (display gen) (display "( ") (display (list data-file-names)) (display " ) -> ") (display dst) (newline) (generate-residual-program dst '() static-inputs gen) (newline) (display "Residual program has been written into ") (display dst) (newline) (post-processing dst scm))) (define (run-gengen) (newline) (let* ((ann (uio:request-file-name "Annotated program file name" "" "ann")) (res (uio:request-name "Residual program file name " "GENGEN")) (dst (string-append res ".mwr")) (scm (string-append res settings:**program-file-ext**)) (static-inputs (list (uio:file->list ann)))) (newline) (display "Generation of the Residual Program Generator:") (newline) (display " gengen( ") (display ann) (display " ) -> ") (display dst) (newline) (generate-residual-program dst '() static-inputs) (newline) (display "Residual program generator has been written into ") (display dst) (newline) (post-processing dst scm))) (define (post-processing src dst) (let ((pgm (uio:cut-off-ext src)) (program #f)) (newline) (display "Post-processing:") (newline) (display " post( ") (display src) (display " ) -> ") (display dst) (newline) (set! program (uio:file->list src)) (set! program (ucgr:main pgm pgm program)) (set! program (uar:main pgm pgm program)) (set! program (ucgr:main pgm pgm program)) (set! program (uensg:main pgm pgm program)) (uio:list->pp-target-file dst program 79) (newline) (display "Target program has been written into ") (display dst) (newline))) (case action ((pe) (run-pe)) ((pepe) (run-pepe)) ((pepepe) (run-pepepe)) ((gengen) (run-gengen)) ((gen) (run-gen)))) (provide (all-defined-out))
c765b77c82b79ef143b0f41ae5cf2f6946e1200fff8664bad3a5b468e00a4fed
avsm/ocaml-ssh
kex.ml
* Copyright ( c ) 2004,2005 Anil Madhavapeddy < > * * Permission to use , copy , modify , and distribute this software for any * purpose with or without fee is hereby granted , provided that the above * copyright notice and this permission notice appear in all copies . * * THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN * ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE . * * Copyright (c) 2004,2005 Anil Madhavapeddy <> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * *) Key - Exchange stuff ------------------------------------------------ open Ssh_utils exception Not_implemented exception Key_too_short module Methods = struct module M = Mpl_stdlib module MP = M.Mpl_mpint module MB = M.Mpl_byte module BS = M.Mpl_string32 module I32 = M.Mpl_uint32 module MR = M.Mpl_raw type mpint = Mpl_stdlib.Mpl_mpint.t type t = | DiffieHellmanGexSHA1 | DiffieHellmanGroup1SHA1 | DiffieHellmanGroup14SHA1 module DHGroup = struct type kex_hash = { v_c: Version.t; (* clients version *) v_s: Version.t; (* servers version *) clients i_s: string; (* servers last kexinit *) k_s: string; (* servers host key *) e: MP.t; (* exchange value sent by client *) f: MP.t; (* response value sent by server *) k: MP.t; (* the shared secret *) } let marshal args = Ssh_pool.get_string_fn (fun env -> let ms x = ignore(BS.marshal env (BS.of_string x)) in let mp x = ignore(MP.marshal env x) in ms (Version.to_string args.v_c); ms (Version.to_string args.v_s); ms args.i_c; ms args.i_s; ms args.k_s; mp args.e; mp args.f; mp args.k; ) end module DHGex = struct type kex_hash = { v_c: Version.t; (* clients version string (no \r\n) *) v_s: Version.t; (* servers version string (no \r\n) *) payload of clients payload of servers last k_s: string; (* servers host key *) min: int32; (* minimal number of bits in group *) n: int32; (* preferred number of bits *) max: int32; (* maximum number of bits in group *) p: MP.t; (* safe prime *) g: MP.t; (* generator for subgroup *) e: MP.t; (* exchange value sent by client *) f: MP.t; (* response value sent by server *) the shared secret } let marshal a = Ssh_pool.get_string_fn (fun env -> let bsm x = ignore(BS.marshal env (BS.of_string x)) in let mpm x = ignore(MP.marshal env x) in let um x = ignore(I32.marshal env (I32.of_int32 x)) in bsm (Version.to_string a.v_c); bsm (Version.to_string a.v_s); bsm a.i_c; bsm a.i_s; bsm a.k_s; um a.min; um a.n; um a.max; mpm a.p; mpm a.g; mpm a.e; mpm a.f; mpm a.k; ) type moduli = (int32, (MP.t * MP.t) list) Hashtbl.t let empty_moduli () = Hashtbl.create 1 let add_moduli ~primes ~size ~prime ~generator = hashtbl_add_to_list primes size (prime,generator) let choose ~min ~want ~max (primes:moduli) = let best_size = Hashtbl.fold (fun size _ best_size -> if size < min || size > max then best_size else begin if (size > want && size < best_size) || (size > best_size && best_size < want) then size else best_size end ) primes 0l in try let options = Hashtbl.find primes best_size in let len = List.length options in let choice = Random.int len in Some (List.nth options choice) with Not_found -> None end exception Unknown of string let to_string = function | DiffieHellmanGexSHA1 -> "diffie-hellman-group-exchange-sha1" | DiffieHellmanGroup1SHA1 -> "diffie-hellman-group1-sha1" | DiffieHellmanGroup14SHA1 -> "diffie-hellman-group14-sha1" let from_string = function | "diffie-hellman-group-exchange-sha1" -> DiffieHellmanGexSHA1 | "diffie-hellman-group1-sha1" -> DiffieHellmanGroup1SHA1 | "diffie-hellman-group14-sha1" -> DiffieHellmanGroup14SHA1 | x -> raise (Unknown x) let public_parameters = function | DiffieHellmanGroup1SHA1 -> RFC2409 - Oakley group 2 , 1024 - bit MODP group let p = binary_of_hex ( "FFFFFFFF FFFFFFFF C90FDAA2 2168C234 C4C6628B 80DC1CD1" ^ "29024E08 8A67CC74 020BBEA6 3B139B22 514A0879 8E3404DD" ^ "EF9519B3 CD3A431B 302B0A6D F25F1437 4FE1356D 6D51C245" ^ "E485B576 625E7EC6 F44C42E9 A637ED6B 0BFF5CB6 F406B7ED" ^ "EE386BFB 5A899FA5 AE9F2411 7C4B1FE6 49286651 ECE65381" ^ "FFFFFFFF FFFFFFFF") in let g = binary_of_hex "02" in (MP.of_string p, MP.of_string g) | DiffieHellmanGroup14SHA1 -> RFC3526 - Oakley group 14 , 2048 - bit MODP group let p = binary_of_hex ( "FFFFFFFF FFFFFFFF C90FDAA2 2168C234 C4C6628B 80DC1CD1" ^ "29024E08 8A67CC74 020BBEA6 3B139B22 514A0879 8E3404DD" ^ "EF9519B3 CD3A431B 302B0A6D F25F1437 4FE1356D 6D51C245" ^ "E485B576 625E7EC6 F44C42E9 A637ED6B 0BFF5CB6 F406B7ED" ^ "EE386BFB 5A899FA5 AE9F2411 7C4B1FE6 49286651 ECE45B3D" ^ "C2007CB8 A163BF05 98DA4836 1C55D39A 69163FA8 FD24CF5F" ^ "83655D23 DCA3AD96 1C62F356 208552BB 9ED52907 7096966D" ^ "670C354E 4ABC9804 F1746C08 CA18217C 32905E46 2E36CE3B" ^ "E39E772C 180E8603 9B2783A2 EC07A28F B5C55DF0 6F4C52C9" ^ "DE2BCBF6 95581718 3995497C EA956AE5 15D22618 98FA0510" ^ "15728E5A 8AACAA68 FFFFFFFF FFFFFFFF") in let g = binary_of_hex "02" in (MP.of_string p, MP.of_string g) | DiffieHellmanGexSHA1 -> (* XXX not yet done, but will depend on the group negotiation *) raise Not_implemented (* Kex algorithm choice, from draft-ietf-secsh-transport-24 Section 7.1 *) let algorithm_choice ~kex ~enc_cs ~enc_sc ~mac_cs ~mac_sc exnfn = let match_supported ty (sl,cl) = let sl = Str.split (Str.regexp_string ",") sl in let cl = Str.split (Str.regexp_string ",") cl in match List.filter (fun k -> List.mem k sl) cl with |hd::tl -> hd |[] -> raise (exnfn ty) in (* Select a key exchange method *) let s_kex = from_string (match_supported "kex" kex) in Select a client->server cipher let s_enc_cs = Algorithms.Cipher.from_string (match_supported "encryption_client_server" enc_cs) in And a server->client cipher let s_enc_sc = Algorithms.Cipher.from_string (match_supported "encryption_server_client" enc_sc) in Select client->server MAC let s_mac_cs = Algorithms.MAC.from_string (match_supported "mac_client_server" mac_cs) in And a server->client MAC let s_mac_sc = Algorithms.MAC.from_string (match_supported "mac_server_client" mac_sc) in (* Return em all *) (s_kex, s_enc_cs, s_enc_sc, s_mac_cs, s_mac_sc) let cryptokit_params p g = let p = MP.to_string p in let g = MP.to_string g in {Cryptokit.DH.p=p; g=g; privlen=256} Initial value to transmit to initiate DH exchange let compute_init rng p g = let params = cryptokit_params p g in let priv = Cryptokit.DH.private_secret ~rng:rng params in let e = MP.of_string (Cryptokit.DH.message params priv) in (e, priv) (* Return the shared secret string given public params and the private secret, and the other sides response mpint *) let compute_shared_secret p g priv resp = let resp = MP.to_string resp in let params = cryptokit_params p g in let s = Cryptokit.DH.shared_secret params priv resp in MP.of_string s Calculate reply to a diffie - hellman key exchange init let compute_reply rng p g e = let params = cryptokit_params p g in (* Generate a response number for us *) let server_private = Cryptokit.DH.private_secret ~rng:rng params in let f = MP.of_string (Cryptokit.DH.message params server_private) in (* Calculate secret from e and f *) let secret = compute_shared_secret p g server_private e in (f, secret) RFC3447 EMSA - PKCS1 - v1_5 , need to pad signature to size n of hostkey . Also hashes the input message using Also hashes the input message using SHA1 *) let pad_rsa_signature hk m = let emlen = MP.bytes hk in let h = Cryptokit.hash_string (Cryptokit.Hash.sha1()) m in let der_sha1 = binary_of_hex "3021300906052b0e03021a05000414" in let t = der_sha1 ^ h in let tlen = String.length t in let padlen = emlen - tlen - 3 in if padlen <= 0 then raise Key_too_short; let ps = String.make padlen '\255' in Printf.sprintf "%c%c%s%c%s" '\000' '\001' ps '\000' t draft-ietf-secsh-transport-18.txt , section 7.2 * K : shared secret ; H : hash ; X : charid ; session_id : first kexinit hash * K:shared secret; H:kexinit hash; X:charid; session_id:first kexinit hash *) let derive_key hashfn k h session_id size x = Be careful here ... the hashfn is only good for one use once evaluated , hence the need to pass a unit arg through the need to pass a unit arg through *) let htrans () = Cryptokit.hash_string (hashfn ()) in let kh = Ssh_pool.get_string_fn (fun env -> ignore(MP.marshal env k); ignore(MR.marshal env h)) in let sidm = Ssh_pool.get_string_fn (fun env -> MR.marshal env kh; MB.marshal env (MB.of_char x); MR.marshal env session_id) in let k1 = htrans () sidm in (* We need this many iterations to have enough for the requested size *) let iterations = size / (String.length k1) in let kn = Array.create (iterations+1) "" in kn.(0) <- k1; if iterations > 0 then begin for i = 1 to iterations do let ksofar = Array.sub kn 0 i in let kcat = String.concat "" (Array.to_list ksofar) in kn.(i) <- htrans () (kh ^ kcat); done; end; let total = String.concat "" (Array.to_list kn) in String.sub total 0 size (* Given a public key, a hash and a signed version of it, make sure they the signed version is valid *) let verify_rsa_signature (pubkey:Message.Key.RSA.o) hash signed = let n = pubkey#n in let key_bits = MP.bits n in let key = { Cryptokit.RSA.size=key_bits; e=MP.to_string pubkey#e; n=MP.to_string n; d=""; p=""; q=""; dp=""; dq=""; qinv=""} in let padded_hash = pad_rsa_signature n hash in let unsigned = Cryptokit.RSA.unwrap_signature key signed in unsigned = padded_hash end
null
https://raw.githubusercontent.com/avsm/ocaml-ssh/26577d1501e7a43e4b520239b08da114c542eda4/lib/kex.ml
ocaml
clients version servers version servers last kexinit servers host key exchange value sent by client response value sent by server the shared secret clients version string (no \r\n) servers version string (no \r\n) servers host key minimal number of bits in group preferred number of bits maximum number of bits in group safe prime generator for subgroup exchange value sent by client response value sent by server XXX not yet done, but will depend on the group negotiation Kex algorithm choice, from draft-ietf-secsh-transport-24 Section 7.1 Select a key exchange method Return em all Return the shared secret string given public params and the private secret, and the other sides response mpint Generate a response number for us Calculate secret from e and f We need this many iterations to have enough for the requested size Given a public key, a hash and a signed version of it, make sure they the signed version is valid
* Copyright ( c ) 2004,2005 Anil Madhavapeddy < > * * Permission to use , copy , modify , and distribute this software for any * purpose with or without fee is hereby granted , provided that the above * copyright notice and this permission notice appear in all copies . * * THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN * ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE . * * Copyright (c) 2004,2005 Anil Madhavapeddy <> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * *) Key - Exchange stuff ------------------------------------------------ open Ssh_utils exception Not_implemented exception Key_too_short module Methods = struct module M = Mpl_stdlib module MP = M.Mpl_mpint module MB = M.Mpl_byte module BS = M.Mpl_string32 module I32 = M.Mpl_uint32 module MR = M.Mpl_raw type mpint = Mpl_stdlib.Mpl_mpint.t type t = | DiffieHellmanGexSHA1 | DiffieHellmanGroup1SHA1 | DiffieHellmanGroup14SHA1 module DHGroup = struct type kex_hash = { clients } let marshal args = Ssh_pool.get_string_fn (fun env -> let ms x = ignore(BS.marshal env (BS.of_string x)) in let mp x = ignore(MP.marshal env x) in ms (Version.to_string args.v_c); ms (Version.to_string args.v_s); ms args.i_c; ms args.i_s; ms args.k_s; mp args.e; mp args.f; mp args.k; ) end module DHGex = struct type kex_hash = { payload of clients payload of servers last the shared secret } let marshal a = Ssh_pool.get_string_fn (fun env -> let bsm x = ignore(BS.marshal env (BS.of_string x)) in let mpm x = ignore(MP.marshal env x) in let um x = ignore(I32.marshal env (I32.of_int32 x)) in bsm (Version.to_string a.v_c); bsm (Version.to_string a.v_s); bsm a.i_c; bsm a.i_s; bsm a.k_s; um a.min; um a.n; um a.max; mpm a.p; mpm a.g; mpm a.e; mpm a.f; mpm a.k; ) type moduli = (int32, (MP.t * MP.t) list) Hashtbl.t let empty_moduli () = Hashtbl.create 1 let add_moduli ~primes ~size ~prime ~generator = hashtbl_add_to_list primes size (prime,generator) let choose ~min ~want ~max (primes:moduli) = let best_size = Hashtbl.fold (fun size _ best_size -> if size < min || size > max then best_size else begin if (size > want && size < best_size) || (size > best_size && best_size < want) then size else best_size end ) primes 0l in try let options = Hashtbl.find primes best_size in let len = List.length options in let choice = Random.int len in Some (List.nth options choice) with Not_found -> None end exception Unknown of string let to_string = function | DiffieHellmanGexSHA1 -> "diffie-hellman-group-exchange-sha1" | DiffieHellmanGroup1SHA1 -> "diffie-hellman-group1-sha1" | DiffieHellmanGroup14SHA1 -> "diffie-hellman-group14-sha1" let from_string = function | "diffie-hellman-group-exchange-sha1" -> DiffieHellmanGexSHA1 | "diffie-hellman-group1-sha1" -> DiffieHellmanGroup1SHA1 | "diffie-hellman-group14-sha1" -> DiffieHellmanGroup14SHA1 | x -> raise (Unknown x) let public_parameters = function | DiffieHellmanGroup1SHA1 -> RFC2409 - Oakley group 2 , 1024 - bit MODP group let p = binary_of_hex ( "FFFFFFFF FFFFFFFF C90FDAA2 2168C234 C4C6628B 80DC1CD1" ^ "29024E08 8A67CC74 020BBEA6 3B139B22 514A0879 8E3404DD" ^ "EF9519B3 CD3A431B 302B0A6D F25F1437 4FE1356D 6D51C245" ^ "E485B576 625E7EC6 F44C42E9 A637ED6B 0BFF5CB6 F406B7ED" ^ "EE386BFB 5A899FA5 AE9F2411 7C4B1FE6 49286651 ECE65381" ^ "FFFFFFFF FFFFFFFF") in let g = binary_of_hex "02" in (MP.of_string p, MP.of_string g) | DiffieHellmanGroup14SHA1 -> RFC3526 - Oakley group 14 , 2048 - bit MODP group let p = binary_of_hex ( "FFFFFFFF FFFFFFFF C90FDAA2 2168C234 C4C6628B 80DC1CD1" ^ "29024E08 8A67CC74 020BBEA6 3B139B22 514A0879 8E3404DD" ^ "EF9519B3 CD3A431B 302B0A6D F25F1437 4FE1356D 6D51C245" ^ "E485B576 625E7EC6 F44C42E9 A637ED6B 0BFF5CB6 F406B7ED" ^ "EE386BFB 5A899FA5 AE9F2411 7C4B1FE6 49286651 ECE45B3D" ^ "C2007CB8 A163BF05 98DA4836 1C55D39A 69163FA8 FD24CF5F" ^ "83655D23 DCA3AD96 1C62F356 208552BB 9ED52907 7096966D" ^ "670C354E 4ABC9804 F1746C08 CA18217C 32905E46 2E36CE3B" ^ "E39E772C 180E8603 9B2783A2 EC07A28F B5C55DF0 6F4C52C9" ^ "DE2BCBF6 95581718 3995497C EA956AE5 15D22618 98FA0510" ^ "15728E5A 8AACAA68 FFFFFFFF FFFFFFFF") in let g = binary_of_hex "02" in (MP.of_string p, MP.of_string g) | DiffieHellmanGexSHA1 -> raise Not_implemented let algorithm_choice ~kex ~enc_cs ~enc_sc ~mac_cs ~mac_sc exnfn = let match_supported ty (sl,cl) = let sl = Str.split (Str.regexp_string ",") sl in let cl = Str.split (Str.regexp_string ",") cl in match List.filter (fun k -> List.mem k sl) cl with |hd::tl -> hd |[] -> raise (exnfn ty) in let s_kex = from_string (match_supported "kex" kex) in Select a client->server cipher let s_enc_cs = Algorithms.Cipher.from_string (match_supported "encryption_client_server" enc_cs) in And a server->client cipher let s_enc_sc = Algorithms.Cipher.from_string (match_supported "encryption_server_client" enc_sc) in Select client->server MAC let s_mac_cs = Algorithms.MAC.from_string (match_supported "mac_client_server" mac_cs) in And a server->client MAC let s_mac_sc = Algorithms.MAC.from_string (match_supported "mac_server_client" mac_sc) in (s_kex, s_enc_cs, s_enc_sc, s_mac_cs, s_mac_sc) let cryptokit_params p g = let p = MP.to_string p in let g = MP.to_string g in {Cryptokit.DH.p=p; g=g; privlen=256} Initial value to transmit to initiate DH exchange let compute_init rng p g = let params = cryptokit_params p g in let priv = Cryptokit.DH.private_secret ~rng:rng params in let e = MP.of_string (Cryptokit.DH.message params priv) in (e, priv) let compute_shared_secret p g priv resp = let resp = MP.to_string resp in let params = cryptokit_params p g in let s = Cryptokit.DH.shared_secret params priv resp in MP.of_string s Calculate reply to a diffie - hellman key exchange init let compute_reply rng p g e = let params = cryptokit_params p g in let server_private = Cryptokit.DH.private_secret ~rng:rng params in let f = MP.of_string (Cryptokit.DH.message params server_private) in let secret = compute_shared_secret p g server_private e in (f, secret) RFC3447 EMSA - PKCS1 - v1_5 , need to pad signature to size n of hostkey . Also hashes the input message using Also hashes the input message using SHA1 *) let pad_rsa_signature hk m = let emlen = MP.bytes hk in let h = Cryptokit.hash_string (Cryptokit.Hash.sha1()) m in let der_sha1 = binary_of_hex "3021300906052b0e03021a05000414" in let t = der_sha1 ^ h in let tlen = String.length t in let padlen = emlen - tlen - 3 in if padlen <= 0 then raise Key_too_short; let ps = String.make padlen '\255' in Printf.sprintf "%c%c%s%c%s" '\000' '\001' ps '\000' t draft-ietf-secsh-transport-18.txt , section 7.2 * K : shared secret ; H : hash ; X : charid ; session_id : first kexinit hash * K:shared secret; H:kexinit hash; X:charid; session_id:first kexinit hash *) let derive_key hashfn k h session_id size x = Be careful here ... the hashfn is only good for one use once evaluated , hence the need to pass a unit arg through the need to pass a unit arg through *) let htrans () = Cryptokit.hash_string (hashfn ()) in let kh = Ssh_pool.get_string_fn (fun env -> ignore(MP.marshal env k); ignore(MR.marshal env h)) in let sidm = Ssh_pool.get_string_fn (fun env -> MR.marshal env kh; MB.marshal env (MB.of_char x); MR.marshal env session_id) in let k1 = htrans () sidm in let iterations = size / (String.length k1) in let kn = Array.create (iterations+1) "" in kn.(0) <- k1; if iterations > 0 then begin for i = 1 to iterations do let ksofar = Array.sub kn 0 i in let kcat = String.concat "" (Array.to_list ksofar) in kn.(i) <- htrans () (kh ^ kcat); done; end; let total = String.concat "" (Array.to_list kn) in String.sub total 0 size let verify_rsa_signature (pubkey:Message.Key.RSA.o) hash signed = let n = pubkey#n in let key_bits = MP.bits n in let key = { Cryptokit.RSA.size=key_bits; e=MP.to_string pubkey#e; n=MP.to_string n; d=""; p=""; q=""; dp=""; dq=""; qinv=""} in let padded_hash = pad_rsa_signature n hash in let unsigned = Cryptokit.RSA.unwrap_signature key signed in unsigned = padded_hash end
e1911e7081685860de67ede3fa96c5c2a485f3dd3a885d2cf4a334e6fbe7fd06
tjammer/raylib-ocaml
raylib_fixed_types.ml
module Types = Raylib_types.Types (Raylib_c_generated_types) open Types external identity : 'a -> 'a = "%identity" let build_enum_bitmask name alist = let lor', land', zero, lnot' = Int64.(logor, logand, zero, lognot) in let unexpected _ k = Printf.ksprintf failwith "Unexpected enum value for %s: %s" name (Int64.to_string k) in let ralist = List.rev alist in let write l = List.fold_left (fun ac k -> lor' (List.assoc k alist) ac) zero l and read res = let rec iter res_orig ac res l = match l with | [] -> if res = zero then ac else unexpected ac res | (a, b) :: tl -> if land' b res_orig = b then iter res_orig (a :: ac) (land' res (lnot' b)) tl else iter res_orig ac res tl in iter res [] res ralist and format_typ k fmt = Format.fprintf fmt "%s%t" name k in Ctypes_static.view ~format_typ ~read ~write Ctypes.int64_t module ConfigFlags = struct include ConfigFlags let t_bitmask = build_enum_bitmask "ConfigFlags" vals let to_int x = Unsigned.UInt32.to_int Ctypes.(coerce t uint32_t x) let of_int i = Ctypes.(coerce uint32_t t (Unsigned.UInt32.of_int i)) end module TraceLogLevel = struct include TraceLogLevel let to_int x = Unsigned.UInt32.to_int Ctypes.(coerce t uint32_t x) let of_int i = Ctypes.(coerce uint32_t t (Unsigned.UInt32.of_int i)) end module Key = struct include Key let to_int x = Unsigned.UInt32.to_int Ctypes.(coerce t uint32_t x) let of_int i = Ctypes.(coerce uint32_t t (Unsigned.UInt32.of_int i)) end module MouseButton = struct include MouseButton let to_int x = Unsigned.UInt32.to_int Ctypes.(coerce t uint32_t x) let of_int i = Ctypes.(coerce uint32_t t (Unsigned.UInt32.of_int i)) end module MouseCursor = struct include MouseCursor let to_int x = Unsigned.UInt32.to_int Ctypes.(coerce t uint32_t x) let of_int i = Ctypes.(coerce uint32_t t (Unsigned.UInt32.of_int i)) end module GamepadButton = struct include GamepadButton let to_int x = Unsigned.UInt32.to_int Ctypes.(coerce t uint32_t x) let of_int i = Ctypes.(coerce uint32_t t (Unsigned.UInt32.of_int i)) end module GamepadAxis = struct include GamepadAxis let to_int x = Unsigned.UInt32.to_int Ctypes.(coerce t uint32_t x) let of_int i = Ctypes.(coerce uint32_t t (Unsigned.UInt32.of_int i)) end module MaterialMapIndex = struct include MaterialMapIndex let to_int x = Unsigned.UInt32.to_int Ctypes.(coerce t uint32_t x) let of_int i = Ctypes.(coerce uint32_t t (Unsigned.UInt32.of_int i)) end module ShaderLocationIndex = struct include ShaderLocationIndex let to_int x = Unsigned.UInt32.to_int Ctypes.(coerce t uint32_t x) let of_int i = Ctypes.(coerce uint32_t t (Unsigned.UInt32.of_int i)) end module ShaderUniformDataType = struct include ShaderUniformDataType let to_int x = Unsigned.UInt32.to_int Ctypes.(coerce t uint32_t x) let of_int i = Ctypes.(coerce uint32_t t (Unsigned.UInt32.of_int i)) end module ShaderAttributeDataType = struct include ShaderAttributeDataType let to_int x = Unsigned.UInt32.to_int Ctypes.(coerce t uint32_t x) let of_int i = Ctypes.(coerce uint32_t t (Unsigned.UInt32.of_int i)) end module PixelFormat = struct include PixelFormat let to_int x = Unsigned.UInt32.to_int Ctypes.(coerce t uint32_t x) let of_int i = Ctypes.(coerce uint32_t t (Unsigned.UInt32.of_int i)) end module TextureFilter = struct include TextureFilter let to_int x = Unsigned.UInt32.to_int Ctypes.(coerce t uint32_t x) let of_int i = Ctypes.(coerce uint32_t t (Unsigned.UInt32.of_int i)) end module TextureWrap = struct include TextureWrap let to_int x = Unsigned.UInt32.to_int Ctypes.(coerce t uint32_t x) let of_int i = Ctypes.(coerce uint32_t t (Unsigned.UInt32.of_int i)) end module CubemapLayout = struct include CubemapLayout let to_int x = Unsigned.UInt32.to_int Ctypes.(coerce t uint32_t x) let of_int i = Ctypes.(coerce uint32_t t (Unsigned.UInt32.of_int i)) end module FontType = struct include FontType let to_int x = Unsigned.UInt32.to_int Ctypes.(coerce t uint32_t x) let of_int i = Ctypes.(coerce uint32_t t (Unsigned.UInt32.of_int i)) end module BlendMode = struct include BlendMode let to_int x = Unsigned.UInt32.to_int Ctypes.(coerce t uint32_t x) let of_int i = Ctypes.(coerce uint32_t t (Unsigned.UInt32.of_int i)) end module Gesture = struct include Gesture let t_bitmask = build_enum_bitmask "Gesture" vals let to_int x = Unsigned.UInt32.to_int Ctypes.(coerce t uint32_t x) let of_int i = Ctypes.(coerce uint32_t t (Unsigned.UInt32.of_int i)) end module CameraMode = struct include CameraMode let to_int x = Unsigned.UInt32.to_int Ctypes.(coerce t uint32_t x) let of_int i = Ctypes.(coerce uint32_t t (Unsigned.UInt32.of_int i)) end module CameraProjection = struct include CameraProjection let to_int x = Unsigned.UInt32.to_int Ctypes.(coerce t uint32_t x) let of_int i = Ctypes.(coerce uint32_t t (Unsigned.UInt32.of_int i)) end module NPatchLayout = struct include NPatchLayout let to_int x = Unsigned.UInt32.to_int Ctypes.(coerce t uint32_t x) let of_int i = Ctypes.(coerce uint32_t t (Unsigned.UInt32.of_int i)) end module Vector2 = Vector2 module Vector3 = Vector3 module Vector4 = Vector4 module Matrix = Matrix module Color = Color module Rectangle = Rectangle module Image = Image module Texture = Texture module RenderTexture = RenderTexture module NPatchInfo = NPatchInfo module GlyphInfo = GlyphInfo module Font = Font module Camera3D = Camera3D module Camera2D = Camera2D module Mesh = Mesh module Shader = Shader module MaterialMap = MaterialMap module Material = Material module Transform = Transform module BoneInfo = BoneInfo module Model = Model module ModelAnimation = ModelAnimation module Ray = Ray module RayCollision = RayCollision module BoundingBox = BoundingBox module Wave = Wave module AudioStream = AudioStream module Sound = Sound module Music = Music module VrDeviceInfo = VrDeviceInfo module VrStereoConfig = VrStereoConfig module FilePathList = FilePathList let max_material_maps = max_material_maps let max_shader_locations = max_shader_locations
null
https://raw.githubusercontent.com/tjammer/raylib-ocaml/bf632bac260b263e9e783a5fc36b6a6b1f5df0d5/src/c/types/raylib_fixed_types.ml
ocaml
module Types = Raylib_types.Types (Raylib_c_generated_types) open Types external identity : 'a -> 'a = "%identity" let build_enum_bitmask name alist = let lor', land', zero, lnot' = Int64.(logor, logand, zero, lognot) in let unexpected _ k = Printf.ksprintf failwith "Unexpected enum value for %s: %s" name (Int64.to_string k) in let ralist = List.rev alist in let write l = List.fold_left (fun ac k -> lor' (List.assoc k alist) ac) zero l and read res = let rec iter res_orig ac res l = match l with | [] -> if res = zero then ac else unexpected ac res | (a, b) :: tl -> if land' b res_orig = b then iter res_orig (a :: ac) (land' res (lnot' b)) tl else iter res_orig ac res tl in iter res [] res ralist and format_typ k fmt = Format.fprintf fmt "%s%t" name k in Ctypes_static.view ~format_typ ~read ~write Ctypes.int64_t module ConfigFlags = struct include ConfigFlags let t_bitmask = build_enum_bitmask "ConfigFlags" vals let to_int x = Unsigned.UInt32.to_int Ctypes.(coerce t uint32_t x) let of_int i = Ctypes.(coerce uint32_t t (Unsigned.UInt32.of_int i)) end module TraceLogLevel = struct include TraceLogLevel let to_int x = Unsigned.UInt32.to_int Ctypes.(coerce t uint32_t x) let of_int i = Ctypes.(coerce uint32_t t (Unsigned.UInt32.of_int i)) end module Key = struct include Key let to_int x = Unsigned.UInt32.to_int Ctypes.(coerce t uint32_t x) let of_int i = Ctypes.(coerce uint32_t t (Unsigned.UInt32.of_int i)) end module MouseButton = struct include MouseButton let to_int x = Unsigned.UInt32.to_int Ctypes.(coerce t uint32_t x) let of_int i = Ctypes.(coerce uint32_t t (Unsigned.UInt32.of_int i)) end module MouseCursor = struct include MouseCursor let to_int x = Unsigned.UInt32.to_int Ctypes.(coerce t uint32_t x) let of_int i = Ctypes.(coerce uint32_t t (Unsigned.UInt32.of_int i)) end module GamepadButton = struct include GamepadButton let to_int x = Unsigned.UInt32.to_int Ctypes.(coerce t uint32_t x) let of_int i = Ctypes.(coerce uint32_t t (Unsigned.UInt32.of_int i)) end module GamepadAxis = struct include GamepadAxis let to_int x = Unsigned.UInt32.to_int Ctypes.(coerce t uint32_t x) let of_int i = Ctypes.(coerce uint32_t t (Unsigned.UInt32.of_int i)) end module MaterialMapIndex = struct include MaterialMapIndex let to_int x = Unsigned.UInt32.to_int Ctypes.(coerce t uint32_t x) let of_int i = Ctypes.(coerce uint32_t t (Unsigned.UInt32.of_int i)) end module ShaderLocationIndex = struct include ShaderLocationIndex let to_int x = Unsigned.UInt32.to_int Ctypes.(coerce t uint32_t x) let of_int i = Ctypes.(coerce uint32_t t (Unsigned.UInt32.of_int i)) end module ShaderUniformDataType = struct include ShaderUniformDataType let to_int x = Unsigned.UInt32.to_int Ctypes.(coerce t uint32_t x) let of_int i = Ctypes.(coerce uint32_t t (Unsigned.UInt32.of_int i)) end module ShaderAttributeDataType = struct include ShaderAttributeDataType let to_int x = Unsigned.UInt32.to_int Ctypes.(coerce t uint32_t x) let of_int i = Ctypes.(coerce uint32_t t (Unsigned.UInt32.of_int i)) end module PixelFormat = struct include PixelFormat let to_int x = Unsigned.UInt32.to_int Ctypes.(coerce t uint32_t x) let of_int i = Ctypes.(coerce uint32_t t (Unsigned.UInt32.of_int i)) end module TextureFilter = struct include TextureFilter let to_int x = Unsigned.UInt32.to_int Ctypes.(coerce t uint32_t x) let of_int i = Ctypes.(coerce uint32_t t (Unsigned.UInt32.of_int i)) end module TextureWrap = struct include TextureWrap let to_int x = Unsigned.UInt32.to_int Ctypes.(coerce t uint32_t x) let of_int i = Ctypes.(coerce uint32_t t (Unsigned.UInt32.of_int i)) end module CubemapLayout = struct include CubemapLayout let to_int x = Unsigned.UInt32.to_int Ctypes.(coerce t uint32_t x) let of_int i = Ctypes.(coerce uint32_t t (Unsigned.UInt32.of_int i)) end module FontType = struct include FontType let to_int x = Unsigned.UInt32.to_int Ctypes.(coerce t uint32_t x) let of_int i = Ctypes.(coerce uint32_t t (Unsigned.UInt32.of_int i)) end module BlendMode = struct include BlendMode let to_int x = Unsigned.UInt32.to_int Ctypes.(coerce t uint32_t x) let of_int i = Ctypes.(coerce uint32_t t (Unsigned.UInt32.of_int i)) end module Gesture = struct include Gesture let t_bitmask = build_enum_bitmask "Gesture" vals let to_int x = Unsigned.UInt32.to_int Ctypes.(coerce t uint32_t x) let of_int i = Ctypes.(coerce uint32_t t (Unsigned.UInt32.of_int i)) end module CameraMode = struct include CameraMode let to_int x = Unsigned.UInt32.to_int Ctypes.(coerce t uint32_t x) let of_int i = Ctypes.(coerce uint32_t t (Unsigned.UInt32.of_int i)) end module CameraProjection = struct include CameraProjection let to_int x = Unsigned.UInt32.to_int Ctypes.(coerce t uint32_t x) let of_int i = Ctypes.(coerce uint32_t t (Unsigned.UInt32.of_int i)) end module NPatchLayout = struct include NPatchLayout let to_int x = Unsigned.UInt32.to_int Ctypes.(coerce t uint32_t x) let of_int i = Ctypes.(coerce uint32_t t (Unsigned.UInt32.of_int i)) end module Vector2 = Vector2 module Vector3 = Vector3 module Vector4 = Vector4 module Matrix = Matrix module Color = Color module Rectangle = Rectangle module Image = Image module Texture = Texture module RenderTexture = RenderTexture module NPatchInfo = NPatchInfo module GlyphInfo = GlyphInfo module Font = Font module Camera3D = Camera3D module Camera2D = Camera2D module Mesh = Mesh module Shader = Shader module MaterialMap = MaterialMap module Material = Material module Transform = Transform module BoneInfo = BoneInfo module Model = Model module ModelAnimation = ModelAnimation module Ray = Ray module RayCollision = RayCollision module BoundingBox = BoundingBox module Wave = Wave module AudioStream = AudioStream module Sound = Sound module Music = Music module VrDeviceInfo = VrDeviceInfo module VrStereoConfig = VrStereoConfig module FilePathList = FilePathList let max_material_maps = max_material_maps let max_shader_locations = max_shader_locations
ae194b120de20eb332a9c2e1e09324df64655eeb3899b97bf90188a3d3002e52
MysteryMachine/jobim
impl.clj
(ns jobim.core.impl) (defn def-form? [form] (= (first form) 'def)) (defn defn-form? [form] (= (first form) 'defn)) (defn def-form [[_ name & code]] `[~name ~@code]) (defn defn-form [[_ name args & code]] `[~name (fn ~name ~args ~@code)]) (defn nameless-form [length code] `[~(symbol (str "%" length)) ~code]) (defn form [length code] (cond (not (seq? code)) (nameless-form length code) (def-form? code) (def-form code) (defn-form? code) (defn-form code) :else (nameless-form length code))) (defn expand-to-form [{:keys [length forms] :as env} code] (-> env (assoc-in [:forms] (conj forms (form length code))) (update-in [:length] inc))) (defn key-pair [[sym & _]] [(keyword sym) sym]) (defn build-forms [code] (:forms (reduce expand-to-form {:length 0 :forms []} code))) (defn transform-code [code] (let [forms (build-forms code)] `(let ~(vec (reduce concat forms)) ~(apply hash-map (reduce concat (map key-pair forms))))))
null
https://raw.githubusercontent.com/MysteryMachine/jobim/6f12212e6958d9a2965b76a3c876f931f2e429e9/src/jobim/core/impl.clj
clojure
(ns jobim.core.impl) (defn def-form? [form] (= (first form) 'def)) (defn defn-form? [form] (= (first form) 'defn)) (defn def-form [[_ name & code]] `[~name ~@code]) (defn defn-form [[_ name args & code]] `[~name (fn ~name ~args ~@code)]) (defn nameless-form [length code] `[~(symbol (str "%" length)) ~code]) (defn form [length code] (cond (not (seq? code)) (nameless-form length code) (def-form? code) (def-form code) (defn-form? code) (defn-form code) :else (nameless-form length code))) (defn expand-to-form [{:keys [length forms] :as env} code] (-> env (assoc-in [:forms] (conj forms (form length code))) (update-in [:length] inc))) (defn key-pair [[sym & _]] [(keyword sym) sym]) (defn build-forms [code] (:forms (reduce expand-to-form {:length 0 :forms []} code))) (defn transform-code [code] (let [forms (build-forms code)] `(let ~(vec (reduce concat forms)) ~(apply hash-map (reduce concat (map key-pair forms))))))